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

installation.ts

64 lines3.7 KB

1import type { Pool, PoolClient } from 'pg'
2import { StorageCompatibilityError, StreamError } from './errors.js'
3import { validateSchema } from './path.js'
4import { transaction } from './transaction.js'
5import type { TransactionOptions } from './transaction.js'
6​
7export interface InstallationIdentity {
8 readonly id: string
9 readonly serving_epoch: string
10 readonly serving_state: 'active' | 'recovering'
11 readonly environment_id: string | null
12 readonly storage_identity: string | null
14​
15/** Pins a runtime to one serving incarnation. All writer locks follow this lock. */
16export class InstallationGuard {
17 private readonly schema: string
18 private identity: Promise<InstallationIdentity> | undefined
19 constructor(private readonly pool: Pool, schema: string, private readonly environmentId?: string,
20 private readonly timeouts: Pick<TransactionOptions, 'timeoutMs' | 'lockTimeoutMs'> = {}) {
21 this.schema = validateSchema(schema)
22 if (environmentId !== undefined && (!environmentId || Buffer.byteLength(environmentId) > 2048)) throw new TypeError('Invalid environment identity')
23 for (const timeout of [timeouts.timeoutMs, timeouts.lockTimeoutMs]) {
24 if (timeout !== undefined && (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 300_000)) throw new RangeError('Invalid Postgres transaction limits')
25 }
26 }
27 private async pin(): Promise<InstallationIdentity> {
28 this.identity ??= this.pool.query<InstallationIdentity>(`SELECT id, serving_epoch, serving_state, environment_id, storage_identity FROM ${this.schema}.installation`)
29 .then((result) => {
30 const row = result.rows[0]
31 if (result.rows.length !== 1 || !row) throw new StorageCompatibilityError('Missing installation identity')
32 if (row.environment_id !== null && row.environment_id !== this.environmentId) throw new StorageCompatibilityError('Environment identity differs; explicit branch adoption is required')
33 return row
34 }).catch((error: unknown) => { this.identity = undefined; throw error })
35 return this.identity
36 }
37 async check(client?: PoolClient, readOnly = true): Promise<InstallationIdentity> {
38 const expected = await this.pin()
39 const result = await (client ?? this.pool).query<InstallationIdentity>(`SELECT id, serving_epoch, serving_state, environment_id, storage_identity
40 FROM ${this.schema}.installation${readOnly ? '' : ' FOR KEY SHARE'}`)
41 const row = result.rows[0]
42 if (!row || row.id !== expected.id || row.serving_epoch !== expected.serving_epoch || row.serving_state !== 'active'
43 || row.environment_id !== expected.environment_id || row.storage_identity !== expected.storage_identity) {
44 throw new StreamError(503, 'INSTALLATION_FENCED', 'Installation is quiesced or this runtime must be restarted after recovery', { 'Retry-After': '5' })
45 }
46 return row
47 }
48 async snapshot(): Promise<InstallationIdentity> { return { ...await this.pin() } }
49 async run<T>(options: TransactionOptions, work: (client: PoolClient) => Promise<T>): Promise<T> {
50 // Pin outside the transaction: a pool with one connection must also work.
51 await this.pin()
52 return transaction(this.pool, { ...this.timeouts, ...options }, async (client) => {
53 await this.check(client, options.readOnly ?? false)
54 return work(client)
55 })
56 }
57 /** Relinquishing a random owned slot remains safe after an epoch fence. */
58 async releaseLiveLease(id: string): Promise<void> {
59 await transaction(this.pool, this.timeouts, async (client) => { await client.query(`DELETE FROM ${this.schema}.live_leases WHERE id = $1`, [id]) })
60 }
61 async releaseReplayPins(id: string): Promise<void> {
62 await transaction(this.pool, this.timeouts, async (client) => { await client.query(`DELETE FROM ${this.schema}.replay_pins WHERE id = $1`, [id]) })
63 }