diff --git a/.scaffold/branches/streaming.md b/.scaffold/branches/streaming.md index 9d1b25a..256e18a 100644 --- a/.scaffold/branches/streaming.md +++ b/.scaffold/branches/streaming.md @@ -2,7 +2,7 @@ branch: Streaming status: active order: 10 -updated: 2026-10-19 +updated: 2026-10-18 started: 2026-10-18 decided: "2026-10-18 — Cardwell: neste steg er Shade-streaming av tekst, video, bilder og lyd under Shade-kappen (filmer, videoer, bilder, logger). Bygges som ny pakke @shade/media oppå den låste stacken — kjernekrypto (ratchet, X3DH, proto) røres ikke, så G0–G4-revisjonen påvirkes ikke." --- @@ -31,10 +31,10 @@ decided: "2026-10-18 — Cardwell: neste steg er Shade-streaming av tekst, video - [x] `media put --web`: HEVC/AC3/DTS-filmer (som Chromium nekter) konverteres før forsegling, innebygde tekstundertekster blir spor; advarsel uten flagget - [x] Lokalt bibliotek: `media ls` med navn, `media link ` gir lenken igjen; kanonisk grant-koding (én grant = én lenke) - [x] Delt mediebibliotek for flere relay-instanser: filmer i S3 (egen SigV4-klient, multipart med begrenset minne), poster og live-pinner i Postgres, feiing av foreldreløse objekter; verifisert mot SeaweedFS med signaturkontroll + Postgres 16, to relayer bak round-robin +- [x] Live på tvers av relay-instanser: relayene sier hvor publisererne er (Postgres), en relay med seere følger den som har publisereren og verifiserer hver ramme; seere får `state` når kanalen går live/stille (nettleser, TS, Android). To feil rettet underveis: relayen merket aldri at publisereren gikk (Hono-WSContext), og ubrukelig mediekatalog ga uhåndtert avvisning ## Neste - Kjør `:shade-media-demo` på dev-telefonen (RFCN504DWJF var ikke tilkoblet 2026-10-18) -- Live-kanaler på tvers av instanser (i dag: rut `/v1/live/*` til én instans) ## Senere - Sanntidssamtaler (V5.0): SFrame-nøkler fra samme kjede over WebRTC Insertable Streams diff --git a/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/10-live-mesh.png b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/10-live-mesh.png new file mode 100644 index 0000000..18c4b0e Binary files /dev/null and b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/10-live-mesh.png differ diff --git a/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/captions.txt b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/captions.txt index 8cb4b0b..f2067e8 100644 --- a/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/captions.txt +++ b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/captions.txt @@ -7,3 +7,4 @@ 07 — En forseglet film med Testfilm.no.srt og Testfilm.en.srt ved siden av: undertekstene følger filmen kryptert, og nettleseren velger norsk fordi den er satt til bokmål 08 — En ekte MKV-film med HEVC-video og AC3 5.1-lyd: Chromium nekter originalen («no supported streams»); med media put --web spiller den med lyd og den innebygde norske underteksten 09 — To relay-instanser bak en round-robin-lastbalanserer deler ett bibliotek (filmbytes i S3, poster i Postgres): opplastet via den ene, spilt og spolt til 24 s med Range-lesinger fra begge +10 — Live-logg på tvers av relayer: publisereren landet på instans A og seeren på B bak lastbalansereren; B følger A, verifiserer hver ramme mot pinnen og viser «live» diff --git a/.scaffold/plan.md b/.scaffold/plan.md index 964d396..3dab135 100644 --- a/.scaffold/plan.md +++ b/.scaffold/plan.md @@ -1,7 +1,7 @@ --- project: "Shade" phase: "Post-4.x GA — hardening til revisjonsklar (G0–G4) før V5.0-design" -updated: 2026-10-19 +updated: 2026-10-18 focus: "GCM-nonce-fiksen er levert (2026-08-13) og @shade/vault står ferdig og testet (2026-08-14), men er IKKE deployet eller publisert. De tre gjenstående G0-P0-ene er publiserings- og CI-saker. Historikk: G0 fikk en andre bestiller: @shade/vault (server-side kryptert fillager, bestilt 2026-08-13 av Scaffold-backupen) bygger på at-rest-stacken, og skal ikke reise seg på en kjent GCM-svakhet. Nonce-fiksens migreringssti er verifisert gratis — aeadOpen leser alltid nonce fra prefiks, så eksisterende blobber åpnes uendret." blockers: - "P0: @shade/observer@4.11.1 tomt på registry (outDir=dist-build, publish shipper dist/)" @@ -34,7 +34,7 @@ Gated hardening — hard utgangsport per steg (full plan + funn: helsesjekk-arti - [ ] **G2 — CI som mur:** biome + coverage-terskel + soak:smoke i CI; fjern/synk `.github/workflows`; publish kjører `prepublish:check`; bryt server↔inbox-server-syklus; rydd sdk/cli/files-deps; `dashboard: private`; pin bun. Port: PR blokkeres ved brudd, alle 8 examples grønne i CI. ## Neste -- **Streaming (`@shade/media`, 4.15.0)** — levert 2026-10-19, se `branches/streaming.md`: forseglede filmer/bilder/lyd (SMF1) og live-strømmer (SLF1) E2E, TS + Kotlin. Gjenstår fMP4 live, ExoPlayer-demo, delt lager + deploy. Ikke publisert. +- **Streaming (`@shade/media`, 4.15.0)** — levert 2026-10-18, se `branches/streaming.md`: forseglede filmer/bilder/lyd (SMF1) og live-strømmer (SLF1) E2E, TS + Kotlin; fMP4 + WebM live, ExoPlayer (Android), album, undertekster, `--web`, delt S3/Postgres-lager. Delte relay-instanser med live på tvers. Gjenstår: demo-APK på enhet. Ikke publisert eller deployet. - **V4.13 — `@shade/vault`: server-side kryptert fillager.** Klient, ruter, `MemoryVaultStore`, `SqliteVaultStore`, ruting i `standalone.ts` og `docs/vault.md` er levert natt til 2026-08-14 (auto-mode); 16 + 7 tester diff --git a/CHANGELOG.md b/CHANGELOG.md index a18ee88..16a8e85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ All notable changes to Shade are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [4.15.0] — 2026-10-19 — Media: films, video, images, audio and live streams, end to end +## [4.15.0] — 2026-10-18 — Media: films, video, images, audio and live streams, end to end New package **`@shade/media`** — see `docs/media.md`. @@ -66,6 +66,12 @@ New package **`@shade/media`** — see `docs/media.md`. `PostgresLivePinStore`, `createSharedMediaBackend` in `@shade/storage-postgres`. A live pin can no longer change key, even between instances (`LivePinTakenError`). +- **Live channels across relay instances.** `LiveRelayOptions.mesh` with a + `LivePublisherLocator` (`PostgresLivePublisherLocator`; + `SHADE_MEDIA_RELAY_URL` / `media serve --advertise`): a relay with viewers + of a channel published elsewhere follows the relay that has the publisher, + verifying every frame against the pin, and viewers follow a publisher that + moves. Viewers get a `state` message when a channel goes live or quiet. - **Library.** `media put` records each upload and its grant in `$XDG_CONFIG_HOME/shade/media-library.jsonl` (0600, append-only); `media ls` shows names, `media link ` prints a link again. Grants now @@ -88,6 +94,12 @@ New package **`@shade/media`** — see `docs/media.md`. - A relay test raced: `flush()` means sent, not received, so a viewer could join mid-burst and (correctly) get an older backlog. The relay now counts `framesIn` in `stats()`, and the test waits on it. +- The live relay never noticed its publisher leave: Hono hands each event its + own `WSContext`, and the close handler compared them by identity. A channel + stayed "live" with nobody publishing, and a replaced publisher's socket was + never closed. They are compared by the socket underneath now. +- `FileMediaStore` on a directory it could not use rejected at start with no + handler (an unhandled rejection). Now every call fails with the reason. - The container refused every request body over 128 MiB (Bun's default), which would have made every film a 413. The cap is raised only when media diff --git a/android/shade-android-media/src/main/kotlin/no/zyon/shade/media/android/LiveWatcher.kt b/android/shade-android-media/src/main/kotlin/no/zyon/shade/media/android/LiveWatcher.kt index 462ae75..530f7b9 100644 --- a/android/shade-android-media/src/main/kotlin/no/zyon/shade/media/android/LiveWatcher.kt +++ b/android/shade-android-media/src/main/kotlin/no/zyon/shade/media/android/LiveWatcher.kt @@ -87,6 +87,8 @@ class LiveWatcher( } listener.onState(if (msg.optBoolean("live")) State.LIVE else State.WAITING) } + // The publisher arrived or left after we joined. + "state" -> listener.onState(if (msg.optBoolean("live")) State.LIVE else State.WAITING) "error" -> listener.onError(LiveRelayException(msg.optString("message", "relay error"))) } } diff --git a/android/shade-android-media/src/test/kotlin/no/zyon/shade/media/android/ShadeLiveTest.kt b/android/shade-android-media/src/test/kotlin/no/zyon/shade/media/android/ShadeLiveTest.kt index 5e73686..3e7aa40 100644 --- a/android/shade-android-media/src/test/kotlin/no/zyon/shade/media/android/ShadeLiveTest.kt +++ b/android/shade-android-media/src/test/kotlin/no/zyon/shade/media/android/ShadeLiveTest.kt @@ -218,4 +218,42 @@ class ShadeLiveTest { assertTrue("states: $states", states.count { it == LiveWatcher.State.LIVE } == 2 && LiveWatcher.State.RECONNECTING in states) assertEquals(LiveWatcher.State.CLOSED, states.last()) } + + @Test + fun watcherFollowsThePublisherArrivingAndLeavingAfterItJoined() { + val server = MockWebServer() + server.start() + val pub = LivePublisher(random(16), random(32), null) + val grant = pub.grant(from = "now", url = server.url("/v1/live/x").toString().replace("http", "ws"), readToken = random(32)) + val first = pub.frame(LiveContent.Chunk(byteArrayOf(1)), keyframe = true) + server.enqueue( + MockResponse().withWebSocketUpgrade(object : WebSocketListener() { + override fun onClosing(webSocket: WebSocket, code: Int, reason: String) { + webSocket.close(1000, null) + } + + override fun onMessage(webSocket: WebSocket, text: String) { + // Joins an empty channel; the publisher arrives, sends, leaves. + webSocket.send("""{"type":"ready","live":false}""") + webSocket.send("""{"type":"state","live":true}""") + webSocket.send(first.toByteString()) + webSocket.send("""{"type":"state","live":false}""") + } + }), + ) + val states = Collections.synchronizedList(ArrayList()) + val left = CountDownLatch(1) + val watcher = LiveWatcher(grant, object : LiveWatcher.Listener { + override fun onFrame(frame: ReceivedFrame) {} + override fun onState(state: LiveWatcher.State) { + states += state + if (state == LiveWatcher.State.WAITING && LiveWatcher.State.LIVE in states) left.countDown() + } + }) + assertTrue("states: $states", left.await(10, TimeUnit.SECONDS)) + watcher.close() + server.shutdown() + val seen = states.filter { it == LiveWatcher.State.WAITING || it == LiveWatcher.State.LIVE } + assertEquals(listOf(LiveWatcher.State.WAITING, LiveWatcher.State.LIVE, LiveWatcher.State.WAITING), seen) + } } diff --git a/docs/media.md b/docs/media.md index 1b10c91..1a31f4e 100644 --- a/docs/media.md +++ b/docs/media.md @@ -90,9 +90,10 @@ With `SHADE_MEDIA_OWNERS` empty, the relay serves what it has and accepts nothin ``` SHADE_MEDIA_S3_URL=https://:@s3.eu-north-1.amazonaws.com/[/] SHADE_MEDIA_PG_URL=postgres://… # falls back to SHADE_PREKEY_PG_URL +SHADE_MEDIA_RELAY_URL=http://10.0.0.5:3000 # this instance, as the others reach it (live channels) ``` -(`shade media serve --s3 … --pg …` does the same outside the container.) Sealed +(`shade media serve --s3 … --pg … --advertise URL` does the same outside the container.) Sealed bytes go to the bucket, records and live-channel pins to Postgres, and any number of instances behind one hostname serve one library. Any S3 API works (AWS, R2, MinIO, SeaweedFS, Garage, B2); credentials left out of the URL come from @@ -110,8 +111,21 @@ off and the rest of the server runs. (a crash mid-upload) are reclaimed after 24 hours, a minute after start and every 6 hours. Every instance may sweep at once. - **Live channels** are pinned in Postgres, so a channel cannot be pinned to two keys - by two instances. Frames still fan out in the memory of the instance the publisher - is connected to: route `/v1/live/*` to one instance (or sticky by channel id). + by two instances. Each instance records which channels' publishers are connected to + it (`shade_live_publishers`, refreshed every 10 s). An instance whose viewers want a + channel published elsewhere subscribes to that instance once, with a viewer's own + read token, and fans the frames out locally. It verifies every frame against the pin + as if the publisher were its own, so a peer, or a poisoned locator row, cannot forge + one. Following an instance again replays its backlog; frames already passed on (by + `seq`) are not passed on twice. If the publisher moves (a deploy), viewers on every + instance follow it within a poll (2 s). What is sent while they look for it reaches + them the way a late joiner gets it, from a keyframe. A token that does not match the + pin held in memory is checked against the shared pin before it is refused, so a + publisher that comes back with a new read token is honoured everywhere. Without + `SHADE_MEDIA_RELAY_URL` an instance cannot be followed, and `/v1/live/*` must go to + one instance. +- Viewers now hear when a channel goes live or quiet after they joined: a + `{"type":"state","live":…}` message, in the browser, the TS client and Android. - The bucket holds only sealed SMF1 bytes. No key, name or plaintext is in it or in Postgres. diff --git a/packages/shade-media/src/cli.ts b/packages/shade-media/src/cli.ts index 5f038e6..134b405 100644 --- a/packages/shade-media/src/cli.ts +++ b/packages/shade-media/src/cli.ts @@ -129,7 +129,16 @@ async function mediaServe(flags: Flags, hooks: MediaCliHooks): Promise { if (pgUrl === undefined) throw new UsageError('--s3 needs --pg: the bucket holds the bytes, Postgres the records relays share'); if (hooks.sharedBackend === undefined) throw new UsageError('--s3/--pg are not available in this build (no Postgres support)'); const backend = await hooks.sharedBackend({ s3Url, pgUrl }); - svc = createMediaService({ owners, store: backend.store, pins: backend.pins, dev: flags.dev === true }); + // --advertise: the address other relays reach this one at, so they can follow its live channels. + const self = str(flags, 'advertise') ?? process.env.SHADE_MEDIA_RELAY_URL; + if (self === undefined) err('live channels stay on this relay (no --advertise URL for the others to follow)'); + svc = createMediaService({ + owners, + store: backend.store, + pins: backend.pins, + dev: flags.dev === true, + ...(self !== undefined ? { live: { mesh: { self, locator: backend.locator } } } : {}), + }); where = backend.describe; const sweep = () => backend.sweep().catch((e: unknown) => err(`! media sweep: ${(e as Error).message}`)); setTimeout(sweep, 60_000).unref(); @@ -608,11 +617,13 @@ async function liveWatch(pos: string[]): Promise { export const MEDIA_HELP = ` media serve [--port 3910] [--dir ./shade-media-data] [--owners k1,k2] [--open] - [--s3 https://key:secret@host/bucket[/prefix] --pg postgres://…] + [--s3 https://key:secret@host/bucket[/prefix] --pg postgres://… [--advertise URL]] Run a media relay: sealed store, live relay, watch page. Only this machine's key (and --owners) may upload/publish. --s3/--pg: films in a bucket, records in Postgres, so - several relays serve one library. + several relays serve one library. --advertise: this + relay's address for the others, so live channels work + whichever relay a viewer lands on. media whoami Print this machine's owner key (to add to a relay's --owners) media put … --server URL [--album T] [--name N] [--mime M] [--web] [--public] [--json] Seal a film/video/image/song, upload it, print a watch link. @@ -646,6 +657,7 @@ export interface MediaCliHooks { sharedBackend?: (o: { s3Url: string; pgUrl: string }) => Promise<{ store: import('./server.js').MediaStore; pins: import('./server.js').LivePinStore; + locator: import('./server.js').LivePublisherLocator; describe: string; sweep(): Promise; }>; diff --git a/packages/shade-media/src/live/client.ts b/packages/shade-media/src/live/client.ts index 6f5b409..898088e 100644 --- a/packages/shade-media/src/live/client.ts +++ b/packages/shade-media/src/live/client.ts @@ -250,6 +250,9 @@ export class LiveWatchClient { if (msg.type === 'ready') { this.retry.reset(); this.opts.onState?.(msg.live ? 'live' : 'waiting'); + } else if (msg.type === 'state') { + // The publisher arrived or left after we joined. + this.opts.onState?.(msg.live ? 'live' : 'waiting'); } else if (msg.type === 'error') { this.opts.onError?.(new Error(msg.message ?? 'relay error')); } diff --git a/packages/shade-media/src/server.ts b/packages/shade-media/src/server.ts index d3c6ee4..631041a 100644 --- a/packages/shade-media/src/server.ts +++ b/packages/shade-media/src/server.ts @@ -6,8 +6,8 @@ export { ObjectMediaStore, MemoryMediaIndex } from './server/object-store.js'; export { S3Bucket, S3Error, signV4 } from './server/s3.js'; export type { S3BucketOptions, S3Credentials, S3Object } from './server/s3.js'; export type { MediaIndex, IndexedMedia, ObjectMediaStoreOptions } from './server/object-store.js'; -export { createLiveRelay, FileLivePinStore, MemoryLivePinStore, LivePinTakenError } from './server/live-relay.js'; -export type { LiveRelay, LiveRelayOptions, LivePin, LivePinStore } from './server/live-relay.js'; +export { createLiveRelay, FileLivePinStore, MemoryLivePinStore, LivePinTakenError, MemoryLivePublisherLocator } from './server/live-relay.js'; +export type { LiveRelay, LiveRelayOptions, LivePin, LivePinStore, LivePublisherLocator } from './server/live-relay.js'; export { createWatchRoutes } from './server/watch-routes.js'; export type { WatchRoutesOptions } from './server/watch-routes.js'; export { createMediaService, parseOwners, mediaMaxRequestBody, MEDIA_BODY_ROUTE } from './server/service.js'; diff --git a/packages/shade-media/src/server/file-store.ts b/packages/shade-media/src/server/file-store.ts index a91b10c..614be6b 100644 --- a/packages/shade-media/src/server/file-store.ts +++ b/packages/shade-media/src/server/file-store.ts @@ -60,6 +60,9 @@ export class FileMediaStore implements MediaStore { constructor(private readonly dir: string) { this.ready = this.load(); + // A directory it cannot use fails every call that awaits `ready`, with + // the reason — not the process, as an unhandled rejection at start. + this.ready.catch(() => {}); } private objectPath(id: string): string { diff --git a/packages/shade-media/src/server/live-relay.ts b/packages/shade-media/src/server/live-relay.ts index 5a4184a..ff48399 100644 --- a/packages/shade-media/src/server/live-relay.ts +++ b/packages/shade-media/src/server/live-relay.ts @@ -60,6 +60,35 @@ export class LivePinTakenError extends Error { } } +/** + * Where a channel's publisher is connected, when several relays share one + * pin store. A relay with viewers but not the publisher looks the channel up + * here and follows the relay that has it (see `LiveRelayOptions.mesh`). + */ +export interface LivePublisherLocator { + /** This relay holds the channel's publisher. Called again as a heartbeat while it does. */ + claim(channelId: string, relayUrl: string, at: number): Promise; + /** The publisher left this relay. Only removes a claim that is still this relay's. */ + release(channelId: string, relayUrl: string): Promise; + /** The relay holding the publisher, if its claim was refreshed after `freshAfter`. */ + find(channelId: string, freshAfter: number): Promise; +} + +/** One process's locator — for tests, and relays that share memory. */ +export class MemoryLivePublisherLocator implements LivePublisherLocator { + private readonly claims = new Map(); + async claim(channelId: string, relayUrl: string, at: number): Promise { + this.claims.set(channelId, { url: relayUrl, at }); + } + async release(channelId: string, relayUrl: string): Promise { + if (this.claims.get(channelId)?.url === relayUrl) this.claims.delete(channelId); + } + async find(channelId: string, freshAfter: number): Promise { + const c = this.claims.get(channelId); + return c !== undefined && c.at > freshAfter ? c.url : null; + } +} + export class MemoryLivePinStore implements LivePinStore { private readonly pins = new Map(); async get(id: string): Promise { @@ -141,6 +170,24 @@ export interface LiveRelayOptions { idleRetentionMs?: number; /** Largest frame accepted. Default 16 MiB + headers. */ maxFrameBytes?: number; + /** + * Several relays, one set of channels. Each relay claims the channels whose + * publisher is connected to it; a relay with viewers of a channel published + * elsewhere subscribes to that relay, once, with a viewer's own read token, + * and fans the frames out to its viewers. It verifies every frame against + * the pin as if the publisher were its own, so a peer cannot forge one. + */ + mesh?: { + /** This relay's base URL as the other relays reach it, e.g. `http://10.0.0.5:3000`. */ + self: string; + locator: LivePublisherLocator; + /** Claim refresh. Default 10 s. */ + heartbeatMs?: number; + /** A claim older than this is a relay that died. Default 30 s. */ + staleMs?: number; + /** How often a channel with viewers looks for a publisher that is not here. Default 2 s. */ + pollMs?: number; + }; now?: () => number; } @@ -162,10 +209,27 @@ interface Channel { sawKeyframe: boolean; ended: boolean; idleSince: number; + /** Highest seq taken this epoch — a relay followed again resends its backlog. */ + lastSeq: number; + /** The relay this one follows for the channel (mesh), when its publisher is there. */ + upstream: WebSocket | null; + /** A read token a viewer proved, to subscribe upstream with. */ + token: string | null; + /** Pending look-up for a publisher elsewhere. */ + poll: ReturnType | null; } type Role = { kind: 'none' } | { kind: 'pub'; ch: Channel } | { kind: 'sub'; ch: Channel; viewer: Viewer }; +/** + * Hono hands each event its own WSContext for one socket, so `===` between + * the one seen at `publish` and the one at close is always false: compare the + * socket underneath. + */ +function sameSocket(a: WSContext | null, b: WSContext): boolean { + return a !== null && (a === b || (a.raw !== undefined && a.raw === b.raw)); +} + function bufferedAmount(ws: WSContext): number { const raw = ws.raw as { getBufferedAmount?: () => number } | undefined; return raw?.getBufferedAmount?.() ?? 0; @@ -223,11 +287,31 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay { sawKeyframe: false, ended: false, idleSince: now(), + lastSeq: -1, + upstream: null, + token: null, + poll: null, }; channels.set(id, ch); return ch; } + /** Adopt a pin read from the shared store. A new signing key is a new channel. */ + function repin(ch: Channel, pin: LivePin): void { + if (pin.signingKey !== ch.pin.signingKey) { + closeUpstream(ch); + ch.verifier = new Ed25519Verifier(fromB64u(pin.signingKey, 32)); + ch.epoch = -1; + ch.sticky = []; + ch.backlog = []; + ch.backlogBytes = 0; + ch.sawKeyframe = false; + ch.lastSeq = -1; + ch.ended = false; + } + ch.pin = pin; + } + function trim(ch: Channel): void { // Keep from the keepKeyframes-th most recent keyframe onward… let seen = 0; @@ -267,11 +351,18 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay { v.ws.send(frame as Uint8Array); } + /** Tell viewers when the channel goes live or quiet after they joined (the `ready` answer is only the start). */ + function notifyViewers(ch: Channel): void { + const live = ch.publisher !== null || ch.upstream !== null; + const msg = JSON.stringify({ type: 'state', live, ended: ch.ended, epoch: ch.epoch }); + for (const v of ch.viewers) v.ws.send(msg); + } + function notifyPublisher(ch: Channel): void { ch.publisher?.send(JSON.stringify({ type: 'viewers', count: ch.viewers.size })); } - async function accept(ch: Channel, frame: Uint8Array): Promise { + async function accept(ch: Channel, frame: Uint8Array, fromUpstream = false): Promise { if (frame.length > maxFrameBytes) return 'frame too large'; let f; try { @@ -289,7 +380,11 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay { ch.backlog = []; ch.backlogBytes = 0; ch.sawKeyframe = false; + ch.lastSeq = -1; } + // Following another relay again replays its backlog: pass on each frame once. + if (fromUpstream && f.header.seq <= ch.lastSeq) return null; + ch.lastSeq = Math.max(ch.lastSeq, f.header.seq); const sticky = (flags & FLAG_STICKY) !== 0; const keyframe = (flags & FLAG_KEYFRAME) !== 0; const copy = frame.slice(); @@ -307,10 +402,96 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay { return null; } + const mesh = opts.mesh; + const heartbeatMs = mesh?.heartbeatMs ?? 10_000; + const staleMs = mesh?.staleMs ?? 30_000; + const pollMs = mesh?.pollMs ?? 2_000; + const self = mesh?.self.replace(/\/$/, ''); + let stopped = false; + + function closeUpstream(ch: Channel): void { + if (ch.poll !== null) { + clearTimeout(ch.poll); + ch.poll = null; + } + const up = ch.upstream; + ch.upstream = null; + up?.close(1000, 'not needed'); + } + + function schedulePoll(ch: Channel): void { + if (ch.poll !== null || stopped) return; + ch.poll = setTimeout(() => { + ch.poll = null; + void follow(ch); + }, pollMs); + (ch.poll as { unref?: () => void }).unref?.(); + } + + /** Follow the relay that has this channel's publisher, while viewers here want it. */ + async function follow(ch: Channel): Promise { + if (mesh === undefined || stopped) return; + if (ch.publisher !== null || ch.upstream !== null || ch.viewers.size === 0 || ch.token === null) return; + let url: string | null; + try { + url = await mesh.locator.find(ch.id, now() - staleMs); + } catch { + url = null; + } + // Re-check: the publisher may have arrived here while we looked. + if (ch.publisher !== null || ch.upstream !== null || ch.viewers.size === 0) return; + if (url === null || url.replace(/\/$/, '') === self) return schedulePoll(ch); + const ws = new WebSocket(`${url.replace(/^http/, 'ws').replace(/\/$/, '')}/v1/live/${ch.id}`); + ws.binaryType = 'arraybuffer'; + ch.upstream = ws; + let chain: Promise = Promise.resolve(); + ws.onopen = () => ws.send(JSON.stringify({ type: 'subscribe', token: ch.token })); + ws.onmessage = (ev) => { + if (typeof ev.data === 'string') { + // The relay we follow took us: viewers here are live from now. + if (ch.upstream === ws && (JSON.parse(ev.data) as { type?: string }).type === 'ready') notifyViewers(ch); + return; + } + const bytes = new Uint8Array(ev.data as ArrayBuffer); + chain = chain.then(async () => { + if (ch.upstream !== ws) return; + // Verified like a publisher's own: a peer relay is not trusted with frames. + const err = await accept(ch, bytes, true); + if (err !== null) ws.close(1008, err.slice(0, 120)); + }); + }; + ws.onclose = () => { + if (ch.upstream !== ws) return; + ch.upstream = null; + notifyViewers(ch); + // The publisher left that relay (or it died): look again while anyone watches. + if (ch.viewers.size > 0 && ch.publisher === null) schedulePoll(ch); + }; + ws.onerror = () => {}; + } + + async function claim(ch: Channel): Promise { + if (mesh === undefined) return; + await mesh.locator.claim(ch.id, self!, now()).catch(() => { + // The next heartbeat tries again; frames flow to local viewers meanwhile. + }); + } + + const heartbeat = + mesh !== undefined + ? setInterval(() => { + for (const ch of channels.values()) if (ch.publisher !== null) void claim(ch); + }, heartbeatMs) + : null; + (heartbeat as { unref?: () => void } | null)?.unref?.(); + function sweep(): void { const t = now(); for (const [id, ch] of channels) { - if (ch.publisher === null && ch.viewers.size === 0 && t - ch.idleSince > idleMs) channels.delete(id); + if (ch.publisher === null && ch.viewers.size === 0 && t - ch.idleSince > idleMs) { + closeUpstream(ch); + channels.delete(id); + } } } const timer = setInterval(sweep, 60_000); @@ -395,10 +576,14 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay { const ch = (await channelFor(channelId))!; ch.pin = pin; // A reconnecting publisher replaces the stale socket. - if (ch.publisher !== null && ch.publisher !== ws) ch.publisher.close(4000, 'replaced by a newer publisher'); + if (ch.publisher !== null && !sameSocket(ch.publisher, ws)) ch.publisher.close(4000, 'replaced by a newer publisher'); ch.publisher = ws; ch.ended = false; + // The publisher is here now: stop following another relay, and say so. + closeUpstream(ch); + await claim(ch); role = { kind: 'pub', ch }; + notifyViewers(ch); ws.send(JSON.stringify({ type: 'ready', role: 'publisher', epoch: ch.epoch, viewers: ch.viewers.size })); return; } @@ -406,12 +591,21 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay { if (msg.type === 'subscribe') { if (typeof msg.token !== 'string') return fail(ws, 'bad subscribe'); const ch = await channelFor(channelId); - let ok = false; - if (ch !== null) { - try { - ok = equalBytes(await sha256(fromB64u(msg.token)), fromB64u(ch.pin.readTokenHash, 32)); - } catch { - ok = false; + let tokenHash: Uint8Array | null = null; + try { + tokenHash = await sha256(fromB64u(msg.token)); + } catch { + tokenHash = null; + } + const matches = () => tokenHash !== null && equalBytes(tokenHash, fromB64u(ch!.pin.readTokenHash, 32)); + let ok = ch !== null && matches(); + if (ch !== null && !ok && ch.publisher === null && mesh !== undefined) { + // The publisher is on another relay and may have come back with a + // new read token: judge by the shared pin, not the copy held here. + const fresh = await opts.pins.get(channelId); + if (fresh !== null) { + repin(ch, fresh); + ok = matches(); } } // Same refusal for "no such channel" and "wrong token". @@ -419,12 +613,14 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay { const viewer: Viewer = { ws, lagging: false }; ch.viewers.add(viewer); role = { kind: 'sub', ch, viewer }; - ws.send( - JSON.stringify({ type: 'ready', role: 'viewer', live: ch.publisher !== null, ended: ch.ended, epoch: ch.epoch }), - ); + // The latest proven token: the one the shared pin accepts now. + ch.token = msg.token; + const live = ch.publisher !== null || ch.upstream !== null; + ws.send(JSON.stringify({ type: 'ready', role: 'viewer', live, ended: ch.ended, epoch: ch.epoch })); for (const f of ch.sticky) ws.send(f as Uint8Array); for (const b of ch.backlog) deliver(viewer, b.frame, false, b.keyframe, ch.sawKeyframe); notifyPublisher(ch); + if (ch.publisher === null) void follow(ch); return; } return fail(ws, 'unknown control message'); @@ -444,13 +640,21 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay { }).catch((e) => fail(ws, String((e as Error)?.message ?? e), 1011)); }, onClose(_evt, ws) { - if (role.kind === 'pub' && role.ch.publisher === ws) { - role.ch.publisher = null; - role.ch.idleSince = now(); + if (role.kind === 'pub' && sameSocket(role.ch.publisher, ws)) { + const ch = role.ch; + ch.publisher = null; + ch.idleSince = now(); + notifyViewers(ch); + if (mesh !== undefined) { + void mesh.locator.release(ch.id, self!).catch(() => {}); + // It may come back on another relay: viewers here follow it there. + if (ch.viewers.size > 0) schedulePoll(ch); + } } else if (role.kind === 'sub') { role.ch.viewers.delete(role.viewer); role.ch.idleSince = now(); notifyPublisher(role.ch); + if (role.ch.viewers.size === 0) closeUpstream(role.ch); } }, }; @@ -470,7 +674,13 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay { }, sweep, stop() { + stopped = true; clearInterval(timer); + if (heartbeat !== null) clearInterval(heartbeat); + for (const ch of channels.values()) { + closeUpstream(ch); + if (mesh !== undefined && ch.publisher !== null) void mesh.locator.release(ch.id, self!).catch(() => {}); + } }, }; } diff --git a/packages/shade-media/tests/file-store.test.ts b/packages/shade-media/tests/file-store.test.ts new file mode 100644 index 0000000..2e91852 --- /dev/null +++ b/packages/shade-media/tests/file-store.test.ts @@ -0,0 +1,11 @@ +import { describe, test, expect } from 'bun:test'; +import { FileMediaStore } from '../src/server.js'; + +describe('FileMediaStore', () => { + test('a directory it cannot use fails each call with the reason, not the process', async () => { + const store = new FileMediaStore('/proc/shade-cannot-write-here'); + await new Promise((r) => setTimeout(r, 20)); // an unhandled rejection would surface here + await expect(store.get('00'.repeat(16))).rejects.toThrow(/ENOENT|EACCES|EROFS|EPERM/); + await expect(store.totalBytes()).rejects.toThrow(); + }); +}); diff --git a/packages/shade-media/tests/live-mesh.test.ts b/packages/shade-media/tests/live-mesh.test.ts new file mode 100644 index 0000000..60888e2 --- /dev/null +++ b/packages/shade-media/tests/live-mesh.test.ts @@ -0,0 +1,234 @@ +import { describe, test, expect } from 'bun:test'; +import { websocket } from 'hono/bun'; +import { Hono } from 'hono'; +import { createLiveRelay, MemoryLivePinStore, MemoryLivePublisherLocator } from '../src/server.js'; +import type { LivePublisherLocator } from '../src/server.js'; +import { LivePublisher, LivePublishClient, LiveWatchClient, encodeGrant, parseGrant } from '../src/index.js'; +import type { LiveGrant, ReceivedFrame } from '../src/index.js'; +import { toB64u } from '../src/bytes.js'; + +const until = async (cond: () => boolean, ms = 10_000) => { + const t = Date.now(); + while (!cond()) { + if (Date.now() - t > ms) throw new Error('timed out'); + await new Promise((r) => setTimeout(r, 10)); + } +}; + +/** N relays sharing pins and a locator, as N instances behind one hostname would. */ +function cluster(n: number, locator: LivePublisherLocator = new MemoryLivePublisherLocator()) { + const pins = new MemoryLivePinStore(); + return Array.from({ length: n }, () => { + let app: Hono | null = null; + const server = Bun.serve({ port: 0, fetch: (req, srv) => app!.fetch(req, { server: srv }), websocket }); + const base = `http://localhost:${server.port}`; + const relay = createLiveRelay({ pins, mesh: { self: base, locator, pollMs: 50, heartbeatMs: 200, staleMs: 1000 } }); + app = new Hono().route('/', relay.app); + return { relay, server, base }; + }); +} + +const chunks = (frames: ReceivedFrame[]) => + frames.filter((f) => f.content.type === 'chunk').map((f) => (f.content as { bytes: Uint8Array }).bytes[0]!); + +describe('live channels across relays (mesh)', () => { + test('publisher on A, viewers on B: waiting first, then live; late join from A\'s backlog; each frame once', async () => { + const [a, b] = cluster(2) as [ReturnType[0], ReturnType[0]]; + try { + const pub = new LivePublisher({ meta: { name: 'cam' } }); + const client = new LivePublishClient({ relay: a.base, publisher: pub, readToken: new Uint8Array(32).fill(7) }); + await client.whenReady(); + const grant = parseGrant(encodeGrant(client.grant('oldest'))) as LiveGrant; + + // A viewer on B before anything is sent: B follows A at once, and tells the viewer it is live. + const early: ReceivedFrame[] = []; + const states: string[] = []; + const v1 = new LiveWatchClient(grant, { url: `${b.base.replace('http', 'ws')}/v1/live/${grant.url!.split('/').pop()}`, onFrame: (f) => void early.push(f), onState: (st) => void states.push(st) }); + await until(() => b.relay.stats().viewers === 1 && a.relay.stats().viewers === 1); + await until(() => states.at(-1) === 'live'); + + await client.send({ type: 'init', mime: 'video/webm; codecs="vp8"', bytes: new Uint8Array([0xaa]) }, { sticky: true }); + for (let i = 0; i < 30; i++) await client.send({ type: 'chunk', bytes: new Uint8Array([i]) }, { keyframe: i % 10 === 0 }); + await until(() => chunks(early).length === 30); + expect(chunks(early)).toEqual(Array.from({ length: 30 }, (_, i) => i)); + expect(early.filter((f) => f.content.type === 'init').length).toBe(1); + + // A late viewer on B gets B's copy of the backlog: init, then from a keyframe. + const late: ReceivedFrame[] = []; + const v2 = new LiveWatchClient(grant, { url: `${b.base.replace('http', 'ws')}/v1/live/${grant.url!.split('/').pop()}`, onFrame: (f) => void late.push(f) }); + await until(() => chunks(late).length >= 10); + expect(late[0]!.content.type).toBe('init'); + expect(chunks(late)[0]! % 10).toBe(0); + // Still one subscription from B to A, however many watch on B. + expect(a.relay.stats().viewers).toBe(1); + + v1.close(); + v2.close(); + // Nobody left on B: B stops following A. + await until(() => a.relay.stats().viewers === 0); + client.close(); + } finally { + for (const r of [a, b]) { + r.relay.stop(); + r.server.stop(true); + } + } + }, 30_000); + + test('the publisher moves from A to B; viewers on both follow it', async () => { + const loc = new MemoryLivePublisherLocator(); + const [a, b] = cluster(2, loc) as [ReturnType[0], ReturnType[0]]; + try { + const pub = new LivePublisher({ meta: { name: 'logs' } }); + const c1 = new LivePublishClient({ relay: a.base, publisher: pub, readToken: new Uint8Array(32).fill(9) }); + await c1.whenReady(); + const grant = parseGrant(encodeGrant(c1.grant('oldest'))) as LiveGrant; + const id = grant.url!.split('/').pop()!; + const onA: ReceivedFrame[] = []; + const onB: ReceivedFrame[] = []; + const va = new LiveWatchClient(grant, { url: `${a.base.replace('http', 'ws')}/v1/live/${id}`, onFrame: (f) => void onA.push(f) }); + const vb = new LiveWatchClient(grant, { url: `${b.base.replace('http', 'ws')}/v1/live/${id}`, onFrame: (f) => void onB.push(f) }); + await until(() => a.relay.stats().viewers === 2); // va, and B following + for (let i = 0; i < 5; i++) await c1.send({ type: 'chunk', bytes: new Uint8Array([i]) }, { keyframe: true }); + await until(() => chunks(onA).length === 5 && chunks(onB).length === 5); + + // The publisher reconnects to B (a deploy moved it). Same publisher, same chain. + // B stops following A; A now follows B, and B's backlog (frames that came + // from A) is replayed to it — A's viewer must still see each frame once. + c1.close(); + const c2 = new LivePublishClient({ relay: b.base, publisher: pub, readToken: new Uint8Array(32).fill(9) }); + await c2.whenReady(); + // A finds the publisher on B within a poll. (What is sent before that + // reaches A's viewers as B's backlog holds it: from a keyframe, like a late join.) + await until(() => b.relay.stats().viewers === 2); + for (let i = 5; i < 10; i++) await c2.send({ type: 'chunk', bytes: new Uint8Array([i]) }, { keyframe: true }); + await until(() => chunks(onA).length === 10 && chunks(onB).length === 10); + expect(chunks(onA)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + expect(chunks(onB)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + va.close(); + vb.close(); + c2.close(); + } finally { + for (const r of [a, b]) { + r.relay.stop(); + r.server.stop(true); + } + } + }, 30_000); + + test('a peer that forges frames gets nothing through: every frame is verified against the pin', async () => { + const locator = new MemoryLivePublisherLocator(); + const [b] = cluster(1, locator) as [ReturnType[0]]; + // An impostor "relay" that the locator points at, sending frames from another key. + const forged: Uint8Array[] = []; + let asked = 0; + const evil = Bun.serve({ + port: 0, + fetch: (req, srv) => (srv.upgrade(req) ? undefined : new Response('no', { status: 400 })), + websocket: { + message(ws) { + asked++; + for (const f of forged) ws.send(f); + }, + }, + }); + try { + const pub = new LivePublisher({ meta: { name: 'real' } }); + const real = new LivePublishClient({ relay: b.base, publisher: pub, readToken: new Uint8Array(32).fill(3) }); + await real.whenReady(); + real.close(); + await until(() => b.relay.stats().channels === 1); + const grant = parseGrant(encodeGrant(real.grant('oldest'))) as LiveGrant; + const id = grant.url!.split('/').pop()!; + // Frames for this channel id, signed by the forger's key. + const fpub = new LivePublisher({ channelId: pub.channelId }); + for (let i = 0; i < 3; i++) forged.push(await fpub.frame({ type: 'chunk', bytes: new Uint8Array([66]) }, { keyframe: true })); + await locator.claim(toB64u(pub.channelId), `http://localhost:${evil.port}`, Date.now()); + + const got: ReceivedFrame[] = []; + const errors: Error[] = []; + const v = new LiveWatchClient(grant, { url: `${b.base.replace('http', 'ws')}/v1/live/${id}`, onFrame: (f) => void got.push(f), onError: (e) => void errors.push(e) }); + await until(() => asked >= 2); // B followed the impostor, was refused frames, and tried again + expect(got.filter((f) => f.content.type === 'chunk')).toEqual([]); + expect(b.relay.stats().framesIn).toBe(0); + v.close(); + } finally { + b.relay.stop(); + b.server.stop(true); + evil.stop(true); + } + }, 30_000); + + test('the publisher comes back with a new read token: viewers with the new grant get in on the other relay too', async () => { + const [a, b] = cluster(2) as [ReturnType[0], ReturnType[0]]; + try { + const pub = new LivePublisher(); + const c1 = new LivePublishClient({ relay: a.base, publisher: pub, readToken: new Uint8Array(32).fill(1) }); + await c1.whenReady(); + const g1 = parseGrant(encodeGrant(c1.grant('oldest'))) as LiveGrant; + const id = g1.url!.split('/').pop()!; + const onB = `${b.base.replace('http', 'ws')}/v1/live/${id}`; + const s1: string[] = []; + const v1 = new LiveWatchClient(g1, { url: onB, onFrame: () => {}, onState: (st) => void s1.push(st) }); + await until(() => s1.at(-1) === 'live'); + v1.close(); + c1.close(); + await until(() => a.relay.stats().viewers === 0); + + // Same channel, new read token (old links revoked): B must not judge by the pin it read first. + const c2 = new LivePublishClient({ relay: a.base, publisher: pub, readToken: new Uint8Array(32).fill(2) }); + await c2.whenReady(); + const g2 = parseGrant(encodeGrant(c2.grant('oldest'))) as LiveGrant; + const got: ReceivedFrame[] = []; + const errs: Error[] = []; + const v2 = new LiveWatchClient(g2, { url: onB, onFrame: (f) => void got.push(f), onError: (e) => void errs.push(e) }); + await until(() => a.relay.stats().viewers === 1 || errs.length > 0); + expect(errs).toEqual([]); + await c2.send({ type: 'chunk', bytes: new Uint8Array([42]) }, { keyframe: true }); + await until(() => chunks(got).includes(42)); + + // And the old token no longer opens it on B either. + const e1: Error[] = []; + const old = new LiveWatchClient(g1, { url: onB, onFrame: () => {}, onError: (e) => void e1.push(e) }); + await until(() => e1.length > 0); + old.close(); + v2.close(); + c2.close(); + } finally { + for (const r of [a, b]) { + r.relay.stop(); + r.server.stop(true); + } + } + }, 30_000); + + test('viewers hear when the publisher arrives and leaves (and the relay notices it left)', async () => { + const relay = createLiveRelay({ pins: new MemoryLivePinStore() }); + const app = new Hono().route('/', relay.app); + const server = Bun.serve({ port: 0, fetch: (req, srv) => app.fetch(req, { server: srv }), websocket }); + try { + const pub = new LivePublisher(); + const c1 = new LivePublishClient({ relay: `http://localhost:${server.port}`, publisher: pub, readToken: new Uint8Array(32).fill(4) }); + await c1.whenReady(); + const grant = parseGrant(encodeGrant(c1.grant('oldest'))) as LiveGrant; + c1.close(); + await until(() => relay.stats().channels === 1); + await new Promise((r) => setTimeout(r, 50)); + + // Joins an empty channel: waiting. The publisher comes back: live. It leaves: waiting. + // (Hono gives each event its own WSContext; a relay comparing them by identity never saw a publisher leave.) + const states: string[] = []; + const v = new LiveWatchClient(grant, { onFrame: () => {}, onState: (st) => void states.push(st) }); + await until(() => states.at(-1) === 'waiting'); + const c2 = new LivePublishClient({ relay: `http://localhost:${server.port}`, publisher: pub, readToken: new Uint8Array(32).fill(4) }); + await c2.whenReady(); + await until(() => states.at(-1) === 'live'); + c2.close(); + await until(() => states.at(-1) === 'waiting'); + v.close(); + } finally { + relay.stop(); + server.stop(true); + } + }); +}); diff --git a/packages/shade-server/src/standalone.ts b/packages/shade-server/src/standalone.ts index 79a9fae..b27e6a4 100644 --- a/packages/shade-server/src/standalone.ts +++ b/packages/shade-server/src/standalone.ts @@ -354,7 +354,22 @@ if (process.env.SHADE_DISABLE_MEDIA === '1') { } } if (backend !== null) { - mediaService = createMediaService({ owners, store: backend.store, pins: backend.pins }); + // Live channels across instances: each says where its publishers are, so + // the others can follow. Without its own address an instance cannot be + // followed, and /v1/live/* must go to one instance. + const self = process.env.SHADE_MEDIA_RELAY_URL; + if (self === undefined) { + logger.warn( + 'Live channels are per instance: set SHADE_MEDIA_RELAY_URL to the address other instances reach this one at ' + + '(e.g. http://10.0.0.5:3000), or route /v1/live/* to a single instance.', + ); + } + mediaService = createMediaService({ + owners, + store: backend.store, + pins: backend.pins, + ...(self !== undefined ? { live: { mesh: { self, locator: backend.locator } } } : {}), + }); where = backend.describe; // Reclaim what crashed uploads left in the bucket. Every instance may // run it; the grace period spares uploads still in flight anywhere. diff --git a/packages/shade-storage-postgres/src/ensure-tables.ts b/packages/shade-storage-postgres/src/ensure-tables.ts index 2f1574b..72b1c4a 100644 --- a/packages/shade-storage-postgres/src/ensure-tables.ts +++ b/packages/shade-storage-postgres/src/ensure-tables.ts @@ -314,4 +314,11 @@ export async function ensureMediaServerTables(sql: Sql): Promise { CREATE INDEX IF NOT EXISTS shade_live_pins_seen_idx ON shade_live_pins(last_seen) `; + await sql` + CREATE TABLE IF NOT EXISTS shade_live_publishers ( + channel_id TEXT PRIMARY KEY, + relay_url TEXT NOT NULL, + seen_at BIGINT NOT NULL + ) + `; } diff --git a/packages/shade-storage-postgres/src/index.ts b/packages/shade-storage-postgres/src/index.ts index 37485e1..41a30fc 100644 --- a/packages/shade-storage-postgres/src/index.ts +++ b/packages/shade-storage-postgres/src/index.ts @@ -3,7 +3,7 @@ export { PostgresPrekeyStore } from './postgres-prekey-store.js'; export { PostgresInboxStore } from './postgres-inbox-store.js'; export { PostgresKTLogStore } from './postgres-kt-store.js'; export { PostgresBlobStore } from './postgres-blob-store.js'; -export { PostgresMediaIndex, PostgresLivePinStore } from './postgres-media-store.js'; +export { PostgresMediaIndex, PostgresLivePinStore, PostgresLivePublisherLocator } from './postgres-media-store.js'; export { createSharedMediaBackend } from './shared-media.js'; export type { SharedMediaBackend } from './shared-media.js'; export { diff --git a/packages/shade-storage-postgres/src/postgres-media-store.ts b/packages/shade-storage-postgres/src/postgres-media-store.ts index bd564cc..3a31b23 100644 --- a/packages/shade-storage-postgres/src/postgres-media-store.ts +++ b/packages/shade-storage-postgres/src/postgres-media-store.ts @@ -1,6 +1,6 @@ import postgres, { type Sql } from 'postgres'; import { LivePinTakenError, MediaExistsError } from '@shade/media/server'; -import type { IndexedMedia, LivePin, LivePinStore, MediaIndex, MediaRecord } from '@shade/media/server'; +import type { IndexedMedia, LivePin, LivePinStore, LivePublisherLocator, MediaIndex, MediaRecord } from '@shade/media/server'; import { ensureMediaServerTables } from './ensure-tables.js'; // "relation already exists, skipping" on every start is not news. @@ -158,3 +158,36 @@ export class PostgresLivePinStore implements LivePinStore { if (rows.length === 0) throw new LivePinTakenError(pin.channelId); } } + +/** + * Which relay holds each live channel's publisher, so relays sharing pins + * can follow one another (`LiveRelayOptions.mesh`). One row per channel: a + * channel's publisher is on one relay at a time, and the newest claim wins. + */ +export class PostgresLivePublisherLocator implements LivePublisherLocator { + private constructor(private readonly sql: Sql) {} + + static async fromClient(sql: Sql): Promise { + await ensureMediaServerTables(sql); + return new PostgresLivePublisherLocator(sql); + } + + async claim(channelId: string, relayUrl: string, at: number): Promise { + await this.sql` + INSERT INTO shade_live_publishers (channel_id, relay_url, seen_at) + VALUES (${channelId}, ${relayUrl}, ${at}) + ON CONFLICT (channel_id) DO UPDATE SET relay_url = EXCLUDED.relay_url, seen_at = EXCLUDED.seen_at + `; + } + + async release(channelId: string, relayUrl: string): Promise { + await this.sql`DELETE FROM shade_live_publishers WHERE channel_id = ${channelId} AND relay_url = ${relayUrl}`; + } + + async find(channelId: string, freshAfter: number): Promise { + const rows = await this.sql<{ relay_url: string }[]>` + SELECT relay_url FROM shade_live_publishers WHERE channel_id = ${channelId} AND seen_at > ${freshAfter} + `; + return rows[0]?.relay_url ?? null; + } +} diff --git a/packages/shade-storage-postgres/src/shared-media.ts b/packages/shade-storage-postgres/src/shared-media.ts index c1ca2d2..f1e1646 100644 --- a/packages/shade-storage-postgres/src/shared-media.ts +++ b/packages/shade-storage-postgres/src/shared-media.ts @@ -1,11 +1,13 @@ import postgres from 'postgres'; import { ObjectMediaStore, S3Bucket } from '@shade/media/server'; -import type { LivePinStore, MediaStore } from '@shade/media/server'; -import { PostgresLivePinStore, PostgresMediaIndex } from './postgres-media-store.js'; +import type { LivePinStore, LivePublisherLocator, MediaStore } from '@shade/media/server'; +import { PostgresLivePinStore, PostgresLivePublisherLocator, PostgresMediaIndex } from './postgres-media-store.js'; export interface SharedMediaBackend { store: MediaStore; pins: LivePinStore; + /** Where each live channel's publisher is, for relays that follow one another. */ + locator: LivePublisherLocator; /** Where the bytes go, for logs — no credentials. */ describe: string; /** Reclaim unreferenced objects and dead uploads; safe on every instance at once. */ @@ -26,6 +28,7 @@ export async function createSharedMediaBackend(opts: { s3Url: string; pgUrl: str try { const index = await PostgresMediaIndex.fromClient(sql); const pins = await PostgresLivePinStore.fromClient(sql); + const locator = await PostgresLivePublisherLocator.fromClient(sql); const store = new ObjectMediaStore(bucket, index, { prefix }); // Fail at start, not at the first upload: a bucket that is not there, or // credentials it refuses, show up here. @@ -33,6 +36,7 @@ export async function createSharedMediaBackend(opts: { s3Url: string; pgUrl: str return { store, pins, + locator, describe: `s3 ${new URL(opts.s3Url).host}/${bucket.bucket}/${prefix}`, sweep: () => store.sweep(), close: () => sql.end(), diff --git a/packages/shade-storage-postgres/tests/postgres-media.test.ts b/packages/shade-storage-postgres/tests/postgres-media.test.ts index f981455..048f36c 100644 --- a/packages/shade-storage-postgres/tests/postgres-media.test.ts +++ b/packages/shade-storage-postgres/tests/postgres-media.test.ts @@ -11,10 +11,12 @@ import { describe, test, expect, beforeAll, afterAll } from 'bun:test'; import postgres, { type Sql } from 'postgres'; import { Hono } from 'hono'; -import { createMediaService, LivePinTakenError, MediaExistsError, S3Bucket } from '@shade/media/server'; +import { createMediaService, LivePinTakenError, MediaExistsError, MemoryMediaStore, S3Bucket } from '@shade/media/server'; import type { IndexedMedia } from '@shade/media/server'; -import { MediaClient, OwnerKey, openGrant, sealMediaBytes, MIN_SEGMENT_SIZE } from '@shade/media'; -import { createSharedMediaBackend, PostgresLivePinStore, PostgresMediaIndex } from '../src/index.js'; +import { MediaClient, OwnerKey, openGrant, sealMediaBytes, MIN_SEGMENT_SIZE, LivePublisher, LivePublishClient, LiveWatchClient, encodeGrant, parseGrant } from '@shade/media'; +import type { LiveGrant, ReceivedFrame } from '@shade/media'; +import { websocket } from 'hono/bun'; +import { createSharedMediaBackend, PostgresLivePinStore, PostgresLivePublisherLocator, PostgresMediaIndex } from '../src/index.js'; const PG_URL = process.env.SHADE_TEST_PG_URL; const S3_URL = process.env.SHADE_TEST_S3_URL; @@ -35,6 +37,7 @@ describe.skipIf(PG_URL === undefined)('Postgres media index and live pins', () = sql = postgres(PG_URL!); await sql`DROP TABLE IF EXISTS shade_media_objects`; await sql`DROP TABLE IF EXISTS shade_live_pins`; + await sql`DROP TABLE IF EXISTS shade_live_publishers`; }); afterAll(async () => { await sql.end(); @@ -101,6 +104,72 @@ describe.skipIf(PG_URL === undefined)('Postgres media index and live pins', () = }); }); +describe.skipIf(PG_URL === undefined)('Postgres live publisher locator', () => { + test('newest claim wins, release only removes its own, stale claims are not found', async () => { + const sql = postgres(PG_URL!, { onnotice: () => {} }); + try { + const loc = await PostgresLivePublisherLocator.fromClient(sql); + await loc.claim('c', 'http://a', 1000); + expect(await loc.find('c', 0)).toBe('http://a'); + await loc.claim('c', 'http://b', 2000); + await loc.release('c', 'http://a'); // a late release from the old relay + expect(await loc.find('c', 0)).toBe('http://b'); + expect(await loc.find('c', 2000)).toBeNull(); // not refreshed since: a dead relay + await loc.release('c', 'http://b'); + expect(await loc.find('c', 0)).toBeNull(); + } finally { + await sql.end(); + } + }); + + test('two media services over Postgres: publish on one, watch on the other', async () => { + const pools = [postgres(PG_URL!, { onnotice: () => {} }), postgres(PG_URL!, { onnotice: () => {} })]; + const relays = await Promise.all( + pools.map(async (p) => { + let app: Hono | null = null; + const server = Bun.serve({ port: 0, fetch: (req, srv) => app!.fetch(req, { server: srv }), websocket }); + const self = `http://localhost:${server.port}`; + const svc = createMediaService({ + owners: 'any', + store: new MemoryMediaStore(), + pins: await PostgresLivePinStore.fromClient(p), + live: { mesh: { self, locator: await PostgresLivePublisherLocator.fromClient(p), pollMs: 100 } }, + }); + app = new Hono().route('/', svc.app); + return { server, svc, self }; + }), + ); + const [a, b] = relays as [(typeof relays)[0], (typeof relays)[0]]; + try { + const pub = new LivePublisher({ meta: { name: 'logg' } }); + const c = new LivePublishClient({ relay: a.self, publisher: pub, readToken: new Uint8Array(32).fill(5) }); + await c.whenReady(); + const grant = parseGrant(encodeGrant(c.grant('oldest'))) as LiveGrant; + const got: ReceivedFrame[] = []; + const v = new LiveWatchClient(grant, { url: grant.url!.replace(a.self.replace('http', 'ws'), b.self.replace('http', 'ws')), onFrame: (f) => void got.push(f) }); + const deadline = Date.now() + 10_000; + while (b.svc.relay.stats().viewers < 1 || a.svc.relay.stats().viewers < 1) { + if (Date.now() > deadline) throw new Error('B never followed A'); + await Bun.sleep(20); + } + for (let i = 0; i < 5; i++) await c.send({ type: 'text', text: `linje ${i}` }, { keyframe: true }); + while (got.length < 5) { + if (Date.now() > deadline) throw new Error(`got ${got.length} of 5`); + await Bun.sleep(20); + } + expect(got.map((f) => (f.content as { text: string }).text)).toEqual([0, 1, 2, 3, 4].map((i) => `linje ${i}`)); + v.close(); + c.close(); + } finally { + for (const r of relays) { + r.svc.stop(); + r.server.stop(true); + } + await Promise.all(pools.map((p) => p.end())); + } + }, 30_000); +}); + describe.skipIf(PG_URL === undefined || S3_URL === undefined)('two relays, one shared backend', () => { test('upload on one relay, play, list and delete on the other; a race for one id is decided once', async () => { const prefix = `relay-test-${Date.now().toString(36)}`;