import { stringifyError } from '@nangohq/utils';
export class Locking {
    store;
    constructor(store) {
        this.store = store;
    }
    async tryAcquire(key, ttlInMs, acquisitionTimeoutMs) {
        if (ttlInMs <= 0) {
            throw new Error(`lock's TTL must be greater than 0`);
        }
        if (acquisitionTimeoutMs <= 0) {
            throw new Error(`acquisitionTimeoutMs must be greater than 0`);
        }
        const start = Date.now();
        while (Date.now() - start < acquisitionTimeoutMs) {
            try {
                await this.acquire(key, ttlInMs);
                return { key };
            }
            catch {
                await new Promise((resolve) => setTimeout(resolve, 50));
            }
        }
        throw new Error(`Acquiring lock for key: ${key} timed out after ${acquisitionTimeoutMs}ms`);
    }
    async acquire(key, ttlInMs) {
        if (ttlInMs <= 0) {
            throw new Error(`lock's TTL must be greater than 0`);
        }
        try {
            await this.store.set(key, '1', false, ttlInMs);
        }
        catch (err) {
            throw new Error(`Failed to acquire lock for key: ${key} ${stringifyError(err)}`);
        }
        return { key };
    }
    async release(lock) {
        await this.store.delete(lock.key);
    }
}
//# sourceMappingURL=locking.js.map