contracts

package
v0.9.2 Latest Latest
Warning

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

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

Documentation

Overview

Package contracts defines the boundaries and service interfaces for the Flow Control system.

Adhering to a "Ports and Adapters" (Hexagonal) architectural style, these interfaces decouple the core `controller.FlowController` engine from its dependencies. They establish the required behaviors and system invariants that concrete implementations must uphold.

The primary contracts are:

  • `FlowRegistry`: The interface for the stateful control plane that manages the lifecycle of flows, queues, and policies.

  • `SaturationDetector`: The interface for a component that provides real-time load signals.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrFlowInstanceNotFound indicates that a requested flow instance (a `ManagedQueue`) does not exist.
	ErrFlowInstanceNotFound = errors.New("flow instance not found")

	// ErrFlowIDEmpty indicates that a flow specification was provided with an empty flow ID.
	ErrFlowIDEmpty = errors.New("flow ID cannot be empty")

	// ErrPriorityBandNotFound indicates that a requested priority band does not exist in the registry configuration.
	ErrPriorityBandNotFound = errors.New("priority band not found")

	// ErrPolicyQueueIncompatible indicates that a selected policy is not compatible with the capabilities of the queue.
	ErrPolicyQueueIncompatible = errors.New("policy is not compatible with queue capabilities")

	// ErrInvalidQueueItemHandle indicates that a QueueItemHandle provided to a SafeQueue operation (e.g.,
	// SafeQueue.Remove()) is not valid for that queue, has been invalidated, or does not correspond to an actual item in
	// the queue.
	ErrInvalidQueueItemHandle = errors.New("invalid queue item handle")

	// ErrQueueItemNotFound indicates that a SafeQueue.Remove(handle) operation did not find an item matching the
	// provided, valid QueueItemHandle. This can occur if the item was removed by a concurrent operation.
	ErrQueueItemNotFound = errors.New("queue item not found for the given handle")
)

Functions

This section is empty.

Types

type ActiveFlowConnection

type ActiveFlowConnection interface {
	// GetDataPlane returns the FlowRegistryDataPlane this connection is pinned to.
	GetDataPlane() FlowRegistryDataPlane
	// FlowKey returns the immutable identity of the flow this connection is pinned to.
	FlowKey() flowcontrol.FlowKey
}

ActiveFlowConnection represents a handle to a scoped, leased session on a flow. It provides a safe entry point to the registry's data plane.

An `ActiveFlowConnection` instance is only valid for the duration of the `WithConnection` callback from which it was received. Callers MUST NOT store a reference to this object or use it after the callback returns.

Lifecycle & Pinning: This interface represents an active "Lease" on the flow. As long as this object is valid (within the callback), the Flow Registry guarantees that the underlying Flow State is "Pinned" and protected from Garbage Collection.

type AggregateStats

type AggregateStats struct {
	// TotalCapacityBytes is the globally configured maximum total byte size limit across all priority bands.
	TotalCapacityBytes uint64
	// TotalCapacityRequests is the globally configured maximum total request count limit across all priority bands.
	TotalCapacityRequests uint64
	// TotalByteSize is the total byte size of all items currently queued across the entire system.
	TotalByteSize uint64
	// TotalLen is the total number of items currently queued across the entire system.
	TotalLen uint64
	// PerPriorityBandStats maps each configured priority level to its globally aggregated statistics.
	PerPriorityBandStats map[int]PriorityBandStats
}

AggregateStats holds globally aggregated statistics for the entire `FlowRegistry`. It is a read-only data object representing a near-consistent snapshot of the registry's state.

type EndpointCandidates

type EndpointCandidates interface {
	// Locate returns a list of endpoint candidate metrics that match the criteria defined in the request metadata.
	Locate(ctx context.Context, requestMetadata map[string]any) []fwkdl.Endpoint
}

EndpointCandidates defines the contract for a component that resolves the set of candidate endpoints for a request based on its metadata (e.g., subsetting).

This interface allows the Flow Controller to fetch a fresh list of candidates dynamically during the dispatch cycle, enabling support for "Scale-from-Zero" scenarios where endpoints may not exist when the request is first enqueued.

type FlowRegistry

FlowRegistry is the complete interface for the global flow control plane. It composes all role-based interfaces. A concrete implementation of this interface is the single source of truth for all flow control state.

