JSPM

@arsat/lock

1.0.0
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • 0
  • Score
    100M100P100Q17301F
  • License ISC

A TypeScript decorator for methods that ensures only one instance of the method can run at a time, using a mutex with a configurable timeout.

Package Exports

  • @arsat/lock
  • @arsat/lock/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@arsat/lock) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Lock

Description

A decorator for methods in TypeScript that ensures that only one instance of the method can be executed at a time, using a mutex with a configurable timeout. This decorator uses the async-mutex library from npm.

Dependencies

This package relies on the async-mutex library from npm. Make sure it is installed in your project:

npm install async-mutex

Key Features:

Installation

You can install the Lock library using npm or yarn.

Using npm

npm install @arsat/lock

Using npm

yarn add @arsat/lock

Usage

Basic Example

Here's a basic example of how to use the Lock library to combine multiple classes:

import { Lock, ILockConfig } from "@arsat/lock";

const delay = (time: number) =>
  new Promise((resolve) => setTimeout(resolve, time));

class InUseError extends Error {
  constructor() {
    super("in use");
  }
}

class OneShot {
  private inUse = false;
  async run() {
    if (this.inUse) {
      throw new InUseError();
    } else {
      this.inUse = true;
      await delay(10);
    }
    this.inUse = false;
  }
}

const config: ILockConfig = {
  timeout: 50,
};

class OneShotLocked extends OneShot {
  @Lock({ timeout: 100 })
  async run() {
    return await super.run();
  }
}

const oneShot = new OneShot();
await Promise.all([oneShot.run(), oneShot.run(), oneShot.run()]); // throw error InUseError

const oneShotLocked = new OneShotLocked();
await Promise.all([oneShotLocked.run(), oneShotLocked.run()]); // not throw error

Configuration

The @Lock decorator accepts a configuration with the following options:

  • timeout: The maximum time (in milliseconds) that the decorator will wait to acquire the lock before throwing an error.
@Lock({ timeout: 100 })
async run() {
  // ...
}

Advanced Examples

Method with lock and wait

lass OneShotLockedEager extends OneShot {
  @Lock({ timeout: 100 })
  async run() {
    await delay(95);
    return await super.run();
  }
}

const oneShotLockedEager = new OneShotLockedEager();
await Promise.all([oneShotLockedEager.run(), oneShotLockedEager.run()]); // throw error E_TIMEOUT