mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-07-31 09:09:54 +08:00
4125038ff8
TODO - [x] basic - [x] storages - [x] producer/consumer - [x] operation pattern - [x] events - [x] worker - [x] readme - [x] peer dependencies
45 lines
974 B
TypeScript
45 lines
974 B
TypeScript
export interface Locker {
|
|
lock(domain: string, resource: string): Promise<Lock>;
|
|
}
|
|
|
|
export class SingletonLocker implements Locker {
|
|
lockedResource = new Map<string, Lock>();
|
|
constructor() {}
|
|
|
|
async lock(domain: string, resource: string) {
|
|
const key = `${domain}:${resource}`;
|
|
let lock = this.lockedResource.get(key);
|
|
|
|
if (!lock) {
|
|
lock = new Lock();
|
|
this.lockedResource.set(key, lock);
|
|
}
|
|
|
|
await lock.acquire();
|
|
|
|
return lock;
|
|
}
|
|
}
|
|
|
|
export class Lock {
|
|
private inner: Promise<void> = Promise.resolve();
|
|
private release: () => void = () => {};
|
|
|
|
async acquire() {
|
|
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
let release: () => void = null!;
|
|
const nextLock = new Promise<void>(resolve => {
|
|
release = resolve;
|
|
});
|
|
|
|
await this.inner;
|
|
this.inner = nextLock;
|
|
this.release = release;
|
|
}
|
|
|
|
[Symbol.asyncDispose]() {
|
|
this.release();
|
|
return Promise.resolve();
|
|
}
|
|
}
|