...

Source file src/go.einride.tech/aip/pagination/request.go

Documentation: go.einride.tech/aip/pagination

     1  package pagination
     2  
     3  import (
     4  	"fmt"
     5  	"hash/crc32"
     6  
     7  	"google.golang.org/protobuf/proto"
     8  )
     9  
    10  // Request is an interface for paginated request messages.
    11  //
    12  // See: https://google.aip.dev/158 (Pagination).
    13  type Request interface {
    14  	proto.Message
    15  	// GetPageToken returns the page token of the request.
    16  	GetPageToken() string
    17  	// GetPageSize returns the page size of the request.
    18  	GetPageSize() int32
    19  }
    20  
    21  type skipRequest interface {
    22  	proto.Message
    23  	// GetSkip returns the skip of the request.
    24  	// See: https://google.aip.dev/158#skipping-results
    25  	GetSkip() int32
    26  }
    27  
    28  // calculateRequestChecksum calculates a checksum for all fields of the request that must be the same across calls.
    29  func calculateRequestChecksum(request Request) (uint32, error) {
    30  	// Clone the original request, clear fields that may vary across calls, then checksum the resulting message.
    31  	clonedRequest := proto.Clone(request)
    32  	r := clonedRequest.ProtoReflect()
    33  	r.Clear(r.Descriptor().Fields().ByName("page_token"))
    34  	r.Clear(r.Descriptor().Fields().ByName("page_size"))
    35  	if _, ok := request.(skipRequest); ok {
    36  		r.Clear(r.Descriptor().Fields().ByName("skip"))
    37  	}
    38  	data, err := proto.Marshal(clonedRequest)
    39  	if err != nil {
    40  		return 0, fmt.Errorf("calculate request checksum: %w", err)
    41  	}
    42  	return crc32.ChecksumIEEE(data), nil
    43  }
    44  

View as plain text