Review the failure paths of a multi-lock wrapper

Review the failure paths of a multi-lock wrapper

●1 ●39
calendar_today ago • schedule2 min read
— Originally published at chriseugenerodriguez.com

Start with the operation that must not run

Imagine an update that needs accounts and settings together. Before considering a successful update, ask what the application should do when settings cannot be acquired. Running half of the critical section is the outcome to rule out.

The included Node fixture makes that decision inspectable. Its recording dependency returns null for settings. The wrapper must return acquired: false and leave workRan false. Read those assertions alongside the callback event log: the accounts callback is entered first, settings is attempted next, and both recording callbacks return without invoking the protected operation. This tests the wrapper’s failure policy; it is not a browser contention experiment.

Reject a malformed resource set before acquisition

Next inspect orderedResourceNames. It rejects an empty resource list, validates each name, sorts a copy and rejects duplicates. The dedicated duplicate-name test expects a RangeError for two accounts entries. The implementation validates the list before requesting locks; callers should not treat a repeated name as another independent resource.

Keep that input check when adapting the helper. Quietly accepting duplicate names changes what the operation means and can introduce another nested request for a resource the same operation already owns.

Use the success case to inspect ownership

Only then read the successful-call test. It supplies settings before accounts, but the work function sees accounts before settings. Inside work, the event log contains both callback entries and no exits. After completion, the exits appear in reverse order. This is a direct check of where the helper places protected work in its nested callback chain.

The result is an application-owned ordering policy that can be passed a real LockManager. It does not prove native lock scheduling or cross-tab deadlock prevention. MDN supplies the API contract; a separate same-origin secure-context browser integration must verify the deployed callers. All multi-resource paths must follow the same order, and ordering cannot make a hung work function finish.

Implementation inspected by these tests

// This is an application-owned ordering wrapper. It does not emulate or prove
// browser Web Locks scheduling; run the same calls in same-origin browser tabs
// or workers to verify real navigator.locks behavior.

/**
 * Returns the one global order used by every multi-resource operation.
 * Duplicate names are rejected: requesting the same named lock twice is not a
 * second independent resource acquisition.
 */
export function orderedResourceNames(resources) {
  if (!Array.isArray(resources) || resources.length === 0) {
    throw new TypeError("resources must be a non-empty array");
  }

  const names = resources.map((name) => {
    if (typeof name !== "string" || name.length === 0) {
      throw new TypeError("every resource name must be a non-empty string");
    }
    return name;
  });

  const ordered = [...names].sort();
  for (let index = 1; index < ordered.length; index += 1) {
    if (ordered[index] === ordered[index - 1]) {
      throw new RangeError(`duplicate resource name: ${ordered[index]}`);
    }
  }
  return ordered;
}

/**
 * Acquires named locks in lexical order and runs work while every callback is
 * still active. Each LockManager.request() releases its lock when its callback
 * returns, so the nested callbacks are the critical-section boundary.
 *
 * With { ifAvailable: true }, a null lock prevents work from running and the
 * already-entered callbacks return, releasing any earlier locks.
 */
export async function withOrderedLocks(lockManager, resources, work, options = {}) {
  if (!lockManager || typeof lockManager.request !== "function") {
    throw new TypeError("lockManager must provide request()");
  }
  if (typeof work !== "function") {
    throw new TypeError("work must be a function");
  }

  const names = orderedResourceNames(resources);

  async function acquire(index, heldLocks) {
    if (index === names.length) {
      return { acquired: true, value: await work(heldLocks) };
    }

    return lockManager.request(names[index], options, async (lock) => {
      // Native Web Locks supplies null for an unavailable ifAvailable request.
      if (lock === null) return { acquired: false };
      return acquire(index + 1, [...heldLocks, lock]);
    });
  }

  return acquire(0, []);
}

Read the full article: https://chriseugenerodriguez.com/blog/prevent-deadlocks-multiple-web-locks

🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

TypeScript Complexity Has Finally Reached the Point of Total Absurdity

Karol Modelski - Apr 23

A Message From Our Founder: On the Winding Down of LaaSy™

Ken W. Algerverified - Oct 29

I’m a Senior Dev and I’ve Forgotten How to Think Without a Prompt

Karol Modelski - Mar 19

Frameworks Are Institutional Memory

Ken W. Algerverified - Sep 17

Your Tech Stack Isn’t Your Ceiling. Your Story Is

Karol Modelski - Apr 9
chevron_left
869 Points • 40 Badges
Santa Monica, CA • chriseugenerodriguez.com
33Posts
0Comments
7Connections
10 years fe

Related Jobs

View all jobs →

Commenters (This Week)

1 comment
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!