remotetranscode

package
v0.3.5 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: GPL-3.0 Imports: 21 Imported by: 0

README

Private encoder execution transport

Opt-in package only: no routes are registered, no existing path is changed, and this is not the complete GPU-offload feature. Supported() and zero options retain HLS and ordinary segment seeks (including the local fMP4 init sentinel -1). Explicit matching WorkerOptions.Capabilities and AdapterOptions.Capabilities may enable ABR, DASH and HTTP only when trusted composition supplies the real backend contracts. These are host-negotiated promises, not peer discovery. Placement must call Adapter.SupportsRequest before reservation. The same side-effect-free SupportsRequest(request, capabilities) predicate is available to broker selectors. Probe, source swaps and full subtitle extraction cannot be enabled. SoftSubtitles separately enables selected embedded text ASS output on HLS/DASH through the same encoder input; selected decision track must match that exact stream. No external/burned track or auxiliary source read is admitted. Controls enables bounded per-operation Touch and HLS/DASH PlaybackState RPCs (playing/paused/stopped). HTTP has Touch only, matching its local session. Control methods have the existing void signatures: transport loss cannot report success, does not retry, and never discards execution responsibility.

Integration dependencies

  • Mount Worker only on a private listener requiring verified client certificates. Its handler additionally requires TLS verified chains, a known boot-scoped peer, and explicit operation authorization, including status and media reads.
  • Supply Security.Authorize backed by authoritative placement. Validate controller, worker boot, session, generation, grant and lease expiry against trusted state; never authorize a generation simply because the caller supplied it. Permit scoped stop/status reconciliation after expiry without permitting new media work.
  • Supply ResolveSource backed by the source owner's grant authority. It must issue one exact worker-local EncoderInputLease and private literal-IP HTTPS range URL, bound to the identity and lifetime. It must prevent redirects and nested fetches, and revoke access when sealed. No caller InputURL, headers, commands, local paths, leases, channels or interfaces enter the wire. Caller loopback URLs are ignored. The backend's outbound HTTPS trust must accept the source certificate. Scope headers are generated by the worker-local lease, not sent over this protocol.
  • Supply a dedicated core.OwnedTranscoder with adaptive ladders/governor, enhancement and automatic source mutation disabled. Do not share its session namespace with unrelated callers. Internal backend IDs hash the complete execution identity.
  • Supply an HTTPS http.Client with *http.Transport, explicit roots, client certificate and TLSClientConfig.VerifyConnection binding the server to the intended worker boot. Certificate provisioning, renewal/revocation, placement, source grants, server HTTP limits/timeouts and durable reconciliation are external. The adapter clones the transport, disables proxies/redirects and requires verified TLS; plaintext is never an alternative.
  • Supply a local decision function and verified hardware snapshot. These are injected, never discovered through this transport. Plan authorization must validate codecs, limits and all encoder choices against trusted placement/capabilities.

StartHLSOwned returns exact responsibility even on an uncertain start. The returned EncoderRetirement is a *Session; call Reconcile(ctx) until there is terminal proof. RetireEncoder requests exact retirement with a five-second RPC deadline; ErrEncoderPending/ErrUncertain retain responsibility. Nil retirement requires both successful backend encoder proof and input-producer proof. Terminal errors retain the charge for external recovery. Transport loss and authority expiry never supply proof. Use the owned API for integration; the legacy StartHLS signature cannot return its extra responsibility token on error, though the adapter retains it internally and Stop(id) still reaches pending execution.

Each start gets an initial authority lease of at most ten minutes (WorkerOptions.MaxLease). Explicit authenticated fenced renewal can extend an active lease as described below; a missing trusted validator disables renewal. Expiry cancels pending work and retires the exact session, without inferring successful retirement. Request cancellation seals late starts too. Media is streamed directly, with backpressure, cancellation, HEAD, range/content/cache headers; no media buffering, automatic retry, or local fallback is used.

The worker retains every record/tombstone for its entire unique boot lifetime; capacity includes them, never evicts them, and fails closed when full. Duplicate starts must match their original plan/grant/expiry. Stop-before-start seals that generation. A higher generation cannot start while an earlier exact execution is unresolved; stale stop/status use the old object and cannot retire its replacement. Worker restart requires a fresh boot identity, making old requests invalid. Never reuse a boot ID. The controller must retain unresolved old-boot responsibility across restart and reconcile with durable placement; losing contact is not retirement proof. Adapter records likewise live until adapter teardown. Teardown cannot be used to discard unresolved ownership. Durable fenced retention/compaction is a subsequent increment.

Explicit unsupported contracts

Without explicit opt-in starts reject DASH/HTTP Matroska. All starts reject live/slate inputs, input headers and caller leases, burned/selected subtitles without the exact soft-output opt-in, external subtitle URLs, audio filter expressions, enhancement, and indexed sources without the explicit complete-index capability before assignment. Remote Probe and SwapInput return ErrUnsupported; source-change/release failover is unsupported. Segment seeks delegate to the existing backend and may restart that exact encoder; start-offset changes require retirement and a new authorized generation.

Session implements concrete HLSLadderSession (bounded backend Rungs snapshot, ServeRungPlaylist/ServeRungSegment), DASHSession (manifest, per-representation init and media), and HTTPSession (progressive Matroska with downstream flushing). These methods reject operations outside the configured capability and execution protocol. Start.Protocol is immutable and included in generation idempotence. The worker sets the additive HLSRequest.ManifestSessionID only from validated execution Identity.Session, keeping public DASH representation URLs separate from private hashed encoder ownership. Caller ManifestSessionID is rejected by preflight; ordinary local requests with that field empty render exactly as before. The worker verifies the returned backend interfaces and retires on any mismatch; a misconfigured promise is a failed owned start, never a local fallback. IndependentSegments reflects only the exact backend session-wide proof (false when the backend cannot prove it). Representation RPCs retain per-operation mTLS authorization, exact fences, HEAD/range/cache forwarding, streaming backpressure and cancellation. HLS rung IDs must be advertised; indexes and DTOs are bounded. No media is buffered or retried. An HTTP backend must implement OwnedEncoderSession in addition to HTTPSession; blocking Close is not an acceptable retirement implementation.

