Help us shape the future of Go! Take the 2026 Go Developer Survey

management

package
v1.1.5 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: 8

Documentation

Overview

Package management defines stable worker/control-plane contracts without implementing queue delivery or backend operations. DTO validation checks shape/bounds, not authentication, privacy or durability. Mutable slices/maps and optional pointers remain caller/provider-owned unless a constructor explicitly copies them. Capability claims are not authorization grants.

Index

Examples

Constants

View Source
const (
	// FailureCodeUnsupportedPayloadVersion identifies a syntactically valid
	// payload whose declared schema version cannot be processed.
	FailureCodeUnsupportedPayloadVersion = "unsupported_payload_version"
	// FailureCodeLeaseLost identifies a delivery that can no longer be settled
	// by the current owner.
	FailureCodeLeaseLost = "lease_lost"
	// FailureCodeDeadLetterDestinationUnavailable identifies a failed durable
	// append to the configured terminal destination.
	FailureCodeDeadLetterDestinationUnavailable = "dead_letter_destination_unavailable"
	// FailureCodeAdministrativeQuarantine identifies an explicit operator
	// decision to prevent normal redelivery.
	FailureCodeAdministrativeQuarantine = "administrative_quarantine"
)
View Source
const (
	// MaxReasonBytes bounds actor-supplied administrative reasons.
	MaxReasonBytes = 1_024
	// MaxBulkSelection bounds one destructive bulk-retry command.
	MaxBulkSelection uint32 = 1_000
)
View Source
const (
	// CurrentEnvelopeVersion is the first complete dead-letter record contract.
	CurrentEnvelopeVersion uint16 = 1
	// MaxAdministrativePayloadBytes bounds privileged payload inspection.
	MaxAdministrativePayloadBytes = 1 << 20
	// MaxFailureSummaryBytes bounds deliberately redacted operator diagnostics.
	MaxFailureSummaryBytes = 1_024
	// MaxRecordTags bounds user-supplied dead-letter record dimensions.
	MaxRecordTags = 32
	// MaxPageSize bounds one failure or dead-letter listing response.
	MaxPageSize uint32 = 200
	// MaxCursorBytes bounds opaque pagination state accepted from a client.
	MaxCursorBytes = 1_024
	// MaxSearchBytes bounds backend-neutral administrative search input.
	MaxSearchBytes = 256
)
View Source
const (
	// MaxIdentityBytes bounds worker, backend, queue, and capability labels.
	MaxIdentityBytes = 256
	// MaxQueuesPerWorker bounds one heartbeat's queue cardinality.
	MaxQueuesPerWorker = 256
	// MaxCapabilitiesPerWorker bounds one heartbeat's capability cardinality.
	MaxCapabilitiesPerWorker = 64
	// MaxWorkerConcurrency bounds reported goroutine concurrency.
	MaxWorkerConcurrency = 1_000_000
	// MaxStatusPageSize bounds one worker or queue status response.
	MaxStatusPageSize = 200
)
View Source
const MaxDesiredStateTargets = 256

MaxDesiredStateTargets bounds one reconciler's copied target set.

View Source
const MaxLifecycleCommandResults = 10_000

MaxLifecycleCommandResults bounds process-local retained command entries without eviction.

View Source
const MaxStatusProviders = 1_000

MaxStatusProviders bounds each configured provider set, not pagination fetch cost.

Variables

View Source
var (
	// ErrDesiredStateNotFound reports a target without an authored state. A
	// worker keeps its current local state and does not infer an active state.
	ErrDesiredStateNotFound = errors.New("management: desired state not found")
	// ErrInvalidDesiredStateConfiguration reports an unsafe reconciler graph.
	ErrInvalidDesiredStateConfiguration = errors.New("management: invalid desired state configuration")
	// ErrInvalidDesiredStateContext reports a nil reconciliation context.
	ErrInvalidDesiredStateContext = errors.New("management: invalid desired state context")
	// ErrInvalidDesiredStateOutput reports malformed or mismatched source data.
	ErrInvalidDesiredStateOutput = errors.New("management: invalid desired state output")
	// ErrDesiredStateRegression prevents an older revision from replacing state.
	ErrDesiredStateRegression = errors.New("management: desired state revision regression")
	// ErrDesiredStateConflict prevents one revision from describing two states.
	ErrDesiredStateConflict = errors.New("management: desired state revision conflict")
)
View Source
var (
	// ErrRecordNotFound reports that the selected management record is absent.
	ErrRecordNotFound = errors.New("management: record not found")
	// ErrUnsupportedCapability reports an operation the backend did not advertise.
	ErrUnsupportedCapability = errors.New("management: unsupported capability")
	// ErrManagementUnavailable reports a temporarily unreachable data plane.
	ErrManagementUnavailable = errors.New("management: unavailable")
	// ErrMalformedCursor reports opaque pagination state that cannot be decoded.
	ErrMalformedCursor = errors.New("management: malformed cursor")
	// ErrInvalidFilter reports filtering the backend cannot safely honor.
	ErrInvalidFilter = errors.New("management: invalid filter")
	// ErrStaleRecord reports a record changed after it was selected or inspected.
	ErrStaleRecord = errors.New("management: stale record")
	// ErrMutationConflict reports an incompatible concurrent or duplicate mutation.
	ErrMutationConflict = errors.New("management: mutation conflict")
	// ErrPartialMutation reports a mutation with both confirmed and failed effects.
	ErrPartialMutation = errors.New("management: partial mutation")
	// ErrUnknownMutation reports a mutation whose durable outcome is ambiguous.
	ErrUnknownMutation = errors.New("management: unknown mutation outcome")
)
View Source
var (
	// ErrInvalidWorkerLifecycleConfiguration reports incomplete target identity.
	ErrInvalidWorkerLifecycleConfiguration = errors.New("management: invalid worker lifecycle configuration")
	// ErrInvalidLifecycleCounter reports unbalanced admission or job accounting.
	ErrInvalidLifecycleCounter = errors.New("management: invalid lifecycle counter")
	// ErrDesiredStateTargetMismatch prevents state from crossing worker scopes.
	ErrDesiredStateTargetMismatch = errors.New("management: desired state target mismatch")
	// ErrInvalidDesiredStateTransition prevents unsupported target lifecycle state.
	ErrInvalidDesiredStateTransition = errors.New("management: invalid desired state transition")
	// ErrInvalidWorkerLifecycleContext reports a nil command context.
	ErrInvalidWorkerLifecycleContext = errors.New("management: invalid worker lifecycle context")
)
View Source
var (
	// ErrInvalidStatusProviders reports an empty, nil, or oversized source set.
	ErrInvalidStatusProviders = errors.New("management: invalid status providers")
	// ErrInvalidStatusCursor reports pagination state outside the source set.
	ErrInvalidStatusCursor = errors.New("management: invalid status cursor")
	// ErrInvalidStatusProviderOutput reports malformed or duplicate observations.
	ErrInvalidStatusProviderOutput = errors.New("management: invalid status provider output")
)

