events

package
v0.5.21 Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2026 License: AGPL-3.0 Imports: 12 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 webhttp/sse broadcast hub. The transport (fan-out, replay ring with Last-Event-ID resume, keepalives, proxy-defensive headers, slow-client eviction) is the library's; this package owns only the subflux event vocabulary and its wire encoding.

Index

Constants

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 ReplayBudget = 256

ReplayBudget is the largest replay a resume cursor may request; a cursor further behind head answers a gap epoch instead (a refetch transaction is cheaper than a bulk replay). It is the fourth disjunct of the handler's pre-check and covers hidden-window growth and native retries alike.

View Source
const SSEReconnectDelay = 1500 * time.Millisecond

SSEReconnectDelay is the stream's advertised `retry:` field, governing the reconnect the BROWSER performs by itself after a transient drop. The app's own ladder in events.ts covers only the readyState CLOSED case, so without this the two browsers disagree and neither is reachable from here: Chrome waits 3s, Firefox 5s. It is deliberately not lower, because the spec routes a connection to a DOWN server through the same timer, and permits but does not require a user agent to back off above it.

View Source
const SSERing = 1024

SSERing is the replay-ring capacity, sized at 4x ReplayBudget so the below-floor and over-budget verdicts stay distinct and the budget can rise without a server change.

Variables

This section is empty.

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, wrapping the sse hub with subflux's resume protocol:

  • The resume cursor is the Last-Event-ID header when present (a native EventSource retry — the header wins, on recreates too); when absent, a valid ?last_id= query derives one (the client's synthetic cursor — EventSource has no header seam). Zero, malformed, or over-2^53 values mean no resume, whatever the source.
  • The pre-check computes the gap verdict against the ring bounds before subscribe; a covered cursor is handed to the hub for replay, a gapped or invalid one is STRIPPED so no partial replay can precede the verdict.
  • Exactly one `epoch` frame per connection is written via OnConnect — after any replay, before live delivery, with no id field — carrying {boot_id, gap, head} in the same {type,data} envelope Publish uses.

Admission — the client cap and the shutdown-drain refusal (both 503 with the standard webhttp error envelope) — is enforced by the sse hub atomically at subscribe time. Headers, keepalives, replay, and frame encoding are the sse 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 per-connection SSE handshake, written exactly once per connection by the events handler: after any Last-Event-ID replay, before live delivery, with NO id field (it must never become a resume cursor). BootID identifies the server process (one random id per process start), so the client can tell a restart from a reconnect. Gap is the server's authoritative replay verdict: true means the presented cursor could not be covered (above head, below the ring floor, or past the replay budget) and the replay was withheld. Head is the newest event id the connection's replay covered; every id at or below it was either replayed or predates the client's cursor.

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) *EventBus

New creates the event bus with the given concurrent-client cap (<= 0 means DefaultMaxSSEClients). The underlying hub keeps a replay ring (SSERing), so a browser that reconnects after a transient drop resumes via the standard Last-Event-ID header instead of silently missing events. The cap is enforced by the hub atomically at admission; SetMaxClients re-applies a hot-reloaded value without rebuilding the hub. The boot id is minted here, once per process start, and rides every connection's epoch handshake so clients can tell a server restart from a reconnect.

func (*EventBus) ClientCount

func (eb *EventBus) ClientCount() int

ClientCount returns the number of connected SSE clients.

func (*EventBus) Publish

func (eb *EventBus) Publish(e Event)

Publish broadcasts an event to every connected client. The wire payload is the JSON-encoded Event (type + data), sent as a NAMED SSE event (`event: <type>`) so the browser dispatches it to the matching addEventListener handler. 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) 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()

Shutdown drains the hub: every connected stream is cancelled and later connection attempts are refused with 503, so graceful shutdown is not held open by long-lived SSE requests. No-op when the bus is nil.

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"      // per-connection handshake (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 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 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 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.

Jump to

Keyboard shortcuts

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