Still absent: SubtitleExtractor, ProbeLive/ProbeLiveWithHeaders, cached/streamed/soft subtitles, PrepareSwap/CheckSwap, SwapInputBuffered/SwapWouldCopyVideo, CurrentSwapInput/WaitForReplacementOutput, RecoveryBuffer, Info/Decision/EncoderStatus, Progress/GoodputKbps, HWAccelerated, SegmentDuration/RequestedPosition/Container/Protocol, and manager-specific policy/capability/download/enhancement introspection. Consumers must not substitute missing values or select workflows needing these. RequireIndependentProof is sent unchanged to the backend, which owns playlist independence claims. No Plex wire equivalence is claimed for unsupported workflows.

Next increment: durable placement/source-grant integration and fenced retention, then additional optional session contracts, source swaps and subtitles, before application wiring or compatibility acceptance.

Explicit lease renewal

The immutable Start includes its original grant and expiry. Its initial execution lease has version zero. Renew is a separate operation, exposed through Session.Renew(ctx, Renewal); the parent drives renewal and Reconcile(ctx). There is no background polling or renewal goroutine in the adapter.

A Renewal carries the exact Identity, PreviousVersion, PreviousDeadline, an absolute Deadline and Operation. Operation is the sequential next version scoped to that identity, not an additive duration or a reusable arbitrary token. Zero and uint64 overflow are rejected. Use UTC timestamps; equality compares exact canonical instants, with no rounding/tolerance. The deadline must advance and be within WorkerOptions.MaxLease of acceptance time. MaxLease remains at most ten minutes per acceptance; timely successive renewals can support longer playback.

WorkerOptions.ValidateRenewal is optional and fails closed when absent: renewal returns HTTP 422 / ErrUnsupported. Status Lease.Renewable reports configured support; Supported() alone does not promise renewable playback. The callback is mandatory before any extension, in addition to ordinary operation authorization. It receives the immutable original Start and exact Renewal and returns a trusted RenewalReceipt echoing that request. PlacementUntil and SourceUntil must each independently cover Deadline. The receipt is not accepted from the wire.

The validator must check durable placement using its authoritative database clock, all controller/worker boot and generation fences, and the authority of the SAME scoped source authority, worker-local gateway URL and input lease through the requested new deadline. Start.Grant is an immutable scoped authority/reader handle, not a requirement to retain an expiring source bearer. A trusted source reader may rotate its internal opaque bearer while preserving that handle, exact source scope/revision/size, gateway URL and input lease. The validator must actually extend or revalidate this same source authority idempotently; it cannot pretend an expired credential remains valid, exchange the source, or start an encoder. If the source implementation cannot extend access without changing input, renewal must fail. Missing database/source authority or uncertain validation must fail closed. Validation runs outside the worker lock; its placement/source updates may conservatively outlive a rejected worker extension, but can never manufacture worker acceptance or retirement proof.

After validation, the worker locks and rechecks the old version/deadline, execution state, stop, expiry, and policy bound before committing. Stop, expiry, and renewal commit serialize under that same lock. A queued timer callback checks its captured version AND deadline under lock, so Timer.Stop races cannot retire a renewed execution. All responses encode immutable snapshots after releasing the worker mutex, so blocked network output cannot delay expiry, Stop or Close. Renew never resolves a source or invokes an encoder. Starts remain byte-immutable even after renewal.

The latest exact operation replay returns the accepted snapshot without another extension or validation side effect. A changed payload at that version, or an older retry after a newer acceptance, returns conflict (adapter ErrUncertain); reconcile status instead. Concurrent exact retries converge on the same snapshot. Status reports current accepted deadline/version/latest Renewal independently of execution state and Stopped. An exact replay after stop/expiry may return history but never clears Stopped or grants current authority; Session.Renew returns ErrUncertain unless the observed execution is running and locally unstopped. After a lost response, repeat the identical request or call Reconcile and inspect Session.Lease(). Do not mint a later version until accepted history is known.

Worker deadlines use the worker clock; placement uses the database clock. The trusted validator and deployment must apply a conservative clock-skew budget before issuing a receipt and before treating authority expiry as safe reassignment. Each accepted start or renewal also records a process-local monotonic cap using time.Now().Add(remainingWallDuration), retaining time.Now's monotonic component. Expiry occurs at the earlier of wall deadline and that elapsed cap: a wall-clock rollback cannot extend the accepted local lifetime, while forward corrections may retire conservatively early. An early callback rearms to the earlier remaining bound without resetting the cap. Timer callbacks fence version, wall deadline and monotonic cap together. Only an authorized new renewal acceptance replaces the cap; retries never reset it. Status reports the wall authority deadline only; this monotonic cap is neither serialized nor portable across worker restarts. This package does not invent a cross-host clock bound. Worker expiry requests retirement; it does not prove the child/input have stopped. External placement retirement still requires exact proofs, or its separately established safe expiry policy. Integration must supply the validator, source extension mechanism, parent-driven renewal schedule, and failure/reassignment policy before enabling long-running remote playback. No application/core/config/placement wiring is included here.

Trusted worker-local input gateway

