import { Service } from "../lib/service" import * as mongodb from "mongodb" import * as Leaf from "leaf-ts" export const Errors = Leaf.ErrorDoc.create() .define("NotAvailable") .generate() as Leaf.ErrorsOf<{ NotAvailable: {} }> export class MemoryLockService extends Service { readonly name = "MemoryLockService" services: {} private locks: { [key: string]: any } = {} constructor() { super({}, {}) } public lock(resource: string | string[], callback: (err: Error, locks?: Locks) => void) { if (resource === "string") { resource = [resource] } let resources = resource let locks: Locks = {} for (let res of resources) { if (!this.locks[res]) { locks[res] = Math.random().toString().slice(3, 10) } else { callback(new Errors.NotAvailable()) return } } for (let res in locks) { this.locks[res] = locks[res] } callback(null, locks) } private counter = 0 private GC_COUNT = 20000 public release(locks: Locks, callback: Function = () => { }) { for (let res in locks) { let lock = locks[res] if (this.locks[res] !== lock) { // skip unequallock continue } this.locks[res] = null this.counter++ } if (this.counter >= this.GC_COUNT) { this.gc() } callback() } // defer callback public defer(locks: Locks, callback: T): T { let fn = (...args: any[]) => { this.release(locks, () => { callback(...args) }) } return fn as any as T } private gc() { let locks = {} // Here we don't delege empty field, we just build a new locks. // There are usually very few living locks for (let prop in this.locks) { let v = this.locks[prop] if (v) { locks[prop] = v } } this.locks = locks } } export interface Locks { [resource: string]: string }