correlation

package module
v1.1.4 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 12 Imported by: 0

README

correlation

CI CodeQL Coverage Mutation Documentation Go Reference Release Go License

correlation is the transport-neutral owner of correlation, request, and causation identifiers. It carries those semantics through HTTP, JSON-RPC, queues, scheduled work, webhooks, logs, and OpenTelemetry without creating a global propagator or redefining trace and idempotency concepts.

The module is a stable v1 library. Its public minimum is Go 1.27.0; development and CI use Go 1.27.2. Stable releases are selected through the v1 module line.

Install

go get github.com/faustbrian/go-correlation@v1

Semantics

  • CorrelationID groups one logical interaction or workflow.
  • RequestID identifies exactly one transport hop or delivery attempt.
  • CausationID identifies that hop's immediate parent request or message.

These types are deliberately distinct. Trace and span IDs remain owned by OpenTelemetry. Idempotency keys and fingerprints remain owned by idempotency. None of these values is authentication, authorization, tenancy, uniqueness, replay protection, or idempotency evidence.

Quick start

factory, err := correlation.NewFactory(correlation.FactoryOptions{})
if err != nil {
    return err
}

root, err := factory.Start()
if err != nil {
    return err
}
child, err := factory.Next(root)
if err != nil {
    return err
}

The complete compiler-checked released-v1 version is the package Example. Further examples cover Factory.Create and Factory.Next.

Create is the canonical operation for fresh root values. Start remains a compatibility alias with identical values and errors. Scheduled work follows the same boundary: schedule.Adapter.Create and schedule.Adapter.Receive are canonical, while Start and Run remain compatible aliases.

The default factory uses an explicitly owned, bounded entropy buffer around the cryptographic UUIDv4 generator from identifier. A caller-supplied generator remains instance scoped and must return canonical text accepted by the configured policy.

Inbound metadata is never trusted by extraction alone:

inbound, err := codec.Extract(carrier)
if err != nil {
    return err
}
values, err := factory.Accept(inbound, correlation.InboundPolicy{
    TrustCorrelation: true,
    TrustRequestAsCausation: true,
})

The application must establish that trust from an authenticated immediate transport boundary first. Every accepted hop receives a new request ID.

Adapters

  • adapters/http sanitizes inbound headers, applies explicit proxy trust, installs immutable context values, and injects outbound hops.
  • http/requestidbridge explicitly adopts a trusted http-middleware/requestid value without importing its private key.
  • adapters/jsonrpc reads and writes a separate metadata object without altering JSON-RPC envelopes.
  • adapters/queue preserves workflow identity while generating a distinct request ID for every retry or redelivery.
  • adapters/schedule starts independent runs unless metadata is deliberately propagated.
  • webhook gives outbound and inbound webhook hops HTTP semantics.
  • adapters/slog supplies redacted, keyed-hash, or explicitly raw slog attrs.
  • adapters/otel attaches attributes to telemetry-owned links and exposes only fixed-cardinality presence flags to metrics.

The former http, jsonrpc, queue, schedule, log, and telemetry import paths remain deprecated compatibility implementations and identity authorities. New code should use the target-oriented adapters/... paths.

W3C Trace Context and Baggage remain optional application-owned propagation. They may be linked to these values, but correlation IDs never become trace or span IDs.

When to use it

Use this module when work crosses process, protocol, queue, retry, or scheduled boundaries and operators need to relate those attempts without conflating their identities. Do not use it as an authorization, tenancy, uniqueness, deduplication, replay-protection, or idempotency mechanism, and do not replace OpenTelemetry trace or span identity with correlation values.

Construction, errors, and lifecycle

NewFactory and NewCodec validate their complete value configuration. NewPropagator and transport constructors reject missing dependencies and validate the policy options they own. The zero Policy accepts canonical ASCII identifiers up to 128 bytes. Stable sentinel categories such as ErrInvalidID, ErrInvalidFactory, and ErrGeneration are matched with errors.Is; wrapped causes remain available where disclosure is safe.

Factory, codec, and adapter operations perform no network I/O, retry, or detached work. WithValues, FromContext, and HTTP middleware use only the caller-owned context passed to that call; they do not retain it. The module starts no goroutines, opens no resources, and owns no Close or Shutdown operation. Applications retain ownership of carriers, headers, maps, contexts, telemetry providers, and supplied callbacks or generators.

