Repository navigation
feat: live inbox updates over SSE - #4
Merged
Merged
Conversation
go-redis ignores context deadlines on socket I/O unless ContextTimeoutEnabled is set, so a stalled Redis held each publish for ReadTimeout (3s) instead of publishTimeout (500ms). The publisher now owns a client with it enabled.
Clearing the write deadline let a client that stops reading hold its goroutine and one of its 32 stream slots until the OS dropped the connection. Each frame now gets a 10s write deadline.
A stream outlived token revocation and preference changes because tickets are checked only when the stream opens. Expiry forces a new ticket; 15m matches the OAuth introspection cache, and up to 20% jitter keeps streams opened together from expiring together.
tenants_listenbrainz_in_app_retention_days (default 30) and tenants_listenbrainz_stream_origins (comma-separated, default https://listenbrainz.org) can now differ per environment.
The browser already holds the user's MusicBrainz token, so a ticket protected nothing. Stream routes now run CORS then the OAuth middleware, so a 401 or 503 is readable by an allowed page, and answer the preflight that the Authorization header triggers.
Streams authenticate with the OAuth token, so the ticket store, the stream-ticket route and their tests have no caller.
The 200-then-close and retry field existed for EventSource, which stops on any non-200. fetch clients read every status, so Redis, hub and preference failures now return 503 and the client owns its backoff.
Ticket minting went through the Surface B limiter; token-authenticated streams skipped it, so a client stuck in a reconnect loop could open streams at network speed, each costing an introspection and a user upsert. Stream routes now run the same per-user limiter after auth.
A token was cached until it expired, so a revoked token kept working on /v1/me and the streams for its whole remaining life. The cache now holds it for at most 15 minutes, as the docs already said.
An unknown tenant has no origins of its own, so the 404 carried no Access-Control-Allow-Origin and the page saw a network error. It now allows any tenant's origins, like the global stream.
Stop on 403/404 instead of retrying forever, arm the watchdog before fetch so a hung connect is retried, return a stop function for logout and unmount, and accept CRLF event endings.
With 2,000 open streams, go-redis v9's default RESP3 lost a large share of messages on the hub's shared pub/sub connection while subscribes were being written (325-930 of 2,000 streams missed their nudge in TestStreamDeliversToManyStreams). The hub now opens its own RESP2 client; the shared client is unchanged.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds live updates to the in-app inbox (#3). When a user's inbox changes, Synapse pushes a nudge over Server-Sent Events to their open tabs, and the page refetches the unread count through the existing routes. Before this, a client only saw new notifications when it polled.
A nudge carries no notification content and no counts:
{"kind": "created" | "changed", "tenant": "…"}. The API stays the only source of truth, so a nudge that is dropped or merged costs nothing, because the next refetch is correct.Architecture: what changes
Publishing is added after the existing commits. Delivery to browsers goes through Redis pub/sub and a hub in each API instance. New parts are green.
flowchart TB subgraph W["Writes (existing)"] direction TB ING["ingest consumer / POST /v1/events<br/>fan-out transaction"] MUT["/v1/me/.../notifications<br/>read, read-all, dismiss"] end PUB["NEW: live.Publisher<br/>after commit, best effort, 500 ms budget<br/>created per (user, tenant) / changed per tenant"] ING -- commit --> PUB MUT -- commit --> PUB R[["NEW: Redis pub/sub<br/>channel synapse:inbox:{user_id}"]] PUB -- PUBLISH --> R subgraph API["Each API instance"] direction TB HUB["NEW: live.Hub<br/>one SUBSCRIBE connection,<br/>per-user channel while the user has a stream open"] S1["NEW: stream (tab 1)"] S2["NEW: stream (tab 2)"] HUB --> S1 HUB --> S2 end R --> HUB B["Browser (fetch)"] B -- "NEW: GET /v1/stream/...<br/>Authorization: Bearer (MusicBrainz token)" --> S1 S1 -- "event: inbox" --> B B -- "refetch count / list (existing routes)" --> MUT classDef added fill:#e6f4ea,stroke:#2e7d32 class PUB,R,HUB,S1,S2 addedRoutes introduced
GET /v1/stream/tenants/{tenant}/notificationsGET /v1/stream/notificationscross_tenant_notificationsis on.OPTIONSon bothAllow-Methods: GET,Allow-Headers: Authorization,Max-Age: 600for allowed originsWhat a stream sends:
created: an ingest committed a notification for the user.changed: the user read, read-all'd or dismissed, in any tab or on any device.ping: every 25 s.How it works
Auth. The browser already holds the user's MusicBrainz token (ListenBrainz's
musicbrainzAuth), so it opens the stream withfetchandAuthorization: Bearer.EventSourcecan't send headers, so it isn't used. The stream routes use the sameNewUserAuthmiddleware and introspection cache as/v1/me/*. CORS runs before auth, so an allowed page can read a 401 (refresh the token) or 503 (back off).Publishing.
createdper deduplicated (user, tenant), never for dry runs or duplicates, and only for event types that allow in-app.changedunless it returns 404; read-all sends one per tenant that had unread notifications.ContextTimeoutEnabled. Without that, go-redis ignores the 500 ms budget and waits its 3 sReadTimeout.Hub (
internal/live/hub.go). One shared RedisPubSubper instance.SUBSCRIBE synapse:inbox:{user}, and the last one to close sendsUNSUBSCRIBE. It uses per-userSUBSCRIBE, notPSUBSCRIBE synapse:inbox:*, so an instance only receives its own users' messages.Registerreturns only after Redis confirms the subscription, so a nudge published after the stream opens is never missed. Confirmations are counted per channel, so a late reply to an earlier subscribe/unsubscribe pair can't mark a newer subscription live.PubSub. Reusing the old one would let go-redis resubscribe old channels on reconnect, and those replies would confuse the confirmation counts.Stream limits (
internal/api/stream.go):/v1/me/*; 429 when exceededReconnect is client-driven. On 401 the client refreshes its token and reconnects; on any other status, a network error or a closed stream it waits a random backoff and reconnects. It refetches on every open, which covers anything missed while disconnected. A Redis, hub or preferences failure before the stream starts returns 503. There's no
retry:field. The full client contract and afetchsnippet are indocs/tenant-integration.md.CORS. Exact match against the tenant's
stream_origins, plusVary: Origin. The global stream accepts any tenant's origins.Notes for review
Last-Event-ID. A reconnect means a refetch.synapse:notificationsscope is a separate PR. The ListenBrainz frontend should ship after it.MarkReadandDismissnow return the tenant (RETURNING n.tenant_id), andMarkAllReadreturns a count per tenant, so the global routes know which tenant to nudge.docs/tenant-integration.md: registering a tenant, publishing events, building the inbox, and adding live updates.docs/architecture.md, a Redis row indocs/failure-handling.md, and the README.Testing
go build,go vet(including-tags integration), and theinternal/livetests and e2e stream tests pass under-raceagainst Postgres, Redis and RabbitMQ.Stress runs:
-raceKnown flakes:
TestPipelineHTTPIngest,TestPipelineAMQPIngestandTestRelayPublishesAndClearsOutboxtime out on a loaded Docker host. They fail the same way without this branch and pass on a clean run.Not automated: the write-deadline path for a stalled client (filling loopback buffers with pings takes minutes), and a browser smoke test against docker-compose.