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
- func Handle(bus *EventBus, w http.ResponseWriter, r *http.Request)
- type ActivityEvent
- type ActivityOp
- type ActivityPublisher
- type AlertEvent
- type AlertOp
- type CoverageEvent
- type EpochEvent
- type Event
- type EventBus
- func (eb *EventBus) ClientCount() int
- func (eb *EventBus) DigestHandler() http.Handler
- func (eb *EventBus) Presence() *Presence
- func (eb *EventBus) Publish(e Event)
- func (eb *EventBus) PublishAlert(op AlertOp, a *activity.Alert)
- func (eb *EventBus) PublishCoverageUpdate(ev *CoverageEvent)
- func (eb *EventBus) PublishNotify(level NotifyLevel, text string)
- func (eb *EventBus) PublishProvider(ev *ProviderEvent)
- func (eb *EventBus) PublishScanDone(ev *ScanEvent)
- func (eb *EventBus) PublishScanStart(ev *ScanEvent)
- func (eb *EventBus) PublishSyncDone(ev *SyncDoneEvent)
- func (eb *EventBus) SampleGauges()
- func (eb *EventBus) SetMaxClients(n int)
- func (eb *EventBus) Shutdown(ctx context.Context) error
- func (eb *EventBus) Versions() *Versions
- type EventData
- type EventType
- type Metrics
- type NotifyEvent
- type NotifyLevel
- type Presence
- type ProviderEvent
- type ProviderOp
- type ProviderTimeoutEntry
- type ScanEvent
- type Stamp
- type SyncDoneEvent
- type Versions
Constants ¶
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.
const DefaultMaxSSEClients = 32
DefaultMaxSSEClients is the upper bound on concurrent SSE connections when no config is loaded or the configured value is zero.
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. 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"
)
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
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.
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 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 ¶
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 ¶
ClientCount returns the number of connected SSE clients.
func (*EventBus) DigestHandler ¶ added in v0.5.39
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
Presence is the per-tag presence table the alive route and the prune ticker drive.
func (*EventBus) Publish ¶
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
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(ev *ProviderEvent)
PublishProvider publishes a provider status delta. The event is dereferenced into the payload and never retained.
func (*EventBus) PublishScanDone ¶ added in v0.4.0
PublishScanDone publishes scan:done with the scan's four-valued terminal outcome (see ScanEvent.Outcome).
func (*EventBus) PublishScanStart ¶ added in v0.4.0
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
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
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.
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 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" )
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
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.
type ProviderEvent ¶ added in v0.5.0
type ProviderEvent struct {
Entry *ProviderTimeoutEntry `json:"entry,omitempty"`
Op ProviderOp `json:"op"`
TimeoutsEnabled bool `json:"timeouts_enabled"`
}
ProviderEvent is the data payload for provider status deltas. Entry carries the provider's full merged status at publish time (health tracker and credential gate together), so a later event never erases an earlier one's half. TimeoutsEnabled mirrors ProvidersResponse.Enabled. 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 became uncallable (raise: timed out, disabled, paused, or a setting rejected) or callable again (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 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.