The built-in factory and immutable strategies are safe for concurrent use. A caller-supplied generator and HTTP Trust callback are borrowed for the owning object's lifetime, so callers must keep them valid and provide any synchronization they require. Extraction and receive operations only read carriers. Send, inject, and HTTP wrap operations update the carrier or headers supplied for that call; callers must not concurrently reuse those mutable values without their own synchronization.

Shared construction, ownership, lifecycle, and composition expectations are in the versioned Golib ecosystem index and its foundations package guidance.

Deterministic correlation

NewDeterministic is an explicit opt-in for stable business workflows. It uses HMAC-SHA-256, a versioned domain, length-delimited input, and bounded output. Use a secret key when the input is private or comes from a small input space. Deterministic correlation is linkable and is never the factory default.

Security defaults

Identifiers use the canonical [A-Za-z0-9_-] alphabet and a default maximum of 128 bytes. Carriers reject empty, oversized, malformed, control-bearing, Unicode, and conflicting values. Injection refuses a populated target field for each non-empty identifier it would write. A direct partial Codec.Inject leaves fields corresponding to empty identifiers unchanged, so callers must clear any unrelated stale fields first. Observability output is redacted unless disclosure is explicitly enabled, and metrics never contain identifier values.

Verification

Run standalone root tests and bounded shared checks:

GOWORK=off go test ./...
make check
make ci

The Make routes use the public pinned verifier and retain a focused race test for concurrent default factory uniqueness. make check-full explicitly selects full assurance, including the configured fuzz, mutation, benchmark, API and integration contracts. Release qualification additionally requires its selected rehearsal; ordinary checks are not release-equivalent. See CONTRIBUTING.md for focused fuzzing, optional single-package mutation and the workspace versus published harness distinction.

See the documentation index, security policy, and changelog. Operational limits and performance caveats are in the operations guide; symptom-driven recovery steps are in troubleshooting. Start with the FAQ and support guide for adoption questions and reproducible non-security defects. Follow the security policy for private vulnerability reports.

Documentation navigation

Complete documentation map · Current source package map

Use the versioned ecosystem entry for package selection. The frozen compatibility cohort is separate from current package releases and unpublished source changes. Adopting them does not silently update that cohort.

Documentation

Overview

Package correlation provides transport-neutral correlation, request, and causation identifiers. Identifiers are diagnostic metadata only; they are never authentication, authorization, tenancy, replay, or idempotency proof. Begin with NewFactory for root/hop values, NewCodec for transport metadata and an explicit InboundPolicy for receipt. Named strings and context storage do not themselves validate or redact IDs; use Parse helpers at untrusted boundaries.

Values are copied structs containing immutable strings; codecs/strategies have immutable configuration. Factories borrow their generator and adapters borrow callbacks and mutable carriers, whose synchronization remains caller-owned. The package owns no background work, transport, retry, trace provider or shutdown. Calls are synchronous with no added deadline or panic recovery for caller code.

Example
package main

import (
	"fmt"

	correlation "github.com/faustbrian/go-correlation"
)

func main() {
	factory, err := correlation.NewFactory(correlation.FactoryOptions{})
	if err != nil {
		fmt.Println("factory error")
		return
	}
	root, err := factory.Start()
	if err != nil {
		fmt.Println("root error")
		return
	}
	child, err := factory.Next(root)
	if err != nil {
		fmt.Println("child error")
		return
	}
	fmt.Println(
		root.CorrelationID != "",
		root.RequestID != "",
		child.CorrelationID == root.CorrelationID,
		child.CausationID.String() == root.RequestID.String(),
		child.RequestID != root.RequestID,
	)
}
Output:
true true true true true

Index

Examples

Constants

View Source
const (
	// DefaultCorrelationField is the transport-neutral correlation key.
	DefaultCorrelationField = "correlation_id"
	// DefaultRequestField is the transport-neutral request key.
	DefaultRequestField = "request_id"
	// DefaultCausationField is the transport-neutral causation key.
	DefaultCausationField = "causation_id"
)

Variables

