UNPKG

syncguard

Version:

Functional TypeScript library for distributed locking across microservices. Prevents race conditions with Redis, PostgreSQL, Firestore, and custom backends. Features automatic lock management, timeout handling, and extensible architecture.

33 lines (32 loc) 1.56 kB
import type { Sql } from "postgres"; import { type ExtendResult, type LockOp } from "../../common/backend.js"; import type { PostgresConfig } from "../types.js"; /** * Creates PostgreSQL extend operation with atomic transaction and authoritative expiresAtMs. * * **Implementation Pattern:** * - Atomic transaction: Query by lockId → verify ownership → update expiresAtMs * - TOCTOU protection: All steps within single `sql.begin()` transaction * - Ownership verification: Explicit `data.lock_id === opts.lockId` check (ADR-003) * - Authoritative time: MUST capture server time inside transaction (ADR-010) * - TTL semantics: Replaces remaining TTL entirely (`nowMs + ttlMs`), not additive * - AbortSignal: Manual cancellation checks via `checkAborted()` at strategic points * * Transaction flow: * 1. Get server time for authoritative timestamp * 2. Query by lockId using index (FOR UPDATE for row-level lock) * 3. Verify ownership (data.lock_id === lockId) * 4. Check liveness using isLive() predicate * 5. If all checks pass, compute new expiresAtMs from server time * 6. Update expires_at_ms in database * 7. Return success with authoritative expiresAtMs * * @param sql - postgres.js SQL instance * @param config - PostgreSQL backend configuration * @returns Extend operation function * * @see docs/specs/interface.md#extend-operation-requirements - Normative TOCTOU requirements */ export declare function createExtendOperation(sql: Sql, config: PostgresConfig): (opts: LockOp & { ttlMs: number; }) => Promise<ExtendResult>;