Conformance: Implementations MUST be goroutine-safe.

Flow Lifecycle

A flow instance, identified by its immutable FlowKey, has a lease-based lifecycle managed by this interface. Any implementation MUST adhere to this lifecycle:

  1. Lease Acquisition: A client calls WithConnection to acquire a lease. This signals that the flow is in use and protects it from garbage collection. If the flow instance does not exist, it is created on first use. Priority bands must be provisioned by the control plane before use; they are not created on the request path.
  2. Active State: A flow is "Active" as long as its lease count is greater than zero.
  3. Lease Release: When the WithConnection callback returns, the lease is released. When the lease count drops to zero, the flow becomes "Idle".
  4. Garbage Collection: The implementation MUST automatically garbage collect a flow after it has remained continuously Idle for a configurable duration.

type FlowRegistryBackground

type FlowRegistryBackground interface {
	PriorityBandUpdateChannel() <-chan map[int]struct{}
	FlowGCTimeout() time.Duration
	ApplyDesiredPriorities(desired map[int]struct{})
	ExecuteGCCycle()
}

FlowRegistryBackground exposes hooks consumed by the Processor maintenance loop.

type FlowRegistryDataPlane

type FlowRegistryDataPlane interface {
	// WithConnection manages a scoped, leased session for a given flow.
	// It is the primary and sole entry point for interacting with the data path.
	//
	// This method handles the entire lifecycle of a flow connection:
	// 1. Flow Registration: If the flow for the given FlowKey does not exist, it is created and registered
	//    automatically. Priority bands must be provisioned by the control plane before use.
	// 2. Lease Acquisition: It acquires a lifecycle lease, protecting the flow from garbage collection.
	// 3. Callback Execution: It invokes the provided function `fn`, passing in a temporary `ActiveFlowConnection` handle.
	// 4. Guaranteed Lease Release: It ensures the lease is safely released when the callback function returns.
	//
	// This functional, callback-based approach makes resource leaks impossible, as the caller is not responsible for
	// manually closing the connection.
	//
	// Errors returned by the callback `fn` are propagated up.
	// Returns `ErrFlowIDEmpty` if the provided key has an empty ID.
	WithConnection(key flowcontrol.FlowKey, fn func(conn ActiveFlowConnection) error) error

	// ManagedQueue retrieves the managed queue for the given, unique FlowKey. This is the primary method for accessing
	// a specific flow's queue for either enqueueing or dispatching requests.
	//
	// Returns an error wrapping ErrPriorityBandNotFound if the priority specified in the key is not configured, or
	// ErrFlowInstanceNotFound if no instance exists for the given key.
	ManagedQueue(key flowcontrol.FlowKey) (ManagedQueue, error)

	// FairnessPolicy retrieves the FairnessPolicy singleton configured for the specified priority band.
	// This method provides access to the immutable logic component that governs inter-flow contention.
	// The registry guarantees that a non-nil policy is returned for any active priority band.
	//
	// Returns:
	//   - FairnessPolicy: The active policy instance.
	//   - error: A wrapped ErrPriorityBandNotFound if the priority level is not configured.
	FairnessPolicy(priority int) (flowcontrol.FairnessPolicy, error)

	// PriorityBandAccessor retrieves the read-only view of the "Flow Group" for a specific priority level.
	// This accessor provides the state of all contending flows within the band and serves as the
	// primary input for FairnessPolicy execution.
	//
	// Returns an error wrapping ErrPriorityBandNotFound if the priority level is not configured.
	PriorityBandAccessor(priority int) (flowcontrol.PriorityBandAccessor, error)

	// AllOrderedPriorityLevels returns all configured priority levels, sorted in descending
	// numerical order. This order corresponds to highest priority (highest numeric value) to lowest priority (lowest
	// numeric value).
	// The returned slice provides a definitive, ordered list of priority levels for iteration, for example, by a
	// `controller.FlowController` worker's dispatch loop.
	AllOrderedPriorityLevels() []int
}

FlowRegistryDataPlane defines the high-throughput, request-path interface for the registry.

type FlowRegistryObserver

type FlowRegistryObserver interface {
	// Stats returns a near-consistent snapshot globally aggregated statistics for the entire `FlowRegistry`.
	Stats() AggregateStats
}