Source.Gateway TrustedGatewayInput is an additive, injected composition boundary; no wire fields or caller InputURL can populate it. Its GatewayInput(Identity, Start.Grant) must return the exact locally constructed URL and input lease, even on error after acquisition. Gateway excludes ordinary Source.URL/Lease; resolvers must not mint an unused second lease. Worker invokes it outside its mutex, rejects mixed results, missing lease and nonliteral/nonloopback or ambiguous URL forms, never falls back, and retains all returned leases for seal/reconciliation on error. The ordinary Source.URL private-HTTPS validator is unchanged. Custom interface implementations remain trusted dependencies responsible for exact identity, listener origin/path binding, no redirects and no input substitution. nodeinput is the concrete verified-Go-Reader implementation; its README specifies lifecycle, renewal evidence and the separate remote source retirement requirement.

Explicit dynamic observations

Capabilities.Observations enables one authenticated inspect operation. Session.Observe(ctx) returns (*ObservedSession, error) with a five-second operation bound and a strict 64 KiB DTO cap. It never changes Adapter.Session map presence, wraps a Start, retries, falls back, or supplies retirement evidence. Missing backend contracts, stopped/expired executions, incomplete/oversized JSON, external source URLs, and transport errors return an error without a sample. The concrete backend must implement the entire supported observation bundle; HLS/DASH Manager Sessions do, while current HTTP sessions do not.

ObservedSession is a detached immutable sample, not a live HLSSession. It exposes exact local signatures: Info, Decision, EncoderStatus, transcode.Progress, GoodputKbps, RecoveryBuffer, RequestedPosition, SegmentDuration, Container, Protocol and HWAccelerated. Contracts() explicitly identifies these supported sample contracts. An actual nil backend EncoderStatus means no active run; it is not replaced with an invented run. Nested slices/pointers are copied on getters. No corresponding no-error getter is added to live Session.

Identity() binds controller boot, worker boot, public session and generation. SampledAt() is worker wall time; RequestStarted() and ReceivedAt() are controller-local times retaining monotonic readings. The bundle is sampled sequentially through existing synchronized backend methods, not atomically across fields. Recovery integration must explicitly request a fresh observation, check exact identity and age (including request RTT, local elapsed time and conservative inter-host clock skew), and fail closed on errors or stale data. Do not reuse an observation across seeks or recovery decisions. An inspection error never establishes session absence, source failure or encoder retirement.

RecoveryBuffer and GoodputKbps preserve the backend's measured values. With the private transport, backend HTTP completion/goodput describe worker-to-controller output, not final controller-to-viewer delivery. In particular DeliveredUntil must not be treated as proof of final viewer delivery. Final-hop delivery evidence requires separate broker integration; no observation invents it here.

Concrete backend preflight

When the injected encoder implements SupportsDistributedRequest(core.HLSRequest) bool, Worker repeats this side-effect-free check on new exact executions before source resolution or admission. Existing immutable duplicate-start replay is resolved first. The check runs outside the worker mutex. Missing optional methods on custom injected backends retain the explicit trusted host capability contract; they do not establish real Manager compatibility by themselves.

transcode.Manager.SupportsDistributedRequest validates the actual normalized command dependencies against startup-probed encoder/filter/hardware inventories and additive muxer/demuxer/decoder/BSF/input-protocol inventories. It checks HTTP AAC and DASH normalization, configured ladder decisions, subtitle output, HDR conversion plans, implicit muxer BSFs and seek-only dependencies without opening sources or spawning processes. Unknown inventories and unsupported combinations deny distributed admission. It does not substitute codecs to make a plan pass.

The extra inventories are optional startup queries with a 15-second overall cap, 3-second per-query bound and 1 MiB combined output cap. Probe failure leaves that inventory unknown and changes no standalone FFmpeg feature fallback behavior. Preflight and execution must use the same dedicated Manager with fixed policy: FastStart/SpikeGovernor/RTX and source mutation disabled; ABR ladders only when explicitly configured and supported end-to-end. Protocol capability admission, current source/placement authorization and actual worker capacity remain separate mandatory checks. Feature support never guarantees successful process/device startup or reserves future capacity.

Trusted terminal reconciliation

Worker.Terminal(ctx, Identity, requestStop) is host-only; no route is installed and normal transport Security callbacks are unchanged. The composing Runtime must independently authenticate current peer membership and freshly authorize the exact OLD durable fence, intended worker boot and lost/revoked authority before calling. The method returns a copied TerminalSnapshot containing only full Identity, TerminalState and Stopped. The closed typed states are TerminalUnknown, TerminalPending, TerminalRunning, TerminalRetired and TerminalUnverified; String is available for transport rendering. Only TerminalRetired is successful local encoder plus local input retirement. It says nothing about remote source-owner or durable placement retirement, which require independent proof.

Status-only absence returns ErrUncertain and does not allocate. Stop-before-start absence creates a permanent stopped tombstone AND monotonic highest-generation floor before local retirement can be returned; the unique never-compacted worker boot is essential to that proof. Closed workers or exhausted capacity cannot create that fence and return ErrUncertain. Known exact records remain readable including after Close. Stops reach only retained exact OwnedEncoderSession and input objects; stale/absent-old stops never target a replacement's public ID. Late starts and delayed input/encoder producers remain pending; nonnil terminal errors remain unverified. No source resolve/start/renew/media work, generic Encoder.Stop, old-controller impersonation or authority extension is performed.

Lossless bounded source indexes and inert enhancement status

Capabilities.Keyframes explicitly enables complete Start.Keyframes transport using the actual core.KeyframePoint Offset/Time types. MaxKeyframes is 1024; ValidateKeyframes(MediaInfo) is the shared pure validator used by composition. Points must have nonnegative, nondecreasing offsets/timestamps. The COMPLETE index must also fit the existing full 64 KiB DTO budget (with assignment reserve in preflight). Nothing sorts, truncates, downsamples or drops genuine metadata to make a request fit. Oversized indexes remain unsupported before assignment.

