util

package
v3.1.0-rc.1.0...-6d180dd Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: AGPL-3.0 Imports: 39 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// FakeTenantID is the tenant ID to be used when operating with authorization disabled
	FakeTenantID = "single-tenant"
)

Variables

View Source
var (
	// ErrTraceNotFound can be used when we don't find a trace
	ErrTraceNotFound = errors.New("trace not found")

	// StatusClientClosedRequest is the status code for when a client request cancellation of an http request
	StatusClientClosedRequest     = 499
	StatusTextClientClosedRequest = "Request Cancelled"

	ErrUnsupported = fmt.Errorf("unsupported")
)

Functions

func Clone

func Clone[S ~[]E, E any](s S) S

Clone returns a copy of the slice. The elements are copied using assignment, so this is a shallow clone. The difference with slices.Clone is that the result will not have additional unused capacity.

func DiffConfig

func DiffConfig(defaultConfig, actualConfig map[interface{}]interface{}) (map[interface{}]interface{}, error)

DiffConfig utility function that returns the diff between two config map objects

func EqualHexStringTraceIDs

func EqualHexStringTraceIDs(a, b string) (bool, error)

EqualHexStringTraceIDs compares two trace ID strings and compares the resulting bytes after padding. Returns true unless there is a reason not to.

func HashForTraceID

func HashForTraceID(tid []byte) uint64

HashForTraceID generates a generic hash for the trace ID, suitable for mapping and deduping.

func HexStringToSpanID

func HexStringToSpanID(id string) ([]byte, error)

func HexStringToTraceID

func HexStringToTraceID(id string) ([]byte, error)

func IsRequestBodyTooLarge

func IsRequestBodyTooLarge(err error) bool

IsRequestBodyTooLarge returns true if the error is "http: request body too large".

func MustGetFreePort

func MustGetFreePort() int

MustGetFreePort returns a TCP port that is available to listen on, for the given (local) host.

This works by binding a new TCP socket on port 0, which requests the OS to allocate a free port. There is no strict guarantee that the port will remain available after this function returns, but it should be safe to assume that a given port will not be allocated again to any process on this machine within a few seconds.

On Unix-based systems, binding to the port returned by this function requires setting the `SO_REUSEADDR` socket option (Go already does that by default, but other languages may not); otherwise, the OS may fail with a message such as "address already in use". Windows default behavior is already appropriate in this regard; on that platform, `SO_REUSEADDR` has a different meaning and should not be set (setting it may have unpredictable consequences).

Copied from github.com/temporalio/temporal/blob/main/common/testing/freeport/freeport.go.

func NewDNSWatcher

func NewDNSWatcher(address string, dnsLookupPeriod time.Duration, notifications DNSNotifications) (services.Service, error)

NewDNSWatcher creates a new DNS watcher and returns a service that is wrapping it.

func NewTokenHasher

func NewTokenHasher() hash.Hash64

NewTokenHasher returns a new hash.Hash64 for use with TokenForID.

func PadTraceIDString

func PadTraceIDString(id string) string

PadTraceIDString left-pads a trace ID hex string to 32 characters with zeros. This produces W3C/OpenTelemetry compliant 32-character lowercase hex trace IDs.

func PadTraceIDTo16Bytes

func PadTraceIDTo16Bytes(traceID []byte) []byte

func ParseProtoReader

func ParseProtoReader(ctx context.Context, reader io.Reader, expectedSize, maxSize int, req proto.Message, compression CompressionType) error

ParseProtoReader parses a compressed proto from an io.Reader.

func PrefixConfig

func PrefixConfig(prefix string, option string) string

func RandomAttrFromTrace

func RandomAttrFromTrace(t *tempopb.Trace) *v1common.KeyValue

RandomAttrFromTrace returns a random attribute from the trace for use in search validation. Integer attributes are never chosen: they are not unique enough for search.

func RenderHTTPResponse

func RenderHTTPResponse(w http.ResponseWriter, v interface{}, t *template.Template, r *http.Request)