FlowRegistryObserver defines the read-only, observation interface for the registry.

type ManagedQueue

type ManagedQueue interface {
	// Add attempts to enqueue an item.
	Add(item flowcontrol.QueueItemAccessor) error

	// Remove atomically finds and removes an item from the underlying queue using its handle.
	Remove(handle flowcontrol.QueueItemHandle) (flowcontrol.QueueItemAccessor, error)

	// Cleanup removes all items from the underlying queue that satisfy the predicate.
	Cleanup(predicate PredicateFunc) []flowcontrol.QueueItemAccessor

	// Drain removes all items from the underlying queue.
	Drain() []flowcontrol.QueueItemAccessor

	// FlowQueueAccessor returns a read-only, flow-aware accessor for this queue, used by policy plugins.
	// Conformance: This method MUST NOT return nil.
	FlowQueueAccessor() flowcontrol.FlowQueueAccessor
}

ManagedQueue defines the interface for a flow's queue. It acts as a stateful decorator that *use an underlying SafeQueue, augmenting it with statistics tracking, and lifecycle awareness.

Conformance: Implementations MUST be goroutine-safe.

type PredicateFunc

type PredicateFunc func(item flowcontrol.QueueItemAccessor) bool

PredicateFunc defines a function that returns true if a given item matches a certain condition. It is used by SafeQueue.Cleanup to filter items.

type PriorityBandControlPlane

type PriorityBandControlPlane interface {
	// SubmitDesiredPriorities queues the set of priority levels that should remain provisioned.
	// Dynamic bands not in this set become eligible for removal once idle.
	SubmitDesiredPriorities(desired map[int]struct{})
}

PriorityBandControlPlane submits priority band topology updates from the control plane.

type PriorityBandStats

type PriorityBandStats struct {
	// Priority is the numerical priority level this struct describes.
	Priority int
	// CapacityBytes is the configured maximum total byte size for this priority band.
	// When viewed via `AggregateStats`, this is the global limit.
	// The `controller.FlowController` enforces this limit.
	// A default non-zero value is guaranteed if not configured.
	CapacityBytes uint64
	// CapacityRequests is the configured maximum total request count for this priority band.
	CapacityRequests uint64
	// ByteSize is the total byte size of items currently queued in this priority band.
	ByteSize uint64
	// Len is the total number of items currently queued in this priority band.
	Len uint64
}

PriorityBandStats holds aggregated statistics for a single priority band. It is a read-only data object representing a near-consistent snapshot of the priority band's state.

type SafeQueue

type SafeQueue interface {
	flowcontrol.QueueInspectionMethods

	// Add enqueues an item. It must associate a new, unique QueueItemHandle with the item by calling
	// item.SetHandle().
	// Contract: The caller MUST NOT provide a nil item.
	Add(item flowcontrol.QueueItemAccessor)

	// Remove atomically finds and removes the item identified by the given handle.
	// On success, implementations MUST invalidate the provided handle by calling handle.Invalidate().
	// Returns the removed item.
	// Returns ErrInvalidQueueItemHandle if the handle is invalid.
	// Returns ErrQueueItemNotFound if the handle is valid but the item is not in the queue.
	Remove(handle flowcontrol.QueueItemHandle) (removedItem flowcontrol.QueueItemAccessor, err error)

	// Cleanup iterates through the queue and atomically removes all items for which the predicate returns true,
	// returning them in a slice.
	// The handle for each removed item MUST be invalidated.
	Cleanup(predicate PredicateFunc) (cleanedItems []flowcontrol.QueueItemAccessor)

	// Drain atomically removes all items from the queue and returns them in a slice.
	// The handle for all removed items MUST be invalidated. The queue MUST be empty after this operation.
	Drain() (drainedItems []flowcontrol.QueueItemAccessor)
}

SafeQueue defines the contract for a single, concurrent-safe queue implementation. This interface is designed for in-memory, synchronous flow control. Implementations are expected to be unbounded; capacity management occurs outside the queue implementation. All implementations MUST be goroutine-safe.

Directories

Path Synopsis
Package mocks provides mocks for the interfaces defined in the `contracts` package.
Package mocks provides mocks for the interfaces defined in the `contracts` package.

Jump to

Keyboard shortcuts

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