npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mutual-exclusion

v1.0.2

Published

Mutual Exclusion (mutex) object for JavaScript.

Downloads

30

Readme

mutual-exclusion (mutex)

GitSpo Mentions Travis build status Coveralls NPM version Canonical Code Style Twitter Follow

Mutual Exclusion (mutex) object for JavaScript.

Motivation

Promised based mutex allows to sequentially perform the same asynchronous operation. A typical use case example is checking if a resource exists and reading/ creating resource as an atomic asynchronous operation.

Suppose that you have a HTTP service that upon request downloads and serves an image. A naive implementation might look something like this:

router.use('/images/:uid', async (incomingMessage, serverResponse) => {
  const uid = incomingMessage.params.uid;

  const temporaryDownloadPath = path.resolve(
    downloadDirectoryPath,
    uid,
  );

  const temporaryFileExists = await fs.pathExists(temporaryDownloadPath);

  if (!temporaryFileExists) {
    try {
      await pipeline(
        // Some external storage engine.
        storage.createReadStream('images/' + uid),
        fs.createWriteStream(temporaryDownloadPath),
      );
    } catch (error) {
      await fs.remove(temporaryDownloadPath);

      throw error;
    }
  }

  fs
    .createReadStream(temporaryDownloadPath)
    .pipe(serverResponse);
});

In the above example, if two requests are made at near the same time, then both of them will identify that temporaryFileExists is false and at least one of them will fail. Mutex solves this problem by limiting concurrent execution of several asynchronous operations (see Image server example).

API

import {
  createMutex,
  HoldTimeoutError,
  WaitTimeoutError,,
} from 'mutual-exclusion';
import type {
  LockConfigurationInputType,
  MutexConfigurationInputType,
  MutexType,
} from 'mutual-exclusion';

/**
 * Thrown in case of `holdTimeout`.
 */
HoldTimeoutError;

/**
 * Thrown in case of `waitTimeout`.
 */
WaitTimeoutError;

const mutex: MutexType = createMutex(mutexConfigurationInput: MutexConfigurationInputType);

(async () => {
  // Lock is acquired.
  await mutex.lock(async () => {
    // Perform whatever operation that requires locking.

    mutex.isLocked();
    // true
  });

  // Lock is released.
  mutex.isLocked();
  // false
})()

Configuration

MutexConfigurationInputType (at the mutex-level) and LockConfigurationInputType (at the individual lock-level) can be used to configure the scope and timeouts.

/**
 * @property holdTimeout The maximum amount of time lock can be held (default: 30000).
 * @property key Used to scope mutex (default: a random generated value).
 * @property waitTimeout The maximum amount of time lock can be waited for (default: 5000).
 */
type MutexConfigurationInputType = {|
  +holdTimeout?: number,
  +key?: string,
  +waitTimeout?: number,
|};

type LockConfigurationInputType = {|
  +holdTimeout?: number,
  +key?: string,
  +waitTimeout?: number,
|};

Usage examples

Image server example

Motivation section of the documentation demonstrates a flawed implementation of an image proxy server. That same service can utilise Mutex to solve the illustrated problem:

router.use('/images/:uid', async (incomingMessage, serverResponse) => {
  const uid = incomingMessage.params.uid;

  const temporaryDownloadPath = path.resolve(
    downloadDirectoryPath,
    uid,
  );

  await mutex.lock(async () => {
    const temporaryFileExists = await fs.pathExists(temporaryDownloadPath);

    if (!temporaryFileExists) {
      try {
        await pipeline(
          // Some external storage engine.
          storage.createReadStream('images/' + uid),
          fs.createWriteStream(temporaryDownloadPath),
        );
      } catch (error) {
        await fs.remove(temporaryDownloadPath);

        throw error;
      }
    }
  }, {
    // Fail if image cannot be downloaded within 30 seconds.
    holdTimeout: 30000,

    // Restrict concurrency only for every unique image request.
    key: uid,

    // Fail subsequent requests if they are not attempted within 5 seconds.
    // This would happen if there is a high-concurrency or if the original request is taking a long time.
    waitTimeout: 5000,
  });

  fs
    .createReadStream(temporaryDownloadPath)
    .pipe(serverResponse);
});

Related libraries

  • await-mutex – Similar implementation to mutual-exclusion, but without separation by key and timeouts.