events

package
v0.6.2 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2026 License: AGPL-3.0 Imports: 15 Imported by: 0

Documentation

Overview

Package events is subflux's typed server-sent-events layer: the sealed Event/EventData types the app publishes, marshaled onto the shared cplieger/sse broadcast hub. The transport (fan-out, replay ring with Last-Event-ID resume, the hello handshake and its verdict, keepalives, proxy-defensive headers, slow-client eviction, the state digest) is the library's; this package owns the subflux event vocabulary, its wire encoding, and the subject versions the digest compares.

Index

Constants

View Source
const (
	SubjectSeries    = "series"    // ref "": GET /api/coverage/series
	SubjectMovies    = "movies"    // ref "": GET /api/coverage/movies
	SubjectDetail    = "detail"    // ref tvdb-N | tmdb-N: the per-root detail GETs
	SubjectHistory   = "history"   // ref "": GET /api/state
	SubjectActivity  = "activity"  // ref "": GET /api/activity
	SubjectAlerts    = "alerts"    // ref "": GET /api/alerts
	SubjectProviders = "providers" // ref "": GET /api/providers/timeout
	SubjectJobs      = "jobs"      // ref "": GET /api/sync/jobs
)

The digest subject kinds. One writer mints each: Publish for the seven event-fed kinds (switching on the event type), the sync-job registry for jobs. A client holds a version per (kind, ref) it read from a stamped GET and asks the digest which ones moved.

View Source
const ActivityEventMinInterval = 1000 * time.Millisecond

ActivityEventMinInterval is the per-activity coalesce window for non-terminal activity upserts (the spec's ACTIVITY_EVENT_MIN_MS): a progress burst publishes at most one event per activity per window, last snapshot wins. Terminal transitions bypass it.

View Source
const DefaultMaxSSEClients = 32

DefaultMaxSSEClients is the upper bound on concurrent SSE connections when no config is loaded or the configured value is zero.

View Source
const ReplyMaxEvents = 256

ReplyMaxEvents is the largest replay one reconnect may receive (sse.WithReplyMaxEvents); a cursor further behind head earns gap_budget and the client reconciles through the digest, which is cheaper than a bulk replay.

View Source
const SSEReconnectDelay = 1500 * time.Millisecond

SSEReconnectDelay is the stream's advertised `retry:` field: the reconnect wait a legacy EventSource performs by itself after a transient drop and the floor of the v3 client's post-EOF backoff. Without it Chrome waits 3s and Firefox 5s; it is deliberately not lower because the spec routes a connection to a DOWN server through the same timer.

View Source
const SSEReplayTTL = 10 * time.Minute

SSEReplayTTL is the longest a ring entry may be replayed after it was published (sse.WithReplayTTL).

View Source
const SSERing = 1024

SSERing is the replay-ring capacity in events (sse.WithReplay).

Variables

View Source
var ErrUnknownSubject = errors.New("events: unknown digest subject")

ErrUnknownSubject is returned by Resolve for a held key outside the registry (an unknown kind, a non-empty ref on a ref-less kind, or a detail ref that is not a root); the digest answers must_refetch.

Functions

func Handle added in v0.4.0

func Handle(bus *EventBus, w http.ResponseWriter, r *http.Request)

Handle streams server-sent events to the browser. The SSE-Wire header decides the overlap: a connection without it is a pre-v3 EventSource and receives the legacy `epoch` frame built from the hello, after the replay and before live delivery, with no id. The SSE-Client header is handed to the hub raw, absent or not; the library owns its grammar and reads the empty string as no tag. Cursor parsing, the verdict, replay, admission (503 over the cap or after shutdown), headers, keepalives and frame encoding are the library's.

Types

type ActivityEvent added in v0.5.0

type ActivityEvent struct {
	Entry *activity.Entry `json:"entry,omitempty"`
	Op    ActivityOp      `json:"op"`
}

ActivityEvent is the data payload for activity log deltas (E1). Upserts carry the post-mutation entry snapshot; removes carry the entry as it was when it left the log, on every removal path (dismiss, prune, cap eviction). Terminal transitions are published immediately; non-terminal progress coalesces per activity (see ActivityPublisher).

type ActivityOp added in v0.5.0

type ActivityOp string

ActivityOp discriminates an activity event: an entry changed or appeared (upsert) or left the log (remove).

const (
	ActivityUpsert ActivityOp = "upsert"
	ActivityRemove ActivityOp = "remove"
)

Activity event operations.

type ActivityPublisher added in v0.5.0

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

ActivityPublisher turns the activity log's hook stream into activity SSE events. Non-terminal upserts coalesce per activity on a trailing window (ActivityEventMinInterval, last snapshot wins). A terminal upsert (the entry's Done transition) publishes IMMEDIATELY behind a flush barrier: any pending window timer is cancelled and its queued snapshot discarded, so no stale progress snapshot can follow the terminal state onto the wire — a non-terminal hook that lost the race to the terminal one is dropped for the same reason. A remove publishes immediately, clears the activity's coalescer state, and is FINAL: no upsert for that id is ever published again.