View Source
var (
	// ErrInvalidCarrier reports malformed, unbounded, or unsupported metadata.
	ErrInvalidCarrier = errors.New("correlation: invalid carrier")
	// ErrConflictingCarrier reports more than one distinct value for a field.
	ErrConflictingCarrier = errors.New("correlation: conflicting carrier values")
	// ErrCarrierOverwrite reports injection into an already populated field.
	ErrCarrierOverwrite = errors.New("correlation: carrier overwrite")
)
View Source
var (
	// ErrInvalidFactory reports invalid factory configuration.
	ErrInvalidFactory = errors.New("correlation: invalid factory")
	// ErrGeneration reports a generator failure or invalid generated value.
	ErrGeneration = errors.New("correlation: generation failed")
)
View Source
var ErrInvalidDerivation = errors.New("correlation: invalid deterministic derivation")

ErrInvalidDerivation reports unsafe deterministic derivation input or configuration.

View Source
var ErrInvalidDisclosure = errors.New("correlation: invalid disclosure policy")

ErrInvalidDisclosure reports unsafe disclosure configuration.

View Source
var ErrInvalidExternalID = errors.New("correlation: invalid external identifier")

ErrInvalidExternalID reports invalid external identifier metadata.

View Source
var ErrInvalidID = errors.New("correlation: invalid identifier")

ErrInvalidID reports an identifier that violates its validation policy.

View Source
var ErrInvalidPropagator = errors.New("correlation: invalid propagator")

ErrInvalidPropagator reports missing explicit propagation dependencies.

Functions

func Disclose

func Disclose(label, value string, policy DisclosurePolicy) (string, error)

Disclose renders an identifier according to an explicit observability policy. label domain-separates correlation, request, and causation hashes; use fixed distinct labels, not attacker-controlled label framing. Hash mode emits 16 HMAC-SHA-256 digest bytes as unpadded base64url (22 characters). Neither label nor value is validated or size-limited here; ExposeDisclosure returns value unchanged. After the key-size check, empty value returns empty, nil even for an unknown mode or missing hash key. Invalid nonempty policies return ErrInvalidDisclosure. Callers bound inputs and synchronize borrowed keys.

func WithValues

func WithValues(ctx context.Context, values Values) context.Context

WithValues returns a derived context carrying a copy of values under a package-private key, replacing prior Values at that key without merging or validation. It preserves parent cancellation/deadlines and panics for nil ctx.

Types

type Carrier

type Carrier interface {
	// Values returns all values for key, preserving duplicates; absence is a
	// zero-length slice, distinct from a present empty string. Providers should
	// bound collection before allocation for hostile transport metadata.
	Values(key string) []string
	// Set replaces key with one value. It must not change unrelated fields;
	// injection preflights before invoking it but cannot undo provider failures.
	Set(key, value string)
}

Carrier is an explicit transport metadata boundary. Values must return a copy or immutable view stable for the call. Set replaces one field with exactly one value. The caller owns carrier lifetime, synchronization, name matching and callback behavior; Codec provides no transaction, timeout or panic recovery.

type CausationID

type CausationID string

CausationID identifies the immediate parent request, message, or event, not an ancestry chain. Empty means absence; direct conversion bypasses validation.

func MustCausationID

func MustCausationID(value string, policy Policy) CausationID

MustCausationID is ParseCausationID for static configuration and tests. It panics with the validation error for invalid input or policy.

func ParseCausationID

func ParseCausationID(value string, policy Policy) (CausationID, error)

ParseCausationID validates nonempty ASCII text exactly as ParseCorrelationID, returning an empty ID and ErrInvalidID-wrapping error on failure.

func (CausationID) String

func (id CausationID) String() string

String returns the underlying text without validation or redaction.

type Codec

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

Codec injects and extracts typed values without assigning trust. Construct with NewCodec; immutable configuration can be shared, but carriers must be synchronized independently. Zero Codec values are not configured codecs.

func NewCodec

func NewCodec(options CodecOptions) (*Codec, error)

NewCodec validates and copies carrier configuration, returning nil and an ErrInvalidCarrier-wrapping error on invalid policy or duplicate/invalid names. Field uniqueness is exact, not case-folded; custom names must also be distinct under the selected transport's own name comparison.