The full point slice participates in immutable start hashing/replay. Worker restores exact Info.Keyframes only from the explicit validated field for backend and concrete Manager preflight, using independent copies. Observation carries an explicit complete index too; Info getters restore it after JSON roundtrips and return separate point ownership. Segment seeks and RequireIndependentProof still reach the existing backend unchanged. Runtime source/preparation/reopen snapshots and capability-request DTOs MUST preserve this same explicit field end-to-end before any composing host enables indexed-source selection; transport-only tests do not establish that integration. Ordinary MediaInfo JSON still excludes indexes.

transcode.SupportsDistributedEnhancement accepts only the existing zero status or observational State=off with Width/Height/Quality all zero, Backend at most 128 bytes and Reason at most 1024 bytes. Genuine default-CPU Manager decisions include this disabled-by-owner status; it is preserved unchanged on wire/backend. No status is stripped or rewritten. All operational/unknown enhancement states, nonzero action fields and oversized metadata remain unsupported. This permits inert displayed status only, not actual enhancement work.

Stronger receipt evidence (host-only)

Worker.TerminalEvidence(ctx, Identity) is read-only: it cannot stop, expire, create tombstones, compact, issue credentials, release claims or publish History. Runtime first obtains separately authorized exact terminal stopping, then freshly verifies the exact old durable fence/current worker peer and independent source retirement before consuming this stronger summary.

Every real record constructor now stores explicit AcceptedStart or StopBeforeStart origin. Backend invocation is registered before entering OwnedTranscoder. Renewal validation callbacks register before invocation and remain joined through every callback/CAS exit via deferred cleanup; network serialization happens after this accounting releases. Stopped records cannot register a later validation callback. Evidence refuses callbacks still capable of extending source authority, even when the older Terminal snapshot already says local resources retired.

AcceptedStart evidence requires the actual retained OwnedEncoderSession, returned Start retirement token AND session-owned token all present, both encoder tokens Done+nil Err, every retained ordinary/gateway input Done+nil Err, stopped admission and all late starts/callbacks joined. Proof getters run outside the worker mutex; exact record/version/seal/history are rechecked afterwards. Pending, cancellation or nonnil terminal errors produce no evidence. Accepted starts that failed before backend invocation or never returned an OwnedSession remain unsupported and retain history; they are never relabeled NeverStarted.

Negative evidence requires an explicitly recorded permanent stop-before-start barrier and generation floor, not absence/hash-zero/TerminalRetired inference. It carries NegativeBarrier proof kinds instead of pretending nil object tokens exist. Request hash, lease and accepted renewal are empty in this case.

TerminalEvidenceSummary v1 is bounded and detached: exact boot-scoped Identity, closed origin/proof kinds, original retained StartHash/InitialDeadline, accepted lease/CAS history, independently joined encoder/input facts and explicit negative barrier generation. AcceptedRenewal is copied. No raw Start/grant/source URL, credential, callback error or source proof appears. Digest/EncoderDigest/InputDigest use distinct versioned SHA-256 domains over the validated <=4 KiB summary. These are commitments to independently authenticated observations, not standalone cryptographic authenticity or permission to publish/compact. Source-owner proof, full cluster/stable-node fence binding and atomic durable History publication are separate trusted Runtime/provider responsibilities.

Local accepted-Start observation prerequisite

Worker.AcceptedStart(ctx, exactIdentity) returns a Worker-owned *AcceptedStartHandle only for an actual retained EvidenceAcceptedStart record. The pointer is installed with that record before Resolve or backend invocation, including while Start is pending or its response is uncertain/blocked. Exact Start retries attach to the same record and handle. This differs from Session.StartCommitment, which retains the controller's marshaled request before sending and cannot establish worker acceptance.

Worker.InspectAcceptedStart(ctx, handle) revalidates the exact Worker pointer, original handle pointer, retained record identity, worker boot, accepted hash, lease consistency and local live state on every call. Nil/zero, caller-created, copied handle objects and freshly deserialized objects are invalid. Keep the returned pointer locally: no snapshot, digest, nonce or wire DTO recreates it. Missing records, negative stop-before-start tombstones, cancellation, closed or stopped workers, expiry and inconsistent records fail closed. Inspection does not run expiry or stop work when it notices an elapsed deadline.

The detached snapshot contains only the complete existing transport Identity, actual worker-retained accepted StartHash, per-record AttemptNonce, original accepted deadline, current accepted LeaseState and Starting flag. AcceptedRenewal is copied. The hash is checked against the retained immutable Start, independently of any controller token. No raw Start, grant, source URL or credential is exposed. The nonce uses the required globally unique worker boot plus the next retained record ordinal, including tombstones; retention and bounded int capacity prevent reuse or uint64 overflow. It needs no random source or fallible counter operation once ownership is installed. It is an identifier, never an authentication secret.

Neither accessor calls Security, preflight, Resolve, backend getters, renewal, stop or retirement; neither creates tombstones, claims, observer arms or evidence. The snapshot is a local acceptance observation only. It carries the existing boot/session/generation Identity, not the full durable cluster/stable-node/source fence. There is no integration caller, public RPC, admission veto, durable seal, authenticated observer, host/runtime/kernel binding or production recovery change in this slice. Those separately owned contracts must be implemented and reviewed before an observer can authenticate this local capability or use it as one prerequisite for live arming. It supplies no execution permission, source proof, retirement proof, signer input or capacity-release authority.

Documentation

Overview

Package remotetranscode provides an opt-in private HLS execution foundation. It installs no routes and changes no local transcoder behavior.

Index

Constants

View Source
const MaxMessage = 64 << 10
View Source
const Version = 1

Variables