Safe for concurrent use; publishes are serialized under the internal mutex, so no two events interleave. Wire order is NOT the log's decision order and cannot be: the log fires its hooks after releasing its own lock, so two mutators of one entry (a terminal End and a Dismiss) can reach this publisher in either order. What is guaranteed per activity is that both finalities hold whichever way that race lands — nothing follows a remove, and no non-terminal snapshot follows a terminal one.

func NewActivityPublisher added in v0.5.0

func NewActivityPublisher(publish func(Event)) *ActivityPublisher

NewActivityPublisher returns a publisher feeding events into publish (normally EventBus.Publish), coalescing at ActivityEventMinInterval.

func (*ActivityPublisher) Remove added in v0.5.0

func (p *ActivityPublisher) Remove(e *activity.Entry)

Remove observes one removal snapshot (the Log's OnRemove hook, adapted by the server): the activity's coalescer state is dropped, the id is tombstoned so no later upsert can resurrect the row, and the remove is published at once.

func (*ActivityPublisher) Upsert added in v0.5.0

func (p *ActivityPublisher) Upsert(e *activity.Entry)

Upsert observes one post-mutation entry snapshot (the Log's OnUpsert hook, adapted by the server). By pointer to keep the entry off the argument copy; the pointee is the hook's own snapshot and may be retained as the queued last-wins candidate.

type AlertEvent added in v0.5.0

type AlertEvent struct {
	Alert *activity.Alert `json:"alert,omitempty"`
	Op    AlertOp         `json:"op"`
}

AlertEvent is the data payload for alert deltas (E1): a raise carries the alert as recorded (a persistent re-raise carries the refreshed snapshot), a dismiss carries the dismissed alert so the client can drop it by id.

type AlertOp added in v0.5.0

type AlertOp string

AlertOp discriminates an alert event: raised (new or refreshed) or dismissed. TTL expiry publishes nothing — the client's reconcile poll owns it, matching the lazy expiry in AlertLog.VisibleAlerts.

const (
	AlertRaise   AlertOp = "raise"
	AlertDismiss AlertOp = "dismiss"
)

Alert event operations.

type CoverageEvent

type CoverageEvent struct {
	MediaType subflux.MediaType `json:"media_type"`
	MediaID   string            `json:"media_id"`
	Language  string            `json:"language"`
	Variant   string            `json:"variant"`
	Source    string            `json:"source"`
}

CoverageEvent is the data payload for coverage updates. It deliberately carries no file path (S7: no filesystem paths on the wire; the UI keys refreshes on media identity alone).

type EpochEvent added in v0.5.0

type EpochEvent struct {
	BootID string `json:"boot_id"`
	Head   uint64 `json:"head"`
	Gap    bool   `json:"gap"`
}

EpochEvent is the legacy per-connection SSE handshake, built from the library's hello and written exactly once, only to a connection that presented no SSE-Wire header (a pre-v3 EventSource bundle): after any replay, before live delivery, with NO id field (it must never become a resume cursor). BootID is the hub epoch, so the client can tell a restart from a reconnect. Gap is the inverse of the hello's resumed: true means the presented cursor could not be covered and the replay was withheld. Head is the hub head at subscribe.

type Event

type Event struct {
	Data EventData `json:"data,omitempty"`
	Type EventType `json:"type"`
}

Event is a server-sent event pushed to connected browsers.

type EventBus

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

EventBus publishes subflux's typed events to connected SSE clients. A nil *EventBus is safe to publish to (no-op), so optional wiring needs no guards.

func New

func New(maxClients int, m Metrics) *EventBus

New creates the event bus with the given concurrent-client cap (<= 0 means DefaultMaxSSEClients) and metrics sink (nil records nothing). Every hub option is a package constant, so a refused option set is a defect fixed here rather than an error a caller could handle, which is what licenses MustNew outside main.

func (*EventBus) ClientCount

func (eb *EventBus) ClientCount() int

ClientCount returns the number of connected SSE clients.

func (*EventBus) DigestHandler added in v0.5.39

func (eb *EventBus) DigestHandler() http.Handler

DigestHandler is the library's state digest over this bus's version table. Mount it inside the authentication and cross-origin middleware, under a route timeout (it does not stream).

func (*EventBus) Presence added in v0.5.39

func (eb *EventBus) Presence() *Presence

Presence is the per-tag presence table the alive route and the prune ticker drive.

func (*EventBus) Publish

func (eb *EventBus) Publish(e Event)

Publish mints the subject versions the event moved and broadcasts it to every connected client. The wire payload is the JSON-encoded Event (type + data), sent as a NAMED SSE event (`event: <type>`), the key the client's frame table decodes by. No-op when the bus is nil.

func (*EventBus) PublishAlert added in v0.5.0

func (eb *EventBus) PublishAlert(op AlertOp, a *activity.Alert)

PublishAlert publishes an alert delta: raised (new or refreshed) or dismissed. The alert is the under-lock snapshot the AlertLog hook carried; it is dereferenced into the payload and never retained.

func (*EventBus) PublishCoverageUpdate added in v0.4.0

func (eb *EventBus) PublishCoverageUpdate(ev *CoverageEvent)

PublishCoverageUpdate publishes a coverage-update event: a subtitle file appeared or disappeared for a media item, so the UI refreshes that row. Callers that know only the media identity (the scan engine) leave the language/source fields zero; the manual download/clear-lock path fills them. The payload is a STRUCT rather than positional arguments because it serves both call shapes with one signature. By pointer only to keep the 80-byte payload off the argument copy; it is dereferenced immediately and never retained.

func (*EventBus) PublishNotify added in v0.4.0

func (eb *EventBus) PublishNotify(level NotifyLevel, text string)

PublishNotify publishes a user-facing toast notification at the given severity. It keeps positional arguments because the two are different types, so a transposition does not compile.

func (*EventBus) PublishProvider added in v0.5.0

func (eb *EventBus) PublishProvider(op ProviderOp, entry *ProviderTimeoutEntry)

PublishProvider publishes a provider timeout delta: raise when a provider trips into cooldown, clear when it leaves it.

func (*EventBus) PublishScanDone added in v0.4.0

func (eb *EventBus) PublishScanDone(ev *ScanEvent)

PublishScanDone publishes scan:done with the scan's four-valued terminal outcome (see ScanEvent.Outcome).

func (*EventBus) PublishScanStart added in v0.4.0

func (eb *EventBus) PublishScanStart(ev *ScanEvent)

PublishScanStart publishes scan:start for a scan activity that has just been accepted. Outcome is meaningless here and is ignored if set.

func (*EventBus) PublishSyncDone added in v0.5.0

func (eb *EventBus) PublishSyncDone(ev *SyncDoneEvent)

PublishSyncDone publishes one sync job's terminal result. The event is dereferenced into the payload and never retained.

func (*EventBus) SampleGauges added in v0.5.39

func (eb *EventBus) SampleGauges()

SampleGauges records the three hub gauges (clients, queued frames, head) into the metrics sink. Driven by the server's prune ticker; the client gauge also moves on every presence event.

func (*EventBus) SetMaxClients added in v0.1.134

func (eb *EventBus) SetMaxClients(n int)

SetMaxClients applies a new client cap (<= 0 means DefaultMaxSSEClients) to the running hub — used by config hot reload. Existing connections above a lowered cap are not evicted. No-op when the bus is nil.

func (*EventBus) Shutdown added in v0.1.134

func (eb *EventBus) Shutdown(ctx context.Context) error

Shutdown drains the hub: every connected stream is sent sse:reset and waited for, and later connection attempts are refused with 503, so graceful shutdown is not held open by long-lived SSE requests. Returns ctx.Err() when the drain outlives ctx. No-op when the bus is nil.

func (*EventBus) Versions added in v0.5.39

func (eb *EventBus) Versions() *Versions

Versions is the digest's version table: Publish mints the event-fed subjects into it, the sync-job registry mints jobs, and the stamp middleware and the digest resolver read it.

type EventData

type EventData interface {
	// contains filtered or unexported methods
}

EventData is a sealed interface restricting Event.Data to known payload types. Implementors: CoverageEvent, NotifyEvent, ScanEvent, EpochEvent, ActivityEvent, AlertEvent, ProviderEvent, SyncDoneEvent.

The wiregen directive below emits the TS union (export type EventData = CoverageEvent | NotifyEvent | ... | SyncDoneEvent) plus its runtime decoders; the discriminator is the SSE envelope's "type" key (Event.Type), which is also the named SSE event the browser dispatches on.

type EventType

type EventType string

EventType is a typed string for server-sent event types.

const (
	CoverageUpdate EventType = "coverage"   // subtitle file added/removed
	Notify         EventType = "notify"     // toast notification for the UI
	ScanStart      EventType = "scan:start" // scan activity started (any scope)
	ScanDone       EventType = "scan:done"  // scan activity finished (succeeded or failed)
	Epoch          EventType = "epoch"      // legacy per-connection handshake, written only without SSE-Wire (never replayed, no id)
	ActivityDelta  EventType = "activity"   // activity log delta (upsert/remove)
	AlertDelta     EventType = "alert"      // alert raised or dismissed
	ProviderDelta  EventType = "provider"   // provider timeout raised or cleared
	SyncDone       EventType = "sync:done"  // one sync job's terminal result
)

Event type constants.

type Metrics added in v0.5.39

type Metrics interface {
	RecordSSEConnect(verdict string, legacy bool)
	RecordSSEDisconnect(cause string)
	RecordSSEPresenceTransition(kind string)
	SetSSEClients(n int)
	SetSSEQueuedFrames(n int)
	SetSSEHead(n uint64)
}

Metrics is the observability sink the bus records into: one counter per hello verdict split by the legacy overlap, one per presence departure cause, one per presence-table transition, and the three hub gauges. *obs.Metrics satisfies it; nil at construction records nothing.

type NotifyEvent

type NotifyEvent struct {
	Level NotifyLevel `json:"level"`
	Text  string      `json:"text"`
}

NotifyEvent is the data payload for toast notifications pushed to the UI.

type NotifyLevel

type NotifyLevel string

NotifyLevel is a typed string for notification severity.

const (
	NotifyError   NotifyLevel = "error"
	NotifySuccess NotifyLevel = "success"
	NotifyInfo    NotifyLevel = "info"
)

Notification level constants.

type Presence added in v0.5.39

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

Presence folds the hub's connect/disconnect feed with the client's keepalive acknowledgements (POST /api/events/alive) per SSE-Client tag. Nothing reads it back; its two transition counters are the deliverable: alive (the first acknowledgement after a connect or after an expiry) and expired (a still-connected tag whose acknowledgement is older than aliveWindow, the count of how often the socket-only view was wrong). Safe for concurrent use.

func (*Presence) Alive added in v0.5.39

func (p *Presence) Alive(tag string, now time.Time)

Alive records one acknowledged keepalive for tag at now. Only the hub's connected event mints a row, so an acknowledgement for a tag no socket has presented to this process records nothing (aliveWindow states the bound that buys). The caller has already validated the tag.

func (*Presence) Sweep added in v0.5.39

func (p *Presence) Sweep(now time.Time)

Sweep drops rows with no socket whose last acknowledgement is older than aliveWindow and counts one expired transition for a connected row that crossed the window since the last sweep. Driven by the server's prune ticker.

type ProviderEvent added in v0.5.0

type ProviderEvent struct {
	Entry *ProviderTimeoutEntry `json:"entry,omitempty"`
	Op    ProviderOp            `json:"op"`
}

ProviderEvent is the data payload for provider timeout deltas (E1): raise when a provider trips into cooldown (Status carries the trip snapshot), clear when it leaves it — expiry observed, success reset, or operator reset. A cooldown nobody asks about expires silently; the client's reconcile poll converges that case.

type ProviderOp added in v0.5.0

type ProviderOp string

ProviderOp discriminates a provider event: a provider tripped into timeout cooldown (raise) or left it (clear).

const (
	ProviderRaise ProviderOp = "raise"
	ProviderClear ProviderOp = "clear"
)

Provider event operations.

type ProviderTimeoutEntry added in v0.5.0

type ProviderTimeoutEntry struct {
	Provider subflux.ProviderID     `json:"provider"`
	Status   subflux.ProviderStatus `json:"status"`
}

ProviderTimeoutEntry pairs a provider with its timeout status, the same per-provider shape GET /api/providers/timeout serves in ProvidersResponse.

type ScanEvent

type ScanEvent struct {
	Action     string           `json:"action"`
	Detail     string           `json:"detail"`
	Source     activity.Source  `json:"source"`
	ActivityID string           `json:"activity_id,omitempty"`
	Outcome    activity.Outcome `json:"outcome,omitempty"`
}

ScanEvent is the data payload for scan:start and scan:done. Action and Detail mirror the activity log entry (e.g. "Full Scan" / "Searching library for missing subtitles"). Source is "scheduled" or "manual". ActivityID correlates the event with its activity entry. Outcome is meaningful only on scan:done and carries the four-valued terminal outcome (completed | failed | cancelled | shutdown) — a cancelled scan is neither a success nor a failure.

type Stamp added in v0.5.39

type Stamp struct {
	Kind    string `json:"kind"`
	Ref     string `json:"ref"`
	Version string `json:"version"`
	Epoch   string `json:"epoch"`
}

Stamp is the subject version a stamped GET carries in its Subject-Stamp response header, JSON-encoded: the version the counter held when the request was admitted and the epoch it was minted under. A client observes it into its version map after applying the payload.

type SyncDoneEvent added in v0.5.0

type SyncDoneEvent struct {
	BatchActivityID string             `json:"batch_activity_id,omitempty"`
	Method          string             `json:"method,omitempty"`
	Error           string             `json:"error,omitempty"`
	Outcome         subflux.JobOutcome `json:"outcome"`
	FileRef         resolve.FileRef    `json:"file_ref"`
	JobID           int64              `json:"job_id"`
	OffsetMs        int64              `json:"offset_ms"`
	Confidence      float64            `json:"confidence"`
	Applied         bool               `json:"applied"`
	DryRun          bool               `json:"dry_run"`
}

SyncDoneEvent is the data payload for sync:done (D1): one sync job's terminal result, published when the job's worker ran (a queued cancellation publishes nothing). JobID is the dialog's correlation key — the 202 handed it over, and replay is idempotent per job_id. OffsetMs is the CUMULATIVE offset (stored plus this run's correction). Outcome is the registry's own typed verdict, always set (the event exists only for a settled job): it is what tells a stopped job from a crashed one, which Error cannot — both carry one.

type Versions added in v0.5.39

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

Versions is the per-subject version table the digest compares against. Counters live in process memory and restart from zero with the epoch: a restart clears every client's map, so no persistence is needed. Safe for concurrent use.

func (*Versions) Bump added in v0.5.39

func (v *Versions) Bump(kind, ref string)

Bump advances the subject's version by one.

func (*Versions) Current added in v0.5.39

func (v *Versions) Current(kind, ref string) string

Current returns the subject's version as the decimal string the wire carries; "0" for a subject never bumped, which is also what a client that read a stamp before the first bump holds.

func (*Versions) Resolve added in v0.5.39

func (v *Versions) Resolve(_ context.Context, held []sse.Held) ([]sse.State, error)

Resolve is the sse.Resolver over this table: one current State per held subject, in order, or ErrUnknownSubject for a key outside the registry. It takes no I/O lock, so a vanished detail root is never reported gone here; its refetch answers 404 and the client already treats that as gone.

func (*Versions) Stamp added in v0.5.39

func (v *Versions) Stamp(kind, ref string) (Stamp, bool)

Stamp returns the subject's current stamp, or false for a (kind, ref) outside the registry, which is then served unstamped.

Jump to

Keyboard shortcuts

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