Something went wrong. Try again.
Stable episode delivery and analytics on pod.place
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192import { PlatformAuth, RateLimiter } from "./auth";import { HttpError, RecordNotFound, json } from "./errors";import { validateMediaUrl, type OriginPolicy } from "./origins";import { isResolverId, isValidCid, parseRecordUri, resolverUrl, showId, validateEpisode, validateShow } from "./validation";import type { RecordReader, ResolverMapping } from "./types";import type { SqliteStore } from "./store";
async function body(request: Request, fields: string[]): Promise<Record<string, unknown>> { if (!/^application\/json(?:;|$)/i.test(request.headers.get("content-type") ?? "")) { throw new HttpError(415, "unsupported_media_type", "Send application/json"); } if (Number(request.headers.get("content-length") ?? 0) > 16_384) throw new HttpError(413, "body_too_large", "Request body too large"); const reader = request.body?.getReader(); if (!reader) throw new HttpError(400, "invalid_body", "JSON object required"); const chunks: Uint8Array<ArrayBuffer>[] = []; let size = 0; while (true) { const { value, done } = await reader.read(); if (done) break; size += value.byteLength; if (size > 16_384) { await reader.cancel(); throw new HttpError(413, "body_too_large", "Request body too large"); } chunks.push(new Uint8Array(value)); } let parsed: unknown; try { parsed = JSON.parse(await new Blob(chunks).text()); } catch { throw new HttpError(400, "invalid_body", "JSON object required"); } if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || Object.keys(parsed).some((key) => !fields.includes(key))) { throw new HttpError(400, "invalid_body", "Unexpected registration fields"); } return parsed as Record<string, unknown>;}
function expectedCid(value: unknown): string { if (!isValidCid(value)) throw new HttpError(400, "invalid_cid", "Provide the CID returned by the PDS write"); return value;}function pagination(url: URL): { after: string; limit: number } { const after = url.searchParams.get("after") ?? ""; const rawLimit = url.searchParams.get("limit") ?? "50"; if ((after && !isResolverId(after)) || !/^\d{1,3}$/.test(rawLimit) || Number(rawLimit) < 1 || Number(rawLimit) > 100) { throw new HttpError(400, "invalid_pagination", "Use a valid after ID and a limit from 1 to 100"); } return { after, limit: Number(rawLimit) };}
export class RegistryApi { private readonly locks = new Map<string, Promise<void>>(); private readonly limiter = new RateLimiter(); constructor( private readonly store: SqliteStore, private readonly reader: RecordReader, private readonly auth: PlatformAuth, private readonly policy: OriginPolicy, private readonly now: () => number = Date.now, ) {}
// Serialize verification and writes for an episode inside this process. SQLite // version checks additionally reject races from another process sharing the DB. private async exclusive<T>(key: string, operation: () => Promise<T>): Promise<T> { const previous = this.locks.get(key) ?? Promise.resolve(); let release!: () => void; const current = new Promise<void>((resolve) => { release = resolve; }); this.locks.set(key, current); await previous; try { return await operation(); } finally { release(); if (this.locks.get(key) === current) this.locks.delete(key); } }
private async read(uri: string, cid?: string) { const envelope = await this.reader.get(uri); if (envelope.uri !== uri) throw new HttpError(502, "invalid_record_response", "Record source returned a mismatched URI"); if (cid && envelope.cid !== cid) throw new HttpError(409, "record_pending", "Trusted source does not yet show the requested record CID; retry"); return envelope; }
private async refresh(episodeUri: string, cid?: string, reactivate = false): Promise<ResolverMapping> { return this.exclusive(episodeUri, async () => { const existing = this.store.getByUri(episodeUri); // Only an explicit authenticated platform request may undo withdrawal. if (!reactivate && existing?.status === "withdrawn") return existing; const envelope = await this.read(episodeUri, cid); try { const record = validateEpisode(envelope, this.policy.baseUrl); if (existing && (existing.showUri !== record.showUri || existing.episodeGuid !== record.guid)) { throw new HttpError(422, "identity_changed", "Keep the registered show URI and episode GUID unchanged"); } const expectedShowCid = this.store.getShow(showId(record.showUri))?.cid ?? null; const showEnvelope = await this.read(record.showUri); const show = validateShow(showEnvelope); await validateMediaUrl(record.media.primary.url, this.policy); if (record.media.source) await validateMediaUrl(record.media.source.url, this.policy); return this.store.activate(episodeUri, envelope.cid, record, showEnvelope.cid, show, new Date(this.now()).toISOString(), existing?.version ?? null, expectedShowCid); } catch (error) { if (existing && error instanceof HttpError && error.status === 422) { this.store.setStatus(existing.id, "unavailable", new Date(this.now()).toISOString(), existing.version); } throw error; } }); }
private view(mapping: ResolverMapping) { return { ...mapping, resolverUrl: resolverUrl(this.policy.baseUrl, mapping.id) }; }
async handle(request: Request): Promise<Response> { const url = new URL(request.url); const path = url.pathname; if (request.method === "GET") { const { after, limit } = pagination(url); if (path === "/v1/shows") { const entries = this.store.listShows(after, limit + 1); const more = entries.length > limit; const items = entries.slice(0, limit); return json({ items, next: more ? items.at(-1)!.id : null }); } const showMatch = /^\/v1\/shows\/([A-Za-z0-9_-]{43})(\/episodes)?$/.exec(path); if (showMatch) { const show = this.store.getShow(showMatch[1]); if (!show) throw new HttpError(404, "show_not_found", "Registered show not found"); if (!showMatch[2]) return json(show); const entries = this.store.listEpisodes(show.uri, after, limit + 1); const items = entries.slice(0, limit); return json({ items: items.map((entry) => this.view(entry)), next: entries.length > limit ? items.at(-1)!.id : null }); } const match = /^\/v1\/resolvers\/([A-Za-z0-9_-]{43})$/.exec(path); if (match) { const mapping = this.store.get(match[1]); if (!mapping) throw new HttpError(404, "episode_not_found", "Registered episode not found"); return json(this.view(mapping)); } throw new HttpError(404, "not_found", "Route not found"); }
if (request.method !== "POST" && request.method !== "DELETE") return json({ error: "method_not_allowed" }, 405, { Allow: "GET, POST, DELETE" }); const grant = this.auth.authenticate(request); this.limiter.check(grant.platform, this.now());
if (path === "/v1/shows" && request.method === "POST") { const data = await body(request, ["showUri", "expectedCid"]); parseRecordUri(data.showUri, "place.pod.show"); const uri = data.showUri as string; const previousCid = this.store.getShow(showId(uri))?.cid ?? null; const envelope = await this.read(uri, expectedCid(data.expectedCid)); const show = validateShow(envelope); return json(this.store.putShow(uri, envelope.cid, show, new Date(this.now()).toISOString(), previousCid)); } if (path === "/v1/resolvers" && request.method === "POST") { const data = await body(request, ["episodeUri", "expectedCid"]); parseRecordUri(data.episodeUri, "place.pod.episode"); const uri = data.episodeUri as string; const mapping = await this.refresh(uri, expectedCid(data.expectedCid), true); return json(this.view(mapping)); } const match = /^\/v1\/resolvers\/([A-Za-z0-9_-]{43})(\/refresh)?$/.exec(path); if (match) { const mapping = this.store.get(match[1]); if (!mapping) throw new HttpError(404, "episode_not_found", "Registered episode not found"); if (request.method === "POST" && match[2]) { const data = await body(request, ["expectedCid"]); return json(this.view(await this.refresh(mapping.episodeUri, expectedCid(data.expectedCid), true))); } if (request.method === "DELETE" && !match[2]) { return json(this.view(this.store.setStatus(mapping.id, "withdrawn", new Date(this.now()).toISOString(), mapping.version)!)); } return json({ error: "method_not_allowed" }, 405, { Allow: match[2] ? "POST" : "GET, DELETE" }); } throw new HttpError(404, "not_found", "Route not found"); }
async reconcile(freshnessMs: number): Promise<void> { const due = this.store.due(new Date(this.now() - freshnessMs).toISOString()); for (const mapping of due) { try { await this.refresh(mapping.episodeUri); } catch (error) { if (error instanceof RecordNotFound) { // Avoid tombstoning a concurrent, successful explicit refresh. const current = this.store.get(mapping.id); if (current?.version === mapping.version && current.verifiedAt === mapping.verifiedAt) { this.store.setStatus(mapping.id, "withdrawn", new Date(this.now()).toISOString(), mapping.version); } } // Upstream failures do not extend verifiedAt; mappings eventually fail closed. } } }}