Documentation
¶
Overview ¶
Package pipeline is the executable graph layer under the goav recipe grammar: sources, stages, and sinks wired by routes into an inspectable, runnable Graph. It owns the flow-control vocabulary — buffer policies, drop policies and counters, backpressure and shutdown sentinels — and the node-level capabilities (describe, pause, control) the runtime discovers by type assertion.
Index ¶
- Variables
- type Admitter
- type BufferPolicy
- type CloseWaitError
- type ContextCloser
- type ControllableSource
- type Delivery
- type DeliveryEmitter
- type DownstreamFlusher
- type DropPolicy
- type DropReporter
- type EdgeSpec
- type Emitter
- type ExecutionSpec
- type FaultDomain
- type FaultError
- type FaultIsolator
- type FaultSnapshot
- type FinalizationError
- type Graph
- type GraphConfig
- type GraphStats
- type Message
- type MessageKind
- type NodeDescriber
- type NodeExecution
- type NodeInjector
- type NodeKind
- type NodePauser
- type NodeRef
- type NodeRemover
- type NodeRemoverContext
- type NodeSpec
- type NodeStats
- type Route
- type RoutePolicy
- type RunErrorReporter
- type Scratch
- type Sink
- type Source
- type SourceControlProber
- type SourceInjector
- type Spec
- type Stage
Constants ¶
This section is empty.
Variables ¶
var ( // ErrAlreadyRunning reports a concurrent Run call on a graph that is // already executing or draining. ErrAlreadyRunning = errors.New("pipeline: already running") // ErrBackpressure reports a strict (non-dropping) queue that is full: the // message was not delivered and a pacing producer should slow down. ErrBackpressure = errors.New("pipeline: backpressure") // ErrBufferedEdgesUnsupported reports a buffered route on a graph // implementation that only executes direct edges. ErrBufferedEdgesUnsupported = errors.New("pipeline: buffered edges unsupported by direct graph") // ErrClosed reports an emit or control into a graph that has shut down. ErrClosed = errors.New("pipeline: closed") // ErrDynamicGraphUnsupported reports a live mutation (connect, disconnect, // remove while running) on a graph that cannot apply it. ErrDynamicGraphUnsupported = errors.New("pipeline: dynamic graph unsupported") // ErrInvalidLink reports a route whose endpoints cannot be wired (a sink // as a route source, a source as a target). ErrInvalidLink = errors.New("pipeline: invalid link") // ErrNilMessage reports a nil message handed to Emit. ErrNilMessage = errors.New("pipeline: nil message") // ErrNodeExists reports an added node whose name is already taken. ErrNodeExists = errors.New("pipeline: node exists") // ErrUnsupportedRoute reports a route policy the graph cannot apply. ErrUnsupportedRoute = errors.New("pipeline: unsupported route") // ErrUnknownNode reports a route or control naming a node the graph does // not contain. ErrUnknownNode = errors.New("pipeline: unknown node") )
Graph and flow-control sentinels, matched with errors.Is.
var ErrCloseWait = errors.New("pipeline: close wait stuck")
ErrCloseWait reports that graph Close or Remove waited too long for a node to drain in-flight work.
var ErrUnsafeFaultDomain = errors.New("pipeline: unsafe fault domain")
ErrUnsafeFaultDomain reports a boundary with shared egress, a source, a converging admission gate, or overlapping membership.
Functions ¶
This section is empty.
Types ¶
type Admitter ¶
Admitter is an optional Stage capability for converging stages: the runners call Admit on the producer's goroutine before delivering a message to the stage, outside the stage's own serialization, so the stage can hold one upstream back (block until it has room, or until ctx ends) without stalling the siblings it is waiting on. A non-nil error fails the delivery like a Handle error. Admit runs concurrently with Handle.
type BufferPolicy ¶
type BufferPolicy struct {
Capacity int `json:"capacity,omitempty"`
Drop DropPolicy `json:"drop,omitempty"`
MaxLatency time.Duration `json:"maxLatency,omitempty"`
// MaxBytes caps the total queued payload bytes for a buffered node; admitting
// a message that would exceed it sheds the message (DropOverflow) instead of
// queuing. Zero disables byte-budget shedding (the default — no per-message
// byte accounting runs on the hot path).
MaxBytes int64 `json:"maxBytes,omitempty"`
}
BufferPolicy configures one node's queue: capacity, overflow behavior (Drop), and staleness and byte budgets. A queued message is a header that holds references to its payload, never a copy of it, so a policy bounds messages, not bytes per message. The zero value means direct (unbuffered) execution.
func (BufferPolicy) IsDirect ¶
func (p BufferPolicy) IsDirect() bool
IsDirect reports whether the policy means unbuffered execution: no capacity and no dropping mode.
type CloseWaitError ¶
CloseWaitError identifies the node that kept a Close or Remove drain from completing before the diagnostic timeout.
func (*CloseWaitError) Error ¶
func (e *CloseWaitError) Error() string
Error renders the stuck close/remove wait with the operation, node, timeout, and any known pending delivery count.
func (*CloseWaitError) Unwrap ¶
func (e *CloseWaitError) Unwrap() error
Unwrap lets callers match CloseWaitError with errors.Is(err, ErrCloseWait).
type ContextCloser ¶
ContextCloser is implemented by graphs whose Close can honor a caller's context deadline while draining nodes. Both runners implement it.
type ControllableSource ¶
ControllableSource is an optional capability of a Source: a source whose running Start loop can be steered by out-of-band control messages (a seek, a segment) delivered through a graph's SourceInjector.
Concurrency contract: Control is called synchronously from the controlling goroutine while Start runs concurrently (or before Start has begun). Implementations must be safe under that overlap — record the request in an atomic or send it on a channel the Start loop reads; do not touch Start-loop-local state directly and do not block waiting for the loop.
Repositioning contract: a source that repositions (av.EventSeek, or av.EventSegment's jump to its start bound) must emit av.EventDiscontinuity from its Start loop before the first message at the new position, so downstream decoders reset their reference state. The graph adds no flush machinery on a seek.
Time-axis contract: a segment (av.EventSegment, start on Event.Timestamp, exclusive end via av.EventSegmentEnd) behaves like a seek to start followed by a natural end at end: the source emits av.EventEndOfStream and returns from Start when the window completes, exactly as at the end of the media. Playback rate is not a source control: it scales the task-wide timeline clock, so paced sources observe it through the clock they sleep on, never through Control. A source that cannot honour a control returns an error from Control instead of ignoring it.
type Delivery ¶
type Delivery struct {
// Delivered counts matching targets that accepted the message. Buffered
// targets accept by queueing; direct targets accept when their handler
// returns nil. Under DropOldest a target may have evicted an older message
// to admit this one — that eviction lands in the target's drop counters.
Delivered int
// Shed counts targets that deliberately dropped this message: a full queue
// under a dropping policy, an exhausted byte budget, a paused branch, or a
// queue torn down mid-route.
Shed int
}
Delivery reports what happened to one emitted message across its matching targets — the per-message answer that drop counters only aggregate. A dropping buffer policy sheds deliberately and without error, so the error from Emit alone cannot tell a producer whether this message was delivered; Delivery can.
type DeliveryEmitter ¶
type DeliveryEmitter interface {
EmitDelivery(ctx context.Context, msg *Message) (Delivery, error)
}
DeliveryEmitter is an optional capability of an Emitter: EmitDelivery behaves exactly like Emit but additionally reports the message's Delivery. Discover it by type assertion, like the other optional runner capabilities:
if de, ok := emitter.(pipeline.DeliveryEmitter); ok {
delivery, err := de.EmitDelivery(ctx, msg)
...
}
The buffered and direct runners both implement it.
type DownstreamFlusher ¶
DownstreamFlusher is implemented by buffered graphs that can flush stale media from queues exclusively downstream of a source before seek/segment control.
type DropPolicy ¶
type DropPolicy string
DropPolicy says why a message or observer event was shed, and doubles as the recorded reason on drop counters (Stats DropReasons).
const ( // DropNever refuses to shed: a full queue fails the emit with // ErrBackpressure instead of dropping. DropNever DropPolicy = "never" // DropOldest sheds the oldest queued message to admit the new one — // keep-latest semantics for realtime previews. DropOldest DropPolicy = "oldest" // DropNewest sheds the incoming message when the queue is full. DropNewest DropPolicy = "newest" // DropUntilSync sheds until a sync point (keyframe) arrives, so a consumer // resumes on decodable media. DropUntilSync DropPolicy = "until_sync" // DropNonKeyVideo sheds non-keyframe video first, preserving sync points // and non-video media. DropNonKeyVideo DropPolicy = "non_key_video" // DropBlock never drops: a full queue blocks the producer until the consumer // drains (true backpressure), instead of erroring. Source paces to the // slowest blocking consumer; no pipeline teardown. DropBlock DropPolicy = "block" // DropStale is the reason recorded when a buffered message is shed because it // waited longer than BufferPolicy.MaxLatency (orthogonal to the drop policy: // any policy can also shed stale messages when MaxLatency is set). DropStale DropPolicy = "stale" // DropOverflow is the reason recorded when a buffered message is shed because // admitting it would exceed the node's BufferPolicy.MaxBytes byte budget // (orthogonal to the drop policy, like DropStale). DropOverflow DropPolicy = "overflow" // DropSync is the reason recorded for messages a node sheds internally to // stay time-aligned (a PTS-sync join dropping stale frames to catch up). // These drops happen inside the node, not in its queue, so they reach the // counters through the optional DropReporter capability at snapshot time. DropSync DropPolicy = "sync" // DropFlush records queued packet/frame media shed from queues exclusively // downstream of a source before seek/segment control. Shared queues and // their descendants retain their bounded admitted tail; unrelated media // must not be discarded. Events and media following a queued discontinuity // are preserved. This is an observation reason, not a selectable policy. DropFlush DropPolicy = "flush" // DropObserver is the reason recorded when the graph's cold-side observer // event channel is full. Media/event delivery to graph routes still // continues; only the raw observer copy is shed. DropObserver DropPolicy = "observer" )
type DropReporter ¶
type DropReporter interface {
DroppedMessages() uint64
}
DropReporter is an optional Source/Stage/Sink capability: a node that sheds messages internally (rather than through its queue policy) reports its running total, and the runners fold it into the node's NodeStats.Dropped under DropSync at snapshot time. DroppedMessages is called concurrently with the node's hot path, so implementations must read an atomic counter.
type EdgeSpec ¶
type EdgeSpec struct {
From NodeRef `json:"from"`
To NodeRef `json:"to"`
Policy RoutePolicy `json:"policy,omitempty"`
Label string `json:"label,omitempty"`
}
EdgeSpec describes one graph edge: its endpoints and the route policy and label filtering it.
type Emitter ¶
Emitter is how a source or stage hands a message downstream. Emit returns ErrBackpressure when a strict queue is full and ErrClosed once the graph has shut down.
type ExecutionSpec ¶
type ExecutionSpec struct {
// Admission is "timestamp" when eligible offline sources take turns by
// packet time, "arrival" otherwise. A pre-open plan reports "runtime"
// when provider or decorator capabilities must first be resolved.
Admission string `json:"admission,omitempty"`
Mode string `json:"mode,omitempty"` // "direct" or "buffered"
Fanout string `json:"fanout,omitempty"` // "shared_producer"
}
ExecutionSpec describes the selected runner and its scheduling contract. Buffered workers may overlap, but a full blocking queue paces its producer and every sibling that producer has yet to visit.
func DescribeExecution ¶
func DescribeExecution(config GraphConfig) ExecutionSpec
DescribeExecution uses the same normalized queue policy as NewGraph.
type FaultDomain ¶
type FaultDomain struct {
// contains filtered or unexported fields
}
FaultDomain is a durable failure record, retained after its nodes retire. Its methods are safe concurrently with delivery, retirement, and Close.
func (*FaultDomain) Failed ¶
func (d *FaultDomain) Failed() bool
Failed reports whether the boundary rejected a handler error.
func (*FaultDomain) Snapshot ¶
func (d *FaultDomain) Snapshot() FaultSnapshot
Snapshot retains the original failure even after resources are reclaimed.
type FaultError ¶
FaultError identifies the first handler failure within an isolated domain. It never becomes the task's Run error; cleanup failures remain graph errors.
func (*FaultError) Error ¶
func (e *FaultError) Error() string
func (*FaultError) Unwrap ¶
func (e *FaultError) Unwrap() error
type FaultIsolator ¶
type FaultIsolator interface {
IsolateFaults(id string, members []NodeRef) (*FaultDomain, error)
}
FaultIsolator is the graph capability for isolating returned handler errors. Members must form an exclusive, downstream-closed suffix. A failure stops delivery immediately and retires the members asynchronously.
type FaultSnapshot ¶
type FaultSnapshot struct {
ID string `json:"id"`
Nodes []NodeRef `json:"nodes"`
Err error `json:"-"`
Error string `json:"error,omitempty"`
Failed bool `json:"failed"`
Retired bool `json:"retired"`
PendingCleanup int `json:"pendingCleanup,omitempty"`
CleanupErr error `json:"-"`
CleanupError string `json:"cleanupError,omitempty"`
}
FaultSnapshot is an immutable view of a failure boundary.
type FinalizationError ¶
FinalizationError identifies one node's actual Close failure. ID distinguishes successive nodes that reused a display name; errors.Is matches Cause.
func (*FinalizationError) Error ¶
func (e *FinalizationError) Error() string
func (*FinalizationError) Unwrap ¶
func (e *FinalizationError) Unwrap() error
type Graph ¶
type Graph interface {
AddSource(Source, BufferPolicy) (NodeRef, error)
AddStage(Stage, BufferPolicy) (NodeRef, error)
AddSink(Sink, BufferPolicy) (NodeRef, error)
Connect(Route) error
Disconnect(Route) error
Remove(NodeRef) error
Spec() Spec
// Run drives the graph until every source ends, ctx is done, or something
// fails. The first error from a source or a node's Handle cancels the
// sibling sources and stops the run promptly in both runners; Run returns
// that error, never the context.Canceled it caused. A shed (drop policy,
// paused or removed branch, isolated fanout backpressure) is not a failure.
//
// Sources run concurrently, except in a direct graph that is not realtime:
// there the format package's file pumps interleave by packet time (the
// earliest next packet goes first), so a run is reproducible.
Run(context.Context) error
Events() <-chan av.Event
Stats() GraphStats
Close() error
// CleanupError retains actual resource finalization failures, including
// deferred cleanup. It excludes caller cancellation and wait timeouts.
CleanupError() error
}
Graph is the executable node graph: add nodes, connect routes, run, and inspect. Mutations (Connect/Disconnect/Remove) are atomic with respect to the running data plane — the runtime swaps routing snapshots, never locks the message path. Remove stops deliveries into a node, delivers what it already queued (bounded by its queue and the close-wait budget), then closes it; remove a chain upstream first to keep its tail.
func NewGraph ¶
func NewGraph(config GraphConfig) (Graph, error)
NewGraph creates the single public pipeline graph. Direct execution is used for direct buffer policy; bounded buffered execution is selected otherwise.
type GraphConfig ¶
type GraphConfig struct {
Name string
Realtime bool
Buffer BufferPolicy
EventCapacity int
CloseWaitTimeout time.Duration
Metadata av.Metadata
}
GraphConfig configures a new graph: its name, realtime pacing, the default node buffer policy, event channel capacity, and diagnostic close/remove wait timeout. A zero EventCapacity keeps the default 256 events, and a zero CloseWaitTimeout the default 30s budget.
type GraphStats ¶
type GraphStats struct {
// PendingCleanup counts retired nodes still draining or finalizing.
PendingCleanup int `json:"pendingCleanup,omitempty"`
Messages uint64 `json:"messages"`
Packets uint64 `json:"packets"`
Frames uint64 `json:"frames"`
Events uint64 `json:"events"`
EventsByType map[av.EventType]uint64 `json:"eventsByType,omitempty"`
Dropped uint64 `json:"dropped"`
DropReasons map[DropPolicy]uint64 `json:"dropReasons,omitempty"`
Delivered uint64 `json:"delivered"`
LastEvent av.Event `json:"-"`
LastEventPresent bool `json:"-"`
Nodes map[string]NodeStats `json:"nodes,omitempty"`
}
GraphStats is a point-in-time counter snapshot for the whole graph, with per-node detail under Nodes. Dropped counts deliberate sheds, keyed by reason in DropReasons. The last event stays out of the JSON: watch the task for its events.
type Message ¶
Message is the one unit that flows between nodes: a packet, a frame, or an event, tagged by Kind. Exactly one payload pointer is non-nil.
Emit and Handle lend a message for the call. The payload is immutable and shared by reference (av.Buffer): a producer keeps its own references across Emit and releases them after, a queued delivery takes references of its own, and a handler that keeps a frame or packet past the call takes one too (av.Frame.Ref, av.Packet.Ref). Nobody writes lent bytes; a handler that must write takes its own reference and calls MakeWritable on it.
type MessageKind ¶
type MessageKind string
MessageKind says which payload field of a Message is set.
const ( MessagePacket MessageKind = "packet" MessageFrame MessageKind = "frame" MessageEvent MessageKind = "event" )
The message kinds: exactly one payload per message.
type NodeDescriber ¶
type NodeDescriber interface {
DescribeNode() NodeSpec
}
NodeDescriber is an optional node capability: a node that can describe itself contributes its details (component, codec, format) to Spec.
type NodeExecution ¶
type NodeExecution struct {
Kind string `json:"kind,omitempty"` // "source", "inline", "worker"
Queue BufferPolicy `json:"queue,omitzero"`
BlocksProducer bool `json:"blocksProducer,omitempty"`
}
NodeExecution reports a source goroutine, inline handler, or serial worker. Queue is the actual normalized policy; a source and an inline handler have no queue. BlocksProducer includes inline work and full blocking queues.
func DescribeNodeExecution ¶
func DescribeNodeExecution(kind NodeKind, config GraphConfig, policy BufferPolicy) NodeExecution
DescribeNodeExecution describes one node's actual delivery boundary.
type NodeInjector ¶
type NodeInjector interface {
// Inject delivers msg to the node named by ref, serialized with inbound
// traffic on that node. It is safe to call concurrently with the running
// graph, so the node's Handle still observes one message at a time with no
// extra locking.
Inject(ctx context.Context, ref NodeRef, msg *Message) error
}
NodeInjector is implemented by graphs that can deliver an out-of-band message to a single named node in a running graph. Both the buffered and direct runners implement it: buffered graphs enqueue onto the node's serial worker, and direct graphs serialize delivery through the node's ownership gate.
type NodePauser ¶
NodePauser is implemented by graphs that can pause/resume delivery to a single node. Both the buffered and direct runners implement it. It is an optional capability discovered by type assertion, so it does not widen the Graph interface for every implementer.
type NodeRef ¶
type NodeRef string
NodeRef is the graph-unique name of an added node, used to connect routes and look up stats.
type NodeRemover ¶
NodeRemover is implemented by graphs whose Remove can also hand back the removed node's final counters, read once its queued tail was delivered. A removed node leaves Stats, so a caller that reports on what it removed (a detached branch) takes them here. Both runners implement it.
type NodeRemoverContext ¶
type NodeRemoverContext interface {
RemoveNodeContext(context.Context, NodeRef) (NodeStats, error)
}
NodeRemoverContext is the context-aware extension of NodeRemover: removal honors ctx cancellation while draining in-flight work. Both runners implement it.
type NodeSpec ¶
type NodeSpec struct {
Name string `json:"name"`
Kind NodeKind `json:"kind"`
Detail string `json:"detail,omitempty"`
Execution NodeExecution `json:"execution,omitzero"`
}
NodeSpec describes one graph node: its unique name, kind, and a free-form detail line (codec, format, configuration) for rendering. Spec is a stable JSON document; Detail is the display fallback, while machine consumers read the typed per-operation metadata in plan.Report (Explain).
type NodeStats ¶
type NodeStats struct {
InMessages uint64 `json:"inMessages"`
InPackets uint64 `json:"inPackets"`
InFrames uint64 `json:"inFrames"`
InEvents uint64 `json:"inEvents"`
OutMessages uint64 `json:"outMessages"`
OutPackets uint64 `json:"outPackets"`
OutFrames uint64 `json:"outFrames"`
OutEvents uint64 `json:"outEvents"`
Dropped uint64 `json:"dropped"`
DropReasons map[DropPolicy]uint64 `json:"dropReasons,omitempty"`
LastEvent av.Event `json:"-"`
LastEventPresent bool `json:"-"`
}
NodeStats is one node's counter snapshot: messages in and out by kind, drops by reason, and the last event seen.
type Route ¶
type Route struct {
From string
To []string
Policy RoutePolicy
Label string
}
Route is one edge declaration: messages leaving From reach every To node, filtered by Policy (Label carries the stream id or event type).
type RoutePolicy ¶
type RoutePolicy string
RoutePolicy says which messages a route forwards.
const ( RouteAll RoutePolicy = "all" RouteByStream RoutePolicy = "by_stream" RouteByEvent RoutePolicy = "by_event" )
The route policies: everything, one stream's messages, or one event type.
type RunErrorReporter ¶
type RunErrorReporter interface {
RunError() error
}
RunErrorReporter is an optional graph capability required by explicit branch drains. RunError reports an already-observed execution failure even while Run is still waiting for sources or handlers to return. It is safe to call during resource finalization and must not call back into those finalizers. It returns nil before a run and while the current run is healthy; isolated branch errors remain local to their fault domain. Both built-in runners implement it.
type Scratch ¶
Scratch is reusable per-worker working memory for nodes that assemble messages and event bursts without allocating on the hot path.
type Sink ¶
Sink is a graph terminal node: Handle consumes one delivered message. Like a stage, a sink is called serially per node. Returning an error fails the task.
type Source ¶
Source is a graph entry node: Start runs the producing loop, emitting until the media ends or the context is cancelled. Optional capabilities (ControllableSource, NodeDescriber, DropReporter) are discovered by type assertion.
type SourceControlProber ¶
SourceControlProber is implemented by graphs that can report whether a source node accepts live control before flushing downstream queues.
type SourceInjector ¶
type SourceInjector interface {
// InjectSource delivers msg to the source named by ref by calling its
// Control method synchronously on the caller's goroutine, concurrently with
// the source's running Start loop (see ControllableSource for the contract
// that makes this race-safe). Targets that are not sources, and sources
// that do not implement ControllableSource, report ErrInvalidLink.
InjectSource(ctx context.Context, ref NodeRef, msg *Message) error
}
SourceInjector is implemented by graphs that can deliver an out-of-band control message to a single SOURCE node. It is the source-side sibling of NodeInjector: a source has no queue or serial worker to ride, so the message is handed to the source's Control method (ControllableSource) instead. It is an optional capability discovered by type assertion, like NodeInjector and NodePauser. Both the buffered and direct runners implement it.
type Spec ¶
type Spec struct {
Name string `json:"name"`
Realtime bool `json:"realtime,omitempty"`
Nodes []NodeSpec `json:"nodes,omitempty"`
Edges []EdgeSpec `json:"edges,omitempty"`
Execution ExecutionSpec `json:"execution,omitzero"`
}
Spec is the inspectable structure of a graph: every node and edge, in deterministic order. Describe on a job or task returns it; rendering lives outside core (graphrender). It marshals to stable JSON for machine consumers.