{"id":30302395,"url":"https://github.com/knowledgecode/critical-section","last_synced_at":"2025-08-17T05:09:08.017Z","repository":{"id":310153901,"uuid":"1038903575","full_name":"knowledgecode/critical-section","owner":"knowledgecode","description":"A mutual exclusion library using objects as lock identifiers","archived":false,"fork":false,"pushed_at":"2025-08-16T03:55:12.000Z","size":40,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-08-16T05:39:13.265Z","etag":null,"topics":["concurrency","critical-section","lock","mutex","mutual-exclusion","synchronization"],"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/knowledgecode.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}},"created_at":"2025-08-16T03:47:09.000Z","updated_at":"2025-08-16T03:55:54.000Z","dependencies_parsed_at":"2025-08-16T05:50:38.663Z","dependency_job_id":null,"html_url":"https://github.com/knowledgecode/critical-section","commit_stats":null,"previous_names":["knowledgecode/critical-section"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/knowledgecode/critical-section","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/knowledgecode%2Fcritical-section","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/knowledgecode%2Fcritical-section/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/knowledgecode%2Fcritical-section/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/knowledgecode%2Fcritical-section/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/knowledgecode","download_url":"https://codeload.github.com/knowledgecode/critical-section/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/knowledgecode%2Fcritical-section/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":270807934,"owners_count":24649346,"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-08-17T02:00:09.016Z","response_time":129,"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":["concurrency","critical-section","lock","mutex","mutual-exclusion","synchronization"],"created_at":"2025-08-17T05:09:07.333Z","updated_at":"2025-08-17T05:09:08.000Z","avatar_url":"https://github.com/knowledgecode.png","language":"TypeScript","readme":"# Critical Section\n\n[![CI](https://github.com/knowledgecode/critical-section/actions/workflows/ci.yml/badge.svg)](https://github.com/knowledgecode/critical-section/actions/workflows/ci.yml)\n[![npm](https://img.shields.io/npm/v/critical-section)](https://www.npmjs.com/package/critical-section)\n\nA lightweight TypeScript/JavaScript library for **object-based mutual exclusion** that treats your domain objects as natural lock identifiers.\n\n## Why Critical Section?\n\nTurn any object into a critical section lock - no string keys, no separate mutex instances to manage:\n\n```typescript\n// Use your existing objects directly as locks\nconst user = { id: 123, name: 'John' };\nawait criticalSection.enter(user);\n\n// Global objects work perfectly too\nawait criticalSection.enter(document);\nawait criticalSection.enter(window);\n```\n\n## Key Features\n\n- **🎯 Object-centric design**: Your domain objects become the locks themselves\n- **🧠 Intuitive mental model**: One object = one critical section, naturally aligned with OOP\n- **♻️ Automatic cleanup**: WeakMap prevents memory leaks through garbage collection\n- **⚡ Lightweight**: Just 3 methods - `enter()`, `tryEnter()`, `leave()`\n- **🌐 Universal**: Works in Node.js, browsers, and all modern JavaScript environments\n- **🔒 Type-safe**: Full TypeScript support with strict type checking\n- **📦 Zero dependencies**: No external runtime dependencies\n\n## Installation\n\n```bash\nnpm install critical-section\n```\n\n## Quick Start\n\n```typescript\nimport { criticalSection } from 'critical-section';\n\n// Any object becomes a critical section lock\nconst database = { host: 'localhost', db: 'users' };\nconst userRecord = { id: 123, email: 'user@example.com' };\n\nasync function updateUser() {\n  // Lock the specific user record to prevent race conditions\n  const entered = await criticalSection.enter(userRecord);\n\n  if (entered) {\n    try {\n      console.log('Updating user record...');\n      await validateUserData(userRecord);\n      await performDatabaseUpdate(userRecord);\n      await updateSearchIndex(userRecord);\n      // All 3 operations complete atomically - no partial updates\n    } finally {\n      // Always release the lock\n      criticalSection.leave(userRecord);\n    }\n  }\n}\n\n// Try immediate access without waiting\nasync function quickUserCheck() {\n  if (criticalSection.tryEnter(userRecord)) {\n    try {\n      console.log('Quick read operation');\n      const userData = await readUserData(userRecord);\n      return userData;\n    } finally {\n      criticalSection.leave(userRecord);\n    }\n  } else {\n    console.log('User record is busy, using cache...');\n    return await getCachedUserData(userRecord.id);\n  }\n}\n\n// Multiple objects = independent locks\nawait Promise.all([\n  updateUser(),           // Uses userRecord lock\n  cleanupDatabase(),      // Uses database lock - runs concurrently!\n]);\n```\n\n## API\n\n### `criticalSection.enter(obj: object, timeout?: number): Promise\u003cboolean\u003e`\n\nEnters a critical section for the given object. If the critical section is already occupied, the promise will wait until it becomes available or times out.\n\n**Parameters:**\n\n- `obj` - Any object to use as the critical section identifier\n- `timeout` (optional) - Maximum time to wait in milliseconds. If not provided, waits indefinitely\n\n**Returns:**\n\n- `Promise\u003cboolean\u003e` - Resolves to `true` when successfully entered, `false` if timeout occurs\n\n**Examples:**\n\n```typescript\n// Wait indefinitely\nconst success = await criticalSection.enter(myResource);\nif (success) {\n  // Critical section is now entered\n}\n\n// Wait with timeout\nconst entered = await criticalSection.enter(myResource, 5000);\nif (entered) {\n  // Got access within 5 seconds\n} else {\n  // Timeout occurred\n}\n```\n\n### `criticalSection.tryEnter(obj: object): boolean`\n\nAttempts to enter a critical section immediately without waiting.\n\n**Parameters:**\n\n- `obj` - Any object to use as the critical section identifier\n\n**Returns:**\n\n- `boolean` - `true` if successfully entered, `false` if already occupied\n\n**Example:**\n\n```typescript\nif (criticalSection.tryEnter(myResource)) {\n  // Got immediate access\n  console.log('Entered critical section');\n} else {\n  // Resource is busy\n  console.log('Resource unavailable');\n}\n```\n\n### `criticalSection.leave(obj: object): void`\n\nLeaves the critical section for the given object, allowing queued entries to proceed.\n\n**Parameters:**\n\n- `obj` - The object to leave the critical section for\n\n**Example:**\n\n```typescript\ncriticalSection.leave(myResource);\n// Critical section is now available for others\n```\n\n## Usage Patterns\n\n### Protecting Async Operations\n\n```typescript\nconst database = { connection: 'db-pool' };\n\nasync function updateUser(userId: string, data: object) {\n  const entered = await criticalSection.enter(database);\n\n  if (entered) {\n    try {\n      const user = await db.findUser(userId);\n      user.update(data);\n      await user.save();\n    } finally {\n      criticalSection.leave(database);\n    }\n  }\n}\n```\n\n### Browser: Preventing Double-Click Issues\n\n```typescript\n// Problem: Double-clicks can cause duplicate form submissions,\n// leading to duplicate orders, payments, or data corruption\nconst submitButton = document.getElementById('submit-btn');\n\nsubmitButton.addEventListener('click', async (event) =\u003e {\n  if (criticalSection.tryEnter(submitButton)) {\n    try {\n      // These operations must complete as a unit\n      await submitForm();\n      showSuccessMessage();\n    } finally {\n      criticalSection.leave(submitButton);\n    }\n  } else {\n    // Already processing - prevents duplicate submission\n    console.log('Form submission already in progress');\n  }\n});\n```\n\n### Browser: Global Object Synchronization\n\n```typescript\n// Use document/window as locks for global operations\nasync function updateGlobalTheme(newTheme: string) {\n  const entered = await criticalSection.enter(document, 1000);\n  if (entered) {\n    try {\n      document.documentElement.setAttribute('data-theme', newTheme);\n      await saveThemeToStorage(newTheme);\n    } finally {\n      criticalSection.leave(document);\n    }\n  }\n}\n\n// Prevent overlapping resize operations\n// Without protection: rapid resize events could cause inconsistent UI state\n// (e.g., canvas size updated but layout calculation still pending)\nasync function handleWindowResize() {\n  if (criticalSection.tryEnter(window)) {\n    try {\n      // These 3 operations must complete atomically\n      await recalculateLayout();\n      await updateCanvasSize();\n      await triggerRedraw();\n    } finally {\n      criticalSection.leave(window);\n    }\n  }\n  // Skip if already processing - prevents UI corruption\n}\n```\n\n### Server: Rate Limiting with tryEnter\n\n```typescript\nconst rateLimiter = { endpoint: '/api/heavy-operation' };\n\nasync function handleRequest(req, res) {\n  if (criticalSection.tryEnter(rateLimiter)) {\n    try {\n      // Process the request\n      await processHeavyOperation(req, res);\n    } finally {\n      criticalSection.leave(rateLimiter);\n    }\n  } else {\n    // Too many requests\n    res.status(429).send('Rate limit exceeded');\n  }\n}\n```\n\n### Timeout-based Operations\n\n```typescript\nconst slowResource = { name: 'slow-service' };\n\nasync function processWithTimeout() {\n  const entered = await criticalSection.enter(slowResource, 3000);\n\n  if (entered) {\n    try {\n      await performSlowOperation();\n    } finally {\n      criticalSection.leave(slowResource);\n    }\n  } else {\n    // Handle timeout\n    await fallbackOperation();\n  }\n}\n```\n\n### Queue Management\n\n```typescript\nconst printQueue = { printer: 'office-printer' };\n\nasync function printDocument(document: string) {\n  console.log(`Queuing document: ${document}`);\n\n  // This will wait in line if printer is busy\n  const entered = await criticalSection.enter(printQueue);\n\n  if (entered) {\n    try {\n      console.log(`Printing: ${document}`);\n      await simulatePrinting(document);\n      console.log(`Finished: ${document}`);\n    } finally {\n      criticalSection.leave(printQueue);\n    }\n  }\n}\n\n// Multiple documents will print in order\nprintDocument('Report A');\nprintDocument('Report B');\nprintDocument('Report C');\n```\n\n## How It Works\n\nUses a `WeakMap` to associate objects with their critical section state. Different objects = independent locks. When objects are garbage collected, their critical section state is automatically cleaned up.\n\n```typescript\nconst fileA = { path: '/tmp/fileA.txt' };\nconst fileB = { path: '/tmp/fileB.txt' };\n\nawait criticalSection.enter(fileA);  // ✅ Acquired\nawait criticalSection.enter(fileB);  // ✅ Also acquired (different object)\n```\n\n## Compatibility\n\n- **TypeScript**: Full type definitions included\n- **Browsers**: Chrome 36+, Firefox 6+, Safari 7.1+, Edge 12+\n- **Node.js**: 12.0+\n- **Modules**: ES modules, CommonJS, all modern bundlers\n\n## License\n\nMIT\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fknowledgecode%2Fcritical-section","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fknowledgecode%2Fcritical-section","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fknowledgecode%2Fcritical-section/lists"}