func (*Codec) Extract

func (codec *Codec) Extract(carrier Carrier) (Values, error)

Extract parses values but deliberately does not decide whether to trust them. Pass the result to Factory.Accept with an explicit InboundPolicy. Absent fields are allowed; at most eight repeated values must all be equal and nonempty. Invalid/conflicting metadata returns zero Values, not a partial parse. Nil codec or nil/typed-nil carrier returns ErrInvalidCarrier. No writes occur.

func (*Codec) Inject

func (codec *Codec) Inject(carrier Carrier, values Values) error

Inject installs non-empty values and refuses to overwrite any populated field, even when the existing value is malformed. Empty output fields are skipped, including overwrite checks. All nonempty values/overwrites are checked before the first Set; this is not atomic against concurrent carrier mutation or a provider panic. Validation/overwrite failure makes no Set calls.

type CodecOptions

type CodecOptions struct {
	// Policy validates carried identifier text; zero selects default limits.
	Policy Policy
	// CorrelationField selects a distinct ASCII name of at most 64 bytes;
	// empty selects DefaultCorrelationField.
	CorrelationField string
	// RequestField is a distinct ASCII name; empty selects DefaultRequestField.
	RequestField string
	// CausationField is a distinct ASCII name; empty selects DefaultCausationField.
	CausationField string
}

CodecOptions configure immutable carrier field names and validation.

type CorrelationID

type CorrelationID string

CorrelationID groups work in one logical interaction or workflow. Its empty value represents absence in Values, though ParseCorrelationID rejects empty input. Direct string conversion bypasses validation and supplies no trust.

func MustCorrelationID

func MustCorrelationID(value string, policy Policy) CorrelationID

MustCorrelationID is ParseCorrelationID for static configuration and tests. It panics with the validation error for invalid input or policy.

func ParseCorrelationID

func ParseCorrelationID(value string, policy Policy) (CorrelationID, error)

ParseCorrelationID accepts nonempty canonical ASCII text unchanged under policy. Invalid alphabet, length or policy returns an empty ID and an error wrapping ErrInvalidID, without rejected input. It does not assign trust.

func (CorrelationID) String

func (id CorrelationID) String() string

String returns the underlying text without validation or redaction.

type Deterministic

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

Deterministic derives linkable IDs for an explicitly stable workflow. It is never selected by Factory defaults and should be keyed for private inputs. Construct with NewDeterministic; configuration/key are immutable and safe for concurrent derivation with stable call inputs. Shorter output retains fewer digest bits; no uniqueness or authentication guarantee is provided.

func NewDeterministic

func NewDeterministic(options DeterministicOptions) (*Deterministic, error)

NewDeterministic validates and copies deterministic strategy configuration. Invalid options return nil wrapping ErrInvalidDerivation. The copied key remains retained for the strategy lifetime; modifying the caller key has no effect.

func (*Deterministic) Derive

func (strategy *Deterministic) Derive(input []byte) (CorrelationID, error)

Derive consumes stable borrowed input synchronously using HMAC-SHA-256 over the package marker, big-endian version and length-delimited domain/input, then prefixes and truncates unpadded base64url digest text to configured Length. Nil strategy, empty or over-1-MiB input returns empty ID with ErrInvalidDerivation. Input is not retained. Repeated configuration/input is linkable; empty-key low entropy input spaces can be enumerated. There is no context/cancellation seam.

type DeterministicOptions

type DeterministicOptions struct {
	// Domain is nonempty canonical ASCII text, at most 128 bytes, separating
	// independently interpreted stable workflows.
	Domain string
	// Version is positive and changes both the HMAC transcript and d<version>_
	// output prefix. Key/domain/version changes alter stable IDs.
	Version uint32
	// Key is copied at construction, at most 1024 bytes. Empty selects HMAC
	// with an empty key, not a private/random strategy; no erasure API is owned.
	Key []byte
	// Length counts total output bytes including d<version>_. It must retain
	// 16 through 43 unpadded base64url digest characters; zero is invalid.
	Length int
}

DeterministicOptions configure an explicitly opted-in stable strategy.

type DisclosureMode

type DisclosureMode uint8

DisclosureMode controls identifier disclosure to logs and telemetry.