View Source
var ErrStatusDenied = errors.Join(ErrUncertain, errors.New("remotetranscode: status denied"))

ErrStatusDenied means the exact worker no longer accepts status observation. It permits replacement, never retirement or capacity release.

View Source
var ErrStatusUnavailable = errors.Join(ErrUncertain, errors.New("remotetranscode: status endpoint unavailable"))

ErrStatusUnavailable identifies explicit endpoint loss, not process retirement.

View Source
var ErrUncertain = errors.New("remotetranscode: execution responsibility requires reconciliation")
View Source
var ErrUnsupported = errors.New("remotetranscode: unsupported capability")

Functions

func SupportsRequest

func SupportsRequest(r core.HLSRequest, c Capabilities) bool

SupportsRequest is side-effect-free and shared with placement preflight.

func ValidateKeyframes

func ValidateKeyframes(info core.MediaInfo) bool

ValidateKeyframes is shared by runtime capability/source DTOs and worker admission. It validates the complete index without changing any point.

Types

type AcceptedStartHandle

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

AcceptedStartHandle is a Worker-owned local capability for one retained actual acceptance. Only Worker.AcceptedStart can return a usable handle. Zero values, caller allocations, copied objects and deserialized values are invalid. It is not a wire DTO, execution permit, authenticated host binding or retirement proof. Retain the returned pointer; neither a snapshot nor a nonce can recreate it.

type AcceptedStartSnapshot

type AcceptedStartSnapshot struct {
	Identity        Identity
	StartHash       [32]byte
	AttemptNonce    string
	InitialDeadline time.Time
	Lease           LeaseState
	Starting        bool
}

AcceptedStartSnapshot is detached observation data, never a usable handle. Identity is the complete transport identity, not the full durable cluster fence. AttemptNonce is unique within the required globally unique Worker boot; it is an identifier, not a secret or an authenticity proof. Lease is accepted history, not proof of current placement/source authority. Starting includes an owned attempt whose source/backend callback or Start response has not completed.

type Adapter

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

func NewAdapter

func NewAdapter(o AdapterOptions) (*Adapter, error)

func (*Adapter) Attach

func (a *Adapter) Attach(ctx context.Context, id Identity) (*Session, error)

Attach observes an already admitted execution. It sends only status, never Start, and requires an exact identity under the caller's current authorization.

func (*Adapter) AttachRetirement

func (a *Adapter) AttachRetirement(ctx context.Context, id Identity) (*Session, error)

AttachRetirement observes an exact existing execution, including pending or retired terminal state. It never sends Start or grants fresh authority. The composing controller must still fence every stop/status with its current epoch.

func (*Adapter) Capabilities

func (a *Adapter) Capabilities() Capabilities

func (*Adapter) Close

func (a *Adapter) Close()

Close closes idle transport connections only; owned executions must be stopped and reconciled explicitly. A connection close never proves encoder retirement.

func (*Adapter) Decide

func (*Adapter) HWAccel

func (a *Adapter) HWAccel() core.HWAccel

func (*Adapter) Probe

func (a *Adapter) Probe(context.Context, string) (*core.MediaInfo, error)

func (*Adapter) Session

func (a *Adapter) Session(id string) (core.HLSSession, bool)

func (*Adapter) StartHLS

func (a *Adapter) StartHLS(ctx context.Context, r core.HLSRequest) (core.HLSSession, error)

func (*Adapter) StartHLSOwned

func (*Adapter) Stop

func (a *Adapter) Stop(id string)

func (*Adapter) SupportsRequest

func (a *Adapter) SupportsRequest(r core.HLSRequest) bool

type AdapterOptions

type AdapterOptions struct {
	// RequestHeaders binds each operation to an external coordination epoch.
	RequestHeaders func(context.Context) (http.Header, error)
	// CommitStart durably binds the installed immutable Start before any Start
	// bytes leave this adapter. It runs synchronously outside locks, with a
	// context bounded to five seconds; implementations must honor cancellation.
	// Failure retains the owned token and never establishes retirement. Nil
	// preserves existing behavior. Only identity and hash cross this boundary.
	CommitStart  func(context.Context, Identity, [32]byte) error
	Capabilities Capabilities // Trusted negotiated worker/backend contracts; zero is fixed HLS.
	Endpoint     string
	// RecheckServer composes current Guard policy for the expected worker identity.
	// Fresh TLS per operation; rebuild on rotation. Callback captures/opaque keys
	// are immutable, callbacks concurrency safe and context cooperative.
	RecheckServer func(context.Context, tls.ConnectionState) error
	Client        *http.Client // Transport must be *http.Transport with verified mutual TLS.
	Assign        func(context.Context, core.HLSRequest) (Assignment, error)
	Decide        func(core.MediaInfo, core.ClientCaps, core.DecideOptions) core.Decision
	Hardware      core.HWAccel
	Capacity      int
}

type Assignment

type Assignment struct {
	Identity Identity
	Grant    string
	Expires  time.Time
}

type Capabilities

type Capabilities struct {
	HLS, SegmentSeek, DASH, HTTP, Probe, SourceSwap, Subtitles, ABR, SoftSubtitles, Controls, Observations, Keyframes bool
	// RecoveryStart negotiates instruction transport only, never successful recovery.
	CopyTimeline  bool `json:",omitempty"`
	AuthoredRamp  bool `json:",omitempty"`
	RecoveryStart bool `json:",omitempty"`
}

Capabilities must be consulted by placement before choosing this adapter. Segment seeks use the backend's ordinary ServeSegment behavior. Source swaps, probe, subtitles, DASH, HTTP Matroska, ABR and optional session controls are not supported.

func NormalizeCapabilities

func NormalizeCapabilities(c Capabilities) (Capabilities, error)

