github.com/grafana/synthetic-monitoring-agent@v0.64.2/internal/pkg/loki/loki.go (about)

     1  package loki
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/gogo/protobuf/proto"
     7  	"github.com/golang/snappy"
     8  	logproto "github.com/grafana/loki/pkg/push"
     9  	"github.com/grafana/synthetic-monitoring-agent/internal/pkg/prom"
    10  )
    11  
    12  // sendSamples to the remote storage with backoff for recoverable errors.
    13  func SendStreamsWithBackoff(ctx context.Context, client *prom.Client, streams []logproto.Stream, buf *[]byte) error {
    14  	req, err := buildStreamsPushRequest(streams, *buf)
    15  	*buf = req
    16  
    17  	if err != nil {
    18  		// Failing to build the write request is non-recoverable, since it will
    19  		// only error if marshaling the proto to bytes fails.
    20  		return err
    21  	}
    22  
    23  	return prom.SendBytesWithBackoff(ctx, client, req)
    24  }
    25  
    26  func buildStreamsPushRequest(streams []logproto.Stream, buf []byte) ([]byte, error) {
    27  	req := &logproto.PushRequest{
    28  		Streams: streams,
    29  	}
    30  
    31  	data, err := proto.Marshal(req)
    32  	if err != nil {
    33  		return nil, err
    34  	}
    35  
    36  	// snappy uses len() to see if it needs to allocate a new slice. Make the
    37  	// buffer as long as possible.
    38  	if buf != nil {
    39  		buf = buf[0:cap(buf)]
    40  	}
    41  
    42  	compressed := snappy.Encode(buf, data)
    43  
    44  	return compressed, nil
    45  }