Manages a per-URL pool of shared NATS WebSocket connections, providing reference-counted acquire/release lifecycle and a coordinated reconnection loop with exponential backoff. ## Key Components ### Constants - **`NATS_DEFAULTS`** — Tuning knobs for timeouts, ping intervals, and retry backoff used as defaults throughout the module. ### Interfaces - **`SharedConnection`** — Internal state for a single URL slot: client handle, reference count, active timers, connect promise, and retry ownership token. - **`NatsReconnectionBackoff`** — Optional backoff configuration (fast retries, exponential phase, jitter cap). - **`AcquireClientOptions`** — Client identity/auth and transport settings passed at acquire time. - **`ReleaseClientOptions`** — Allows callers to override the default 3-second close grace period. - **`ConnectionLifecycleOptions`** / **`ConnectionLifecycleHandle`** — Input and output for `startConnectionLifecycle`. ### Functions | Function | Description | |---|---| | `acquireClient(url, opts?)` | Returns (or creates) the `SharedConnection` for a URL, increments `refCount`, cancels any pending close timer. | | `releaseClient(url, opts?)` | Decrements `refCount`; schedules connection teardown after a grace period if count reaches zero. | | `getSharedConnectionFor(url)` | Direct per-URL lookup; preferred over the legacy accessor. | | `getSharedConnection()` | Legacy single-slot accessor — returns the first live connection. Avoid in new code. | | `startConnectionLifecycle(options)` | Attaches a status observer and manages reconnect scheduling via a single `retryOwner` token. Returns a `stop()` handle. | ## Usage Example ```typescript import { acquireClient, releaseClient, startConnectionLifecycle, } from './shared-connection' const conn = acquireClient('wss://nats.example.com', { name: 'my-service', user: 'machine', pass: 'secret', }) const lifecycle = startConnectionLifecycle({ conn, wsUrl: 'wss://nats.example.com', getFreshUrl: () => 'wss://nats.example.com', backoff: { fastRetries: 2, fastRetryDelayMs: 500, maxDelayMs: 15_000 }, onStatusChange: (status) => console.log('NATS status:', status), }) // On component unmount: lifecycle.stop() releaseClient('wss://nats.example.com', { delayMs: 5000 }) ``` > **Retry ownership:** only one lifecycle instance drives `scheduleRetry` per URL at a time. The `retryOwner` token prevents concurrent reconnect races when multiple consumers share the same connection — remaining consumers re-claim ownership opportunistically on the next status event after the owner stops.