Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
184 changes: 184 additions & 0 deletions src/sandbox/distributed-lock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
import { randomUUID } from "node:crypto";

export interface DistributedLockHandle {
lockId: string;
resourceKey: string;
ownerId: string;
fenceToken: number;
acquiredAt: number;
expiresAt: number;
leaseTtlMs: number;
}

export interface DistributedLockOptions {
leaseTtlMs?: number; // default: 5000ms
retryCount?: number; // default: 3
retryDelayMs?: number; // default: 50ms
ownerId?: string;
}

export interface LockStateSnapshot {
resourceKey: string;
ownerId: string;
fenceToken: number;
remainingTtlMs: number;
}

/**
* Enterprise Multi-Replica Distributed Lock & State Synchronization Manager.
* Enforces transaction isolation and mutual exclusion across distributed DBShield
* proxy replicas during two-phase commit verification and dry-run shadow execution.
* Implements monotonic fencing tokens to prevent split-brain mutations.
*/
export class DistributedLockManager {
private static globalFenceCounter = 1;
private readonly locks: Map<string, DistributedLockHandle> = new Map();
private readonly lockHistory: DistributedLockHandle[] = [];

/**
* Attempts to acquire a distributed lock on a database resource or table.
* Returns a lock handle containing a monotonically increasing fencing token.
*/
public async acquireLock(
resourceKey: string,
options: DistributedLockOptions = {},
): Promise<DistributedLockHandle | null> {
const leaseTtlMs = options.leaseTtlMs ?? 5000;
const retryCount = options.retryCount ?? 3;
const retryDelayMs = options.retryDelayMs ?? 20;
const ownerId = options.ownerId || `replica_${randomUUID().slice(0, 8)}`;

for (let attempt = 0; attempt <= retryCount; attempt++) {
const now = Date.now();
const existing = this.locks.get(resourceKey);

// 1. If lock exists but has expired, automatically purge it
if (existing && existing.expiresAt <= now) {
this.locks.delete(resourceKey);
}

// 2. If unlocked, acquire atomically
if (!this.locks.has(resourceKey)) {
const fenceToken = ++DistributedLockManager.globalFenceCounter;
const handle: DistributedLockHandle = {
lockId: `lock_${randomUUID().slice(0, 12)}`,
resourceKey,
ownerId,
fenceToken,
acquiredAt: now,
expiresAt: now + leaseTtlMs,
leaseTtlMs,
};

this.locks.set(resourceKey, handle);
this.lockHistory.push(handle);
return handle;
}

// 3. Retry with jittered backoff
if (attempt < retryCount) {
const jitter = Math.floor(Math.random() * 10);
await new Promise((resolve) => setTimeout(resolve, retryDelayMs + jitter));
}
}

// Failed to acquire within retry ceiling
return null;
}

/**
* Releases an acquired lock safely with owner and fencing token validation.
*/
public async releaseLock(handle: DistributedLockHandle): Promise<boolean> {
if (!handle || !handle.resourceKey) return false;

const current = this.locks.get(handle.resourceKey);
if (!current) return true; // Already expired and released

// Guard against releasing a lock that was overtaken by another worker
if (current.lockId === handle.lockId && current.ownerId === handle.ownerId) {
this.locks.delete(handle.resourceKey);
return true;
}

return false;
}

/**
* Extends lease time for long-running two-phase commit verification.
*/
public async renewLease(handle: DistributedLockHandle, extraTtlMs?: number): Promise<boolean> {
const current = this.locks.get(handle.resourceKey);
if (!current || current.lockId !== handle.lockId) return false;

const extension = extraTtlMs ?? handle.leaseTtlMs;
current.expiresAt = Date.now() + extension;
handle.expiresAt = current.expiresAt;
return true;
}

/**
* Executes a critical database operation protected by a distributed lease.
*/
public async withDistributedLock<T>(
resourceKey: string,
action: (fenceToken: number) => Promise<T>,
options?: DistributedLockOptions,
): Promise<T> {
const lock = await this.acquireLock(resourceKey, options);
if (!lock) {
throw new Error(
`[DBShield:DistributedLock] Failed to acquire isolation lease on resource '${resourceKey}'`,
);
}

try {
return await action(lock.fenceToken);
} finally {
await this.releaseLock(lock);
}
}

/**
* Checks if a resource is actively locked by any replica.
*/
public isLocked(resourceKey: string): boolean {
const existing = this.locks.get(resourceKey);
if (!existing) return false;
if (existing.expiresAt <= Date.now()) {
this.locks.delete(resourceKey);
return false;
}
return true;
}

/**
* Returns snapshot of all currently active locks across the cluster.
*/
public getActiveLocks(): LockStateSnapshot[] {
const now = Date.now();
const active: LockStateSnapshot[] = [];

for (const [key, lock] of this.locks.entries()) {
if (lock.expiresAt > now) {
active.push({
resourceKey: key,
ownerId: lock.ownerId,
fenceToken: lock.fenceToken,
remainingTtlMs: lock.expiresAt - now,
});
} else {
this.locks.delete(key);
}
}

return active;
}

/**
* Clears all locks (e.g. for testing cleanup).
*/
public clear(): void {
this.locks.clear();
}
}
1 change: 1 addition & 0 deletions src/sandbox/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ export * from "./tokens.js";
export * from "./engine.js";
export * from "./distributed-tokens.js";
export * from "./distributed.js";
export * from "./distributed-lock.js";
export * from "./shadow-db.js";
120 changes: 120 additions & 0 deletions tests/distributed-lock.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import assert from "node:assert/strict";
import test from "node:test";
import { DistributedLockManager } from "../src/sandbox/distributed-lock.js";