Functions

This section is empty.

Types

type Capability

type Capability string

Capability identifies an optional management or visibility operation. Capability claims are not authorization grants.

const (
	// CapabilityWorkerStatus advertises optional worker observations.
	CapabilityWorkerStatus Capability = "worker_status"
	// CapabilityQueueStatus advertises optional queue observations.
	CapabilityQueueStatus Capability = "queue_status"
	// CapabilityPause advertises optional intake suspension.
	CapabilityPause Capability = "pause"
	// CapabilityResume advertises optional intake resumption.
	CapabilityResume Capability = "resume"
	// CapabilityDrain advertises optional graceful drain.
	CapabilityDrain Capability = "drain"
	// CapabilityTerminate advertises optional termination.
	CapabilityTerminate Capability = "terminate"
	// CapabilityFailures advertises optional failure listing/inspection.
	CapabilityFailures Capability = "failures"
	// CapabilityDeadLetters advertises optional terminal listing/inspection.
	CapabilityDeadLetters Capability = "dead_letters"
	// CapabilityRetry advertises optional single-record retry.
	CapabilityRetry Capability = "retry"
	// CapabilityBulkRetry advertises optional bounded selected retry.
	CapabilityBulkRetry Capability = "bulk_retry"
	// CapabilityDelete advertises optional record deletion.
	CapabilityDelete Capability = "delete"
	// CapabilityPurge advertises optional target purge.
	CapabilityPurge Capability = "purge"
	// CapabilityReplay advertises optional explicit administrative replay.
	CapabilityReplay Capability = "replay"
	// CapabilityRetentionCount advertises optional maximum-count retention.
	CapabilityRetentionCount Capability = "retention_count"
	// CapabilityRetentionTime advertises optional time retention.
	CapabilityRetentionTime Capability = "retention_time"
	// CapabilityRetentionBytes advertises optional byte retention.
	CapabilityRetentionBytes Capability = "retention_bytes"
)

type Classification

type Classification string

Classification is the stable backend-neutral failure disposition used by workers, dead-letter records, and management clients.

const (
	// ClassificationRetryable permits another delivery attempt.
	ClassificationRetryable Classification = "retryable"
	// ClassificationPermanent prevents policy-driven handler retries.
	ClassificationPermanent Classification = "permanent"
	// ClassificationMalformed identifies an undecodable or unsupported input.
	ClassificationMalformed Classification = "malformed"
	// ClassificationCanceled identifies interrupted work that is not terminal
	// unless an explicit backend policy says otherwise.
	ClassificationCanceled Classification = "canceled"
	// ClassificationInfrastructure identifies broker or settlement uncertainty.
	ClassificationInfrastructure Classification = "infrastructure"
)

func ClassifyFailure

func ClassifyFailure(err error) Classification

ClassifyFailure returns the classification selected by ResolveFailure.

type Command

type Command struct {
	// ID correlates one command and its returned result.
	ID string
	// IdempotencyKey selects provider-owned duplicate handling; shape validation supplies no durable deduplication.
	IdempotencyKey string
	// Actor is a caller assertion; authenticate it outside this envelope.
	Actor string
	// Reason is required bounded operator text, not automatically redacted.
	Reason string
	// Protocol is the management protocol version; zero is unknown or invalid.
	Protocol ProtocolVersion
	// Action selects the requested management operation.
	Action CommandAction
	// Target scopes the operation to one logical resource.
	Target Target
	// RequestedAt is the nonzero caller request time.
	RequestedAt time.Time
	// Deadline must follow RequestedAt; Validate does not compare it with the current clock.
	Deadline time.Time
	// Confirmed is required for purge, bulk retry and replay; it is not an access credential.
	Confirmed bool
	// Selection is retained mutable bulk selection; do not change it while a command is in use.
	Selection *Selection
	// Replay is retained mutable replay configuration; providers may retain it for deduplication.
	Replay *ReplayOptions
}

Command is the stable envelope enforced by a queue management adapter.

func (Command) Validate

func (c Command) Validate() error

Validate rejects malformed, unsupported, or unsafe control commands.

type CommandAction

type CommandAction string

CommandAction identifies a data-plane management operation.

