{"id":31051549,"url":"https://github.com/paperstrike/keyed-mutex","last_synced_at":"2025-09-15T00:28:38.795Z","repository":{"id":313413325,"uuid":"1051347133","full_name":"PaperStrike/keyed-mutex","owner":"PaperStrike","description":"Lightweight keyed mutex for JS/TS — per-key async locks (shared \u0026 exclusive) to coordinate concurrent readers and writers.","archived":false,"fork":false,"pushed_at":"2025-09-10T16:07:09.000Z","size":71,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-09-12T22:34:54.356Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/PaperStrike.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-09-05T20:41:35.000Z","updated_at":"2025-09-10T16:06:53.000Z","dependencies_parsed_at":"2025-09-05T22:26:06.527Z","dependency_job_id":"99f67760-a1f3-4a69-ab9e-af45f7b74afc","html_url":"https://github.com/PaperStrike/keyed-mutex","commit_stats":null,"previous_names":["paperstrike/keyed-mutex"],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/PaperStrike/keyed-mutex","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PaperStrike%2Fkeyed-mutex","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PaperStrike%2Fkeyed-mutex/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PaperStrike%2Fkeyed-mutex/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PaperStrike%2Fkeyed-mutex/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/PaperStrike","download_url":"https://codeload.github.com/PaperStrike/keyed-mutex/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PaperStrike%2Fkeyed-mutex/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":275189020,"owners_count":25420635,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-14T02:00:10.474Z","response_time":75,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-09-15T00:28:36.207Z","updated_at":"2025-09-15T00:28:38.774Z","avatar_url":"https://github.com/PaperStrike.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# keyed-mutex\n\n[![npm Package](https://img.shields.io/npm/v/keyed-mutex?logo=npm \"keyed-mutex\")](https://www.npmjs.com/package/keyed-mutex)\n\nLightweight keyed mutex for TypeScript / ESM — provide per-key mutual exclusion and reader/writer semantics so different keys can be locked independently while preserving fairness for writers.\n\nThis repository implements two complementary APIs:\n\n* `KeyedMutex` – low‑level handle based API (you manage the critical section) for locks keyed by an arbitrary string (or other key).\n* `AsyncKeyedMutex` – convenience API that runs a function while holding the mutex for a specific key.\n\nBoth support shared (concurrent/read) and exclusive (mutating/write) acquisition scoped to a single key.\n\n## Quick start (task style)\n\n```ts\nimport { AsyncKeyedMutex } from 'keyed-mutex'\n\nconst mtx = new AsyncKeyedMutex()\n\n// Exclusive (writer) for a specific key\nawait mtx.lock('user:42', async () =\u003e {\n  // only one task may run for key 'user:42'\n  await doWrite()\n})\n\n// Shared (reader) – many may run together for the same key\nconst [a, b, c] = await Promise.all([\n  mtx.lockShared('user:42', () =\u003e readValue('a')),\n  mtx.lockShared('user:42', () =\u003e readValue('b')),\n  mtx.lockShared('user:42', () =\u003e readValue('c')),\n])\n```\n\nBecause locks are keyed, operations for different keys proceed independently and concurrently.\n\n## Quick start (handle style)\n\n```ts\nimport { KeyedMutex } from 'keyed-mutex'\n\nconst mtx = new KeyedMutex()\n\n// Exclusive for a key\nconst exclusive = await mtx.lock('session:abc')\ntry {\n  await doWrite()\n}\nfinally {\n  exclusive.unlock()\n}\n\n// Shared for a key\nconst shared = await mtx.lockShared('session:abc')\ntry {\n  const v = await readValue()\n  console.log(v)\n}\nfinally {\n  shared.unlock()\n}\n```\n\n### With TypeScript `using` (TS 5.2+)\n\n```ts\nimport { KeyedMutex } from 'keyed-mutex'\nconst mtx = new KeyedMutex()\n\nasync function update() {\n  using lock = await mtx.lock('doc:1') // unlocks automatically at end of scope\n  await mutate()\n}\n```\n\n\u003e If your runtime lacks native `Symbol.dispose`, add a small polyfill or call `unlock()` manually.\n\n## When to use\n\nUse when you need to coordinate access to resources partitioned by key, for example:\n\n* Per-user or per-session locks in a server.\n* Per-document or per-record concurrency control in a cache or in-memory datastore.\n* Allow many readers for the same key while ensuring exclusive writers run alone.\n\nBecause keys are independent, a heavy writer on one key won't block unrelated keys.\n\n## Semantics\n\n* Shared acquisitions for a key overlap with other shared acquisitions for the same key if no earlier exclusive is pending for that key.\n* An exclusive for a key waits for currently active (or already queued before it) shared holders for the same key to finish, then runs alone.\n* Shared acquisitions requested after an exclusive has queued for the same key must wait until that exclusive finishes.\n* Exclusives for the same key are serialized in request order.\n* Errors inside a task propagate; the lock for that key is still released.\n* `try*` variants attempt instantaneous acquisition and return `null` if not immediately possible (no queuing side effects).\n\nThis provides predictable writer progress per key while still batching readers that arrive before the next writer.\n\n## Memory / cleanup\n\nTo avoid memory leaks the mutex clears its internal per-key bookkeeping (maps/queues) as soon as a key has no active holders and no pending requests. That means using many short‑lived keys won't leave lingering entries — only keys with active holders or queued requests consume memory.\n\nExample — transient keys are cleaned up after release\n\n```ts\nimport { KeyedMutex } from 'keyed-mutex'\n\nconst mtx = new KeyedMutex\u003cstring\u003e()\n\n// create and immediately release many short-lived keys\nfor (let i = 0; i \u003c 1000; i++) {\n  const key = `temp:${i}`\n  const h = await mtx.lockShared(key)\n  h.unlock()\n}\n\n// Internal bookkeeping for `temp:*` keys is removed once each key has no holders/requests.\n```\n\nNo manual cleanup API is required.\n\n## API\n\n### `class KeyedMutex\u003cK = PropertyKey\u003e`\n\nLow level; you get locks you must unlock. Locks are scoped to a key `K`.\n\n| Method | Returns | Description |\n| ------ | ------- | ----------- |\n| `lock(key: K)` | `Promise\u003cLockHandle\u003e` | Await an exclusive (writer) handle for `key`. |\n| `tryLock(key: K)` | `LockHandle \\| null` | Immediate exclusive attempt for `key`. `null` if busy. |\n| `lockShared(key: K)` | `Promise\u003cLockHandle\u003e` | Await a shared (reader) handle for `key`. |\n| `tryLockShared(key: K)` | `LockHandle \\| null` | Immediate shared attempt for `key` (fails if an exclusive is active/pending for that key). |\n\n`LockHandle`:\n\n* `unlock(): void` – idempotent; may be called multiple times.\n* `[Symbol.dispose]()` – same as `unlock()` enabling `using`.\n\n### `class AsyncKeyedMutex\u003cK = PropertyKey\u003e`\n\nHigher-level runner that executes a function while holding a keyed lock.\n\n| Method | Returns | Description |\n| ------ | ------- | ----------- |\n| `lock(key, task)` | `Promise\u003cT\u003e` | Run `task` exclusively for `key`. |\n| `tryLock(key, task)` | `Promise\u003cT\u003e \\| null` | Immediate exclusive attempt for `key`. If acquired, runs `task`; else `null`. |\n| `lockShared(key, task)` | `Promise\u003cT\u003e` | Run `task` under a shared lock for `key`. |\n| `tryLockShared(key, task)` | `Promise\u003cT\u003e \\| null` | Immediate shared attempt for `key`. |\n\n`task` signature: `() =\u003e T | PromiseLike\u003cT\u003e`\n\n### Error handling\n\nIf `task` throws / rejects, the keyed lock is released and the error is re-thrown. No additional wrapping.\n\n## Patterns\n\nDebounce writes while permitting many simultaneous reads per key:\n\n```ts\nconst state = new AsyncKeyedMutex\u003cstring\u003e()\nlet cache: Record\u003cstring, Data\u003e\n\nexport const readState = (id: string) =\u003e state.lockShared(id, () =\u003e cache[id])\nexport const updateState = (id: string, patch: Partial\u003cData\u003e) =\u003e state.lock(id, async () =\u003e {\n  cache[id] = { ...cache[id], ...patch }\n})\n```\n\nFast read path that falls back to waiting if a writer is in flight for the same key:\n\n```ts\nconst mtx = new KeyedMutex\u003cstring\u003e()\n\nexport async function getSnapshot(key: string) {\n  const h = mtx.tryLockShared(key) || await mtx.lockShared(key)\n  try {\n    return snapshotForKey(key)\n  }\n  finally {\n    h.unlock()\n  }\n}\n```\n\n## Target\n\nModern Node / browsers, ES2022.\n\n## Limitations / Notes\n\n* Not reentrant for the same key – calling lock methods for the same key from inside an already held lock will deadlock (no detection performed).\n* Fairness beyond the described ordering is not attempted (e.g., readers arriving while a long queue of writers exists for a key will wait until those writers finish).\n* No timeout / cancellation primitive provided. Compose with `AbortController` in your tasks if required.\n\n## Comparison\n\n| | `KeyedMutex` | `AsyncKeyedMutex` |\n| - | - | - |\n| Style | Manual handles scoped to a key | Higher level task runner scoped to a key |\n| Cleanup | Call `unlock()` / `using` | Automatic around function |\n| Overhead | Slightly lower | Wrapper promise per task |\n\n## License\n\nMIT\n\n---\n\nFeedback and PRs welcome — ideas: timeouts, cancellation helpers, metrics, or stronger typing for keys.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpaperstrike%2Fkeyed-mutex","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpaperstrike%2Fkeyed-mutex","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpaperstrike%2Fkeyed-mutex/lists"}