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

operations.ts

216 lines16.5 KB

1import { randomUUID } from 'node:crypto'
2import type { Pool } from 'pg'
3import { decodeChunk } from './chunk-codec.js'
4import { StorageCompatibilityError } from './errors.js'
5import type { InstallationIdentity } from './installation.js'
6import { validateSchema } from './path.js'
7import type { ChunkStorage } from './storage.js'
8import { transaction } from './transaction.js'
9import { SubscriptionSigner } from './subscription-crypto.js'
10import type { SubscriptionKeyring } from './subscription-crypto.js'
11​
12export type { InstallationIdentity } from './installation.js'
13export interface OperationTarget { readonly schema?: string }
14export interface RecoveryOptions extends OperationTarget {
15 /** Persist this UUID before calling; reuse it after a lost response. */
16 readonly operationId: string
17 readonly expectedInstallationId: string
18 readonly expectedServingEpoch: string
19 /** A stable deployment identity, normally the consumer's Neon branch ID. */
20 readonly environmentId: string
21 /** The target branch/bucket. Every sealed object must already exist there. */
22 readonly storageIdentity: string | null
23 /** Set when adopting to a new server URL; omit to retain the original URL. */
24 readonly publicBaseUrl?: string
26interface RecoveryRow extends InstallationIdentity {
27 recovery_token: string | null
28 recovery_source_epoch: string | null
29 completed_recovery_token: string | null
30 recovery_target_public_base_url: string | null
31 recovery_target_environment: string | null
32 recovery_target_storage: string | null
33 recovery_cursor: string | null
34 recovery_verified: string
35 recovery_complete: boolean
37function target(options: OperationTarget): string { return validateSchema(options.schema ?? 'durable_streams') }
38function validRecovery(row: RecoveryRow | undefined, token: string): asserts row is RecoveryRow {
39 if (!row || row.serving_state !== 'recovering' || row.recovery_token !== token) throw new StorageCompatibilityError('Recovery token is stale or installation is active')
41/** Administrative data-plane operation; never expose through the stream API. */
42export async function inspectInstallation(pool: Pool, options: OperationTarget = {}): Promise<InstallationIdentity> {
43 const result = await pool.query<InstallationIdentity>(`SELECT id, serving_epoch, serving_state, environment_id, storage_identity FROM ${target(options)}.installation`)
44 if (result.rows.length !== 1) throw new StorageCompatibilityError('Missing installation identity')
45 return result.rows[0]!
47​
48export interface ReclamationPolicyOptions extends OperationTarget {
49 /** An active, explicitly quiesced recovery operation from beginRecovery. */
50 readonly token: string
51 readonly enabled: boolean
52 /** Include the entire supported PITR AND external-backup recovery window. */
53 readonly recoveryWindowMs: number
54 /** At least fifteen minutes in addition to the recovery window. */
55 readonly safetyMarginMs?: number
57export type ReclamationStatus = { readonly supported: false } | {
58 readonly supported: true
59 readonly enabled: boolean
60 readonly recoveryWindowMs: number
61 readonly safetyMarginMs: number
62 readonly holdUntil: Date
63 readonly inventoryCompletedAt: Date | null
64 readonly backlog?: { readonly pendingDeletes: number; readonly orphanCandidates: number; readonly quarantinedObjects: number; readonly oldestCollectAfter: Date | null }
66/** Operator diagnostics. Backlog aggregates are opt-in; use a separate pool. */
67export async function inspectReclamation(pool: Pool, options: OperationTarget & { readonly includeBacklog?: boolean } = {}): Promise<ReclamationStatus> {
68 const schema = target(options)
69 if (options.includeBacklog !== undefined && typeof options.includeBacklog !== 'boolean') throw new TypeError('Invalid reclamation diagnostics selection')
70 return transaction(pool, { readOnly: true, repeatableRead: true }, async (client) => {
71 if (!(await client.query(`SELECT 1 FROM ${schema}.migrations WHERE id='0006_reclamation'`)).rowCount) return { supported: false }
72 const policy = (await client.query<{ enabled: boolean; recovery_window_ms: string; safety_margin_ms: number; hold_until: Date; inventory_completed_at: Date | null }>(`SELECT * FROM ${schema}.reclamation_policy`)).rows[0]!
73 const result = { supported: true as const, enabled: policy.enabled, recoveryWindowMs: Number(policy.recovery_window_ms), safetyMarginMs: policy.safety_margin_ms,
74 holdUntil: policy.hold_until, inventoryCompletedAt: policy.inventory_completed_at }
75 if (!options.includeBacklog) return result
76 const counts = (await client.query<{ pending: string; orphans: string; quarantined: string; oldest: Date | null }>(`SELECT
77 count(*) FILTER (WHERE retired_at IS NOT NULL AND collected_at IS NULL) AS pending,
78 count(*) FILTER (WHERE orphan_candidate) AS orphans,
79 count(*) FILTER (WHERE quarantine_reason IS NOT NULL) AS quarantined,
80 min(collect_after) FILTER (WHERE retired_at IS NOT NULL AND collected_at IS NULL) AS oldest FROM ${schema}.chunk_objects`)).rows[0]!
81 return { ...result, backlog: { pendingDeletes: Number(counts.pending), orphanCandidates: Number(counts.orphans), quarantinedObjects: Number(counts.quarantined), oldestCollectAfter: counts.oldest } }
82 })
84/** Once per recovery operation; retry with identical settings after lost replies. */
85export async function configureReclamation(pool: Pool, options: ReclamationPolicyOptions): Promise<void> {
86 const schema = target(options), margin = options.safetyMarginMs ?? 900_000
87 if (typeof options.enabled !== 'boolean' || !Number.isSafeInteger(options.recoveryWindowMs) || options.recoveryWindowMs < 0 || options.recoveryWindowMs > 315_576_000_000
88 || !Number.isSafeInteger(margin) || margin < 900_000 || margin > 2_147_483_647) throw new RangeError('Invalid reclamation recovery policy')
89 await transaction(pool, {}, async (client) => {
90 const row = (await client.query<RecoveryRow>(`SELECT * FROM ${schema}.installation FOR UPDATE`)).rows[0]
91 validRecovery(row, options.token)
92 const policy = (await client.query<{ configured_recovery_token: string | null; enabled: boolean; recovery_window_ms: string; safety_margin_ms: number }>(`SELECT * FROM ${schema}.reclamation_policy FOR UPDATE`)).rows[0]!
93 if (policy.configured_recovery_token === options.token) {
94 if (policy.enabled !== options.enabled || BigInt(policy.recovery_window_ms) !== BigInt(options.recoveryWindowMs) || policy.safety_margin_ms !== margin) {
95 throw new StorageCompatibilityError('This recovery operation already configured a different reclamation policy')
96 }
97 return
98 }
99 await client.query(`UPDATE ${schema}.reclamation_policy SET enabled=$1,recovery_window_ms=$2,safety_margin_ms=$3,configured_recovery_token=$4,
100 inventory_cursor=NULL,hold_until=GREATEST(hold_until,clock_timestamp()+($2::bigint+$3::integer)*interval '1 millisecond')`, [options.enabled, options.recoveryWindowMs, margin, options.token])
101 // Existing promises may be extended, never shortened by a policy change.
102 // The global hold above covers a restore that discarded older promises.
103 })
105​
106/** Waits for existing writer transactions, changes epoch, and stops admission. */
107export async function beginRecovery(pool: Pool, options: RecoveryOptions): Promise<{ token: string; servingEpoch: string }> {
108 const schema = target(options)
109 if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(options.operationId)) throw new TypeError('Recovery operationId must be a UUID')
110 if (!options.environmentId || Buffer.byteLength(options.environmentId) > 2048
111 || (options.storageIdentity !== null && (!options.storageIdentity || options.storageIdentity.length > 2048))) throw new TypeError('Invalid recovery destination')
112 let publicBase: string | null = null
113 if (options.publicBaseUrl !== undefined) {
114 const url = new URL(options.publicBaseUrl)
115 if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password || url.search || url.hash || url.pathname.endsWith('/')) throw new TypeError('Invalid recovery public base URL')
116 publicBase = url.href
117 }
118 return transaction(pool, {}, async (client) => {
119 // FOR UPDATE conflicts with all writer KEY SHARE guards. Do not replace
120 // this with an ordinary UPDATE (which would take NO KEY UPDATE).
121 const current = (await client.query<RecoveryRow>(`SELECT * FROM ${schema}.installation FOR UPDATE`)).rows[0]
122 if (current?.serving_state === 'recovering' && current.id === options.expectedInstallationId && current.recovery_token === options.operationId
123 && current.recovery_source_epoch === options.expectedServingEpoch && current.recovery_target_environment === options.environmentId
124 && current.recovery_target_storage === options.storageIdentity && current.recovery_target_public_base_url === publicBase) {
125 return { token: options.operationId, servingEpoch: current.serving_epoch }
126 }
127 if (!current || current.id !== options.expectedInstallationId || current.serving_epoch !== options.expectedServingEpoch || current.serving_state !== 'active') {
128 throw new StorageCompatibilityError('Installation changed; inspect its current identity before starting recovery')
129 }
130 if (current.storage_identity !== null && options.storageIdentity === null) throw new StorageCompatibilityError('A tiered installation requires object storage during recovery')
131 const token = options.operationId, servingEpoch = randomUUID()
132 await client.query(`UPDATE ${schema}.installation SET serving_state = 'recovering', serving_epoch = $1, recovery_token = $2, recovery_source_epoch = $6,
133 recovery_target_environment = $3, recovery_target_storage = $4, recovery_target_public_base_url = $5, recovery_cursor = NULL, recovery_verified = 0,
134 recovery_complete = false, recovery_started_at = clock_timestamp()`, [servingEpoch, token, options.environmentId, options.storageIdentity, publicBase, options.expectedServingEpoch])
135 return { token, servingEpoch }
136 })
138​
139export interface VerifyRecoveryOptions extends OperationTarget {
140 readonly token: string
141 readonly objects?: ChunkStorage
142 readonly keyring?: SubscriptionKeyring
143 readonly maxChunks?: number
145/** Resumable, checksum-validated reconciliation. Object I/O holds no SQL lock. */
146export async function verifyRecovery(pool: Pool, options: VerifyRecoveryOptions): Promise<{ complete: boolean; verified: number }> {
147 const schema = target(options), maximum = options.maxChunks ?? 16
148 if (!Number.isSafeInteger(maximum) || maximum < 1 || maximum > 128) throw new RangeError('Invalid recovery batch size')
149 const before = (await pool.query<RecoveryRow>(`SELECT * FROM ${schema}.installation`)).rows[0]
150 validRecovery(before, options.token)
151 if ((options.objects?.identity ?? null) !== before.recovery_target_storage) throw new StorageCompatibilityError('Recovery object storage differs from the recorded target')
152 const signing = await pool.query(`SELECT 1 FROM ${schema}.webhook_signing_keys WHERE active`)
153 if (signing.rowCount) {
154 if (!options.keyring) throw new StorageCompatibilityError('Recovery requires the subscription wrapping keyring')
155 await new SubscriptionSigner(pool, options.schema ?? 'durable_streams', options.keyring).signature(Buffer.alloc(0))
156 }
157 if (before.recovery_complete) return { complete: true, verified: Number(before.recovery_verified) }
158 const reclamation = await pool.query(`SELECT 1 FROM ${schema}.migrations WHERE id='0006_reclamation'`)
159 const manifests = await pool.query<{ id: string; stream_id: string; object_key: string; sha256: string; encoded_bytes: number; frame_count: number; payload_bytes: string; start_offset: string; end_offset: string }>(
160 `SELECT * FROM ${schema}.chunks WHERE state = 'sealed' ${reclamation.rowCount ? 'AND retired_at IS NULL' : ''}
161 AND ($1::uuid IS NULL OR id > $1) ORDER BY id LIMIT $2`, [before.recovery_cursor, maximum])
162 for (const chunk of manifests.rows) {
163 if (!options.objects) throw new StorageCompatibilityError('Sealed manifests require target object storage')
164 const bytes = await options.objects.get(chunk.object_key, chunk.encoded_bytes)
165 if (bytes.length !== chunk.encoded_bytes) throw new StorageCompatibilityError('Recovery object length differs from manifest')
166 const frames = decodeChunk(bytes, { installationId: before.id, streamId: chunk.stream_id, chunkId: chunk.id }, chunk.sha256).frames
167 if (frames.length !== chunk.frame_count || frames[0]?.start !== chunk.start_offset || frames.at(-1)?.end !== chunk.end_offset
168 || BigInt(frames.reduce((n, frame) => n + frame.payload.length, 0)) !== BigInt(chunk.payload_bytes)) throw new StorageCompatibilityError('Recovery object frames differ from manifest')
169 }
170 return transaction(pool, {}, async (client) => {
171 const current = (await client.query<RecoveryRow>(`SELECT * FROM ${schema}.installation FOR UPDATE`)).rows[0]
172 validRecovery(current, options.token)
173 if (current.recovery_cursor !== before.recovery_cursor || current.recovery_verified !== before.recovery_verified) throw new StorageCompatibilityError('Recovery batch advanced concurrently; retry from its persisted cursor')
174 const complete = manifests.rows.length < maximum
175 const verified = Number(before.recovery_verified) + manifests.rows.length
176 await client.query(`UPDATE ${schema}.installation SET recovery_cursor = $1, recovery_verified = $2, recovery_complete = $3`,
177 [manifests.rows.at(-1)?.id ?? before.recovery_cursor, verified, complete])
178 return { complete, verified }
179 })
181​
182/** Activates only a completed reconciliation and fences all restored wakes. */
183export async function finishRecovery(pool: Pool, options: OperationTarget & { readonly token: string }): Promise<InstallationIdentity> {
184 const schema = target(options)
185 return transaction(pool, { timeoutMs: 60_000 }, async (client) => {
186 const row = (await client.query<RecoveryRow>(`SELECT * FROM ${schema}.installation FOR UPDATE`)).rows[0]
187 if (row?.serving_state === 'active' && row.completed_recovery_token === options.token) {
188 return { id: row.id, serving_epoch: row.serving_epoch, serving_state: row.serving_state, environment_id: row.environment_id, storage_identity: row.storage_identity }
189 }
190 validRecovery(row, options.token)
191 if (!row.recovery_complete) throw new StorageCompatibilityError('Verify every sealed manifest before activating this installation')
192 const readers = await client.query(`SELECT 1 FROM ${schema}.live_leases WHERE expires_at > clock_timestamp() AND serving_epoch <> $1 LIMIT 1`, [row.serving_epoch])
193 if (readers.rowCount) throw new StorageCompatibilityError('Drain active live readers or wait for their bounded leases before activating recovery')
194 const reclamation = await client.query(`SELECT 1 FROM ${schema}.migrations WHERE id='0006_reclamation'`)
195 if (reclamation.rowCount) {
196 const replays = await client.query(`SELECT 1 FROM ${schema}.replay_pins WHERE expires_at>clock_timestamp() AND serving_epoch<>$1 LIMIT 1`, [row.serving_epoch])
197 if (replays.rowCount) throw new StorageCompatibilityError('Drain active replay readers or wait for their bounded pins before activating recovery')
198 await client.query(`DELETE FROM ${schema}.replay_pins`)
199 await client.query(`UPDATE ${schema}.chunk_objects SET claim_token=NULL, claim_until=NULL, claim_epoch=claim_epoch+1 WHERE retired_at IS NOT NULL`)
200 await client.query(`UPDATE ${schema}.reclamation_policy SET inventory_cursor=NULL,
201 hold_until=GREATEST(hold_until,clock_timestamp()+(recovery_window_ms+safety_margin_ms)*interval '1 millisecond')`)
202 }
203 // Process eviction can leave durable claims and leases behind. UUID tokens
204 // invalidate callbacks issued on either side of a point-in-time rollback.
205 await client.query(`UPDATE ${schema}.chunks SET claim_token = NULL, claim_until = NULL, claim_epoch = claim_epoch + 1 WHERE state = 'frozen'`)
206 await client.query(`UPDATE ${schema}.subscription_wakes SET state = 'fenced', delivery_claim = NULL, delivery_until = NULL WHERE state IN ('ready', 'delivered')`)
207 await client.query(`UPDATE ${schema}.subscriptions SET current_wake = NULL, holder = NULL, lease_until = NULL,
208 retry_count = 0, retry_at = NULL, next_work_at = clock_timestamp(),
209 public_base_url = COALESCE((SELECT recovery_target_public_base_url FROM ${schema}.installation), public_base_url) WHERE deleted_at IS NULL`)
210 await client.query(`DELETE FROM ${schema}.live_leases`)
211 const activated = await client.query<InstallationIdentity>(`UPDATE ${schema}.installation SET serving_state = 'active',
212 environment_id = recovery_target_environment, storage_identity = recovery_target_storage, completed_recovery_token = recovery_token, recovery_token = NULL
213 RETURNING id, serving_epoch, serving_state, environment_id, storage_identity`)
214 return activated.rows[0]!
215 })