NormalizeCapabilities preserves fixed HLS for zero options and rejects promises for operations that have no concrete private implementation.

func Supported

func Supported() Capabilities

type EvidenceOrigin

type EvidenceOrigin uint8
const (
	EvidenceOriginUnknown EvidenceOrigin = iota
	EvidenceAcceptedStart
	EvidenceStopBeforeStart
)

type Identity

type Identity struct {
	Controller string
	Worker     string
	Session    string
	Generation uint64
}

Identity is assigned by trusted placement, never by a public request decoder. Controller and Worker are boot-scoped identities, not stable node names alone.

type LeaseState

type LeaseState struct {
	Deadline  time.Time
	Version   uint64
	Accepted  *Renewal `json:",omitempty"`
	Renewable bool
}

LeaseState distinguishes accepted lease history from current execution state. Accepted is the latest operation only; older retries reconcile this snapshot.

type ObservationContracts

type ObservationContracts struct {
	Info, Decision, EncoderStatus, Progress, Goodput, RecoveryBuffer       bool
	RequestedPosition, SegmentDuration, Container, Protocol, HWAccelerated bool
}

ObservationContracts identifies the optional contracts supplied by this sample. Observe currently requires the complete bundle: unsupported backends return an error before any ObservedSession is constructed. A nil EncoderStatus is a real backend observation (no active run), not an unsupported-contract sentinel.

type ObservedSession

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

ObservedSession is an immutable detached sample, not a live HLSSession. Its optional getters describe only this observation. Recovery callers must request a new Observe and reject errors/old samples before making a recovery decision. SampledAt is the worker clock. RequestStarted/ReceivedAt are controller-local times (including monotonic readings); account for RTT and host clock skew.

func (*ObservedSession) Container

func (s *ObservedSession) Container() string

func (*ObservedSession) Contracts

func (s *ObservedSession) Contracts() ObservationContracts

func (*ObservedSession) Decision

func (s *ObservedSession) Decision() core.Decision

func (*ObservedSession) EncoderStatus

func (s *ObservedSession) EncoderStatus() *core.EncoderStatus

func (*ObservedSession) GoodputKbps

func (s *ObservedSession) GoodputKbps() int

func (*ObservedSession) HWAccelerated

func (s *ObservedSession) HWAccelerated() bool

func (*ObservedSession) Identity

func (s *ObservedSession) Identity() Identity

func (*ObservedSession) Info

func (s *ObservedSession) Info() core.MediaInfo

func (*ObservedSession) Progress

func (s *ObservedSession) Progress() transcode.Progress

func (*ObservedSession) Protocol

func (s *ObservedSession) Protocol() string

func (*ObservedSession) ReceivedAt

func (s *ObservedSession) ReceivedAt() time.Time

func (*ObservedSession) RecoveryBuffer

func (s *ObservedSession) RecoveryBuffer() core.RecoveryBuffer

func (*ObservedSession) RequestStarted

func (s *ObservedSession) RequestStarted() time.Time

func (*ObservedSession) RequestedPosition

func (s *ObservedSession) RequestedPosition() time.Duration

func (*ObservedSession) SampledAt

func (s *ObservedSession) SampledAt() time.Time

func (*ObservedSession) SegmentDuration

func (s *ObservedSession) SegmentDuration() time.Duration

type Renewal

type Renewal struct {
	Identity         Identity
	Operation        uint64
	PreviousVersion  uint64
	PreviousDeadline time.Time
	Deadline         time.Time
}

Renewal is a compare-and-swap of the execution lease, never a new Start. Operation is the next version, scoped to Identity; zero is the initial lease. Deadlines on the wire must use UTC. Equality compares canonical instants.

type RenewalReceipt

type RenewalReceipt struct {
	Renewal        Renewal
	PlacementUntil time.Time
	SourceUntil    time.Time
}

RenewalReceipt is returned only by a trusted injected validator, never decoded from the caller. It attests durable placement AND continued access using the SAME source authority handle, gateway URL and input lease through Deadline. Start.Grant stays immutable; internal source bearers may rotate while preserving exact source scope/revision/size. The validator must actually extend/revalidate that source authority; an expired bearer alone is not proof. No source replacement or encoder invocation is permitted in this callback. It must account for DB/worker clock skew conservatively and fail on uncertainty.

type RepresentationCompletion

type RepresentationCompletion struct {
	StatusCode                             int
	ContentLength, ReadBytes, WrittenBytes int64
	BodyPresent, EOF, Closed               bool
	ReadError, WriteError, CloseError      bool
	EncodedOrChunked, Trailers             bool
}

RepresentationCompletion records one synchronous response read and body close. It contains no transport errors, URLs, credentials or playback-continuity proof. Byte counts alone cannot certify completion. Only an actual EOF without a read, downstream write, or close error can complete a known full representation.

func (RepresentationCompletion) Complete

func (c RepresentationCompletion) Complete() bool

type ResolveSource

type ResolveSource func(context.Context, string, Start) (Source, error)

type Security

type Security struct {
	Authenticate func(*http.Request) (string, error)
	Authorize    func(context.Context, string, string, Identity, *Start) error
}

Security authenticates mTLS peer identity and authorizes the complete operation. Authorize must check current placement/source authority, generation and expiry; an authenticated certificate alone does not authorize work. Called for reads too. For renew, Start is nil and ValidateRenewal separately validates its full DTO. Permit exact scoped stop/status after expiry; neither grants execution authority.

type Session

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

func (*Session) Close

func (s *Session) Close() error

func (*Session) EncoderDone

func (s *Session) EncoderDone() <-chan struct{}

func (*Session) EncoderErr

func (s *Session) EncoderErr() error

func (*Session) EncoderRetirement

func (s *Session) EncoderRetirement() core.EncoderRetirement