const (
	// RedactDisclosure is the safe default and emits only a marker.
	RedactDisclosure DisclosureMode = iota
	// HashDisclosure emits a keyed, domain-separated stable token.
	HashDisclosure
	// ExposeDisclosure emits raw identifier text unchanged; Disclose itself does
	// not validate it. Use only for explicitly approved diagnostic data.
	ExposeDisclosure
)

type DisclosurePolicy

type DisclosurePolicy struct {
	// Mode selects redaction (zero), keyed hashing or explicit raw exposure.
	Mode DisclosureMode
	// Key is borrowed during Disclose, never copied/erased; keep it stable for
	// concurrent calls. Hash mode requires nonempty key, and every mode rejects
	// more than 1024 key bytes. This is separate from deterministic workflow keys.
	Key []byte
}

DisclosurePolicy must explicitly opt into linkable or raw output.

type ExternalID

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

ExternalID is an optional typed external identifier with explicit source and trust metadata. It is not implicitly promoted to any correlation ID. Its immutable strings are safe to copy/share; zero ExternalID is absent metadata, not a successfully validated identifier. Accessors expose unredacted values.

func NewExternalID

func NewExternalID(options ExternalIDOptions) (ExternalID, error)

NewExternalID validates external metadata in Kind, Source, Value order, returning zero ExternalID and an ErrInvalidExternalID-wrapping error without input on failure. String values are immutable; caller trust is stored, not verified.

func (ExternalID) Kind

func (external ExternalID) Kind() string

Kind returns the external identifier's declared semantic kind.

func (ExternalID) Source

func (external ExternalID) Source() string

Source returns the declared transport or system source.

func (ExternalID) Trusted

func (external ExternalID) Trusted() bool

Trusted reports the caller's explicit trust decision.

func (ExternalID) Value

func (external ExternalID) Value() string

Value returns the validated external identifier text.

type ExternalIDOptions

type ExternalIDOptions struct {
	// Kind declares semantic meaning using nonempty ASCII text up to 64 bytes.
	Kind string
	// Value is nonempty identifier text validated under Policy.
	Value string
	// Source declares a system/transport name using ASCII text up to 64 bytes.
	Source string
	// Trusted records the caller's decision; no source authentication is run.
	Trusted bool
	// Policy applies to Value only, not the fixed Kind/Source limits.
	Policy Policy
}

ExternalIDOptions require the caller to state type, source, and trust.

type Factory

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

Factory creates hop identifiers without global mutable state. Use NewFactory; its configuration is immutable, but concurrent use requires a concurrency-safe Generator (the built-in UUID generator is safe). No uniqueness ledger or collision detection is owned; custom generators determine those properties.

func NewFactory

func NewFactory(options FactoryOptions) (*Factory, error)

NewFactory validates policy, then constructs a factory. The default is a buffered crypto/rand-backed UUIDv4 generator from Identifier v2.0.1. Its canonical 36-byte output is trusted, even with Policy.MaxLength below 36. Custom generators are retained and their successful output is validated. Invalid configuration returns nil with ErrInvalidFactory; no generator is run.

func (*Factory) Accept

func (factory *Factory) Accept(inbound Values, policy InboundPolicy) (Values, error)

Accept starts a receiving hop. No inbound value is used unless its exact semantic trust is enabled. Missing trusted values still select generation; inbound causation is ignored. Successful receipt generates a request ID; errors return zero Values on failure without rolling back consumed generator state. Use a constructed nonnil factory: a nil receiver panics when TrustCorrelation is true and inbound.CorrelationID is nonempty; other nil paths fail generation.

func (*Factory) Create added in v1.1.0

func (factory *Factory) Create() (Values, error)

Create generates correlation first, then request identity, with no causation. It returns zero Values on any ErrGeneration-wrapping failure, retaining custom generator causes; already consumed generator state is not rolled back. Nil or uninitialized factories return ErrGeneration here.

Example
generator := &sequenceGenerator{values: []string{"workflow", "root-request"}}
factory, err := correlation.NewFactory(correlation.FactoryOptions{Generator: generator})
if err != nil {
	fmt.Println("factory error")
	return
}
root, err := factory.Create()
if err != nil {
	fmt.Println("create error")
	return
}
fmt.Println(root.CorrelationID, root.RequestID, root.CausationID)
Output:
workflow root-request

