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.

28 lines (27 loc) 1.27 kB
import type { Sql } from "postgres"; import { type AcquireResult, type KeyOp } from "../../common/backend.js"; import type { PostgresCapabilities, PostgresConfig } from "../types.js"; /** * Creates PostgreSQL acquire operation with atomic transaction. * * Transaction flow: * 1. Acquire advisory lock on storage key (serializes concurrent acquires) * 2. Get server time * 3. Check if lock exists and is live * 4. If live, return contention * 5. Increment fence counter atomically using two-step pattern: * a. INSERT ... ON CONFLICT DO NOTHING (ensures row exists) * b. UPDATE ... RETURNING (implicit row lock serializes concurrent increments) * This pattern prevents absent-row race where multiple clients both see * missing row and both insert fence=1. * 6. Insert/update lock with new lockId and fence * 7. Return success with authoritative server-time expiresAtMs * 8. Advisory lock automatically released on transaction commit * * @param sql - postgres.js SQL instance * @param config - PostgreSQL backend configuration * @returns Acquire operation function */ export declare function createAcquireOperation(sql: Sql, config: PostgresConfig): (opts: KeyOp & { ttlMs: number; }) => Promise<AcquireResult<PostgresCapabilities>>;