func (*Session) ID

func (s *Session) ID() string

func (*Session) IndependentSegments

func (s *Session) IndependentSegments() bool

The exact backend owns this session-wide claim, including every advertised rung.

func (*Session) LastAccess

func (s *Session) LastAccess() time.Time

func (*Session) Lease

func (s *Session) Lease() LeaseState

Lease reports accepted history, not proof that execution remains authorized. Inspect execution/retirement state and reconcile uncertainty independently.

func (*Session) Observe

func (s *Session) Observe(ctx context.Context) (*ObservedSession, error)

Observe performs one authenticated, authorized read of this exact generation. Failure neither changes map presence nor supplies any retirement evidence.

func (*Session) PlaybackDelivered

func (s *Session) PlaybackDelivered() bool

PlaybackDelivered reports real media writes through this remote execution.

func (*Session) PlaybackState

func (s *Session) PlaybackState(state string)

func (*Session) Reconcile

func (s *Session) Reconcile(ctx context.Context) error

Reconcile obtains proof for this exact execution after a failed/late start, disconnect or expiry. No polling goroutine or timeout manufactures proof.

func (*Session) Renew

func (s *Session) Renew(ctx context.Context, n Renewal) (LeaseState, error)

Renew is parent-driven; there are no automatic renewal/polling goroutines. Reuse the identical request after a lost response, or Reconcile then inspect Lease. Older operations after a newer acceptance return ErrUncertain; they never extend authority. A missing worker validator returns ErrUnsupported.

func (*Session) RetireEncoder

func (s *Session) RetireEncoder() error

func (*Session) RetireEncoderContext

func (s *Session) RetireEncoderContext(ctx context.Context) (resultErr error)

func (*Session) Rungs

func (s *Session) Rungs() []core.HLSRung

Rungs is the backend's bounded immutable ladder, never a synthesized rendition.

func (*Session) ServeHTTP

func (s *Session) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Session) ServeInit

func (s *Session) ServeInit(w http.ResponseWriter, r *http.Request, rep int)

func (*Session) ServeManifest

func (s *Session) ServeManifest(w http.ResponseWriter, r *http.Request)

func (*Session) ServeMedia

func (s *Session) ServeMedia(w http.ResponseWriter, r *http.Request, rep, n int)

func (*Session) ServePlaylist

func (s *Session) ServePlaylist(w http.ResponseWriter, r *http.Request)

func (*Session) ServeRungPlaylist

func (s *Session) ServeRungPlaylist(w http.ResponseWriter, r *http.Request, rung string)

func (*Session) ServeRungSegment

func (s *Session) ServeRungSegment(w http.ResponseWriter, r *http.Request, rung string, n int)

func (*Session) ServeRungSegmentObserved

func (s *Session) ServeRungSegmentObserved(w http.ResponseWriter, q *http.Request, rung string, n int) RepresentationCompletion

func (*Session) ServeSegment

func (s *Session) ServeSegment(w http.ResponseWriter, r *http.Request, n int)

func (*Session) ServeSegmentObserved

func (s *Session) ServeSegmentObserved(w http.ResponseWriter, q *http.Request, n int) RepresentationCompletion

ServeSegmentObserved has exactly the ordinary segment path and returns only after its response body is closed. It performs no retry or additional read.

func (*Session) ServeSoftSubtitle

func (s *Session) ServeSoftSubtitle(w http.ResponseWriter, r *http.Request, index int) bool

ServeSoftSubtitle attaches only to this execution's selected embedded ASS output. It never extracts via an additional URL, source reader or process.

func (*Session) StartCommitment

func (s *Session) StartCommitment() (Identity, [32]byte, error)

StartCommitment returns the identity and hash of the exact immutable marshaled Start retained before attempting the start RPC. It exposes no raw request, grant or URL. An uncertain, stopped or retired token retains this commitment. Success says nothing about sending, worker acceptance, availability, source verification or retirement. No network work or state transition occurs here.

func (*Session) SwapInput

func (*Session) Touch

func (s *Session) Touch()

Touch and PlaybackState use bounded explicit RPCs; there is no background loop. HTTP sessions support Touch but have no local PlaybackState contract.

type Source

type Source struct {
	// Gateway excludes URL/Lease. Resolver must never acquire an unused second lease.
	Gateway TrustedGatewayInput
	URL     string
	Lease   core.EncoderInputLease
}

Source is produced by trusted source-grant validation, never by a wire URL. Ordinary URL/Lease uses the existing private literal-IP HTTPS contract, with redirects/nested fetches forbidden and exact identity/expiry binding. Gateway is an exclusive trusted local capability. Interface implementations must bind identity, origin/path, and lease, and must never redirect or substitute input.

type Start

type Start struct {
	Ramp               core.HLSRamp         `json:",omitzero"`
	Resume             *core.HLSResume      `json:",omitempty"`
	RecoveryStart      *core.RecoveryStart  `json:",omitempty"`
	Keyframes          []core.KeyframePoint `json:",omitempty"`
	SoftSubtitleStream *int                 `json:",omitempty"`
	Protocol           string               `json:",omitempty"`
	ReleaseID          string
	Identity           Identity
	Grant              string
	Expires            time.Time
	Info               core.MediaInfo
	Decision           core.Decision
	Offset             time.Duration
	SegmentDuration    time.Duration
	IndependentProof   bool
}

type TerminalEvidenceSummary