const (
	// CommandPause requests intake suspension without ending already running work.
	CommandPause CommandAction = "pause"
	// CommandResume requests active intake after a supported paused/draining state.
	CommandResume CommandAction = "resume"
	// CommandDrain requests intake closure and in-flight completion.
	CommandDrain CommandAction = "drain"
	// CommandTerminate requests irreversible terminating state and drain.
	CommandTerminate CommandAction = "terminate"
	// CommandRetry requests one failure/dead-letter retry under backend policy.
	CommandRetry CommandAction = "retry"
	// CommandBulkRetry requests a confirmed bounded backend-owned selection.
	CommandBulkRetry CommandAction = "bulk_retry"
	// CommandDelete requests removal of one administrative record.
	CommandDelete CommandAction = "delete"
	// CommandPurge requests confirmed removal of a supported target; queue support is provider-specific.
	CommandPurge CommandAction = "purge"
	// CommandReplay requests confirmed allowlisted replay with explicit duplicate policy.
	CommandReplay CommandAction = "replay"
)

type CommandResult

type CommandResult struct {
	// CommandID echoes the command identity.
	CommandID string
	// IdempotencyKey echoes the duplicate-operation key.
	IdempotencyKey string
	// WorkerID identifies the reporting worker or aggregate.
	WorkerID string
	// Protocol is the management protocol version; zero is unknown or invalid.
	Protocol ProtocolVersion
	// Status distinguishes acknowledged, rejected, partial and unknown outcomes.
	Status CommandResultStatus
	// FailureCode is an operational failure label, not arbitrary error text.
	FailureCode string
	// CompletedAt is the nonzero reporting time, not proof of durable handler completion.
	CompletedAt time.Time
}

CommandResult is the redacted data-plane acknowledgement for one command. FailureCode must be a stable code and must never contain payloads, credentials, tokens, or backend endpoints.

func (CommandResult) Validate

func (r CommandResult) Validate() error

Validate checks result identity, protocol, status and nonzero completion time. FailureCode is shape-checked only for statuses requiring it; no content redaction or durable effect reconciliation is performed.

type CommandResultStatus

type CommandResultStatus string

CommandResultStatus describes an acknowledged or safely unknown outcome.

const (
	// CommandAcknowledged reports provider-confirmed command completion, not handler execution.
	CommandAcknowledged CommandResultStatus = "acknowledged"
	// CommandRejected reports a policy or input refusal.
	CommandRejected CommandResultStatus = "rejected"
	// CommandFailed reports a known operation failure.
	CommandFailed CommandResultStatus = "failed"
	// CommandUnsupported reports absent protocol/action capability.
	CommandUnsupported CommandResultStatus = "unsupported"
	// CommandTimedOut reports an expired operation budget; applied effects may remain.
	CommandTimedOut CommandResultStatus = "timed_out"
	// CommandPartial reports mixed or incompletely reconciled effects.
	CommandPartial CommandResultStatus = "partial"
	// CommandUnknown reports an outcome the provider cannot determine.
	CommandUnknown CommandResultStatus = "unknown"
)

type Compatibility

type Compatibility struct {
	// State classifies version compatibility, independently of authentication.
	State CompatibilityState
	// Enabled is a sorted, deduplicated intersection only for compatible peers.
	Enabled []Capability
	// WorkerOnly contains sorted worker-only capability claims.
	WorkerOnly []Capability
	// ControlPlaneOnly contains sorted control-plane-only capability claims.
	ControlPlaneOnly []Capability
}

Compatibility is the deterministic result of version and capability negotiation.

func Negotiate

func Negotiate(
	supported ProtocolRange,
	worker ProtocolVersion,
	workerCapabilities []Capability,
	controlPlaneCapabilities []Capability,
) Compatibility

Negotiate enables only capabilities both peers report at a compatible protocol version. Unknown and incompatible peers remain visible but are not controllable.

type CompatibilityState

type CompatibilityState string

CompatibilityState describes a worker relative to a supported protocol range.

const (
	// CompatibilityCompatible means the version falls within the inclusive range.
	CompatibilityCompatible CompatibilityState = "compatible"
	// CompatibilityWorkerOlder means the worker version is below the supported minimum.
	CompatibilityWorkerOlder CompatibilityState = "worker_older"
	// CompatibilityWorkerNewer means the worker version is above the supported maximum.
	CompatibilityWorkerNewer CompatibilityState = "worker_newer"
	// CompatibilityUnknown means a reversed range or zero worker version prevents negotiation.
	CompatibilityUnknown CompatibilityState = "unknown"
)

type Controller

type Controller interface {
	// Execute applies a command under provider-owned deduplication/outcome rules.
	// Authorization remains caller-owned.
	Execute(context.Context, Command) (CommandResult, error)
}

Controller is implemented by queue adapters that can safely enforce management commands. A control plane depends on this interface rather than issuing backend commands directly.

type DesiredRecord

type DesiredRecord struct {
	// Target scopes the operation to one logical resource.
	Target Target
	// State is the reported or requested lifecycle state, not transport connectivity proof.
	State DesiredState
	// Revision is a positive target-local revision; regressions are rejected by the reconciler.
	Revision uint64
	// ChangedAt is the nonzero authored time, not an ordering substitute for Revision.
	ChangedAt time.Time
	// CommandID attributes the desired revision to a bounded command identity.
	CommandID string
}

DesiredRecord is one attributed, monotonic target-state revision.

func (DesiredRecord) Validate

func (r DesiredRecord) Validate() error

Validate checks revision, target, state, command identity and time shape. It does not authenticate authorship or establish durability.

type DesiredState

type DesiredState string

DesiredState is the durable lifecycle state authored by a control plane.

const (
	// DesiredActive permits local intake.
	DesiredActive DesiredState = "active"
	// DesiredPaused stops new admissions and waits for admission reservations, not active jobs.
	DesiredPaused DesiredState = "paused"
	// DesiredDraining stops intake and waits for admissions and jobs.
	DesiredDraining DesiredState = "draining"
	// DesiredTerminating irreversibly stops intake and waits for drain.
	DesiredTerminating DesiredState = "terminating"
)

