xctx

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2026 License: Apache-2.0 Imports: 5 Imported by: 0

Documentation

Overview

Package xctx provides typed context helpers for request-scoped execution metadata. Context values are for cancellation, deadlines, and request metadata; application state should remain in explicit action parameters.

Index

Constants

View Source
const MaxTraceEvents = 128

MaxTraceEvents bounds the per-request trace ring. Once full, the oldest event is dropped to make room. Exported so callers can size assertions and load tests without a magic literal.

Variables

View Source
var ApprovalTokenKey = NewKey[string]("nexss.approval.token")

ApprovalTokenKey is the single, framework-wide context key for the approval token. Every consumer — flow, agent/permission, agent/policy reads and writes through this one key so a token minted by one package is visible to all others.

View Source
var EventPublisherKey = NewKey[EventPublisher]("nexss.event.publisher")
View Source
var TenantDB = NewKey[any]("tenant_db")

TenantDB is the context key for the active tenant's DB connection or transaction handle.

Functions

func AddTrace

func AddTrace(ctx context.Context, event string)

AddTrace appends a diagnostic event to the request's trace ring.

Safe for concurrent use: it is the only method that mutates TraceEvents while the request is in flight. Contention is limited to concurrent PublishEvent failures on the same request — an error path, not a hot path — so a plain mutex is the correct tool. A lock-free ring would require either a 128-bit atomic (no stdlib support) or per-slot allocations, both of which lose on the actual workload.

func ApprovalTokenFrom added in v0.8.0

func ApprovalTokenFrom(ctx context.Context) string

ApprovalTokenFrom extracts the approval token, or "".

func ClientIPFrom

func ClientIPFrom(ctx context.Context) string

func CloneForAsync

func CloneForAsync(ctx context.Context) context.Context

CloneForAsync returns a context whose scope is a deep copy of ctx's, detached from ctx's cancellation. Use before handing ctx to a goroutine that outlives the request (background publish, batch flush, best-effort audit) so that canceling the parent does not abort the detached work and the detached work does not race the parent's pooled scope.

func EndpointFrom

func EndpointFrom(ctx context.Context) string

func ExecutionIDFrom added in v0.9.3

func ExecutionIDFrom(ctx context.Context) string

func FeaturesFrom

func FeaturesFrom(ctx context.Context) []string

func FromClaims

func FromClaims(scope *RequestScope, claims map[string]any)

FromClaims populates a scope from a decoded JWT claim map. Recognized keys: sub, ten, jti, roles, features, perms. Unknown keys are ignored.

func HasAnyRole

func HasAnyRole(ctx context.Context, allowed ...string) bool

HasAnyRole reports whether the scope has any of the listed roles. Passing zero roles returns false.

func HasFeature

func HasFeature(ctx context.Context, feature string) bool

HasFeature reports whether the scope has the given feature flag enabled. system_admin always passes; "all" and "*" are treated as wildcards.

func HasPermission

func HasPermission(ctx context.Context, perm string) bool

HasPermission reports whether the scope grants perm or the wildcard "*".

func HasRole

func HasRole(ctx context.Context, required string) bool

HasRole reports whether the scope has the given role, either as its primary Role or anywhere in the Roles slice.

func PermissionsFrom

func PermissionsFrom(ctx context.Context) []string

func RequestIDFrom

func RequestIDFrom(ctx context.Context) string

func RootExecutionIDFrom added in v0.11.0

func RootExecutionIDFrom(ctx context.Context) string

RootExecutionIDFrom returns the top-level execution ID recorded by WithRootExecutionID, or "" when none was set.

func SpanIDFrom added in v0.9.3

func SpanIDFrom(ctx context.Context) string

func TenantIDFrom

func TenantIDFrom(ctx context.Context) string

func TraceIDFrom

func TraceIDFrom(ctx context.Context) string

func UserIDFrom

func UserIDFrom(ctx context.Context) string

func WithApprovalToken added in v0.8.0