type TerminalEvidenceSummary struct {
	Version                                     uint8
	Identity                                    Identity
	Origin                                      EvidenceOrigin
	StartHash                                   [32]byte
	InitialDeadline                             time.Time
	Renewable                                   bool
	LeaseVersion                                uint64
	LeaseDeadline                               time.Time
	AcceptedRenewal                             *Renewal
	EncoderProof                                TerminalProofKind
	BackendInvoked                              bool
	BackendTokenJoined, OwnedSessionTokenJoined bool
	InputProof                                  TerminalProofKind
	// Slots are the original ordinary/gateway input leases, never source-owner proof.
	InputPresent              [2]bool
	InputNilTerminal          [2]bool
	NegativeBarrierGeneration uint64
}

TerminalEvidenceSummary is immutable local proof data, not execution authority or source-owner proof. Digests commit authenticated observations; they cannot authenticate themselves. Runtime must verify the exact full durable fence and current intended worker peer independently before publishing a receipt.

func (TerminalEvidenceSummary) Digest

func (e TerminalEvidenceSummary) Digest() ([32]byte, error)

Digest produces a bounded versioned commitment, never an authenticity proof. The separate domains let a trusted receipt provider bind independently checked encoder and local-input observations without substituting a source-owner proof.

func (TerminalEvidenceSummary) EncoderDigest

func (e TerminalEvidenceSummary) EncoderDigest() ([32]byte, error)

func (TerminalEvidenceSummary) InputDigest

func (e TerminalEvidenceSummary) InputDigest() ([32]byte, error)

type TerminalProofKind

type TerminalProofKind uint8
const (
	TerminalProofUnknown TerminalProofKind = iota
	TerminalProofNilObjects
	TerminalProofNegativeBarrier
)

type TerminalSnapshot

type TerminalSnapshot struct {
	Identity Identity
	State    TerminalState
	Stopped  bool
}

TerminalSnapshot contains no grants, source data, lease extension or execution authority. This value is a detached local observation of the complete identity. It does not establish source-owner retirement or durable placement retirement.

type TerminalState

type TerminalState uint8

TerminalState is the closed set of local execution observations. Only TerminalRetired attests successful exact encoder AND local input retirement. Running/Pending/Unverified/Unknown never authorize reassignment or capacity release.

const (
	TerminalUnknown TerminalState = iota
	TerminalPending
	TerminalRunning
	TerminalRetired
	TerminalUnverified
)

func (TerminalState) String

func (s TerminalState) String() string

type TrustedGatewayInput

type TrustedGatewayInput interface {
	GatewayInput(Identity, string) (string, core.EncoderInputLease, error)
}

TrustedGatewayInput is a trusted, injected composition boundary, never a wire DTO. It must bind the exact execution and immutable grant handle to an existing loopback listener capability. Return the acquired lease even on error. Arbitrary implementations are not made safe by this interface; host composition owns trust.

type ValidateRenewal

type ValidateRenewal func(context.Context, string, Start, Renewal) (RenewalReceipt, error)

type Worker

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

func NewWorker

func NewWorker(o WorkerOptions) (*Worker, error)

func (*Worker) AcceptedStart

func (w *Worker) AcceptedStart(ctx context.Context, id Identity) (*AcceptedStartHandle, error)

AcceptedStart observes only an actual retained acceptance, including starting attempts and uncertain/blocked Start responses. Absence and negative tombstones are unknown. No authorization callback, preflight, expiry, Resolve, backend, renewal, stop, claim, arm or retirement operation is invoked here.

func (*Worker) Close

func (w *Worker) Close() error

Close stops admission and requests retirement of every exact execution. It does not claim completion; callers must reconcile pending records before exit.

func (*Worker) InspectAcceptedStart

func (w *Worker) InspectAcceptedStart(ctx context.Context, h *AcceptedStartHandle) (AcceptedStartSnapshot, error)

InspectAcceptedStart revalidates the exact Worker, handle pointer, live retained record, boot, immutable accepted hash and lease history on every call. A prior successful snapshot grants no future validity. It performs no state transition and copies all mutable data under mu without calling backend getters.

func (*Worker) ServeHTTP

func (w *Worker) ServeHTTP(out http.ResponseWriter, r *http.Request)

func (*Worker) Terminal

func (w *Worker) Terminal(ctx context.Context, id Identity, requestStop bool) (TerminalSnapshot, error)

Terminal is a HOST-ONLY exact-execution reconciliation boundary. It is not an HTTP handler and does not bypass the normal per-operation Security callbacks. The trusted host must first authenticate the peer independently and freshly authorize the exact old durable placement fence, intended worker boot and revoked/expired authority. Never call this based on caller-asserted identity, missing membership, time elapsed or worker contact loss.

requestStop seals only this exact execution using its retained owned session and inputs. It neither calls Encoder.Stop(publicID) nor starts/renews/resolves sources. Status-only absence is unknown. A stop-before-start can attest local retirement only after installing the permanent bounded tombstone and highest generation floor in this never-compacted, unique worker boot. Closed/capacity rejection cannot supply that proof. All late starts/producers remain charged.

func (*Worker) TerminalEvidence

func (w *Worker) TerminalEvidence(ctx context.Context, id Identity) (TerminalEvidenceSummary, error)

TerminalEvidence reads retained provenance only. It never stops/expires work, creates a negative barrier, issues credentials or infers proof from absence. Caller first stops the exact execution through its separately authorized host Terminal API. Cancellation, pending callbacks/producers or nonnil terminal errors produce no evidence. Ambiguous accepted starts retain their history.

type WorkerOptions

type WorkerOptions struct {
	WatchAuthority  func(string, func()) func()
	Capabilities    Capabilities    // Explicit backend contract; zero retains fixed HLS.
	ValidateRenewal ValidateRenewal // Nil explicitly disables renewal.
	Boot            string
	Capacity        int // Includes all retained tombstones; never evicts unresolved work.
	MaxLease        time.Duration
	Security        Security
	Resolve         ResolveSource
	Encoder         core.OwnedTranscoder
}

Jump to

Keyboard shortcuts

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