type DesiredStateApplier

type DesiredStateApplier interface {
	// ApplyDesiredState applies a revision; a returned error need not undo effects already applied.
	ApplyDesiredState(context.Context, DesiredRecord) error
}

DesiredStateApplier changes local queue admission or lifecycle state.

type DesiredStateReader

type DesiredStateReader interface {
	// GetDesiredState returns target-scoped authoritative state or ErrDesiredStateNotFound.
	GetDesiredState(context.Context, Target) (DesiredRecord, error)
}

DesiredStateReader reads authoritative tenant-scoped desired state.

type DesiredStateReconciler

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

DesiredStateReconciler remembers successfully applied revisions per target in this process only. An Applier that fails after a side effect can be called again; this is not durable exactly-once application. Scheduling/retry remain caller-owned. The mutex serializes complete reconciliation, including Reader and Applier calls. Those callbacks must not reenter Reconcile, and must honor their contexts.

func NewDesiredStateReconciler

func NewDesiredStateReconciler(
	config DesiredStateReconcilerConfig,
) (*DesiredStateReconciler, error)

NewDesiredStateReconciler creates a bounded revision-aware reconciler.

func (*DesiredStateReconciler) Reconcile

func (r *DesiredStateReconciler) Reconcile(ctx context.Context) error

Reconcile reads and applies targets in configured order, holding its mutex through all provider calls. Waiting for the mutex is not context-aware. Successfully applied revisions remain committed when a later target fails.

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/faustbrian/go-queue/management"
)

func main() {
	target := management.Target{Kind: management.TargetQueue, Name: "critical"}
	reconciler, err := management.NewDesiredStateReconciler(
		management.DesiredStateReconcilerConfig{
			Reader: desiredExampleReader{record: management.DesiredRecord{
				Target: target, State: management.DesiredPaused, Revision: 3,
				ChangedAt: time.Date(2026, 7, 16, 10, 0, 0, 0, time.UTC),
				CommandID: "pause-critical-3",
			}},
			Applier: desiredExampleApplier{},
			Targets: []management.Target{target},
		},
	)
	if err != nil {
		panic(err)
	}
	if err := reconciler.Reconcile(context.Background()); err != nil {
		panic(err)
	}
}

type desiredExampleReader struct {
	record management.DesiredRecord
}

func (r desiredExampleReader) GetDesiredState(
	context.Context,
	management.Target,
) (management.DesiredRecord, error) {
	return r.record, nil
}

type desiredExampleApplier struct{}

func (desiredExampleApplier) ApplyDesiredState(
	_ context.Context,
	record management.DesiredRecord,
) error {
	fmt.Printf(
		"apply %s to %s %s at revision %d\n",
		record.State,
		record.Target.Kind,
		record.Target.Name,
		record.Revision,
	)
	return nil
}
Output:
apply paused to queue critical at revision 3

type DesiredStateReconcilerConfig

type DesiredStateReconcilerConfig struct {
	// Reader is a borrowed authoritative provider called under the reconciler mutex.
	Reader DesiredStateReader
	// Applier is a borrowed synchronous callback called under the reconciler mutex.
	Applier DesiredStateApplier
	// Targets is copied at construction and applied in configured order; duplicates are rejected.
	Targets []Target
}

DesiredStateReconcilerConfig defines one bounded pull reconciliation set.

type DrainState

type DrainState string

DrainState describes progress of a graceful drain request.

const (
	// DrainNotRequested means no drain is reported.
	DrainNotRequested DrainState = "not_requested"
	// DrainRequested means drain was requested but progress is not yet reported.
	DrainRequested DrainState = "requested"
	// DrainInProgress means admissions or jobs are still owned.
	DrainInProgress DrainState = "in_progress"
	// DrainCompleted means the provider reports its drain boundary completed.
	DrainCompleted DrainState = "completed"
	// DrainTimedOut means the drain budget expired, not that the requested state was rolled back.
	DrainTimedOut DrainState = "timed_out"
)

type Failure

type Failure struct {
	// Classification selects backend failure disposition; it does not redact the cause.
	Classification Classification
	// Code is caller-supplied failure text; keep it stable and non-sensitive.
	Code string
	// contains filtered or unexported fields
}

Failure attaches a stable classification and safe code while preserving the original cause for errors.Is and errors.As.

func NewFailure

func NewFailure(classification Classification, code string, cause error) *Failure

NewFailure retains cause and caller-supplied classification/code without validation. The caller must provide non-sensitive code text; Error prints it.

func (*Failure) Error

func (e *Failure) Error() string

Error implements error.

func (*Failure) Unwrap

func (e *Failure) Unwrap() error

Unwrap preserves the classified cause for errors.Is and errors.As.

func (*Failure) Validate

func (e *Failure) Validate() error

Validate rejects unknown dispositions and blank or oversized codes. It does not redact content or establish that caller-supplied text is safe to disclose.

type FailureResolution

type FailureResolution struct {
	// Classification selects backend failure disposition; it does not redact the cause.
	Classification Classification
	// Code is the selected winning-classification code, or empty when absent.
	Code string
}

FailureResolution is the stable classification and safe code selected from a wrapped or joined failure graph. Code is empty when no classified failure supplied one.

func ResolveFailure

func ResolveFailure(err error) FailureResolution

ResolveFailure resolves wrapped and joined failures with deterministic safety precedence: infrastructure, canceled, malformed, permanent, then retryable. Codes come only from the winning classification; equal-rank codes use lexical order among visited nodes. The walk visits at most 64 nodes, so larger graphs can depend on traversal order. Custom Unwrap/Is methods remain caller code; their termination and panic behavior are not controlled here.

type InspectRequest

