Documentation
¶
Overview ¶
Package events owns the in-process Server-Sent Events hub for the mock's GET /events endpoint. The hub fans out events posted via POST /admin0/events to every connected subscriber whose event_type filter matches, backed by a bounded ring buffer that lets dropped subscribers resume via Last-Event-ID / ?from / ?from_timestamp.
The package wraps github.com/tmaxmax/go-sse: sse.Server is the HTTP handler, sse.Joe is the in-memory pub/sub provider, and recordingReplayer (this package) owns the buffer itself, adding the (id, timestamp) index that resolves ?from_timestamp against the library's Last-Event-ID-driven Replay path — and answering the one case that has no cursor, an instant predating every buffered event, with the whole buffer instead.
Index ¶
- Constants
- func SetKeepAliveIntervalForTest(t interface{ ... }, d time.Duration)
- type Event
- type Hub
- func (h *Hub) ActiveSubscribers() int
- func (h *Hub) ExpireAll() int
- func (h *Hub) ExpireBefore(cursor string) (dropped int, found bool)
- func (h *Hub) Handler() http.Handler
- func (h *Hub) Publish(evt Event) error
- func (h *Hub) Reset(ctx context.Context) error
- func (h *Hub) Shutdown(ctx context.Context) error
- func (h *Hub) TotalSubscribers() int
- type HubOption
Constants ¶
const DefaultKeepAliveInterval = 15 * time.Second
DefaultKeepAliveInterval is the cadence at which a `:keep-alive` comment is broadcast to every connected subscriber. 15s matches what most SSE deployments use; the library doesn't auto-emit.
const DefaultReconnectHint = 3 * time.Second
DefaultReconnectHint is the value sent in the SSE `retry:` field on connect, telling clients how long to wait before reconnecting after a disconnect (Auth0's Events API sends one too). A value <= 0 omits the hint, so clients fall back to their built-in default.
Variables ¶
This section is empty.
Functions ¶
func SetKeepAliveIntervalForTest ¶
SetKeepAliveIntervalForTest changes the keep-alive cadence for the duration of a single test. Registers t.Cleanup to restore the original value, so tests can't accidentally bleed configuration between cases. Intended for use only from _test.go files.
The new cadence only affects Hub instances constructed AFTER the call: runKeepAlive captures the duration in its time.Ticker at hub startup, so changing it later doesn't retro-actively shorten an already-running ticker. Build the hub inside the test (or right after SetKeepAliveIntervalForTest) to apply the override.
Types ¶
type Event ¶
type Event struct {
Type string
ID string
Payload json.RawMessage
}
Event is the wire shape the control plane pushes into the hub. Type is the CloudEvent discriminator (e.g. "user.created") and drives the SSE `event:` field. ID is the SSE `id:` field — the offset cursor a consumer resumes from; when empty the message is delivered live but never stored for replay (error control frames). Payload is the raw JSON body streamed in the SSE `data:` field — it MUST include the same `type` value (the OpenAPI schema requires it as the oneOf discriminator), but this type doesn't enforce that; the /admin0/events handler validates against the schema before calling Hub.Publish.
type Hub ¶
type Hub struct {
// contains filtered or unexported fields
}
Hub is the SSE fan-out the mock owns. One Hub per process; the HTTP handler at GET /events is hub.Handler(), and POST /admin0/events pushes via hub.Publish. Hub is safe for concurrent use; every underlying primitive (sse.Server, sse.Joe, recordingReplayer) is.
Lifecycle:
- NewHub starts a keep-alive goroutine.
- Reset drains current subscribers and rebuilds the underlying server + replay buffer, so /admin0/reset between tests is non-destructive to the hub itself.
- Shutdown drains every subscriber permanently and stops the keep-alive goroutine; intended for process shutdown.
func NewHub ¶
NewHub constructs a Hub. BufferSize is the cap of the replay buffer (used for resume via Last-Event-ID / ?from / ?from_timestamp); values <= 0 disable replay entirely (sse.Joe accepts a nil Replayer). Now is the clock the replayer's timestamp index uses; nil falls back to time.Now. The caller should wire this to internal/clock.Clock.Now when a controllable clock is present so ?from_timestamp behaves deterministically in clock-controlled tests. Opts customise the hub — e.g. WithReconnectHint sets the SSE retry: value sent on connect.
func (*Hub) ActiveSubscribers ¶ added in v0.229.0
ActiveSubscribers reports how many subscribers are connected to GET /events right now. A subscriber leaves the active set only when the server's read loop notices its connection closed, so a reading taken immediately after a client disconnects may briefly lag.
func (*Hub) ExpireAll ¶ added in v0.232.0
ExpireAll ages out every buffered resume cursor and reports how many it dropped. Returns 0 when replay is disabled.
This is the deterministic way to provoke the aged-out path: a subscriber that later resumes from an expired cursor gets 410 Gone / event_aged_out, without having to push past the buffer's capacity or reset the whole mock. Unlike Reset it touches nothing else — live subscribers keep streaming, the server is not rebuilt, and counters are left alone.
Both this and ExpireBefore hold mu across the call, the way Publish does, so the expiry and the replayer it reads are not torn apart by a concurrent Reset swapping the buffer in between. Neither can stop a Reset that lands immediately afterwards from discarding what was just expired; the count is only ever true as of the moment it was taken.
Holding mu costs nothing extra: the replayer's own write lock is held only for the truncation, because Replay writes to its subscriber unlocked. It is NOT a guarantee that an expiry can never block — a subscriber that stops reading stalls Joe, which leaves Publish holding mu.RLock, and a Reset queued behind it then blocks every later RLock including this one. That hazard predates expiry and is shared with the keep-alive and the handler's aged-out lookup.
Both report 0 on a closed hub rather than erroring as Publish does: nothing was expired, and the hub only reaches that state during shutdown. ExpireBefore additionally reports the cursor as not found there and when replay is disabled, which is literally true — there is no buffer holding it — and gives the endpoint a 404 to answer with instead of a success that expired nothing.
func (*Hub) ExpireBefore ¶ added in v0.232.0
ExpireBefore ages out every cursor older than cursor, leaving cursor itself — and everything after it — resumable. It reports how many it dropped and whether the buffer held cursor at all; a cursor it doesn't hold drops nothing. Found is false when replay is disabled.
Repeating the call is therefore safe but not silent: the second one drops 0 and reports found, because cursor is still buffered — it is the boundary, not one of the casualties. It only stops being found once something else evicts it.
An empty cursor drops nothing rather than falling through to expire-everything: ExpireAll is how you say that, all the way down to the buffer, so no caller can widen the blast radius by passing through an unset value.
func (*Hub) Handler ¶
Handler returns the HTTP handler for GET /events. Wire it under bearer middleware at mount time.
The handler:
- Disables the http.Server WriteTimeout for this connection (SSE is long-lived; the server default would tear down healthy subscribers after the configured timeout).
- Parses the query string strictly. A string that will not unescape is 400 invalid_query rather than a 200 that silently dropped the pair it choked on — Go's parser keeps the pairs it managed and discards both the error and the bad pair, so a lost ?from would join live instead of 410-ing and a lost ?event_type would turn a filtered subscription into a firehose.
- Refuses the resume shapes that parse cleanly and then mean something the caller did not ask for, each with its own code: an empty (or whitespace-only) ?from, ?from_timestamp, ?event_type or Last-Event-ID is 400 invalid_from / invalid_from_timestamp / invalid_event_type / invalid_last_event_id, because present-but-empty is a different request from omitted; a repeated ?from or ?from_timestamp is 400 invalid_query, since a cursor can only name one position. Repeating ?event_type stays legal — that is how a caller asks for several types. Unknown parameters are ignored, as the real Auth0 API ignores them.
- Promotes Auth0's ?from and ?from_timestamp query parameters to the SSE-spec Last-Event-ID header so the replay buffer resolves them on the normal resume path. ?from wins over ?from_timestamp, and an explicit Last-Event-ID wins over both — but all three are validated first, so a malformed ?from_timestamp is rejected even when a winning ?from means it would never be read. A ?from_timestamp that predates every buffered event is the one case with no cursor to promote to — replay runs strictly after a cursor, and none means "before the oldest" — so it asks for the whole buffer instead; see replayAllTopic. ?from_timestamp accepts RFC 3339; clients that send the timezone `+` unencoded (which URL-decodes to space) are tolerated by retrying with the space restored.
- Surfaces aged-out resume requests as 410 Gone (matching the OpenAPI declaration). Every 400 above uses the standard mgmt error envelope.
- Pre-flushes the SSE response headers so http.Client.Do returns immediately rather than waiting for the first event.
- Tracks the request context in the active set so Reset / Shutdown can drain in-flight subscribers cleanly.
- Delegates to the underlying *sse.Server. The topic list is derived here, from the query string this handler already parsed and validated, and handed to the OnSession callback on the request context — so the values that were validated and the values that are subscribed to cannot be two different things.
func (*Hub) Publish ¶
Publish broadcasts evt to every subscriber whose topic set intersects. A regular event is sent to broadcastTopic (reaches every filterless subscriber) and to evt.Type (reaches every filtered subscriber that listed this type). Error frames and offset-only progress markers are stream-wide control signals routed to the every-subscriber topic — see the branches below. Keep-alives use a separate topic and never go through this method.
The RLock is held across server.Publish so a concurrent Reset can't swap h.server underneath an in-flight publish and produce a spurious "provider is closed" error.
func (*Hub) Reset ¶
Reset swaps in a fresh server + replay buffer (so any concurrent Publish atomically moves to the new instance), drains the subscribers that were attached to the old server, then shuts the old server down — all while the new server is already serving new subscribers and publishes. The swap-before-shutdown ordering is what closes the Publish/Reset race: a publisher that grabbed the RLock immediately before Reset's mu.Lock acquired sees the OLD server (and Reset's Lock blocks until the publish completes because Publish holds RLock across the call); every publisher after that sees the NEW server. The OLD server is then shut down with no concurrent publish in flight.
Intended for the /admin0/reset control-plane hook between tests. Idempotent under concurrent callers (serialised via lifecycleMu).
func (*Hub) Shutdown ¶
Shutdown drains every subscriber, stops the keep-alive goroutine, and marks the hub closed permanently. Intended for process shutdown. Idempotent — extra calls are no-ops.
Uses the same swap-before-shutdown ordering as Reset to keep in-flight publishers race-free: the swap to a nil server happens atomically under mu.Lock, then the old server is shut down with no lock held.
func (*Hub) TotalSubscribers ¶ added in v0.229.0
TotalSubscribers reports how many subscriptions have connected since the hub was created or last Reset. It increments on every connect and never decrements within a window; Reset zeroes it.
type HubOption ¶ added in v0.230.0
type HubOption func(*Hub)
HubOption customises a Hub at construction.
func WithReconnectHint ¶ added in v0.230.0
WithReconnectHint sets the SSE `retry:` reconnect-delay hint sent on connect; <= 0 omits it. Wire it to the EVENTS_RECONNECT_HINT config. Defaults to DefaultReconnectHint when unset.