func (*Factory) Next

func (factory *Factory) Next(parent Values) (Values, error)

Next preserves correlation, creates a request ID, and makes the prior request the immediate cause. Parent causation is ignored. Parent validation precedes generation; failures return zero Values wrapping ErrGeneration and the validation/generator cause. The receiver must be nonnil.

Example
generator := &sequenceGenerator{values: []string{"child-request"}}
factory, err := correlation.NewFactory(correlation.FactoryOptions{Generator: generator})
if err != nil {
	fmt.Println("factory error")
	return
}
parent := correlation.Values{
	CorrelationID: correlation.MustCorrelationID("workflow", correlation.Policy{}),
	RequestID:     correlation.MustRequestID("parent-request", correlation.Policy{}),
}
child, err := factory.Next(parent)
if err != nil {
	fmt.Println("next error")
	return
}
fmt.Println(child.CorrelationID, child.RequestID, child.CausationID)
Output:
workflow child-request parent-request

func (*Factory) Start deprecated

func (factory *Factory) Start() (Values, error)

Start creates a new correlation and request identifier.

Deprecated: use Create.

type FactoryOptions

type FactoryOptions struct {
	// Policy validates parents, trusted inbound values and custom generated
	// results; it does not truncate/revalidate built-in 36-byte UUID results.
	Policy Policy
	// Generator is borrowed for the Factory lifetime, never copied or closed.
	// Literal nil selects the cryptographic default; typed nil is invalid.
	Generator Generator
}

FactoryOptions configure an immutable Factory.

type Generator

type Generator interface {
	// New returns nonempty text accepted by Factory's Policy or an error.
	// Factories validate successful custom results, wrap errors without
	// redaction, and neither recover panics nor impose cancellation.
	New() (string, error)
}

Generator supplies canonical random identifier text. It is structurally compatible with identifier.Generator[string] from identifier. Factory borrows it: implementations own synchronization, randomness/uniqueness and lifetime. Calls are synchronous, may consume state on failure and must not assume retry.

type GeneratorFunc

type GeneratorFunc func() (string, error)

GeneratorFunc adapts a borrowed synchronous function to Generator. Nil functions panic when called directly and are rejected by NewFactory.

func (GeneratorFunc) New

func (function GeneratorFunc) New() (string, error)

New calls the wrapped function, preserving its result, error and panic. The function must supply its own synchronization when shared.

type InboundPolicy

type InboundPolicy struct {
	// TrustCorrelation permits retaining a validated nonempty inbound workflow
	// ID. It records the caller's boundary decision, not authentication.
	TrustCorrelation bool
	// TrustRequestAsCausation permits a validated inbound request ID as the
	// immediate cause. Inbound causation itself is always ignored.
	TrustRequestAsCausation bool
}

InboundPolicy explicitly identifies which inbound semantics cross a trust boundary. Request IDs are never preserved because each hop gets a new one.

type Policy

type Policy struct {
	// MaxLength is the maximum ASCII byte length, not a normalization target.
	// Zero selects 128; positive values through 1024 are supported. Other
	// values reject parsing/construction. Built-in Factory UUID generation is
	// trusted separately and always emits its 36-byte representation.
	MaxLength int
}

Policy bounds and validates an identifier. The zero value accepts the canonical ASCII alphabet [A-Za-z0-9_-] up to 128 bytes.

type Propagator

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

Propagator explicitly composes hop generation with a transport codec. It retains both dependencies, owns no carrier or transport resources and inherits Factory's generator synchronization and Carrier's caller-owned mutation rules.

func NewPropagator

func NewPropagator(factory *Factory, codec *Codec) (*Propagator, error)

NewPropagator rejects nil dependencies with ErrInvalidPropagator. Supply constructed Factory/Codec values; it does not validate their internal state.

func (*Propagator) Receive

func (propagator *Propagator) Receive(carrier Carrier, policy InboundPolicy) (Values, error)

Receive extracts untrusted metadata and applies an explicit trust policy while creating a fresh delivery-attempt request ID. Extraction checks every carried field before trust, so malformed untrusted metadata still fails here. Failures return zero Values with the extraction/generation cause preserved.

