fix(media): relays release their live-channel claims on shutdown
LiveRelay.stop() fired the claim releases and forgot them, and nothing closed the shared backend's Postgres pool: on a redeploy the process could exit first, leaving the other instances to follow a dead relay until the claim went stale (30 s). stop() is now async and resolves once the releases are written; MediaService.stop() passes it through; the container awaits it and closes the backend on SIGTERM, and `media serve` gained SIGINT/SIGTERM handling that does the same and closes open sockets so publishers and viewers reconnect elsewhere. Verified: a test that a stopped relay's claim is gone at once; a real `media serve --s3 --pg --advertise` with a live publisher: SIGTERM → exit in ~0.4 s, its shade_live_publishers row 1 → 0, the publisher reconnecting. Suites green (media 101, storage-postgres 20, server 55, cli 15). Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -79,6 +79,10 @@ New package **`@shade/media`** — see `docs/media.md`.
|
|||||||
of a channel published elsewhere follows the relay that has the publisher,
|
of a channel published elsewhere follows the relay that has the publisher,
|
||||||
verifying every frame against the pin, and viewers follow a publisher that
|
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.
|
moves. Viewers get a `state` message when a channel goes live or quiet.
|
||||||
|
`LiveRelay.stop()` / `MediaService.stop()` now resolve once the relay's
|
||||||
|
claims are released; the container and `media serve` (SIGINT/SIGTERM) wait
|
||||||
|
for it and close the Postgres pool, so a redeploy does not leave other
|
||||||
|
instances pointing at a relay that is gone.
|
||||||
- **Library.** `media put` records each upload and its grant in
|
- **Library.** `media put` records each upload and its grant in
|
||||||
`$XDG_CONFIG_HOME/shade/media-library.jsonl` (0600, append-only); `media
|
`$XDG_CONFIG_HOME/shade/media-library.jsonl` (0600, append-only); `media
|
||||||
ls` shows names, `media link <name|id>` prints a link again. Grants now
|
ls` shows names, `media link <name|id>` prints a link again. Grants now
|
||||||
|
|||||||
@@ -127,6 +127,7 @@ async function mediaServe(flags: Flags, hooks: MediaCliHooks): Promise<number> {
|
|||||||
const pgUrl = str(flags, 'pg') ?? process.env.SHADE_MEDIA_PG_URL;
|
const pgUrl = str(flags, 'pg') ?? process.env.SHADE_MEDIA_PG_URL;
|
||||||
let svc: import('./server.js').MediaService;
|
let svc: import('./server.js').MediaService;
|
||||||
let where = dir;
|
let where = dir;
|
||||||
|
let closeBackend: () => Promise<void> = async () => {};
|
||||||
if (s3Url !== undefined) {
|
if (s3Url !== undefined) {
|
||||||
if (pgUrl === undefined) throw new UsageError('--s3 needs --pg: the bucket holds the bytes, Postgres the records relays share');
|
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)');
|
if (hooks.sharedBackend === undefined) throw new UsageError('--s3/--pg are not available in this build (no Postgres support)');
|
||||||
@@ -142,6 +143,7 @@ async function mediaServe(flags: Flags, hooks: MediaCliHooks): Promise<number> {
|
|||||||
...(self !== undefined ? { live: { mesh: { self, locator: backend.locator } } } : {}),
|
...(self !== undefined ? { live: { mesh: { self, locator: backend.locator } } } : {}),
|
||||||
});
|
});
|
||||||
where = backend.describe;
|
where = backend.describe;
|
||||||
|
closeBackend = () => backend.close();
|
||||||
const sweep = () => backend.sweep().catch((e: unknown) => err(`! media sweep: ${(e as Error).message}`));
|
const sweep = () => backend.sweep().catch((e: unknown) => err(`! media sweep: ${(e as Error).message}`));
|
||||||
setTimeout(sweep, 60_000).unref();
|
setTimeout(sweep, 60_000).unref();
|
||||||
setInterval(sweep, 6 * 3600_000).unref();
|
setInterval(sweep, 6 * 3600_000).unref();
|
||||||
@@ -160,7 +162,16 @@ async function mediaServe(flags: Flags, hooks: MediaCliHooks): Promise<number> {
|
|||||||
});
|
});
|
||||||
err(`shade media: serving on http://localhost:${server.port} (data in ${where})`);
|
err(`shade media: serving on http://localhost:${server.port} (data in ${where})`);
|
||||||
err(owners === 'any' ? 'open relay: any key may upload and publish' : `owners: ${owners.join(', ')}`);
|
err(owners === 'any' ? 'open relay: any key may upload and publish' : `owners: ${owners.join(', ')}`);
|
||||||
await new Promise(() => {});
|
// Stop cleanly: release live-channel claims so other relays look elsewhere at once.
|
||||||
|
await new Promise<void>((resolve) => {
|
||||||
|
const shutdown = () => resolve();
|
||||||
|
process.once('SIGINT', shutdown);
|
||||||
|
process.once('SIGTERM', shutdown);
|
||||||
|
});
|
||||||
|
err('shade media: stopping');
|
||||||
|
await svc.stop();
|
||||||
|
server.stop(true); // open sockets too: publishers and viewers reconnect to another relay
|
||||||
|
await closeBackend();
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -790,6 +801,7 @@ export interface MediaCliHooks {
|
|||||||
locator: import('./server.js').LivePublisherLocator;
|
locator: import('./server.js').LivePublisherLocator;
|
||||||
describe: string;
|
describe: string;
|
||||||
sweep(): Promise<unknown>;
|
sweep(): Promise<unknown>;
|
||||||
|
close(): Promise<void>;
|
||||||
}>;
|
}>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -249,7 +249,8 @@ export interface LiveRelay {
|
|||||||
stats(): { channels: number; viewers: number; backlogBytes: number; framesIn: number };
|
stats(): { channels: number; viewers: number; backlogBytes: number; framesIn: number };
|
||||||
/** Drop idle channels now (also runs on a timer). */
|
/** Drop idle channels now (also runs on a timer). */
|
||||||
sweep(): void;
|
sweep(): void;
|
||||||
stop(): void;
|
/** Stop timers and links to other relays; resolves once this relay's publisher claims are released. */
|
||||||
|
stop(): Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
|
export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
|
||||||
@@ -673,14 +674,17 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
|
|||||||
return { channels: channels.size, viewers, backlogBytes, framesIn };
|
return { channels: channels.size, viewers, backlogBytes, framesIn };
|
||||||
},
|
},
|
||||||
sweep,
|
sweep,
|
||||||
stop() {
|
async stop() {
|
||||||
stopped = true;
|
stopped = true;
|
||||||
clearInterval(timer);
|
clearInterval(timer);
|
||||||
if (heartbeat !== null) clearInterval(heartbeat);
|
if (heartbeat !== null) clearInterval(heartbeat);
|
||||||
|
const releases: Promise<void>[] = [];
|
||||||
for (const ch of channels.values()) {
|
for (const ch of channels.values()) {
|
||||||
closeUpstream(ch);
|
closeUpstream(ch);
|
||||||
if (mesh !== undefined && ch.publisher !== null) void mesh.locator.release(ch.id, self!).catch(() => {});
|
// Released now, the others look elsewhere at once instead of after the claim goes stale.
|
||||||
|
if (mesh !== undefined && ch.publisher !== null) releases.push(mesh.locator.release(ch.id, self!).catch(() => {}));
|
||||||
}
|
}
|
||||||
|
await Promise.all(releases);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,7 +42,8 @@ export interface MediaServiceOptions {
|
|||||||
export interface MediaService {
|
export interface MediaService {
|
||||||
app: Hono;
|
app: Hono;
|
||||||
relay: LiveRelay;
|
relay: LiveRelay;
|
||||||
stop(): void;
|
/** Resolves once live-channel claims are released (see `LiveRelay.stop`). */
|
||||||
|
stop(): Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -202,6 +202,19 @@ describe('live channels across relays (mesh)', () => {
|
|||||||
}
|
}
|
||||||
}, 30_000);
|
}, 30_000);
|
||||||
|
|
||||||
|
test('a relay that stops releases its claims at once, so the others need not wait for them to go stale', async () => {
|
||||||
|
const loc = new MemoryLivePublisherLocator();
|
||||||
|
const [a] = cluster(1, loc) as [ReturnType<typeof cluster>[0]];
|
||||||
|
const pub = new LivePublisher();
|
||||||
|
const c = new LivePublishClient({ relay: a.base, publisher: pub, readToken: new Uint8Array(32).fill(6) });
|
||||||
|
await c.whenReady();
|
||||||
|
expect(await loc.find(toB64u(pub.channelId), 0)).toBe(a.base);
|
||||||
|
await a.relay.stop();
|
||||||
|
expect(await loc.find(toB64u(pub.channelId), 0)).toBeNull();
|
||||||
|
c.close();
|
||||||
|
a.server.stop(true);
|
||||||
|
});
|
||||||
|
|
||||||
test('viewers hear when the publisher arrives and leaves (and the relay notices it left)', async () => {
|
test('viewers hear when the publisher arrives and leaves (and the relay notices it left)', async () => {
|
||||||
const relay = createLiveRelay({ pins: new MemoryLivePinStore() });
|
const relay = createLiveRelay({ pins: new MemoryLivePinStore() });
|
||||||
const app = new Hono().route('/', relay.app);
|
const app = new Hono().route('/', relay.app);
|
||||||
|
|||||||
@@ -316,6 +316,7 @@ if (vaultDisabled) {
|
|||||||
// Several instances share one library with SHADE_MEDIA_S3_URL (sealed bytes
|
// Several instances share one library with SHADE_MEDIA_S3_URL (sealed bytes
|
||||||
// in a bucket) + SHADE_MEDIA_PG_URL (records and live pins in Postgres).
|
// in a bucket) + SHADE_MEDIA_PG_URL (records and live pins in Postgres).
|
||||||
let mediaService: import('@shade/media/server').MediaService | null = null;
|
let mediaService: import('@shade/media/server').MediaService | null = null;
|
||||||
|
let mediaBackend: import('@shade/storage-postgres').SharedMediaBackend | null = null;
|
||||||
const mediaS3 = process.env.SHADE_MEDIA_S3_URL;
|
const mediaS3 = process.env.SHADE_MEDIA_S3_URL;
|
||||||
const mediaPg = process.env.SHADE_MEDIA_PG_URL ?? process.env.SHADE_PREKEY_PG_URL;
|
const mediaPg = process.env.SHADE_MEDIA_PG_URL ?? process.env.SHADE_PREKEY_PG_URL;
|
||||||
if (process.env.SHADE_DISABLE_MEDIA === '1') {
|
if (process.env.SHADE_DISABLE_MEDIA === '1') {
|
||||||
@@ -353,6 +354,7 @@ if (process.env.SHADE_DISABLE_MEDIA === '1') {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
mediaBackend = backend;
|
||||||
if (backend !== null) {
|
if (backend !== null) {
|
||||||
// Live channels across instances: each says where its publishers are, so
|
// Live channels across instances: each says where its publishers are, so
|
||||||
// the others can follow. Without its own address an instance cannot be
|
// the others can follow. Without its own address an instance cannot be
|
||||||
@@ -461,7 +463,8 @@ async function shutdown(signal: string) {
|
|||||||
try {
|
try {
|
||||||
cleanupTask.stop();
|
cleanupTask.stop();
|
||||||
inboxPrune.stop();
|
inboxPrune.stop();
|
||||||
mediaService?.stop();
|
await mediaService?.stop();
|
||||||
|
await mediaBackend?.close();
|
||||||
server.stop();
|
server.stop();
|
||||||
if ('close' in store && typeof store.close === 'function') {
|
if ('close' in store && typeof store.close === 'function') {
|
||||||
await store.close();
|
await store.close();
|
||||||
|
|||||||
Reference in New Issue
Block a user