Skip to content
Source
Sign inSign up
samwillis/neon-durable-streams
Open History to see the last commit

admission.ts

25 lines1.6 KB

1import { randomUUID } from 'node:crypto'
2import type { InstallationGuard } from './installation.js'
3import { StreamError } from './errors.js'
4import { validateSchema } from './path.js'
5​
6/** Serialized installation-wide admission; expiry recovers slots after eviction. */
7export async function admitLive(guard: InstallationGuard, schema: string, lifetimeMs: number): Promise<() => Promise<void>> {
8 const identifier = validateSchema(schema)
9 const id = randomUUID()
10 await guard.run({}, async (client) => {
11 const capacity = await client.query<{ max_readers: number }>(`SELECT max_readers FROM ${identifier}.live_capacity FOR UPDATE`)
12 if (!capacity.rows[0]) throw new Error('Missing installation live capacity')
13 // Take the count in a new statement after acquiring the capacity lock, so
14 // it sees the previous admission's commit even if lock acquisition waited.
15 const admitted = await client.query(`WITH expired AS (
16 DELETE FROM ${identifier}.live_leases WHERE expires_at <= clock_timestamp()
17 ) INSERT INTO ${identifier}.live_leases (id, serving_epoch, expires_at)
18 SELECT $1, serving_epoch, clock_timestamp() + $2 * interval '1 millisecond' FROM ${identifier}.installation
19 WHERE (SELECT count(*) FROM ${identifier}.live_leases WHERE expires_at > clock_timestamp()) < $3 RETURNING id`, [id, lifetimeMs, capacity.rows[0].max_readers])
20 if (!admitted.rowCount) {
21 throw new StreamError(429, 'INSTALLATION_LIVE_LIMIT', 'Installation live reader capacity reached', { 'Retry-After': '1' })
22 }
23 })
24 return () => guard.releaseLiveLease(id)