test("DistributedLockManager acquires lock with monotonic fencing token", async () => {
const manager = new DistributedLockManager();

const handle1 = await manager.acquireLock("table:accounts", { ownerId: "replica_A" });
assert.ok(handle1, "Must acquire lock successfully");
assert.equal(handle1.resourceKey, "table:accounts");
assert.equal(handle1.ownerId, "replica_A");
assert.ok(handle1.fenceToken > 0, "Fence token must be positive monotonic number");

const isLocked = manager.isLocked("table:accounts");
assert.equal(isLocked, true);

await manager.releaseLock(handle1);
assert.equal(manager.isLocked("table:accounts"), false);
});

test("DistributedLockManager enforces mutual exclusion across concurrent replicas", async () => {
const manager = new DistributedLockManager();

const lock1 = await manager.acquireLock("table:orders", {
ownerId: "replica_1",
leaseTtlMs: 2000,
});
assert.ok(lock1);

// Replica 2 attempts to acquire the same resource concurrently
const lock2 = await manager.acquireLock("table:orders", {
ownerId: "replica_2",
retryCount: 1,
retryDelayMs: 10,
});
assert.equal(lock2, null, "Concurrent replica must be blocked while lock is held");

// Release lock 1
const released = await manager.releaseLock(lock1);
assert.equal(released, true);

// Now Replica 2 can acquire
const lock2After = await manager.acquireLock("table:orders", {
ownerId: "replica_2",
});
assert.ok(lock2After, "Replica 2 must acquire after lock 1 is released");
assert.ok(lock2After.fenceToken > lock1.fenceToken, "Fencing token must strictly increase");

await manager.releaseLock(lock2After);
});

test("DistributedLockManager prevents stale worker from releasing hijacked lock", async () => {
const manager = new DistributedLockManager();

const lockA = await manager.acquireLock("table:ledger", { ownerId: "worker_slow" });
assert.ok(lockA);

// Fake stolen handle with different owner
const fakeHandle = { ...lockA, ownerId: "worker_imposter" };
const released = await manager.releaseLock(fakeHandle);
assert.equal(released, false, "Imposter or stale owner must not be allowed to release lock");

// Clean release by real owner
assert.equal(await manager.releaseLock(lockA), true);
});

test("DistributedLockManager automatically purges expired leases", async () => {
const manager = new DistributedLockManager();

// Acquire with tiny TTL (50ms)
const lock = await manager.acquireLock("table:ephemeral", {
ownerId: "worker_quick",
leaseTtlMs: 50,
});
assert.ok(lock);

// Wait 70ms for expiration
await new Promise((r) => setTimeout(r, 70));

assert.equal(manager.isLocked("table:ephemeral"), false);

// New worker can immediately acquire without deadlocking
const newLock = await manager.acquireLock("table:ephemeral", {
ownerId: "worker_new",
});
assert.ok(newLock, "New worker must acquire expired lock seamlessly");

await manager.releaseLock(newLock);
});

test("withDistributedLock executes protected block and releases automatically on error", async () => {
const manager = new DistributedLockManager();

let executedToken = 0;
await manager.withDistributedLock("table:customers", async (fenceToken) => {
executedToken = fenceToken;
assert.ok(manager.isLocked("table:customers"));
});

assert.ok(executedToken > 0);
assert.equal(manager.isLocked("table:customers"), false, "Lock must be released after block");

// Verify release even on exception
let caught = false;
try {
await manager.withDistributedLock("table:customers", async () => {
throw new Error("Simulated mutation failure");
});
} catch (err: any) {
caught = true;
assert.equal(err.message, "Simulated mutation failure");
}

assert.equal(caught, true);
assert.equal(
manager.isLocked("table:customers"),
false,
"Lock must be released even after thrown error",
);
});
Loading