RenderHTTPResponse either responds with json or a rendered html page using the passed in template by checking the Accepts header

func SerializeProtoResponse

func SerializeProtoResponse(w http.ResponseWriter, resp proto.Message, compression CompressionType) error

SerializeProtoResponse serializes a protobuf response into an HTTP response.

func SpanIDAndKindToToken

func SpanIDAndKindToToken(id []byte, kind int) uint64

SpanIDAndKindToToken converts a span ID into a token for use as key in a hash map. The token is generated such that it has a low collision probability. In zipkin traces the span id is not guaranteed to be unique as it is shared between client and server spans. Therefore, it is sometimes required to take the span kind into account.

func SpanIDToHexString

func SpanIDToHexString(byteID []byte) string

SpanIDToHexString converts a span ID to its string representation and WITHOUT removing any leading zeros. If the id is < 16, left pad with 0s

func SpanIDToUint64

func SpanIDToUint64(id []byte) uint64

SpanIDToUint64 converts a span ID into an uint64 representation. This is useful when using a span ID as key in a map. If the ID is longer than 8 bytes, the bytes at larger positions are discarded. The function does not make any guarantees about the endianess or ordering of converted IDs.

Note: span IDs are not always unique within a trace (e.g. zipkin traces) SpanIDAndKindToToken could be more appropriate in some cases.

func StatusText

func StatusText(code int) string

func StreamWriteYAMLResponse

func StreamWriteYAMLResponse(w http.ResponseWriter, iter chan interface{}, logger log.Logger)

StreamWriteYAMLResponse stream writes data as http response

func StringifyAnyValue

func StringifyAnyValue(anyValue *v1common.AnyValue) string

func TabOut

func TabOut(s fmt.Stringer) string

func TokenFor

func TokenFor(userID string, b []byte) uint32

TokenFor generates a token used for finding ingesters from ring. Not suitable for in-memory hashing or deduping because it is only 32-bit. The collision rate is about 1 in 8000.

func TokenForID

func TokenForID(h hash.Hash64, buffer []byte, kind int32, id []byte) uint64

TokenForID returns a token for use as a key in a hash map given a span ID and span kind. h and buffer (must be at least 4 bytes) are provided by the caller for reuse across calls to avoid repeated allocations. Use NewTokenHasher to create h. kind is included because in zipkin traces the span id is shared between client and server spans.

func TokenForTraceID

func TokenForTraceID(b []byte) uint32

TokenForTraceID generates a hashed value for a trace id. Used for bloom lookups. Do not change because it will break lookups on existing bloom filters.

func TraceIDToHexString

func TraceIDToHexString(byteID []byte) string

TraceIDToHexString converts a trace ID to its string representation and removes any leading zeros.

func WriteHTMLResponse

func WriteHTMLResponse(w http.ResponseWriter, message string)

Sends message as text/html response with 200 status code.

func WriteJSONResponse

func WriteJSONResponse(w http.ResponseWriter, v interface{})

WriteJSONResponse writes some JSON as a HTTP response.

func WriteTextResponse

func WriteTextResponse(w http.ResponseWriter, message string)

Sends message as text/plain response with 200 status code.

func WriteYAMLResponse

func WriteYAMLResponse(w http.ResponseWriter, v interface{})

WriteYAMLResponse writes some YAML as a HTTP response.

func YAMLMarshalUnmarshal

func YAMLMarshalUnmarshal(in interface{}) (map[interface{}]interface{}, error)

YAMLMarshalUnmarshal utility function that converts a YAML interface in a map doing marshal and unmarshal of the parameter

Types

type ActiveUsers

type ActiveUsers struct {
	// contains filtered or unexported fields
}

ActiveUsers keeps track of latest user's activity timestamp, and allows purging users that are no longer active.

func NewActiveUsers

func NewActiveUsers() *ActiveUsers

func (*ActiveUsers) PurgeInactiveUsers

func (m *ActiveUsers) PurgeInactiveUsers(deadline int64) []string

