This repository has no description
0

Configure Feed

Select the types of activity you want to include in your feed.

semble / src / shared / infrastructure / locking / InMemoryDistributedLockService.ts
1.1 kB 40 lines
1import { IDistributedLockService } from './IDistributedLockService'; 2 3/** 4 * In-memory distributed locking service for development and testing. 5 * 6 * Provides lock functionality using in-memory state. This is suitable for: 7 * - Local development with a single worker 8 * - Unit/integration tests 9 * - Mock persistence mode 10 * 11 * NOT suitable for production with multiple workers/instances. 12 */ 13export class InMemoryDistributedLockService implements IDistributedLockService { 14 private locks: Map<string, boolean> = new Map(); 15 16 async withLock<T>( 17 key: string, 18 ttl: number, 19 fn: () => Promise<T>, 20 ): Promise<T> { 21 // Simple lock acquisition - throws if already locked 22 if (this.locks.get(key)) { 23 throw new Error(`Lock already held for key: ${key}`); 24 } 25 26 this.locks.set(key, true); 27 28 // Set TTL to auto-release lock (safety mechanism) 29 const timeout = setTimeout(() => { 30 this.locks.delete(key); 31 }, ttl); 32 33 try { 34 return await fn(); 35 } finally { 36 clearTimeout(timeout); 37 this.locks.delete(key); 38 } 39 } 40}