type InspectRequest struct {
	// Kind selects the supported resource or record category.
	Kind RecordKind
	// ID is the provider-owned identity, not an authenticated credential.
	ID string
	// Visibility selects disclosure; hidden is the zero value, not an authorization check.
	Visibility PayloadVisibility
}

InspectRequest asks for one record at an explicit payload visibility.

func (InspectRequest) Validate

func (r InspectRequest) Validate() error

Validate rejects ambiguous or unbounded inspection requests.

type JobRecord

type JobRecord struct {
	// Kind selects the supported resource or record category.
	Kind RecordKind
	// ID identifies this backend failure/dead-letter record, separately from OriginalID.
	ID string
	// Backend identifies the reporting transport, not its address or credentials.
	Backend string
	// Queue identifies the logical queue, not a connection URI.
	Queue string
	// OccurredAt is the backend/event time of this observation, not a universal ordering clock.
	OccurredAt time.Time
	// Attempts counts backend delivery attempts, independently of local handler retries.
	Attempts uint32
	// FailureCode is an operational failure label, not arbitrary error text.
	FailureCode string
	// Payload holds disclosure-controlled mutable application bytes.
	Payload Payload

	// EnvelopeVersion is zero for basic legacy records or CurrentEnvelopeVersion for extended metadata.
	EnvelopeVersion uint16
	// PayloadSchemaVersion is optional application schema identity; this package does not validate that schema.
	PayloadSchemaVersion string
	// OriginalID is optional application identity, distinct from backend source identity.
	OriginalID string
	// Topic is optional source topic identity.
	Topic string
	// Stream is the logical stream key, not a transport endpoint.
	Stream string
	// RoutingKey is optional source routing identity.
	RoutingKey string
	// ConsumerGroup is optional source consumer-group identity.
	ConsumerGroup string
	// SourceRecordID identifies the original backend source entry when known.
	SourceRecordID string
	// EnqueuedAt is an optional nonzero enqueue time; nil means unknown.
	EnqueuedAt *time.Time
	// FirstDeliveryAt is optional first-delivery time; nil means unknown.
	FirstDeliveryAt *time.Time
	// LastDeliveryAt is optional last-delivery time, ordered after FirstDeliveryAt when both known.
	LastDeliveryAt *time.Time
	// DeadLetteredAt is required for a versioned terminal record.
	DeadLetteredAt *time.Time
	// RetryPolicy is optional application policy identity, not executable retry configuration.
	RetryPolicy string
	// Classification selects the recorded backend-neutral failure disposition.
	Classification Classification
	// FailureSummary is deliberately safe operator text; Validate bounds but does not redact it.
	FailureSummary string
	// Diagnostics uses independent disclosure bounds; it must not expose bytes implicitly.
	Diagnostics Payload
	// HandlerType is an optional handler label, not serialized code.
	HandlerType string
	// JobType is optional application job identity.
	JobType string
	// Tags contains mutable application dimensions with bounded keys, values and count.
	Tags map[string]string
	// TraceID is optional caller-supplied trace identity, not authenticated evidence.
	TraceID string
	// TenantID is optional caller-supplied tenancy metadata, not access enforcement.
	TenantID string
	// ProducerVersion identifies the producer application when known.
	ProducerVersion string
	// WorkerVersion identifies the handling application when known.
	WorkerVersion string
	// OriginalDeadLetterID identifies the first terminal record in replay lineage.
	OriginalDeadLetterID string
	// PriorDeadLetterID identifies the terminal record immediately preceding this replay.
	PriorDeadLetterID string
	// ReplayGeneration is positive only with complete original/prior lineage; zero means no replay metadata.
	ReplayGeneration uint32
	// RetentionDeadline is optional nonzero expiry, later than DeadLetteredAt when both known.
	RetentionDeadline *time.Time
}

JobRecord is the backend-neutral failure or dead-letter representation.

func (JobRecord) Validate

func (r JobRecord) Validate() error

Validate checks record shape, chronology and disclosure byte bounds. It neither authenticates metadata nor redacts FailureSummary, tags or identity content, and it does not copy mutable data. Reveal authorization is external.

type Measurement

type Measurement[T any] struct {
	// Value is meaningful only when Supported is true.
	Value T
	// Supported distinguishes an actual measured zero from an unavailable value.
	Supported bool
}

Measurement distinguishes an honestly measured zero from an unsupported backend metric.

type PageRequest

type PageRequest struct {
	// Cursor is provider-specific pagination state; empty begins traversal.
	Cursor string
	// Limit is the positive requested item ceiling, checked against the applicable limit.
	Limit uint32
	// Search is bounded provider-defined metadata search, not payload search.
	Search string
	// Sort selects requested ordering; a provider may reject unsupported fields.
	Sort SortField
	// Direction selects ascending or descending traversal.
	Direction SortDirection
}

PageRequest defines bounded cursor pagination, sorting, and search.

func (PageRequest) Validate

func (r PageRequest) Validate() error

Validate rejects unbounded or unsupported record-list requests.

type Payload

type Payload struct {
	// Visibility selects disclosure; hidden is the zero value, not an authorization check.
	Visibility PayloadVisibility
	// ContentType is an optional application media-type label, not verified payload content.
	ContentType string
	// Size reports original byte size and may exceed revealed Data length.
	Size int64
	// Data is mutable; value copies share its backing array. Validation permits
	// bytes only when revealed.
	Data []byte
}

Payload is a bounded administrative representation. Data must remain empty unless privileged access explicitly requested revealed content.

type PayloadVisibility

type PayloadVisibility string

PayloadVisibility describes the disclosure applied by an authorized inspection. Its zero value is hidden so payloads are never exposed by default.

const (
	// PayloadHidden omits data and is the fail-closed zero visibility.
	PayloadHidden PayloadVisibility = ""
	// PayloadRedacted marks nonrevealed disclosure; Data still must be empty.
	PayloadRedacted PayloadVisibility = "redacted"
	// PayloadRevealed permits bounded Data after caller-owned authorization.
	PayloadRevealed PayloadVisibility = "revealed"
)

