github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/network/p2p/unicast/protocols/gzip.go (about)

     1  package protocols
     2  
     3  import (
     4  	libp2pnet "github.com/libp2p/go-libp2p/core/network"
     5  	"github.com/libp2p/go-libp2p/core/protocol"
     6  	"github.com/rs/zerolog"
     7  
     8  	"github.com/onflow/flow-go/model/flow"
     9  	"github.com/onflow/flow-go/network/compressor"
    10  	"github.com/onflow/flow-go/network/p2p/unicast/protocols/internal"
    11  )
    12  
    13  const GzipCompressionUnicast = ProtocolName("gzip-compression")
    14  
    15  func FlowGzipProtocolId(sporkId flow.Identifier) protocol.ID {
    16  	return protocol.ID(FlowLibP2PProtocolGzipCompressedOneToOne + sporkId.String())
    17  }
    18  
    19  // GzipStream is a stream compression creates and returns a gzip-compressed stream out of input stream.
    20  type GzipStream struct {
    21  	protocolId     protocol.ID
    22  	defaultHandler libp2pnet.StreamHandler
    23  	logger         zerolog.Logger
    24  }
    25  
    26  func NewGzipCompressedUnicast(logger zerolog.Logger, sporkId flow.Identifier, defaultHandler libp2pnet.StreamHandler) *GzipStream {
    27  	return &GzipStream{
    28  		protocolId:     FlowGzipProtocolId(sporkId),
    29  		defaultHandler: defaultHandler,
    30  		logger:         logger.With().Str("subsystem", "gzip-unicast").Logger(),
    31  	}
    32  }
    33  
    34  // UpgradeRawStream wraps gzip compression and decompression around the plain libp2p stream.
    35  func (g GzipStream) UpgradeRawStream(s libp2pnet.Stream) (libp2pnet.Stream, error) {
    36  	return internal.NewCompressedStream(s, compressor.GzipStreamCompressor{})
    37  }
    38  
    39  func (g GzipStream) Handler(s libp2pnet.Stream) {
    40  	// converts native libp2p stream to gzip-compressed stream
    41  	s, err := g.UpgradeRawStream(s)
    42  	if err != nil {
    43  		g.logger.Error().Err(err).Msg("could not create compressed stream")
    44  		return
    45  	}
    46  	g.defaultHandler(s)
    47  }
    48  
    49  func (g GzipStream) ProtocolId() protocol.ID {
    50  	return g.protocolId
    51  }