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

migrations.ts

79 lines5.0 KB

1import { createHash, randomUUID } from 'node:crypto'
2import { readFile } from 'node:fs/promises'
3import type { Pool } from 'pg'
4import { StorageCompatibilityError } from './errors.js'
5import { validateSchema } from './path.js'
6import { transaction } from './transaction.js'
7​
8export const MIGRATION_IDS = ['0001_core', '0002_chunks', '0003_forks', '0004_subscriptions', '0005_operations', '0006_reclamation'] as const
9​
10export interface Migration {
11 readonly id: string
12 readonly checksum: string
13 readonly sql: string
15​
16export async function migrationPlan(schema = 'durable_streams'): Promise<readonly Migration[]> {
17 const identifier = validateSchema(schema)
18 return Promise.all(MIGRATION_IDS.map(async (id) => {
19 const source = await readFile(new URL(`../migrations/${id}.sql`, import.meta.url), 'utf8')
20 return { id, checksum: createHash('sha256').update(source).digest('hex'), sql: source.replaceAll('__SCHEMA__', identifier) }
21 }))
23​
24/** Explicit, transactional DDL. Call through the deployment's direct connection. */
25export async function migrate(pool: Pool, options: { readonly schema?: string; readonly storageIdentity?: string; readonly environmentId?: string; readonly maxLiveReaders?: number
26 /** Explicit legacy compatibility installation; physical collection is unavailable. */
27 readonly target?: '0005_operations' } = {}): Promise<readonly string[]> {
28 const schema = options.schema ?? 'durable_streams'
29 const identifier = validateSchema(schema)
30 const plan = await migrationPlan(schema)
31 if (options.target !== undefined && options.target !== '0005_operations') throw new TypeError('Unsupported migration target')
32 const selected = options.target ? plan.slice(0, 5) : plan
33 return transaction(pool, { timeoutMs: 60_000 }, async (client) => {
34 await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [`durable-streams:migrate:${schema}`])
35 await client.query(`CREATE SCHEMA IF NOT EXISTS ${identifier}`)
36 await client.query(`CREATE TABLE IF NOT EXISTS ${identifier}.migrations (
37 id text PRIMARY KEY, checksum text NOT NULL, applied_at timestamptz NOT NULL DEFAULT clock_timestamp())`)
38 const applied = await client.query<{ id: string; checksum: string }>(`SELECT id, checksum FROM ${identifier}.migrations ORDER BY id`)
39 for (const row of applied.rows) {
40 if (!plan.some((m) => m.id === row.id && m.checksum === row.checksum)) {
41 throw new StorageCompatibilityError(`Unknown or modified migration: ${row.id}`)
42 }
43 if (!selected.some((migration) => migration.id === row.id)) throw new StorageCompatibilityError('Migrations cannot downgrade an existing installation')
44 }
45 const completed: string[] = []
46 for (const migration of selected) {
47 if (applied.rows.some((m) => m.id === migration.id)) continue
48 await client.query(migration.sql)
49 await client.query(`INSERT INTO ${identifier}.migrations (id, checksum) VALUES ($1, $2)`, [migration.id, migration.checksum])
50 completed.push(migration.id)
51 }
52 if (completed.includes('0001_core')) {
53 await client.query(`INSERT INTO ${identifier}.installation (id, storage_version) VALUES ($1, 1)`, [randomUUID()])
54 } else {
55 const installation = await client.query<{ storage_version: number }>(`SELECT storage_version FROM ${identifier}.installation`)
56 if (installation.rows.length !== 1 || installation.rows[0]!.storage_version !== 1) {
57 throw new StorageCompatibilityError('Missing or incompatible installation identity; explicit recovery required')
58 }
59 }
60 await client.query(`SELECT id FROM ${identifier}.installation FOR UPDATE`)
61 if (options.storageIdentity !== undefined) {
62 if (!options.storageIdentity || options.storageIdentity.length > 2048) throw new TypeError('Invalid storage identity')
63 const binding = await client.query(`UPDATE ${identifier}.installation SET storage_identity = $1
64 WHERE storage_identity IS NULL OR storage_identity = $1 RETURNING id`, [options.storageIdentity])
65 if (binding.rowCount !== 1) throw new StorageCompatibilityError('Storage identity differs; explicit branch adoption or recovery is required')
66 }
67 if (options.environmentId !== undefined) {
68 if (!options.environmentId || Buffer.byteLength(options.environmentId) > 2048) throw new TypeError('Invalid environment identity')
69 const bound = await client.query(`UPDATE ${identifier}.installation SET environment_id = $1
70 WHERE environment_id IS NULL OR environment_id = $1 RETURNING id`, [options.environmentId])
71 if (bound.rowCount !== 1) throw new StorageCompatibilityError('Environment identity differs; explicit branch adoption is required')
72 }
73 if (options.maxLiveReaders !== undefined) {
74 if (!Number.isSafeInteger(options.maxLiveReaders) || options.maxLiveReaders < 1 || options.maxLiveReaders > 100_000) throw new RangeError('Invalid installation live reader capacity')
75 await client.query(`UPDATE ${identifier}.live_capacity SET max_readers = $1`, [options.maxLiveReaders])
76 }
77 return completed
78 })