type ProtocolRange

type ProtocolRange struct {
	// Minimum is the inclusive lower supported version.
	Minimum ProtocolVersion
	// Maximum is the inclusive upper supported version; reversed ranges negotiate unknown.
	Maximum ProtocolVersion
}

ProtocolRange is an inclusive set of protocol versions supported during a rolling upgrade.

type ProtocolVersion

type ProtocolVersion struct {
	// Major orders versions before Minor.
	Major uint16
	// Minor orders versions within one Major.
	Minor uint16
}

ProtocolVersion identifies a worker/control-plane management protocol.

type ProviderStatusReader

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

ProviderStatusReader composes bounded native adapter observations.

func NewStatusReader

func NewStatusReader(config StatusReaderConfig) (*ProviderStatusReader, error)

NewStatusReader copies bounded provider slices (at least one nonempty), rejecting nil and typed-nil entries. Providers remain borrowed; concurrent reader use requires their own concurrency safety and context-aware return behavior.

func (*ProviderStatusReader) ListQueues

func (r *ProviderStatusReader) ListQueues(
	ctx context.Context,
	request StatusPageRequest,
) (QueueStatusPage, error)

ListQueues observes every queue provider on each request, rejects duplicate backend/queue identities and sorts before offset pagination. It does not hold a stable snapshot across requests or preempt a provider that ignores context.

func (*ProviderStatusReader) ListWorkers

func (r *ProviderStatusReader) ListWorkers(
	ctx context.Context,
	request StatusPageRequest,
) (WorkerStatusPage, error)

ListWorkers calls every worker provider sequentially on each request, validates and sorts by ID, then returns a shallow page. Nested slices retain provider aliases. Offset cursors refer to newly fetched data, not a stable snapshot; the page bound does not bound observation work. Context is passed to providers.

type QueueMetrics

type QueueMetrics struct {
	// Depth reports outstanding work under the provider's scope; stream backends
	// combine pending and known lag.
	Depth Measurement[int64]
	// Lag counts undelivered group entries when supported; unknown lag uses
	// Supported=false rather than a supported negative value.
	Lag Measurement[int64]
	// Pending counts entries delivered to the consumer group but not acknowledged.
	Pending Measurement[int64]
	// OldestAge reports age of the backend's oldest supported outstanding entry.
	OldestAge Measurement[time.Duration]
	// Throughput is a finite nonnegative backend-reported rate when supported.
	Throughput Measurement[float64]
	// Runtime reports backend-measured elapsed runtime when supported.
	Runtime Measurement[time.Duration]
	// Succeeded counts backend-observed success under that provider's scope.
	Succeeded Measurement[uint64]
	// Failed counts backend-observed failures under that provider's scope.
	Failed Measurement[uint64]
	// Retried counts backend-observed retry deliveries, not necessarily local handler attempts.
	Retried Measurement[uint64]
	// Reclaimed counts recovered pending entries under the provider's scope.
	Reclaimed Measurement[uint64]
	// DeadLettered counts terminal transfers under the provider's scope.
	DeadLettered Measurement[uint64]
	// SettlementErrors counts failed backend settlement operations under the provider's scope.
	SettlementErrors Measurement[uint64]
}

QueueMetrics reports current gauges and monotonic lifecycle counters where the backend can measure them honestly.

type QueueStatus

type QueueStatus struct {
	// Backend identifies the reporting transport, not its address or credentials.
	Backend string
	// Queue identifies the logical queue, not a connection URI.
	Queue string
	// ObservedAt is the nonzero report time.
	ObservedAt time.Time
	// Metrics retains support flags instead of inventing unsupported measurements.
	Metrics QueueMetrics
}

QueueStatus is a point-in-time backend-neutral queue observation.

func (QueueStatus) Validate

func (s QueueStatus) Validate() error

Validate rejects malformed queue observations.

type QueueStatusPage

type QueueStatusPage struct {
	// Items contains this page's records; slice storage is mutable and not copied by validation.
	Items []QueueStatus
	// NextCursor is provider-specific continuation state; empty finishes traversal.
	NextCursor string
}

QueueStatusPage is one bounded page of queue observations.

func (QueueStatusPage) Validate

func (p QueueStatusPage) Validate() error

Validate rejects malformed or oversized queue adapter output.

type QueueStatusProvider

type QueueStatusProvider interface {
	// ObserveQueue reports native queue support flags and values, not invented metrics.
	ObserveQueue(context.Context) (QueueStatus, error)
}

QueueStatusProvider emits one logical backend queue observation.

type RecordKind

type RecordKind string

RecordKind distinguishes failed jobs from terminal dead letters.

const (
	// RecordFailure identifies a failed delivery attempt, not necessarily terminal work.
	RecordFailure RecordKind = "failure"
	// RecordDeadLetter identifies a terminal delivery record.
	RecordDeadLetter RecordKind = "dead_letter"
)

type RecordPage

type RecordPage struct {
	// Items contains this page's records; slice storage is mutable and not copied by validation.
	Items []JobRecord
	// NextCursor is provider-specific continuation state; empty finishes traversal.
	NextCursor string
}

RecordPage is one bounded page of failure or dead-letter metadata.

func (RecordPage) Validate

func (p RecordPage) Validate() error

Validate rejects oversized cursors, pages, and malformed adapter records.

type RecordReader

type RecordReader interface {
	// ListFailures lists bounded metadata with payload and diagnostics hidden.
	ListFailures(context.Context, PageRequest) (RecordPage, error)
	// ListDeadLetters lists bounded terminal metadata with payload and diagnostics hidden.
	ListDeadLetters(context.Context, PageRequest) (RecordPage, error)
	// Inspect returns one record with no more disclosure than requested; authorization is caller-owned.
	Inspect(context.Context, InspectRequest) (JobRecord, error)
}