func WithApprovalToken(ctx context.Context, token string) context.Context

WithApprovalToken binds an approval token to ctx.

func WithClientIP

func WithClientIP(ctx context.Context, ip string) context.Context

func WithEndpoint

func WithEndpoint(ctx context.Context, endpoint string) context.Context

func WithEventPublisher

func WithEventPublisher(ctx context.Context, pub EventPublisher) context.Context

func WithExecutionID added in v0.9.3

func WithExecutionID(ctx context.Context, id string) context.Context

func WithFeatures

func WithFeatures(ctx context.Context, features []string) context.Context

func WithPermissions

func WithPermissions(ctx context.Context, perms []string) context.Context

func WithRequestID

func WithRequestID(ctx context.Context, id string) context.Context

func WithRoles

func WithRoles(ctx context.Context, roles []string) context.Context

WithRoles replaces the roles slice and sets Role to the first element. Passing nil clears both.

func WithRootExecutionID added in v0.11.0

func WithRootExecutionID(ctx context.Context, id string) context.Context

func WithScope

func WithScope(ctx context.Context, s *RequestScope) context.Context

WithScope binds s to ctx directly. Prefer NewScope for pooled scopes.

func WithSpanID added in v0.9.3

func WithSpanID(ctx context.Context, id string) context.Context

func WithTenantID

func WithTenantID(ctx context.Context, id string) context.Context

func WithTraceContext added in v0.10.1

func WithTraceContext(ctx context.Context, traceID, spanID string) context.Context

WithTraceContext sets TraceID and/or SpanID in one call. Empty strings are ignored, so passing ("trace", "") sets only the trace ID.

func WithTraceID

func WithTraceID(ctx context.Context, id string) context.Context

func WithUserID

func WithUserID(ctx context.Context, id string) context.Context

Types

type EventPublisher

type EventPublisher interface {
	PublishEvent(ctx context.Context, subject string, payload any) error
}

func EventPublisherFrom

func EventPublisherFrom(ctx context.Context) (EventPublisher, bool)

type Key

type Key[T any] struct {
	// contains filtered or unexported fields
}

Key is a typed context key. Unlike a bare string, two Key values of different types never collide, and From returns a typed value without a runtime assertion at the callsite.

func NewKey

func NewKey[T any](name string) Key[T]

NewKey creates a typed context key. name is used only in error messages.

func (Key[T]) From

func (k Key[T]) From(ctx context.Context) (T, bool)

From returns the bound value and true, or the zero value and false. Safe on a nil context.

func (Key[T]) MustFrom

func (k Key[T]) MustFrom(ctx context.Context) T

MustFrom returns the bound value or panics. Use only at boot / startup where a missing value is a programmer error, never on a request path.

func (Key[T]) With

func (k Key[T]) With(ctx context.Context, val T) context.Context

With returns ctx with the value bound to this key.

type RequestScope

type RequestScope struct {
	RequestID       string
	ExecutionID     string
	RootExecutionID string
	TraceID         string
	SpanID          string
	Endpoint        string
	UserID          string
	TenantID        string
	Role            string
	ClientIP        string
	Roles           []string
	Permissions     []string
	Features        []string
	TraceEvents     []string
	// contains filtered or unexported fields
}

RequestScope carries per-request metadata. Mutators run on the request's owning goroutine; AddTrace is the sole exception and is guarded by traceMu. See scope_trace.go.

func NewScope

func NewScope(parent context.Context) (context.Context, *RequestScope, func())

NewScope returns a pooled RequestScope bound to parent, plus a cleanup function that returns the scope to the pool. cleanup is idempotent.

func ScopeFrom

func ScopeFrom(ctx context.Context) *RequestScope

ScopeFrom returns the RequestScope bound to ctx, or nil.

func (*RequestScope) Reset

func (s *RequestScope) Reset()

Reset clears every field, retaining slice capacity up to the trace ring size. Called by the pool before returning a scope for reuse.

Jump to

Keyboard shortcuts

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