func (*Propagator) Send

func (propagator *Propagator) Send(carrier Carrier, parent Values) (Values, error)

Send creates the next hop before injecting its values. Failure returns zero Values and may have consumed generator state; injection errors are wrapped. It performs no send, retry or acknowledgment, and cannot roll back callbacks.

type RequestID

type RequestID string

RequestID identifies one transport request or delivery attempt. Empty means absent metadata; direct conversion bypasses ParseRequestID validation.

func MustRequestID

func MustRequestID(value string, policy Policy) RequestID

MustRequestID is ParseRequestID for static configuration and tests. It panics with the validation error for invalid input or policy.

func ParseRequestID

func ParseRequestID(value string, policy Policy) (RequestID, error)

ParseRequestID validates nonempty ASCII text exactly as ParseCorrelationID, returning an empty ID and ErrInvalidID-wrapping error on failure.

func (RequestID) String

func (id RequestID) String() string

String returns the underlying text without validation or redaction.

type Values

type Values struct {
	// CorrelationID is workflow identity, preserved only by explicit hop/trust
	// policy. Assignment does not validate it.
	CorrelationID CorrelationID
	// RequestID is this hop/attempt identity, newly generated at each boundary.
	RequestID RequestID
	// CausationID is the immediate parent's request identity, or empty at a root.
	CausationID CausationID
}

Values carries the three deliberately distinct identifier semantics.

func FromContext

func FromContext(ctx context.Context) (Values, bool)

FromContext returns a copy of Values installed by WithValues. Nil or absent context returns zero Values, false; explicitly stored zero Values returns true. It does not validate, authenticate or redact the stored strings.

Directories

Path Synopsis
adapters
http
Package httpcorrelation is the target-oriented path for HTTP correlation.
Package httpcorrelation is the target-oriented path for HTTP correlation.
jsonrpc
Package correlationjsonrpc is the target-oriented path for JSON-RPC correlation.
Package correlationjsonrpc is the target-oriented path for JSON-RPC correlation.
otel
Package correlationotel projects correlation metadata into OpenTelemetry attributes and links without treating correlation IDs as trace or span IDs.
Package correlationotel projects correlation metadata into OpenTelemetry attributes and links without treating correlation IDs as trace or span IDs.
queue
Package correlationqueue is the target-oriented path for queue correlation propagation.
Package correlationqueue is the target-oriented path for queue correlation propagation.
schedule
Package correlationschedule is the target-oriented path for scheduled-work correlation.
Package correlationschedule is the target-oriented path for scheduled-work correlation.
slog
Package correlationslog provides at most three diagnostic slog attributes through Attrs, without installing a logger or handler.
Package correlationslog provides at most three diagnostic slog attributes through Attrs, without installing a logger or handler.
Package httpcorrelation explicitly propagates correlation metadata over HTTP.
Package httpcorrelation explicitly propagates correlation metadata over HTTP.
requestidbridge
Package requestidbridge integrates explicitly with request ID middleware such as http-middleware/requestid without importing hidden context keys.
Package requestidbridge integrates explicitly with request ID middleware such as http-middleware/requestid without importing hidden context keys.
Package jsonrpc propagates correlation through an explicit JSON-RPC metadata object.
Package jsonrpc propagates correlation through an explicit JSON-RPC metadata object.
Package log provides bounded slog attributes compatible with log's standard log/slog composition API.
Package log provides bounded slog attributes compatible with log's standard log/slog composition API.
Package queue propagates correlation metadata through backend-neutral queue metadata maps.
Package queue propagates correlation metadata through backend-neutral queue metadata maps.
Package schedule provides explicit correlation lifecycle helpers for scheduled work.
Package schedule provides explicit correlation lifecycle helpers for scheduled work.
Package telemetry links correlation metadata to OpenTelemetry without treating correlation IDs as trace or span IDs.
Package telemetry links correlation metadata to OpenTelemetry without treating correlation IDs as trace or span IDs.
Package webhook provides an explicit webhook-named HTTP correlation adapter.
Package webhook provides an explicit webhook-named HTTP correlation adapter.

Jump to

Keyboard shortcuts

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