RecordReader is implemented by queue adapters that expose safe failure and dead-letter inspection without leaking native backend clients.

type ReplayOptions

type ReplayOptions struct {
	// Destination must identify an explicitly allowed logical queue/stream.
	Destination string
	// IdempotencyPolicy selects replacement or rejection within the backend's retention/window semantics.
	IdempotencyPolicy ReplayPolicy
}

ReplayOptions contains the mandatory data-plane replay safeguards.

type ReplayPolicy

type ReplayPolicy string

ReplayPolicy declares how an explicit replay destination handles duplicate job identities. It does not claim exactly-once execution.

const (
	// ReplayRejectDuplicate rejects a previously registered replay within backend retention.
	ReplayRejectDuplicate ReplayPolicy = "reject_duplicate"
	// ReplayReplaceDuplicate replaces a registered queued replay, not prior application effects.
	ReplayReplaceDuplicate ReplayPolicy = "replace_duplicate"
)

type Selection

type Selection struct {
	// Limit is the positive requested item ceiling, checked against the applicable limit.
	Limit uint32
}

Selection bounds a backend-owned bulk administrative operation. Adapters must apply their own deterministic selection semantics within this limit.

type SortDirection

type SortDirection string

SortDirection identifies ascending or descending ordering.

const (
	// SortAscending requests forward ordering.
	SortAscending SortDirection = "asc"
	// SortDescending requests reverse ordering.
	SortDescending SortDirection = "desc"
)

type SortField

type SortField string

SortField identifies bounded record-list ordering.

const (
	// SortOccurredAt requests observation-time order.
	SortOccurredAt SortField = "occurred_at"
	// SortQueue requests logical queue order where supported.
	SortQueue SortField = "queue"
	// SortAttempts requests delivery-attempt order where supported.
	SortAttempts SortField = "attempts"
)

type StatusMetadata

type StatusMetadata struct {
	// ID is the provider-owned identity, not an authenticated credential.
	ID string
	// Version is the reporter/application version label, not protocol negotiation.
	Version string
	// Concurrency is configured reporting concurrency, from one to MaxWorkerConcurrency.
	Concurrency uint32
	// Protocol is the management protocol version; zero is unknown or invalid.
	Protocol ProtocolVersion
}

StatusMetadata configures stable identity for a native worker reporter.

func (StatusMetadata) Validate

func (m StatusMetadata) Validate() error

Validate rejects incomplete or unbounded native reporter metadata.

type StatusPageRequest

type StatusPageRequest struct {
	// Cursor is provider-specific pagination state; empty begins traversal.
	Cursor string
	// Limit is the positive requested item ceiling, checked against the applicable limit.
	Limit uint32
}

StatusPageRequest defines bounded opaque-cursor status pagination.

func (StatusPageRequest) Validate

func (r StatusPageRequest) Validate() error

Validate rejects unbounded status requests.

type StatusProvider

type StatusProvider interface {
	WorkerStatusProvider
	QueueStatusProvider
}

StatusProvider emits both worker and queue observations.

type StatusReader

type StatusReader interface {
	// ListWorkers returns a bounded page under provider-owned cursor/snapshot semantics.
	ListWorkers(context.Context, StatusPageRequest) (WorkerStatusPage, error)
	// ListQueues returns a bounded page under provider-owned cursor/snapshot semantics.
	ListQueues(context.Context, StatusPageRequest) (QueueStatusPage, error)
}

StatusReader is implemented by queue adapters that expose bounded backend-neutral worker and queue observations.

type StatusReaderConfig

type StatusReaderConfig struct {
	// Workers contains borrowed providers; construction copies the slice, not providers.
	Workers []WorkerStatusProvider
	// Queues contains borrowed providers; construction copies the slice, not providers.
	Queues []QueueStatusProvider
}

StatusReaderConfig separates worker cardinality from logical queue sources.

type Target

type Target struct {
	// Kind selects the supported resource or record category.
	Kind TargetKind
	// Name is the logical target identity, bounded by MaxIdentityBytes.
	Name string
}

Target identifies a resource without exposing backend addressing.

type TargetKind

type TargetKind string

TargetKind identifies the data-plane resource affected by a command.

const (
	// TargetQueue scopes an operation to a logical queue.
	TargetQueue TargetKind = "queue"
	// TargetWorker scopes an operation to one worker identity.
	TargetWorker TargetKind = "worker"
	// TargetWorkerGroup scopes an operation to one worker group.
	TargetWorkerGroup TargetKind = "worker_group"
	// TargetFailure selects failed-attempt records.
	TargetFailure TargetKind = "failure"
	// TargetDeadLetter selects terminal records.
	TargetDeadLetter TargetKind = "dead_letter"
)

type ValidationError

type ValidationError struct {
	// Field identifies a validation field; caller construction must keep the label safe.
	Field string
	// Problem describes the rejected shape; caller construction controls its disclosure.
	Problem string
}

ValidationError identifies one invalid management-contract field.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements error.

type WorkerLifecycle

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

WorkerLifecycle owns queue admission, in-flight job accounting, desired revisions, and bounded duplicate command results. It never touches a backend.

func NewWorkerLifecycle

func NewWorkerLifecycle(config WorkerLifecycleConfig) (*WorkerLifecycle, error)

NewWorkerLifecycle creates an active queue lifecycle with bounded command history. Command history is never evicted; capacity exhaustion fails closed. Metadata is copied, Now is borrowed, and all state is process-local. Admission and job counters are uint32 with unchecked overflow; callers must balance them and keep actual concurrency within the configured operational limits.

