Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

1.7 KB
Raw Blame
import { E_ALREADY_LOCKED, E_TIMEOUT, Mutex, MutexInterface, tryAcquire as makeTryAcquire, withTimeout } from 'async-mutex'

const memoryLocks = new Map<string, MutexInterface>()

export const memoryLock = {
    acquire: async (key: string, timeout?: number): Promise<ApLock> => {
        let lock = memoryLocks.get(key)
        if (!lock) {
            if (timeout) {
                lock = withTimeout(new Mutex(), timeout)
            }
            else {
                lock = new Mutex()
            }
            memoryLocks.set(key, lock)
        }
        const release = await lock.acquire()
        return {
            release: async () => {
                release()
            },
        }
    },
    tryAcquire: async (key: string): Promise<ApLock | null> => {
        let lock = memoryLocks.get(key)
        if (!lock) {
            lock = new Mutex()
            memoryLocks.set(key, lock)
        }
        try {
            const release = await makeTryAcquire(lock).acquire()
            return {
                release: async () => {
                    release()
                },
            }
        }
        catch (e) {
            if (e === E_ALREADY_LOCKED) {
                return null
            }
            throw e
        }
    },
    isTimeoutError: (e: unknown): boolean => {
        return e === E_TIMEOUT
    },
    runExclusive: async <T>({ key, fn }: RunExclusiveParams<T>): Promise<T> => {
        const lock = await memoryLock.acquire(key)
        try {
            return await fn()
        }
        finally {
            await lock.release()
        }
    },
}

type RunExclusiveParams<T> = {
    key: string
    fn: () => Promise<T>
}

export type ApLock = {
    release(): Promise<unknown>
}