Files
MikrotikManager/backend/src/db/database-restore-quarantine.ts
T

142 lines
6.8 KiB
TypeScript

/** Provision outside application migrations, after the control schema exists. */
export const DATABASE_RESTORE_QUARANTINE_DDL = `
CREATE TABLE mmapp_control.database_restore_quarantine (
id smallint PRIMARY KEY CHECK (id = 1),
operation_id uuid,
journal_prefix_bytes integer,
journal_prefix_sha256 text,
CONSTRAINT database_restore_quarantine_journal_head CHECK (
(journal_prefix_bytes IS NULL) = (journal_prefix_sha256 IS NULL)
AND journal_prefix_bytes BETWEEN 1 AND 8388608
AND journal_prefix_sha256 ~ '^[a-f0-9]{64}$'
)
);
INSERT INTO mmapp_control.database_restore_quarantine (id) VALUES (1);
`
interface QuarantineClient {
query(sql: string, values: (string | null)[]): Promise<unknown>
}
export interface RestoreJournalHead {
bytes: number
sha256: string
}
interface RestoreJournalHeadAdvance {
expected: RestoreJournalHead | null
next: RestoreJournalHead
}
const operationId = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/
// A transaction holding a writer key must see the currently committed claim.
const readSql = `SELECT operation_id::pg_catalog.text AS operation_id
FROM mmapp_control.database_restore_quarantine
WHERE id = 1 AND pg_catalog.current_setting('transaction_isolation') = 'read committed'`
// The restore caller commits the change with synchronous_commit enabled.
const updateSql = `UPDATE mmapp_control.database_restore_quarantine
SET operation_id = $1::pg_catalog.uuid
WHERE id = 1 AND operation_id IS NOT DISTINCT FROM $2::pg_catalog.uuid
RETURNING operation_id::pg_catalog.text AS operation_id`
const readHeadSql = `SELECT pg_catalog.to_jsonb(quarantine) AS quarantine
FROM mmapp_control.database_restore_quarantine AS quarantine
WHERE id = 1 AND pg_catalog.current_setting('transaction_isolation') = 'read committed'`
const updateHeadSql = `UPDATE mmapp_control.database_restore_quarantine
SET operation_id = $1::pg_catalog.uuid, journal_prefix_bytes = $3::pg_catalog.int4, journal_prefix_sha256 = $4::pg_catalog.text
WHERE id = 1 AND operation_id IS NOT DISTINCT FROM $2::pg_catalog.uuid
AND journal_prefix_bytes IS NOT DISTINCT FROM $5::pg_catalog.int4
AND journal_prefix_sha256 IS NOT DISTINCT FROM $6::pg_catalog.text
RETURNING operation_id::pg_catalog.text AS operation_id, journal_prefix_bytes, journal_prefix_sha256`
function unavailable() {
return Object.assign(new Error("Состояние базы после восстановления не подтверждено"), {
code: "DATABASE_RESTORE_QUARANTINE_UNAVAILABLE", statusCode: 503,
})
}
export function databaseRestoreQuarantineEnabled(): boolean {
return process.env.DATABASE_RESTORE_QUARANTINE === "true"
}
function isRecord(value: unknown): value is Record<string, unknown> {
return !!value && typeof value === "object" && !Array.isArray(value)
}
async function readSingleRow(client: QuarantineClient, sql: string, values: (string | null)[]): Promise<Record<string, unknown>> {
let result
try { result = await client.query(sql, values) }
catch { throw unavailable() }
if (!isRecord(result) || !Array.isArray(result.rows) || result.rows.length !== 1 || !isRecord(result.rows[0])) throw unavailable()
return result.rows[0]
}
function validHead(bytes: unknown, sha256: unknown): boolean {
return typeof bytes === "number" && Number.isInteger(bytes) && bytes >= 1 && bytes <= 8_388_608 &&
typeof sha256 === "string" && sha256.length === 64 && /^[a-f0-9]{64}$/.test(sha256)
}
async function requireState(client: QuarantineClient, nextId: string | null, previousId: string | null, heads?: RestoreJournalHeadAdvance): Promise<void> {
const values = [nextId, previousId]
if (!heads) {
const row = await readSingleRow(client, updateSql, values)
if (row.operation_id !== nextId || Object.keys(row).length !== 1) throw unavailable()
return
}
const { expected, next } = heads
if (!validHead(next.bytes, next.sha256) || (expected && !validHead(expected.bytes, expected.sha256)) ||
next.bytes <= (expected?.bytes ?? 0)) throw unavailable()
const row = await readSingleRow(client, updateHeadSql, [
...values, String(next.bytes), next.sha256, expected ? String(expected.bytes) : null, expected?.sha256 ?? null,
])
if (row.operation_id !== nextId || row.journal_prefix_bytes !== next.bytes ||
row.journal_prefix_sha256 !== next.sha256 || Object.keys(row).length !== 3) throw unavailable()
}
export async function assertDatabaseRestoreQuarantineOpen(client: QuarantineClient): Promise<void> {
const row = await readSingleRow(client, readSql, [])
if (row.operation_id !== null || Object.keys(row).length !== 1) throw unavailable()
}
/** Undefined is the original schema. Null is a provisioned head before its first write. */
async function readQuarantineRow(client: QuarantineClient) {
const row = await readSingleRow(client, readHeadSql, [])
const { quarantine } = row
if (Object.keys(row).length !== 1 || !isRecord(quarantine) || quarantine.id !== 1) throw unavailable()
return quarantine
}
function journalHead(quarantine: Record<string, unknown>): RestoreJournalHead | null | undefined {
const hasBytes = Object.hasOwn(quarantine, "journal_prefix_bytes")
const hasDigest = Object.hasOwn(quarantine, "journal_prefix_sha256")
if (!hasBytes && !hasDigest) return undefined
const { journal_prefix_bytes: bytes, journal_prefix_sha256: sha256 } = quarantine
if (bytes === null && sha256 === null) return null
if (!validHead(bytes, sha256)) throw unavailable()
return { bytes: bytes as number, sha256: sha256 as string }
}
export async function readDatabaseRestoreJournalHead(client: QuarantineClient, expectedOperationId?: string): Promise<RestoreJournalHead | null | undefined> {
const quarantine = await readQuarantineRow(client)
if (expectedOperationId !== undefined && (!operationId.test(expectedOperationId) || quarantine.operation_id !== expectedOperationId)) throw unavailable()
return journalHead(quarantine)
}
export async function readDatabaseRestoreQuarantineStatus(client: QuarantineClient) {
const quarantine = await readQuarantineRow(client)
const activeOperationId = quarantine.operation_id
const head = journalHead(quarantine)
if (head === undefined || (activeOperationId !== null && (typeof activeOperationId !== "string" || !operationId.test(activeOperationId)))) throw unavailable()
return { activeOperationId, head }
}
export async function beginDatabaseRestoreQuarantine(client: QuarantineClient, id: string, heads?: RestoreJournalHeadAdvance): Promise<void> {
if (typeof id !== "string" || !operationId.test(id)) throw unavailable()
await requireState(client, id, null, heads)
}
export async function completeDatabaseRestoreQuarantine(client: QuarantineClient, id: string, heads?: RestoreJournalHeadAdvance): Promise<void> {
if (typeof id !== "string" || !operationId.test(id)) throw unavailable()
await requireState(client, null, id, heads)
}