func (*WorkerLifecycle) ApplyDesiredState

func (l *WorkerLifecycle) ApplyDesiredState(
	ctx context.Context,
	record DesiredRecord,
) error

ApplyDesiredState applies one durable revision and waits for the requested safe admission boundary. Cancellation leaves the requested state applied but does not record the revision; retry can finish the wait. applyMu serializes transitions, and waiting for that mutex itself is not context-aware.

func (*WorkerLifecycle) BeginAdmission

func (l *WorkerLifecycle) BeginAdmission() bool

BeginAdmission reserves one backend request when the lifecycle is active.

func (*WorkerLifecycle) DecorateWorkerStatus

func (l *WorkerLifecycle) DecorateWorkerStatus(
	status WorkerStatus,
) (WorkerStatus, error)

DecorateWorkerStatus overlays queue-owned admission state and capabilities on a native backend observation after verifying both describe one worker.

func (*WorkerLifecycle) EndAdmission

func (l *WorkerLifecycle) EndAdmission() error

EndAdmission releases a request that did not produce a runnable job.

func (*WorkerLifecycle) EndJob

func (l *WorkerLifecycle) EndJob() error

EndJob releases one in-flight job after handler settlement completes.

func (*WorkerLifecycle) Execute

func (l *WorkerLifecycle) Execute(
	ctx context.Context,
	command Command,
) (CommandResult, error)

Execute enforces lifecycle commands and returns a bounded correlated result. Failure/dead-letter and backend mutation actions remain unsupported. Command Selection/Replay pointers are retained for equality checks; do not mutate them after submission. Duplicate waits can report unknown on cancellation while the first caller continues. Waiting for applyMu is not context-aware.

func (*WorkerLifecycle) PromoteAdmissionToJob

func (l *WorkerLifecycle) PromoteAdmissionToJob() error

PromoteAdmissionToJob atomically converts one request into in-flight work.

func (*WorkerLifecycle) Snapshot

Snapshot returns synchronized worker lifecycle presentation state.

type WorkerLifecycleConfig

type WorkerLifecycleConfig struct {
	// Metadata identifies the worker/protocol/concurrency scope.
	Metadata StatusMetadata
	// WorkerGroup identifies the permitted group target.
	WorkerGroup string
	// Queue identifies the permitted queue target.
	Queue string
	// MaxCommandResults bounds retained command entries in [1, MaxLifecycleCommandResults]; no entries are evicted.
	MaxCommandResults int
	// Now is a required borrowed clock callback; it must return meaningful times and not reenter locked operations.
	Now func() time.Time
}

WorkerLifecycleConfig identifies the queue admission scope controlled by one Queue instance and bounds its in-memory duplicate-command protection.

type WorkerLifecycleSnapshot

type WorkerLifecycleSnapshot struct {
	// State presents the local admission state.
	State WorkerState
	// DrainStatus presents admissions/jobs completion or timeout, not backend connectivity.
	DrainStatus DrainState
	// CurrentJobs counts promoted work wrappers still awaiting EndJob.
	CurrentJobs uint32
	// Terminating marks the irreversible terminating state.
	Terminating bool
}

WorkerLifecycleSnapshot is one synchronized admission and drain view.

type WorkerState

type WorkerState string

WorkerState is the state reported by a live worker.

const (
	// WorkerRunning presents active worker intake.
	WorkerRunning WorkerState = "running"
	// WorkerPaused presents suspended intake.
	WorkerPaused WorkerState = "paused"
	// WorkerDraining presents intake withdrawal while work drains.
	WorkerDraining WorkerState = "draining"
	// WorkerStopped presents stopped worker state, not exactly-once delivery.
	WorkerStopped WorkerState = "stopped"
)

type WorkerStatus

type WorkerStatus struct {
	// ID identifies this worker report, bounded by MaxIdentityBytes.
	ID string
	// Version is the reporter/application version label, not protocol negotiation.
	Version string
	// StartedAt is the required nonzero process start time.
	StartedAt time.Time
	// HeartbeatAt is the report time and must not precede StartedAt.
	HeartbeatAt time.Time
	// Queues contains mutable logical queue labels, at most MaxQueuesPerWorker.
	Queues []string
	// Concurrency reports configured concurrency, from one to MaxWorkerConcurrency.
	Concurrency uint32
	// State is the reported or requested lifecycle state, not transport connectivity proof.
	State WorkerState
	// CurrentJobs must not exceed Concurrency in a valid report.
	CurrentJobs uint32
	// DrainStatus describes requested drain progress.
	DrainStatus DrainState
	// Backend identifies the reporting transport, not its address or credentials.
	Backend string
	// Protocol is the management protocol version; zero is unknown or invalid.
	Protocol ProtocolVersion
	// Capabilities contains mutable bounded capability claims, not authorization grants.
	Capabilities []Capability
}

WorkerStatus is the bounded status contract emitted by a worker.

func (WorkerStatus) Validate

func (s WorkerStatus) Validate() error

Validate rejects malformed or unbounded worker reports.

type WorkerStatusPage

type WorkerStatusPage struct {
	// Items contains this page's records; slice storage is mutable and not copied by validation.
	Items []WorkerStatus
	// NextCursor is provider-specific continuation state; empty finishes traversal.
	NextCursor string
}

WorkerStatusPage is one bounded page of worker observations.

func (WorkerStatusPage) Validate

func (p WorkerStatusPage) Validate() error

Validate rejects malformed or oversized worker adapter output.

type WorkerStatusProvider

type WorkerStatusProvider interface {
	// ObserveWorker reports native worker state; the provider owns context handling and concurrency.
	ObserveWorker(context.Context) (WorkerStatus, error)
}

WorkerStatusProvider emits one native worker observation.

Jump to

Keyboard shortcuts

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