PurgeInactiveUsers removes users that were last active before given deadline, and returns removed users.

func (*ActiveUsers) UpdateUserTimestamp

func (m *ActiveUsers) UpdateUserTimestamp(userID string, ts int64)

type ActiveUsersCleanupService

type ActiveUsersCleanupService struct {
	services.Service
	// contains filtered or unexported fields
}

ActiveUsersCleanupService tracks active users, and periodically purges inactive ones while running.

func NewActiveUsersCleanupService

func NewActiveUsersCleanupService(cleanupInterval, inactiveTimeout time.Duration, cleanupFn func(string)) *ActiveUsersCleanupService

func NewActiveUsersCleanupWithDefaultValues

func NewActiveUsersCleanupWithDefaultValues(cleanupFn func(string)) *ActiveUsersCleanupService

func (*ActiveUsersCleanupService) UpdateUserTimestamp

func (s *ActiveUsersCleanupService) UpdateUserTimestamp(user string, now time.Time)

type BasicAuth

type BasicAuth struct {
	Username string `yaml:"basic_auth_username"`
	Password string `yaml:"basic_auth_password"`
}

BasicAuth configures basic authentication for HTTP clients.

func (BasicAuth) IsEnabled

func (b BasicAuth) IsEnabled() bool

IsEnabled returns false if basic authentication isn't enabled.

func (*BasicAuth) RegisterFlagsWithPrefix

func (b *BasicAuth) RegisterFlagsWithPrefix(prefix string, f *flag.FlagSet)

type CompressionType

type CompressionType int

CompressionType for encoding and decoding requests and responses.

const (
	NoCompression CompressionType = iota
	RawSnappy
)

Values for CompressionType

type DNSNotifications

type DNSNotifications interface {
	// New address has been discovered by DNS watcher for supplied hostname.
	AddressAdded(address string)

	// Previously-discovered address is no longer resolved for the hostname.
	AddressRemoved(address string)
}

Notifications about address resolution. All notifications are sent on the same goroutine.

type JaegerClient

type JaegerClient interface {
	EmitBatch(ctx context.Context, b *jaeger.Batch) error
}

JaegerClient is an interface used to mock the underlying client in tests.

type TraceInfo

type TraceInfo struct {
	// contains filtered or unexported fields
}

TraceInfo is used to construct synthetic traces and manage the expectations.

func NewTraceInfo

func NewTraceInfo(timestamp time.Time, tempoOrgID string) *TraceInfo

NewTraceInfo is used to produce a new TraceInfo.

func NewTraceInfoWithMaxLongWrites

func NewTraceInfoWithMaxLongWrites(timestamp time.Time, maxLongWrites int64, tempoOrgID string) *TraceInfo

func NewTraceInfos

func NewTraceInfos(timestamp time.Time, count int, tempoOrgID string) []*TraceInfo

NewTraceInfos creates multiple trace infos with slightly different timestamps to ensure different trace seeds are used.

func (*TraceInfo) ConstructTraceFromEpoch

func (t *TraceInfo) ConstructTraceFromEpoch() (*tempopb.Trace, error)

func (*TraceInfo) Done

func (t *TraceInfo) Done()

func (*TraceInfo) EmitAllBatches

func (t *TraceInfo) EmitAllBatches(c JaegerClient) error

EmitAllBatches sends all the batches that would normally be sent at some interval when using EmitBatches.

func (*TraceInfo) EmitBatches

func (t *TraceInfo) EmitBatches(ctx context.Context, c JaegerClient) error

func (*TraceInfo) HexID

func (t *TraceInfo) HexID() string

func (*TraceInfo) LongWritesRemaining

func (t *TraceInfo) LongWritesRemaining() int64

func (*TraceInfo) Ready

func (t *TraceInfo) Ready(now time.Time, writeBackoff, longWriteBackoff time.Duration) bool

func (*TraceInfo) Timestamp

func (t *TraceInfo) Timestamp() time.Time

func (*TraceInfo) TraceID

func (t *TraceInfo) TraceID() ([]byte, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址