124 lines
5.9 KiB
TypeScript
124 lines
5.9 KiB
TypeScript
/** Trusted runner-only reuse of its OWN operation advisory connection.
|
|
* No arbitrary SQL, checkout, healthy release or raw-client access is exported. */
|
|
import { AsyncLocalStorage } from "node:async_hooks"
|
|
import type { PoolClient, QueryResultRow } from "pg"
|
|
|
|
export interface OperationConfigurationLockClient {
|
|
query<T extends QueryResultRow = QueryResultRow>(text: string, values?: unknown[]): Promise<{ rows: T[] }>
|
|
release(unsafe?: boolean): void
|
|
}
|
|
type Entry = {
|
|
active: boolean; client: PoolClient; retireOwned: () => void
|
|
ownerSignal: AbortSignal
|
|
requestSignal?: AbortSignal
|
|
borrowers: Set<symbol>; pending: symbol | undefined
|
|
stopped: Promise<never>; rejectStopped: () => void
|
|
completed: Promise<void>
|
|
}
|
|
const scope = new AsyncLocalStorage<Entry>()
|
|
function refused(): never { throw new Error("Operation configuration lock lease is closed or busy") }
|
|
function capture(text: string, values?: unknown[]): unknown[] | undefined {
|
|
if (text === "SELECT pg_try_advisory_lock(hashtextextended('mm-config:application',0)) AS acquired"
|
|
|| text === "SELECT pg_advisory_unlock(hashtextextended('mm-config:application',0))") {
|
|
if (values !== undefined && (!Array.isArray(values) || values.length !== 0 || Reflect.ownKeys(values).length !== 1)) refused()
|
|
return undefined
|
|
}
|
|
if (text !== "SELECT pg_try_advisory_lock(hashtextextended($1,0)) AS acquired"
|
|
&& text !== "SELECT pg_advisory_unlock(hashtextextended($1,0))") refused()
|
|
if (!Array.isArray(values) || values.length !== 1 || Reflect.ownKeys(values).length !== 2) refused()
|
|
const descriptor=Object.getOwnPropertyDescriptor(values,"0")
|
|
if(!descriptor||!("value" in descriptor)||!descriptor.enumerable||typeof descriptor.value!=="string")refused()
|
|
const key=descriptor.value as string
|
|
const match = /^mm-config:([1-9][0-9]*)$/.exec(key)
|
|
if (!match || !Number.isSafeInteger(Number(match[1]))) refused()
|
|
return [key]
|
|
}
|
|
function close(entry: Entry, unsafe = false): void {
|
|
if (!entry.active) return
|
|
entry.active = false
|
|
entry.rejectStopped()
|
|
// A pending query, or a child still owning a lock facade, cannot return the
|
|
// operation client to the pool. The runner is the sole physical releaser.
|
|
if (unsafe || entry.pending !== undefined || entry.borrowers.size) entry.retireOwned()
|
|
}
|
|
export function assertNoOperationConfigurationLockContext(): void { if (scope.getStore()) refused() }
|
|
/** Fixed automatic-job handoff waits for original runner WORK to settle. This
|
|
* exposes no client, scope clearing function or arbitrary execution callback. */
|
|
export function captureOperationConfigurationLockHandoff(): Promise<void> | undefined {
|
|
const entry = scope.getStore()
|
|
if (!entry) return undefined
|
|
if (!entry.active) refused()
|
|
return entry.completed
|
|
}
|
|
export function assertOperationConfigurationLockScope(): void {
|
|
const entry = scope.getStore()
|
|
if (entry && !entry.active) refused()
|
|
entry?.requestSignal?.throwIfAborted()
|
|
}
|
|
export function operationConfigurationSignal(): AbortSignal | undefined { return scope.getStore()?.ownerSignal }
|
|
export function operationDatabaseRequestSignal(): AbortSignal | undefined { return scope.getStore()?.requestSignal }
|
|
function checkpoint(entry: Entry): void {
|
|
if (!entry.active) refused()
|
|
if (entry.pending !== undefined || entry.borrowers.size) { close(entry, true); refused() }
|
|
}
|
|
/** A terminal acknowledgement cannot adopt dangling borrowed lock work. */
|
|
export function assertOperationConfigurationLockCheckpoint(): void {
|
|
const entry = scope.getStore()
|
|
if (!entry) refused()
|
|
checkpoint(entry)
|
|
entry.requestSignal?.throwIfAborted()
|
|
}
|
|
export async function withOperationConfigurationLockClient<T>(client: PoolClient, retireOwned: () => void, ownerSignal: AbortSignal, work: () => Promise<T>, requestSignal?: AbortSignal): Promise<T> {
|
|
if (scope.getStore()?.active) refused()
|
|
let rejectStopped!: () => void
|
|
const stopped = new Promise<never>((_resolve, reject) => { rejectStopped = () => reject(new Error("Operation configuration lock scope ended")) })
|
|
// A scope with no borrowed query still closes this lifetime promise.
|
|
void stopped.catch(() => {})
|
|
let complete!: () => void
|
|
const completed = new Promise<void>(resolve => { complete = resolve })
|
|
const entry: Entry = { active: true, client, retireOwned, ownerSignal, requestSignal, borrowers: new Set(), pending: undefined, stopped, rejectStopped, completed }
|
|
const ownerStopped = () => close(entry, true)
|
|
ownerSignal.addEventListener("abort", ownerStopped, { once: true })
|
|
try {
|
|
if (ownerSignal.aborted) { close(entry, true); refused() }
|
|
const result = await scope.run(entry, work)
|
|
checkpoint(entry)
|
|
return result
|
|
} finally {
|
|
ownerSignal.removeEventListener("abort", ownerStopped)
|
|
try { close(entry) } finally { complete() }
|
|
}
|
|
}
|
|
export function borrowOperationConfigurationLockClient(): OperationConfigurationLockClient | undefined {
|
|
const entry = scope.getStore()
|
|
if (!entry) return undefined
|
|
assertOperationConfigurationLockScope()
|
|
const owner = Symbol()
|
|
let active = true
|
|
entry.borrowers.add(owner)
|
|
const live = () => { if (!entry.active || !active) refused() }
|
|
return Object.freeze({
|
|
async query<T extends QueryResultRow = QueryResultRow>(text: string, values?: unknown[]) {
|
|
live()
|
|
const captured = capture(text, values)
|
|
if (entry.pending !== undefined) { close(entry, true); refused() }
|
|
entry.pending = owner
|
|
try {
|
|
const result = await Promise.race([
|
|
Promise.resolve().then(() => { live(); return entry.client.query<T>(text, captured) }),
|
|
entry.stopped,
|
|
])
|
|
live()
|
|
return result
|
|
} catch { close(entry, true); refused() }
|
|
finally { if (entry.pending === owner) entry.pending = undefined }
|
|
},
|
|
release(unsafe = false) {
|
|
if (!active) return
|
|
active = false
|
|
entry.borrowers.delete(owner)
|
|
if (entry.active && (unsafe || entry.pending === owner)) close(entry, true)
|
|
},
|
|
})
|
|
}
|