Open History to see the last commit
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_installation', '0002_streams', '0003_storage', '0004_subscriptions'] as const
9export const STORAGE_VERSION = 3
10
11export interface Migration {
12 readonly id: string
13 readonly checksum: string
14 readonly sql: string
15}
16
17export async function migrationPlan(schema = 'durable_streams'): Promise<readonly Migration[]> {
18 const identifier = validateSchema(schema)
19 return Promise.all(MIGRATION_IDS.map(async (id) => {
20 const source = await readFile(new URL(`../migrations/${id}.sql`, import.meta.url), 'utf8')
21 return { id, checksum: createHash('sha256').update(source).digest('hex'), sql: source.replaceAll('__SCHEMA__', identifier) }
22 }))
23}
24
25/** Explicit, transactional DDL. Call through the deployment's direct connection. */
26export async function migrate(pool: Pool, options: { readonly schema?: string; readonly storageIdentity?: string; readonly environmentId?: string; readonly maxLiveReaders?: number } = {}): Promise<readonly string[]> {
27 const schema = options.schema ?? 'durable_streams'
28 const identifier = validateSchema(schema)
29 const plan = await migrationPlan(schema)
30 for (const key of Object.keys(options)) {
31 if (!['schema', 'storageIdentity', 'environmentId', 'maxLiveReaders'].includes(key)) throw new TypeError(`Unsupported migration option: ${key}`)
32 }
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 [index, row] of applied.rows.entries()) {
40 const expected = plan[index]
41 if (expected?.id !== row.id || expected.checksum !== row.checksum) {
42 throw new StorageCompatibilityError(`Unknown or modified migration: ${row.id}; this development baseline requires a fresh schema`)
43 }
44 }
45 const completed: string[] = []
46 for (const migration of plan) {
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_installation')) {
53 await client.query(`INSERT INTO ${identifier}.installation (id, storage_version) VALUES ($1, $2)`, [randomUUID(), STORAGE_VERSION])
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 !== STORAGE_VERSION) {
57 throw new StorageCompatibilityError('Missing or incompatible installation identity; explicit recovery required')
58 }
59 }
60 const beforeBinding = (await client.query<{ storage_identity: string | null }>(`SELECT storage_identity FROM ${identifier}.installation FOR UPDATE`)).rows[0]!
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 if (beforeBinding.storage_identity === null) {
67 // Enabling tiered storage on an existing hot-only installation also
68 // enrolls its old tails. This one-time administrative scan keeps the
69 // ordinary append path/indexes free of extra due-counter updates.
70 await client.query(`INSERT INTO ${identifier}.hot_chunks SELECT id,clock_timestamp()+interval '1 hour'
71 FROM ${identifier}.streams WHERE hot_frames>0 ON CONFLICT DO NOTHING`)
72 }
73 }
74 if (options.environmentId !== undefined) {
75 if (!options.environmentId || Buffer.byteLength(options.environmentId) > 2048) throw new TypeError('Invalid environment identity')
76 const bound = await client.query(`UPDATE ${identifier}.installation SET environment_id = $1
77 WHERE environment_id IS NULL OR environment_id = $1 RETURNING id`, [options.environmentId])
78 if (bound.rowCount !== 1) throw new StorageCompatibilityError('Environment identity differs; explicit branch adoption is required')
79 }
80 if (options.maxLiveReaders !== undefined) {
81 if (!Number.isSafeInteger(options.maxLiveReaders) || options.maxLiveReaders < 1 || options.maxLiveReaders > 100_000) throw new RangeError('Invalid installation live reader capacity')
82 await client.query(`UPDATE ${identifier}.live_capacity SET max_readers = $1`, [options.maxLiveReaders])
83 }
84 return completed
85 })
86}