@0xdoublesharp/lru-cache-clustered 2.0.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -3
- package/README.md +132 -38
- package/dist/codec.d.ts +7 -7
- package/dist/codec.d.ts.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +38 -8
- package/dist/index.d.ts +38 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/l1.d.ts +41 -0
- package/dist/l1.d.ts.map +1 -0
- package/dist/memoize.d.ts +3 -3
- package/dist/memoize.d.ts.map +1 -1
- package/dist/messages.d.ts +14 -0
- package/dist/messages.d.ts.map +1 -1
- package/dist/primary.d.ts +6 -0
- package/dist/primary.d.ts.map +1 -1
- package/dist/worker.d.ts +7 -1
- package/dist/worker.d.ts.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,42 @@
|
|
|
1
|
+
# 2.1.0 / 2026-05-03
|
|
2
|
+
|
|
3
|
+
## Features
|
|
4
|
+
|
|
5
|
+
- **Local L1 cache** -- new `localL1` option adds a per-worker LRU cache in front of the primary-owned shared cache. Off by default. Requires `experimental: true` in v2.1 as an explicit opt-in acknowledgement of the eventual-consistency model.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
new LRUCacheClustered({
|
|
9
|
+
namespace: 'users',
|
|
10
|
+
max: 50_000,
|
|
11
|
+
ttl: 60_000,
|
|
12
|
+
localL1: { enabled: true, experimental: true, ttl: 2_000 },
|
|
13
|
+
});
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
- **Per-call bypass options** -- `get`, `has`, `peek`, `mGet`, `fetch`, and `memoize` accept `{ bypassL1: true }` to skip the local cache on a single call. `set` accepts `{ updateL1: true }` to populate the caller's L1 after a successful write; bulk writes clear the local L1.
|
|
17
|
+
|
|
18
|
+
- **Method-level L1 controls** -- `localL1.methods` can restrict L1 to specific read families (`get`, `has`, and `fetch`). When `methods` is provided, omitted method keys are disabled. `memoize()` delegates to `fetch()`, so its L1 behavior follows the `fetch` setting.
|
|
19
|
+
|
|
20
|
+
- **Invalidation mode control** -- the default `localL1.invalidation: 'broadcast'` subscribes same-process and cross-worker invalidation pushes. `localL1.invalidation: 'ttl-only'` is available for callers that intentionally want to rely only on the local TTL window.
|
|
21
|
+
|
|
22
|
+
- **New methods**:
|
|
23
|
+
- `clearLocal()` -- flush this worker's L1 for the namespace without touching the primary.
|
|
24
|
+
- `invalidateLocal(key)` -- drop a single key from this worker's L1.
|
|
25
|
+
- `localStats()` -- returns `{ enabled, hits, misses, sets, invalidations, evictions, staleHits, size, ipcAvoided }`.
|
|
26
|
+
- `withoutLocal()` -- returns a bypass view that routes all reads through the primary; the original instance is unaffected.
|
|
27
|
+
|
|
28
|
+
- **New events**: `l1:hit`, `l1:miss`, `l1:set`, `l1:invalidate`, `l1:evict`, and `l1:stale-hit`. Each carries `{ namespace, key }`; namespace-wide invalidations use `key: '*'`.
|
|
29
|
+
|
|
30
|
+
- **Wire format** -- IPC responses now carry an optional `version` field; push (invalidation broadcast) messages were added. Backward compatible: a v2.0 worker talking to a v2.1 primary ignores the unknown field; a v2.1 worker talking to a v2.0 primary simply receives no invalidation broadcasts and relies on TTL expiry.
|
|
31
|
+
|
|
32
|
+
## Fixes and validation
|
|
33
|
+
|
|
34
|
+
- Fixed `fetch(..., { bypassL1: true })` so followers do not observe or repopulate stale L1 state while preserving primary-side single-flight coordination.
|
|
35
|
+
- Tightened L1 method-option semantics so provided `methods` objects consistently disable omitted read families.
|
|
36
|
+
- Hardened local invalidation handling for nullish or unencodable keys, repeated unsubscribe calls, worker destroy, bulk operations, TTL changes, capacity changes, and primary load/purge paths.
|
|
37
|
+
- Added regression coverage for L1 TTL clamping, per-entry TTL handling, local stats/events, same-process invalidation, worker invalidation broadcasts, and fetch bypass behavior.
|
|
38
|
+
- Test coverage now reaches 100% statements, branches, functions, and lines for `src/**/*.ts`.
|
|
39
|
+
|
|
1
40
|
# 2.0.0 / 2026-04-28
|
|
2
41
|
|
|
3
42
|
## Breaking changes — TypeScript rewrite
|
|
@@ -15,13 +54,13 @@
|
|
|
15
54
|
## Features and infrastructure
|
|
16
55
|
|
|
17
56
|
- Canonical package name is now `@0xdoublesharp/lru-cache-clustered`; `lru-cache-for-clusters-as-promised` is published from the same build at the same version
|
|
18
|
-
-
|
|
57
|
+
- Renamed canonical class to `LRUCacheClustered`; `LRUCacheForClustersAsPromised` is retained as a backward-compatible alias (both are exported)
|
|
19
58
|
- Repository moved to `github.com/doublesharp/lru-cache-clustered`
|
|
20
59
|
- Publish workflow (`scripts/prepare-publish.mjs` + `.github/workflows/npm-publish.yml`) builds once, prepares scoped and legacy package directories, and publishes both at the same version with npm provenance via GitHub Actions OIDC, triggered by `v*` tags
|
|
21
60
|
- Publish prep validates required build artifacts before creating package directories
|
|
22
61
|
- Scoped and legacy package copies share primary state in one process to avoid duplicate IPC listeners during migration
|
|
23
62
|
- Dual ESM + CJS publish via `package.json` `exports`
|
|
24
|
-
- Generic types: `
|
|
63
|
+
- Generic types: `LRUCacheClustered<K, V>`
|
|
25
64
|
- Node `>=22` required
|
|
26
65
|
- Added `destroy()` to tear down namespace caches, stats, and fetch coordination state on the primary
|
|
27
66
|
- Added explicit startup controls via `LRUCacheClustered.bootstrap()` and `cache.healthCheck()`
|
|
@@ -46,7 +85,7 @@ See README "Migrating from older releases" for the full mapping.
|
|
|
46
85
|
|
|
47
86
|
# 1.7.1 / 2021-03-25
|
|
48
87
|
|
|
49
|
-
- Added `static getInstance(options)` to asynchronously return an `
|
|
88
|
+
- Added `static getInstance(options)` to asynchronously return an `LRUCacheClustered` once the underlying `LRUCache` is guaranteed to exist.
|
|
50
89
|
- Added `static getAllCaches()` to return all underlying `LRUCache` instances keyed by namespace. _Use only when `cluster.isMaster === true`._
|
|
51
90
|
- Added `getCache()` to return underlying `LRUCache` instance. _Use only when `cluster.isMaster === true`._
|
|
52
91
|
- Added test coverage via GitHub Actions
|
package/README.md
CHANGED
|
@@ -21,7 +21,7 @@ Node's `cluster` module gives every worker its own heap, so an in-process cache
|
|
|
21
21
|
This package keeps a single `lru-cache` in the primary and lets every worker read and write it over `cluster` IPC. One copy of the data, shared warmth across workers, and atomic counters and single-flight fetches that stay correct cluster-wide. No Redis tier, no sidecar.
|
|
22
22
|
|
|
23
23
|
<p align="center">
|
|
24
|
-
<img src="https://raw.githubusercontent.com/doublesharp/lru-cache-clustered/main/assets/topology.svg" alt="
|
|
24
|
+
<img src="https://raw.githubusercontent.com/doublesharp/lru-cache-clustered/main/assets/topology.svg" alt="Clustered LRU topology. The primary process owns authoritative namespaced caches and version counters; workers can use typed IPC or optional local L1 caches for hot reads, with writes broadcasting invalidations." width="100%">
|
|
25
25
|
</p>
|
|
26
26
|
|
|
27
27
|
## Highlights
|
|
@@ -32,6 +32,7 @@ This package keeps a single `lru-cache` in the primary and lets every worker rea
|
|
|
32
32
|
| **No per-worker cold start** | The first worker to load a value warms it for every other worker. |
|
|
33
33
|
| **Atomic counters** | `incr` / `decr` execute on the primary, so they stay race-safe under any worker count. |
|
|
34
34
|
| **Cluster-wide single-flight** | Concurrent misses for the same key collapse to one fetch via `fetch()` / `memoize()`. |
|
|
35
|
+
| **Optional local L1** | Per-worker hot-read cache skips IPC while the primary remains authoritative. |
|
|
35
36
|
| **Atomic claims** | `setIfAbsent()` lets exactly one worker win a key — perfect for idempotent intake or once-only init. |
|
|
36
37
|
| **Pluggable codecs** | `wrap()` layers gzip, MessagePack, or any symmetric encoder over a cache without changing call sites. |
|
|
37
38
|
| **Per-namespace stats** | Hits, misses, sets, deletes, evictions, size — ready to scrape, no extra wiring. |
|
|
@@ -78,7 +79,7 @@ if (cluster.isPrimary) {
|
|
|
78
79
|
|
|
79
80
|
A few things worth knowing up front:
|
|
80
81
|
|
|
81
|
-
- **`LRUCacheClustered` is the
|
|
82
|
+
- **`LRUCacheClustered` is the canonical class.** `LRUCacheForClustersAsPromised` is still exported as a backward-compatible alias.
|
|
82
83
|
- **Import in the primary before `cluster.fork()`.** The primary-side IPC listener is installed at module import. Call `LRUCacheClustered.bootstrap()` if you want that setup to be explicit.
|
|
83
84
|
- **This is a coordination layer, not a security boundary.** Any code in any worker can use any namespace it knows; do not expose namespaces to untrusted callers.
|
|
84
85
|
|
|
@@ -98,14 +99,77 @@ Reach for something else when you need sharing across multiple machines (use Red
|
|
|
98
99
|
|
|
99
100
|
## Examples
|
|
100
101
|
|
|
101
|
-
Runnable clustered server examples — see [`examples/README.md`](./examples/README.md) for
|
|
102
|
+
Runnable clustered server examples — see [`examples/README.md`](./examples/README.md) for curl recipes and environment variables.
|
|
102
103
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
104
|
+
| Example | Run | Feature it demonstrates |
|
|
105
|
+
| ------------------------------------------------------------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------ |
|
|
106
|
+
| [`clustered-users-server.ts`](./examples/clustered-users-server.ts) | `pnpm example:users` | Shared read-through user cache via `memoize()` / `fetch()` |
|
|
107
|
+
| [`clustered-rate-limit-server.ts`](./examples/clustered-rate-limit-server.ts) | `pnpm example:rate-limit` | Fixed-window rate limiting via atomic `incr()` |
|
|
108
|
+
| [`clustered-session-server.ts`](./examples/clustered-session-server.ts) | `pnpm example:sessions` | Shared `set()` / `get()` / `delete()` state across workers |
|
|
109
|
+
| [`clustered-idempotency-server.ts`](./examples/clustered-idempotency-server.ts) | `pnpm example:idempotency` | Idempotent job intake via `setIfAbsent()` |
|
|
110
|
+
| [`clustered-compressed-documents-server.ts`](./examples/clustered-compressed-documents-server.ts) | `pnpm example:documents` | Compressed document caching via `wrap()` |
|
|
111
|
+
| [`clustered-l1-server.ts`](./examples/clustered-l1-server.ts) | `node --import tsx examples/clustered-l1-server.ts` | Local L1 mode with per-worker stats, bypass reads, and invalidation |
|
|
112
|
+
| [`clustered-l1-controls-server.ts`](./examples/clustered-l1-controls-server.ts) | `pnpm example:l1` | v2.1 L1 controls: method filtering, `withoutLocal()`, `updateL1`, local invalidation |
|
|
113
|
+
| [`clustered-multilayer-redis-server.ts`](./examples/clustered-multilayer-redis-server.ts) | `pnpm example:multilayer` | Clustered LRU as L1 in front of Redis L2 with single-flight cold-miss collapsing |
|
|
114
|
+
|
|
115
|
+
## Local L1 mode
|
|
116
|
+
|
|
117
|
+
Add a per-worker LRU cache in front of the primary-owned shared cache to skip IPC for hot reads. The primary cache remains the source of truth and still owns every write.
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
const products = new LRUCacheClustered<string, Product>({
|
|
121
|
+
namespace: 'products',
|
|
122
|
+
max: 25_000,
|
|
123
|
+
ttl: 60_000,
|
|
124
|
+
localL1: { enabled: true, experimental: true, ttl: 2_000 },
|
|
125
|
+
});
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
> L1 improves repeated read latency by avoiding IPC, but it can briefly serve stale data. Keep L1 TTL short and bypass L1 for correctness-sensitive reads.
|
|
129
|
+
|
|
130
|
+
In v2.1, set `experimental: true` to opt in. The L1 TTL is capped at the primary TTL; if omitted, it defaults to `min(primaryTtl * 0.1, 5000)` with a 100 ms floor.
|
|
131
|
+
|
|
132
|
+
Read paths can bypass L1 per call:
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
await products.get('sku:123', { bypassL1: true });
|
|
136
|
+
await products.mGet(['sku:123', 'sku:456'], { bypassL1: true });
|
|
137
|
+
await products.fetch('sku:789', loadProduct, { ttl: 60_000, bypassL1: true });
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
For a reusable fresh-read view, use `withoutLocal()`:
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
const freshProducts = products.withoutLocal();
|
|
144
|
+
await freshProducts.get('sku:123'); // always goes to the primary
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
The local surface also includes:
|
|
148
|
+
|
|
149
|
+
| Method | Description |
|
|
150
|
+
| ------------------------ | -------------------------------------------------------------------------------------------------------- |
|
|
151
|
+
| `localStats()` | Returns `{ enabled, hits, misses, sets, invalidations, evictions, staleHits, size, ipcAvoided }`. |
|
|
152
|
+
| `clearLocal()` | Flushes this instance's local L1 without touching the primary cache. |
|
|
153
|
+
| `invalidateLocal(key)` | Drops one local L1 key without touching the primary cache. |
|
|
154
|
+
| `withoutLocal()` | Returns a read-through-primary wrapper over the same cache instance. |
|
|
155
|
+
| `on(event, listener)` | Subscribes to L1 events: `l1:hit`, `l1:miss`, `l1:set`, `l1:invalidate`, `l1:evict`, and `l1:stale-hit`. |
|
|
156
|
+
| `off(...)` / `once(...)` | Standard event listener helpers. |
|
|
157
|
+
|
|
158
|
+
`localL1.methods` can restrict which read families use L1:
|
|
159
|
+
|
|
160
|
+
```ts
|
|
161
|
+
localL1: {
|
|
162
|
+
enabled: true,
|
|
163
|
+
experimental: true,
|
|
164
|
+
methods: { get: true, has: false, fetch: true },
|
|
165
|
+
}
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
When `methods` is provided, omitted method keys are disabled. `memoize()` delegates to `fetch()`, so its L1 behavior follows the `fetch` setting.
|
|
169
|
+
|
|
170
|
+
By default, same-process and cross-worker writes broadcast invalidations so hot local entries are dropped before their TTL expires. If you intentionally want TTL-only consistency, set `localL1.invalidation: 'ttl-only'`.
|
|
171
|
+
|
|
172
|
+
See [`docs/l1.md`](docs/l1.md) for the full consistency model, stats, events, method options, and failure modes.
|
|
109
173
|
|
|
110
174
|
## How it works
|
|
111
175
|
|
|
@@ -122,6 +186,7 @@ Instances in different workers that share a `namespace` operate on the same prim
|
|
|
122
186
|
|
|
123
187
|
- **Primary mode** — operations dispatch directly to the local `lru-cache` instance, bypassing the IPC machinery entirely (no message build, no request-ID allocation, no pending-response bookkeeping).
|
|
124
188
|
- **Worker mode** — every cache operation is an IPC round trip through the primary.
|
|
189
|
+
- **Worker mode with local L1** — hot `get`, `has`, `peek`, `mGet`, and `fetch` reads can be served from process-local memory with no IPC; misses still go to the primary.
|
|
125
190
|
- **Hot misses** — `fetch()` and `memoize()` collapse concurrent misses for the same key across workers, so origin work scales with unique keys, not concurrent callers.
|
|
126
191
|
- **Design tradeoff** — pick this package when cross-worker sharing and single-copy memory matter more than per-call latency; pick plain per-process `lru-cache` when your hottest path cannot afford the IPC hop.
|
|
127
192
|
|
|
@@ -129,11 +194,27 @@ Instances in different workers that share a `namespace` operate on the same prim
|
|
|
129
194
|
|
|
130
195
|
The serializable subset of [`lru-cache`](https://github.com/isaacs/node-lru-cache) constructor options passes through (`max`, `maxSize`, `maxEntrySize`, `ttl`, `allowStale`, `updateAgeOnGet`, `updateAgeOnHas`, `noDeleteOnStaleGet`, `ttlAutopurge`). Plus:
|
|
131
196
|
|
|
132
|
-
| Option | Type
|
|
133
|
-
| ----------- |
|
|
134
|
-
| `namespace` | `string`
|
|
135
|
-
| `timeout` | `number`
|
|
136
|
-
| `failsafe` | `'resolve' \| 'reject'`
|
|
197
|
+
| Option | Type | Default | Description |
|
|
198
|
+
| ----------- | ------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------- |
|
|
199
|
+
| `namespace` | `string` | `'default'` | Logical name. Instances sharing a namespace share state on the primary. |
|
|
200
|
+
| `timeout` | `number` | `100` | Worker IPC timeout in ms. |
|
|
201
|
+
| `failsafe` | `'resolve' \| 'reject'` | `'resolve'` | On worker IPC timeout: `'resolve'` resolves with `undefined`; `'reject'` rejects with `Error('IPC timeout')`. |
|
|
202
|
+
| `localL1` | `false \| LocalL1Options` | `undefined` | Optional local hot-read cache. Pass `{ enabled: true, experimental: true }` to opt in. |
|
|
203
|
+
|
|
204
|
+
`LocalL1Options`:
|
|
205
|
+
|
|
206
|
+
| Option | Type | Default | Description |
|
|
207
|
+
| ---------------- | --------------------------- | ------------- | ----------------------------------------------------------------------------------------------------- |
|
|
208
|
+
| `enabled` | `boolean` | `true` | Set `false` to disable when an options object is reused. |
|
|
209
|
+
| `experimental` | `boolean` | required | Must be `true` in v2.1 to acknowledge eventual consistency. |
|
|
210
|
+
| `max` | `number` | `1000` | Maximum local entries per instance. |
|
|
211
|
+
| `maxSize` | `number` | `undefined` | Optional local size bound. Uses one size unit per entry. |
|
|
212
|
+
| `ttl` | `number` | derived | Local TTL in ms, capped by primary TTL and per-entry remaining TTL. |
|
|
213
|
+
| `updateAgeOnGet` | `boolean` | `true` | Passed to the local `lru-cache`. |
|
|
214
|
+
| `allowStale` | `boolean` | `false` | Passed to the local `lru-cache`; stale reads increment `localStats().staleHits`. |
|
|
215
|
+
| `invalidation` | `'broadcast' \| 'ttl-only'` | `'broadcast'` | Whether this instance subscribes to local/IPC invalidation pushes or relies only on local TTL expiry. |
|
|
216
|
+
| `methods` | `{ get?, has?, fetch? }` | all enabled | Restrict which read families use L1. If present, omitted keys are disabled. |
|
|
217
|
+
| `cacheUndefined` | `boolean` | unsupported | Reserved for future negative-result caching; currently forced off. |
|
|
137
218
|
|
|
138
219
|
Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalculation`, or `fetchMethod` do not cross IPC and are not supported by this wrapper.
|
|
139
220
|
|
|
@@ -157,23 +238,23 @@ Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalc
|
|
|
157
238
|
|
|
158
239
|
### Core
|
|
159
240
|
|
|
160
|
-
| Method
|
|
161
|
-
|
|
|
162
|
-
| `get(key)`
|
|
163
|
-
| `set(key, value, { ttl?, size? })`
|
|
164
|
-
| `setIfAbsent(key, value, { ttl?, size? })`
|
|
165
|
-
| `delete(key)`
|
|
166
|
-
| `has(key)`
|
|
167
|
-
| `peek(key)`
|
|
168
|
-
| `clear()`
|
|
241
|
+
| Method | Returns | Notes |
|
|
242
|
+
| --------------------------------------------- | ------------------------- | -------------------------------------------------------------- |
|
|
243
|
+
| `get(key, { bypassL1? })` | `Promise<V \| undefined>` | |
|
|
244
|
+
| `set(key, value, { ttl?, size?, updateL1? })` | `Promise<boolean>` | `updateL1` populates the caller's L1 after a successful write. |
|
|
245
|
+
| `setIfAbsent(key, value, { ttl?, size? })` | `Promise<boolean>` | Atomic on the primary. `false` if the key already exists. |
|
|
246
|
+
| `delete(key)` | `Promise<boolean>` | |
|
|
247
|
+
| `has(key, { bypassL1? })` | `Promise<boolean>` | |
|
|
248
|
+
| `peek(key, { bypassL1? })` | `Promise<V \| undefined>` | Does not update LRU position. |
|
|
249
|
+
| `clear()` | `Promise<void>` | Clears the primary cache and this instance's L1. |
|
|
169
250
|
|
|
170
251
|
### Multi
|
|
171
252
|
|
|
172
|
-
| Method | Returns | Notes
|
|
173
|
-
| -------------------------------- | --------------------------------- |
|
|
174
|
-
| `mGet(keys)`
|
|
175
|
-
| `mSet(entries, { ttl?, size? })` | `Promise<void>` | `entries: Iterable<[K, V] \| [K, V, { ttl?, size? }]>`; outer opts apply as defaults. |
|
|
176
|
-
| `mDelete(keys)` | `Promise<void>` |
|
|
253
|
+
| Method | Returns | Notes |
|
|
254
|
+
| -------------------------------- | --------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
|
|
255
|
+
| `mGet(keys, { bypassL1? })` | `Promise<Map<K, V \| undefined>>` | Preserves input key order even when L1 partially hits. |
|
|
256
|
+
| `mSet(entries, { ttl?, size? })` | `Promise<void>` | `entries: Iterable<[K, V] \| [K, V, { ttl?, size? }]>`; outer opts apply as defaults. Clears this instance's L1. |
|
|
257
|
+
| `mDelete(keys)` | `Promise<void>` | |
|
|
177
258
|
|
|
178
259
|
### Enumeration
|
|
179
260
|
|
|
@@ -189,12 +270,25 @@ Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalc
|
|
|
189
270
|
|
|
190
271
|
### Counters and cache-aside
|
|
191
272
|
|
|
192
|
-
| Method
|
|
193
|
-
|
|
|
194
|
-
| `incr(key, amount?, { ttl?, size? })`
|
|
195
|
-
| `decr(key, amount?, { ttl?, size? })`
|
|
196
|
-
| `fetch(key, fetcher, { ttl?, size?, forceRefresh })` | `Promise<V>` | Cache-aside with cluster-wide single-flight semantics. See [Single-flight semantics](#single-flight-semantics). |
|
|
197
|
-
| `memoize(cache, fn, keyFn, opts?)`
|
|
273
|
+
| Method | Returns | Notes |
|
|
274
|
+
| ---------------------------------------------------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------ |
|
|
275
|
+
| `incr(key, amount?, { ttl?, size? })` | `Promise<number>` | Atomic on the primary. `ttl` is set on the **first** write only; later increments do not reset it (rate limiters). |
|
|
276
|
+
| `decr(key, amount?, { ttl?, size? })` | `Promise<number>` | Same. |
|
|
277
|
+
| `fetch(key, fetcher, { ttl?, size?, forceRefresh?, bypassL1? })` | `Promise<V>` | Cache-aside with cluster-wide single-flight semantics. See [Single-flight semantics](#single-flight-semantics). |
|
|
278
|
+
| `memoize(cache, fn, keyFn, opts?)` | `(args) => Promise<V>` | Top-level helper. Single-flight via `cache.fetch()`. See [`memoize` helper](#memoize-helper). |
|
|
279
|
+
|
|
280
|
+
### Local L1
|
|
281
|
+
|
|
282
|
+
| Method / event | Returns / payload | Notes |
|
|
283
|
+
| ------------------------------------------------- | ------------------------- | ---------------------------------------------------------------------------------------- |
|
|
284
|
+
| `localStats()` | `L1Stats \| undefined` | `undefined` when local L1 is disabled. |
|
|
285
|
+
| `clearLocal()` | `void` | Local-only flush. |
|
|
286
|
+
| `invalidateLocal(key)` | `void` | Local-only single-key invalidation. |
|
|
287
|
+
| `withoutLocal()` | `LRUCacheClustered<K, V>` | Bypass view for `get`, `has`, `peek`, `mGet`, and `fetch`; writes pass through normally. |
|
|
288
|
+
| `on('l1:hit' \| 'l1:miss' \| 'l1:set', listener)` | `{ namespace, key }` | Key is the original cache key, not an internal encoded key. |
|
|
289
|
+
| `on('l1:invalidate', listener)` | `{ namespace, key }` | `key` may be `'*'` for namespace-wide invalidation. |
|
|
290
|
+
| `on('l1:evict' \| 'l1:stale-hit', listener)` | `{ namespace, key }` | `stale-hit` fires when a TTL-stale local value is returned under `allowStale`. |
|
|
291
|
+
| `off(event, listener)` / `once(event, listener)` | `this` | Standard event helpers. |
|
|
198
292
|
|
|
199
293
|
### Lifecycle, metrics, tunables
|
|
200
294
|
|
|
@@ -207,8 +301,8 @@ Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalc
|
|
|
207
301
|
| `destroy()` | `Promise<boolean>` | Removes the namespace cache, stats, and primary-side coordination state. Later use of the same instance recreates it with the original options. |
|
|
208
302
|
| `getCache()` | `LRUCache \| undefined` | Underlying `lru-cache` for this namespace. **Primary only**. |
|
|
209
303
|
| `ready` | `Promise<void>` | Resolves once worker init has been dispatched. Useful for ordering only; use `getInstance()` if init failures should reject. |
|
|
210
|
-
| `max(value?)` | `Promise<number>` | Getter and setter. Setter preserves entries and remaining TTL metadata.
|
|
211
|
-
| `ttl(value?)` | `Promise<number>` | Getter and setter.
|
|
304
|
+
| `max(value?)` | `Promise<number>` | Getter and setter. Setter preserves primary entries and remaining TTL metadata, then clears this instance's L1. |
|
|
305
|
+
| `ttl(value?)` | `Promise<number>` | Getter and setter. Setter clears this instance's L1. |
|
|
212
306
|
| `allowStale(value?)` | `Promise<boolean>` | Getter and setter. |
|
|
213
307
|
|
|
214
308
|
## `wrap` — codec / compression
|
|
@@ -232,7 +326,7 @@ await cache.set('user:42', { id: 42, name: 'ada' });
|
|
|
232
326
|
await cache.get('user:42'); // decoded back to { id: 42, name: 'ada' }
|
|
233
327
|
```
|
|
234
328
|
|
|
235
|
-
`encode` and `decode` may be sync or async. The wrapped surface covers value-touching ops (`get`, `set`, `setIfAbsent`, `peek`, `mGet`, `mSet`, `values`, `entries`, async iteration, `fetch`) plus the lifecycle and metric pass-throughs (`has`, `delete`, `keys`, `size`, `clear`, `destroy`, `healthCheck`, `purgeStale`, `getRemainingTTL`, `stats`).
|
|
329
|
+
`encode` and `decode` may be sync or async. The wrapped surface covers value-touching ops (`get`, `set`, `setIfAbsent`, `peek`, `mGet`, `mSet`, `values`, `entries`, async iteration, `fetch`) plus the lifecycle and metric pass-throughs (`has`, `delete`, `keys`, `size`, `clear`, `destroy`, `healthCheck`, `purgeStale`, `getRemainingTTL`, `stats`). Wrapped `get`, `has`, `peek`, `mGet`, and `fetch` forward read options such as `{ bypassL1: true }` to the underlying cache.
|
|
236
330
|
|
|
237
331
|
`incr` / `decr` and `dump` / `load` are not wrapped — they speak in numbers or the raw stored form. Reach them via `wrapped.cache` if you need them.
|
|
238
332
|
|
|
@@ -262,7 +356,7 @@ await getUser('42'); // second call: cached
|
|
|
262
356
|
|
|
263
357
|
Both `memoize()` and `cache.fetch()` coordinate through the primary so concurrent misses for the same key collapse to one in-flight fetch across instances and workers.
|
|
264
358
|
|
|
265
|
-
Passing `forceRefresh: true` skips both the cache lookup and any in-flight claim and starts a fresh leader fetch. Concurrent callers without `forceRefresh` still wait on whichever fetch is in flight and reuse its result.
|
|
359
|
+
Passing `forceRefresh: true` skips both the cache lookup and any in-flight claim and starts a fresh leader fetch. Concurrent callers without `forceRefresh` still wait on whichever fetch is in flight and reuse its result. Passing `bypassL1: true` skips local L1 reads and population for that call while preserving the primary-side single-flight behavior.
|
|
266
360
|
|
|
267
361
|
The cache `timeout` option only bounds each worker IPC request. It does not cancel user fetcher work after a worker owns the primary-side single-flight lock, so production fetchers should enforce their own upstream timeout or abort policy.
|
|
268
362
|
|
package/dist/codec.d.ts
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
import type { Stats } from './messages.js';
|
|
2
|
-
import type { FetchOptions,
|
|
2
|
+
import type { FetchOptions, LRUCacheClustered, MSetEntry, ReadOptions, WriteOptions } from './index.js';
|
|
3
3
|
export interface Codec<V, U> {
|
|
4
4
|
encode(value: V): U | Promise<U>;
|
|
5
5
|
decode(raw: U): V | Promise<V>;
|
|
6
6
|
}
|
|
7
7
|
export interface WrappedCache<K extends {}, V extends {}> {
|
|
8
|
-
readonly cache:
|
|
8
|
+
readonly cache: LRUCacheClustered<K, never>;
|
|
9
9
|
readonly namespace: string;
|
|
10
10
|
readonly ready: Promise<void>;
|
|
11
|
-
get(key: K): Promise<V | undefined>;
|
|
11
|
+
get(key: K, opts?: ReadOptions): Promise<V | undefined>;
|
|
12
12
|
set(key: K, value: V, opts?: WriteOptions): Promise<boolean>;
|
|
13
13
|
setIfAbsent(key: K, value: V, opts?: WriteOptions): Promise<boolean>;
|
|
14
|
-
has(key: K): Promise<boolean>;
|
|
15
|
-
peek(key: K): Promise<V | undefined>;
|
|
14
|
+
has(key: K, opts?: ReadOptions): Promise<boolean>;
|
|
15
|
+
peek(key: K, opts?: ReadOptions): Promise<V | undefined>;
|
|
16
16
|
delete(key: K): Promise<boolean>;
|
|
17
17
|
getRemainingTTL(key: K): Promise<number>;
|
|
18
|
-
mGet(keys: K[]): Promise<Map<K, V | undefined>>;
|
|
18
|
+
mGet(keys: K[], opts?: ReadOptions): Promise<Map<K, V | undefined>>;
|
|
19
19
|
mSet(entries: Iterable<MSetEntry<K, V>>, opts?: WriteOptions): Promise<void>;
|
|
20
20
|
mDelete(keys: K[]): Promise<void>;
|
|
21
21
|
keys(): Promise<K[]>;
|
|
@@ -30,5 +30,5 @@ export interface WrappedCache<K extends {}, V extends {}> {
|
|
|
30
30
|
stats(): Promise<Stats>;
|
|
31
31
|
fetch(key: K, fetcher: (key: K) => Promise<V> | V, opts?: FetchOptions): Promise<V>;
|
|
32
32
|
}
|
|
33
|
-
export declare function wrap<K extends {}, V extends {}, U extends {}>(cache:
|
|
33
|
+
export declare function wrap<K extends {}, V extends {}, U extends {}>(cache: LRUCacheClustered<K, U>, codec: Codec<V, U>): WrappedCache<K, V>;
|
|
34
34
|
//# sourceMappingURL=codec.d.ts.map
|
package/dist/codec.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codec.d.ts","sourceRoot":"","sources":["../src/codec.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,KAAK,EAAE,YAAY,EAAE,
|
|
1
|
+
{"version":3,"file":"codec.d.ts","sourceRoot":"","sources":["../src/codec.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,KAAK,EAAE,YAAY,EAAE,iBAAiB,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAOxG,MAAM,WAAW,KAAK,CAAC,CAAC,EAAE,CAAC;IACzB,MAAM,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IACjC,MAAM,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CAChC;AAQD,MAAM,WAAW,YAAY,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,EAAE;IACtD,QAAQ,CAAC,KAAK,EAAE,iBAAiB,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;IAC5C,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IAE9B,GAAG,CAAC,GAAG,EAAE,CAAC,EAAE,IAAI,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC;IACxD,GAAG,CAAC,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,IAAI,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAC7D,WAAW,CAAC,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,IAAI,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACrE,GAAG,CAAC,GAAG,EAAE,CAAC,EAAE,IAAI,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAClD,IAAI,CAAC,GAAG,EAAE,CAAC,EAAE,IAAI,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC;IACzD,MAAM,CAAC,GAAG,EAAE,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACjC,eAAe,CAAC,GAAG,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAEzC,IAAI,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,IAAI,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC;IACpE,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7E,OAAO,CAAC,IAAI,EAAE,CAAC,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAElC,IAAI,IAAI,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC;IACrB,MAAM,IAAI,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC;IACvB,OAAO,IAAI,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IAClC,IAAI,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;IACxB,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,qBAAqB,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IAExD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;IAC5B,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7B,UAAU,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;IAC/B,KAAK,IAAI,OAAO,CAAC,KAAK,CAAC,CAAC;IAExB,KAAK,CAAC,GAAG,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CACrF;AAGD,wBAAgB,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,EAAE,EAC3D,KAAK,EAAE,iBAAiB,CAAC,CAAC,EAAE,CAAC,CAAC,EAC9B,KAAK,EAAE,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,GACjB,YAAY,CAAC,CAAC,EAAE,CAAC,CAAC,CAoFpB"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Y=Object.create;var v=Object.defineProperty;var J=Object.getOwnPropertyDescriptor;var Q=Object.getOwnPropertyNames;var ee=Object.getPrototypeOf,te=Object.prototype.hasOwnProperty;var ne=(t,e)=>{for(var s in e)v(t,s,{get:e[s],enumerable:!0})},I=(t,e,s,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Q(e))!te.call(t,r)&&r!==s&&v(t,r,{get:()=>e[r],enumerable:!(n=J(e,r))||n.enumerable});return t};var z=(t,e,s)=>(s=t!=null?Y(ee(t)):{},I(e||!t||!t.__esModule?v(s,"default",{value:t,enumerable:!0}):s,t)),se=t=>I(v({},"__esModule",{value:!0}),t);var we={};ne(we,{LRUCacheClustered:()=>R,LRUCacheForClustersAsPromised:()=>R,default:()=>be,memoize:()=>X,wrap:()=>Z});module.exports=se(we);var k=z(require("cluster"),1);var O=z(require("cluster"),1),T=z(require("debug"),1),M=require("lru-cache");var y="lcfcap",g="lru-cache-clustered";function D(t){return F(t,0,new Set)}function F(t,e,s){if(t instanceof Error){if(s.has(t))return{name:t.name,message:"[circular cause]"};s.add(t);let n={name:t.name,message:t.message};t.stack&&(n.stack=t.stack);let r=t.code;(typeof r=="string"||typeof r=="number")&&(n.code=r);let i=t.cause;return i!==void 0&&(e+1>=8?n.cause={name:"Error",message:"[cause chain truncated]"}:n.cause=F(i,e+1,s)),n}return{name:"Error",message:typeof t=="string"?t:String(t)}}function E(t){let e=new Error(t.message);return e.name=t.name,t.stack&&(e.stack=t.stack),t.code!==void 0&&(e.code=t.code),t.cause!==void 0&&(e.cause=E(t.cause)),e}var _=(0,T.default)(`${g}-primary`),re=(0,T.default)(`${g}-messages`),oe=3e4,ie=Symbol.for("lru-cache-clustered.primary"),b=globalThis[ie]??={caches:new Map,stats:new Map,fetchLocks:new Map,clusterListenerInstalled:!1,nextFetchToken:0},h=b.caches,P=b.stats,p=b.fetchLocks;function j(t){return{namespace:t,hits:0,misses:0,sets:0,deletes:0,evictions:0,size:0}}function f(t){let e=P.get(t);return e||(e=j(t),P.set(t,e)),e}function G(t){let e=t;return{max:e.max,maxSize:e.maxSize,maxEntrySize:e.maxEntrySize,ttl:e.ttl,allowStale:e.allowStale,updateAgeOnGet:e.updateAgeOnGet,updateAgeOnHas:e.updateAgeOnHas,noDeleteOnStaleGet:e.noDeleteOnStaleGet,ttlAutopurge:e.ttlAutopurge}}function l(t,e){let s=h.get(t);return s||x(t,e.cacheOptions)}function ue(t,e,s){if(!s)return;let n=G(e),r=[];for(let[i,o]of Object.entries(s))o!==void 0&&n[i]!==o&&r.push(`${i}=${String(n[i])} (existing) != ${String(o)} (incoming)`);if(r.length>0)throw new Error(`Conflicting options for namespace '${t}': ${r.join(", ")}`)}function d(t,e){if(e==null)throw new TypeError(`${t} must not be null or undefined`);return e}function S(t){let e={};return t.ttl!==void 0&&(e.ttl=t.ttl),t.size!==void 0&&(e.size=t.size),t.noUpdateTTL&&(e.noUpdateTTL=!0),Object.keys(e).length>0?e:void 0}function ae(t,e){let s=t.info(e);return typeof s?.size=="number"?s.size:void 0}function ce(t){let e=p.get(t);return e||(e=new Map,p.set(t,e)),e}function A(t){p.get(t)?.size===0&&p.delete(t)}function le(t){for(let[e,s]of p){for(let[n,r]of s)r.ownerWorkerId===t&&s.delete(n);A(e)}}function q(t,e){let s={...t,dispose:(r,i,o)=>{o==="evict"&&(e.evictions+=1)}},n=s.max===void 0&&s.maxSize===void 0&&s.ttl===void 0?{...s,max:1e3}:s;return new M.LRUCache(n)}function x(t,e){let s=h.get(t);if(s)ue(t,s,e);else{let n=j(t);P.set(t,n),s=q(e??{},n),h.set(t,s),_(`Created LRUCache for namespace '${t}'`)}return s}function K(t,e,s={}){switch(e.op){case"init":{let n=!h.has(t),r=x(t,e.options);return{namespace:t,isNew:n,max:r.max}}case"healthCheck":x(t,e.cacheOptions);return;case"destroy":{let n=h.delete(t),r=P.delete(t),i=p.delete(t);return n||r||i}case"get":{let r=l(t,e).get(d("cache key",e.key)),i=f(t);return r!==void 0?i.hits+=1:i.misses+=1,r}case"set":return l(t,e).set(d("cache key",e.key),d("cache value",e.value),S({ttl:e.ttl,size:e.size})),f(t).sets+=1,!0;case"setIfAbsent":{let n=l(t,e),r=d("cache key",e.key);return n.peek(r)!==void 0?!1:(n.set(r,d("cache value",e.value),S({ttl:e.ttl,size:e.size})),f(t).sets+=1,!0)}case"delete":{let r=l(t,e).delete(d("cache key",e.key));return r&&(f(t).deletes+=1),r}case"has":return l(t,e).has(d("cache key",e.key));case"peek":return l(t,e).peek(d("cache key",e.key));case"getRemainingTTL":return l(t,e).getRemainingTTL(d("cache key",e.key));case"clear":l(t,e).clear();return;case"mGet":{let n=l(t,e),r=f(t);return e.keys.map(i=>{let o=n.get(d("cache key",i));return o!==void 0?r.hits+=1:r.misses+=1,[i,o]})}case"mSet":{let n=l(t,e),r=f(t);for(let[i,o,u]of e.entries)n.set(d("cache key",i),d("cache value",o),S({ttl:u?.ttl??e.ttl,size:u?.size??e.size})),r.sets+=1;return}case"mDelete":{let n=l(t,e),r=f(t);for(let i of e.keys)n.delete(d("cache key",i))&&(r.deletes+=1);return}case"keys":return[...l(t,e).keys()];case"values":return[...l(t,e).values()];case"entries":return[...l(t,e).entries()];case"dump":return l(t,e).dump();case"load":{let n=l(t,e),r=e.entries.map(([i,o])=>{let u=d("cache key",i);return d("cache value",o.value),[u,o]});n.load(r);return}case"size":return l(t,e).size;case"stats":{let n=l(t,e),r=f(t);return r.size=n.size,{...r}}case"purgeStale":return l(t,e).purgeStale();case"incr":case"decr":{let n=l(t,e),r=d("cache key",e.key),i=n.peek(r),o=i!==void 0,u=typeof i=="number"?i:0,a=(e.amount??1)*(e.op==="decr"?-1:1),c=u+a,m=e.size??(o?ae(n,r):void 0),C=S(o?{size:m,noUpdateTTL:!0}:{ttl:e.ttl,size:m});return n.set(r,c,C),f(t).sets+=1,c}case"fetchClaim":{let n=l(t,e),r=d("cache key",e.key),i=ce(t),o=Date.now();if(!e.forceRefresh){let a=n.get(r);if(a!==void 0)return{kind:"value",value:a};let c=i.get(r);if(c&&o-c.claimedAt<oe)return{kind:"follower"}}let u=`fetch-${++b.nextFetchToken}`;return i.set(r,{token:u,ownerWorkerId:s.workerId,claimedAt:o}),{kind:"leader",token:u}}case"fetchStore":{let n=l(t,e),r=d("cache key",e.key),i=p.get(t),o=i?.get(r);return!o||o.token!==e.token?!1:(n.set(r,d("cache value",e.value),S({ttl:e.ttl,size:e.size})),i?.delete(r),A(t),f(t).sets+=1,!0)}case"fetchAbort":{let n=d("cache key",e.key),r=p.get(t),i=r?.get(n);return!i||i.token!==e.token?!1:(r?.delete(n),A(t),!0)}case"max":{let n=l(t,e);if(typeof e.value=="number"&&e.value!==n.max){let r=f(t),i={...G(n),max:e.value},o=q(i,r);return o.load(n.dump()),h.set(t,o),o.max}return n.max}case"ttl":{let n=l(t,e);return typeof e.value=="number"&&(n.ttl=e.value),n.ttl}case"allowStale":{let n=l(t,e);return typeof e.value=="boolean"&&(n.allowStale=e.value),n.allowStale}default:{let n=e.op;throw new Error(`unhandled op: ${n}`)}}}function de(t,e={}){if(typeof t!="object"||t===null)return L(t,"invalid request: not an object");if(!$(t))return L(t,"invalid request: missing required fields");try{return fe(t,K(t.namespace,t,e))}catch(s){return L(t,s)}}function fe(t,e){return{id:t.id,source:y,ok:!0,value:e}}function L(t,e){return{id:typeof t=="object"&&t!==null&&typeof t.id=="string"?t.id:"",source:y,ok:!1,error:D(e)}}function V(){if(!b.clusterListenerInstalled){b.clusterListenerInstalled=!0,O.default.on("exit",t=>{le(t.id)}),O.default.on("fork",t=>{W(t)});for(let t of Object.values(O.default.workers??{}))t&&W(t)}}function W(t){t.on("message",e=>{if(!$(e))return;re(`primary <- worker ${t.id}`,e);let s=de(e,{workerId:t.id});if(t.isConnected())try{t.send(s)}catch(n){_(`worker ${t.id} send failed (likely disconnected): %s`,n)}})}function $(t){return typeof t=="object"&&t!==null&&t.source===y&&typeof t.id=="string"&&typeof t.namespace=="string"&&typeof t.op=="string"}var w=require("timers"),H=z(require("debug"),1);var me=(0,H.default)(`${g}-messages`),he=0;function pe(t){let e=new Map;return t.on("message",s=>{if(!ke(s))return;let n=e.get(s.id);n&&(e.delete(s.id),n(s))}),{sendToPrimary(s,n){let r=String(++he),i={id:r,namespace:s.namespace,source:y,...n};return new Promise((o,u)=>{let a=(0,w.setTimeout)(()=>{e.delete(r),s.failsafe==="reject"?u(new Error("IPC timeout")):o(void 0)},s.timeout);e.set(r,c=>{(0,w.clearTimeout)(a),c.ok?o(c.value):u(E(c.error))}),me("worker -> primary",i);try{t.send(i)===!1&&((0,w.clearTimeout)(a),e.delete(r),s.failsafe==="reject"?u(new Error("IPC backpressure")):o(void 0))}catch(c){(0,w.clearTimeout)(a),e.delete(r),u(c instanceof Error?c:new Error(String(c)))}})}}}function ke(t){if(typeof t!="object"||t===null||t.source!==y||typeof t.id!="string"||typeof t.ok!="boolean")return!1;if(t.ok===!1){let e=t.error;if(typeof e!="object"||e===null||typeof e.name!="string"||typeof e.message!="string")return!1}return!0}var U;function B(){if(!U){if(typeof process.send!="function")throw new Error("lru-cache-clustered: worker IPC client requested in a process without `process.send` (not a cluster worker).");let t=process.send.bind(process);U=pe({send:e=>t(e),on:(e,s)=>process.on(e,s)})}return U}function X(t,e,s,n){return async(...r)=>{let i=s(...r);return t.fetch(i,()=>e(...r),n)}}function Z(t,e){let s=o=>e.encode(o),n=o=>e.decode(o);return{cache:t,namespace:t.namespace,ready:t.ready,async get(o){let u=await t.get(o);return u===void 0?void 0:await n(u)},async set(o,u,a){return t.set(o,await s(u),a)},async setIfAbsent(o,u,a){return t.setIfAbsent(o,await s(u),a)},has:o=>t.has(o),async peek(o){let u=await t.peek(o);return u===void 0?void 0:await n(u)},delete:o=>t.delete(o),getRemainingTTL:o=>t.getRemainingTTL(o),async mGet(o){let u=await t.mGet(o),a=new Map;for(let[c,m]of u)a.set(c,m===void 0?void 0:await n(m));return a},async mSet(o,u){let a=[];for(let c of o){let[m,C,N]=c;N===void 0?a.push([m,await s(C)]):a.push([m,await s(C),N])}return t.mSet(a,u)},mDelete:o=>t.mDelete(o),keys:()=>t.keys(),async values(){let o=await t.values(),u=[];for(let a of o)u.push(await n(a));return u},async entries(){let o=await t.entries(),u=[];for(let[a,c]of o)u.push([a,await n(c)]);return u},size:()=>t.size(),async*[Symbol.asyncIterator](){for(let[o,u]of await this.entries())yield[o,u]},clear:()=>t.clear(),destroy:()=>t.destroy(),healthCheck:()=>t.healthCheck(),purgeStale:()=>t.purgeStale(),stats:()=>t.stats(),async fetch(o,u,a){let c=await t.fetch(o,async m=>await s(await u(m)),a);return await n(c)}}}k.default.isPrimary&&V();var ye=5,R=class t{namespace;timeout;failsafe;ready;#t;#n=new Map;constructor(e={}){this.namespace=e.namespace??"default",this.timeout=e.timeout??100,this.failsafe=e.failsafe==="reject"?"reject":"resolve";let{namespace:s,timeout:n,failsafe:r,noInit:i,...o}=e;this.#t=o,k.default.isPrimary?(x(this.namespace,this.#t),this.ready=Promise.resolve(void 0)):e.noInit?this.ready=Promise.resolve(void 0):this.ready=this.#e({op:"init",options:this.#t}).then(()=>{},()=>{})}static async getInstance(e={}){let s=new t({...e,noInit:!0});return k.default.isWorker&&await s.#s({op:"init",options:s.#t}),s}static bootstrap(){k.default.isPrimary&&V()}static getAllCaches(){if(k.default.isWorker)throw new Error("LRUCacheForClustersAsPromised.getAllCaches() must not be called from a worker");return h}getCache(){if(k.default.isWorker)throw new Error("LRUCacheForClustersAsPromised.getCache() must not be called from a worker");return h.get(this.namespace)}get(e){return this.#e({op:"get",key:e})}set(e,s,n){return this.#e({op:"set",key:e,value:s,ttl:n?.ttl,size:n?.size})}delete(e){return this.#e({op:"delete",key:e})}has(e){return this.#e({op:"has",key:e})}peek(e){return this.#e({op:"peek",key:e})}clear(){return this.#e({op:"clear"})}purgeStale(){return this.#e({op:"purgeStale"})}async mGet(e){let s=await this.#e({op:"mGet",keys:e}),n=new Map;for(let[r,i]of s??[])n.set(r,i===null?void 0:i);return n}mSet(e,s){return this.#e({op:"mSet",entries:[...e].map(n=>n.length===3?[n[0],n[1],n[2]]:[n[0],n[1]]),ttl:s?.ttl,size:s?.size})}mDelete(e){return this.#e({op:"mDelete",keys:e})}keys(){return this.#e({op:"keys"})}values(){return this.#e({op:"values"})}entries(){return this.#e({op:"entries"})}dump(){return this.#e({op:"dump"})}size(){return this.#e({op:"size"})}incr(e,s,n){return this.#e({op:"incr",key:e,amount:s,ttl:n?.ttl,size:n?.size})}decr(e,s,n){return this.#e({op:"decr",key:e,amount:s,ttl:n?.ttl,size:n?.size})}async allowStale(e){let s=await this.#e({op:"allowStale",value:e});return this.#t.allowStale=s,s}async max(e){let s=await this.#e({op:"max",value:e});return this.#t.max=s,s}async ttl(e){let s=await this.#e({op:"ttl",value:e});return this.#t.ttl=s,s}async getRemainingTTL(e){let s=await this.#e({op:"getRemainingTTL",key:e});return s===null?1/0:s}setIfAbsent(e,s,n){return this.#e({op:"setIfAbsent",key:e,value:s,ttl:n?.ttl,size:n?.size})}load(e){return this.#e({op:"load",entries:e})}destroy(){return this.#n.clear(),this.#e({op:"destroy"})}healthCheck(){return this.#s({op:"healthCheck"})}stats(){return this.#e({op:"stats"})}async*[Symbol.asyncIterator](){let e=await this.entries();for(let s of e)yield s}async fetch(e,s,n){if(!n?.forceRefresh){let o=this.#n.get(e);if(o)return o.promise}let r;r={promise:(async()=>{if(!n?.forceRefresh){let u=await this.get(e);if(u!==void 0)return u}let o=n?.forceRefresh===!0;for(;;){let u=await this.#s({op:"fetchClaim",key:e,forceRefresh:o});if(u.kind==="value")return u.value;if(u.kind==="leader")try{let c=await s(e);return await this.#s({op:"fetchStore",key:e,token:u.token,value:c,ttl:n?.ttl,size:n?.size}),c}catch(c){try{await this.#s({op:"fetchAbort",key:e,token:u.token})}catch{}throw c}let a=await this.peek(e);if(a===void 0){o=!1,await new Promise(c=>setTimeout(c,ye));continue}return a}})()},this.#n.set(e,r);try{return await r.promise}finally{this.#n.get(e)===r&&this.#n.delete(e)}}#e(e){return this.#r(e,this.failsafe)}#s(e){return this.#r(e,"reject")}#r(e,s){let n={...e,cacheOptions:this.#t};if(k.default.isPrimary)try{return Promise.resolve(K(this.namespace,n))}catch(r){return Promise.reject(r instanceof Error?r:new Error(String(r)))}return B().sendToPrimary({namespace:this.namespace,timeout:this.timeout,failsafe:s},n)}};var be=R;0&&(module.exports={LRUCacheClustered,LRUCacheForClustersAsPromised,memoize,wrap});
|
|
1
|
+
"use strict";var le=Object.create;var z=Object.defineProperty;var ce=Object.getOwnPropertyDescriptor;var de=Object.getOwnPropertyNames;var fe=Object.getPrototypeOf,he=Object.prototype.hasOwnProperty;var me=(t,e)=>{for(var n in e)z(t,n,{get:e[n],enumerable:!0})},H=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of de(e))!he.call(t,i)&&i!==n&&z(t,i,{get:()=>e[i],enumerable:!(s=ce(e,i))||s.enumerable});return t};var R=(t,e,n)=>(n=t!=null?le(fe(t)):{},H(e||!t||!t.__esModule?z(n,"default",{value:t,enumerable:!0}):n,t)),pe=t=>H(z({},"__esModule",{value:!0}),t);var Ge={};me(Ge,{LRUCacheClustered:()=>T,LRUCacheForClustersAsPromised:()=>T,default:()=>je,memoize:()=>oe,wrap:()=>ae});module.exports=pe(Ge);var y=R(require("cluster"),1),ue=require("events");var P=R(require("cluster"),1),U=R(require("debug"),1),Z=require("lru-cache");var m="lcfcap",S="lru-cache-clustered";function $(t){return q(t,0,new Set)}function q(t,e,n){if(t instanceof Error){if(n.has(t))return{name:t.name,message:"[circular cause]"};n.add(t);let s={name:t.name,message:t.message};t.stack&&(s.stack=t.stack);let i=t.code;(typeof i=="string"||typeof i=="number")&&(s.code=i);let r=t.cause;return r!==void 0&&(e+1>=8?s.cause={name:"Error",message:"[cause chain truncated]"}:s.cause=q(r,e+1,n)),s}return{name:"Error",message:typeof t=="string"?t:String(t)}}function V(t){let e=new Error(t.message);return e.name=t.name,t.stack&&(e.stack=t.stack),t.code!==void 0&&(e.code=t.code),t.cause!==void 0&&(e.cause=V(t.cause)),e}function B(t){if(typeof t!="object"||t===null||t.source!==m||typeof t.namespace!="string"||typeof t.version!="number")return!1;let e=t.push;return e==="l1:invalidate"||e==="l1:invalidate-namespace"}var N=(0,U.default)(`${S}-primary`),be=(0,U.default)(`${S}-messages`),ve=3e4,ke=Symbol.for("lru-cache-clustered.primary"),v=globalThis[ke]??={caches:new Map,stats:new Map,fetchLocks:new Map,versions:new Map,clusterListenerInstalled:!1,nextFetchToken:0},k=v.caches,E=v.stats,Be=v.versions,g=v.fetchLocks;function w(t){return v.versions.get(t)??0}function p(t){let e=(v.versions.get(t)??0)+1;return v.versions.set(t,e),e}function Y(t){return{namespace:t,hits:0,misses:0,sets:0,deletes:0,evictions:0,size:0}}function b(t){let e=E.get(t);return e||(e=Y(t),E.set(t,e)),e}function J(t){let e=t;return{max:e.max,maxSize:e.maxSize,maxEntrySize:e.maxEntrySize,ttl:e.ttl,allowStale:e.allowStale,updateAgeOnGet:e.updateAgeOnGet,updateAgeOnHas:e.updateAgeOnHas,noDeleteOnStaleGet:e.noDeleteOnStaleGet,ttlAutopurge:e.ttlAutopurge}}function f(t,e){let n=k.get(t);return n||O(t,e.cacheOptions)}function ye(t,e,n){if(!n)return;let s=J(e),i=[];for(let[r,o]of Object.entries(n))o!==void 0&&s[r]!==o&&i.push(`${r}=${String(s[r])} (existing) != ${String(o)} (incoming)`);if(i.length>0)throw new Error(`Conflicting options for namespace '${t}': ${i.join(", ")}`)}function h(t,e){if(e==null)throw new TypeError(`${t} must not be null or undefined`);return e}function x(t){let e={};return t.ttl!==void 0&&(e.ttl=t.ttl),t.size!==void 0&&(e.size=t.size),t.noUpdateTTL&&(e.noUpdateTTL=!0),Object.keys(e).length>0?e:void 0}function ge(t,e){let n=t.info(e);return typeof n?.size=="number"?n.size:void 0}function we(t){let e=g.get(t);return e||(e=new Map,g.set(t,e)),e}function K(t){g.get(t)?.size===0&&g.delete(t)}function Le(t){for(let[e,n]of g){for(let[s,i]of n)i.ownerWorkerId===t&&n.delete(s);K(e)}}function Q(t,e){let n={...t,dispose:(i,r,o)=>{o==="evict"&&(e.evictions+=1)}},s=n.max===void 0&&n.maxSize===void 0&&n.ttl===void 0?{...n,max:1e3}:n;return new Z.LRUCache(s)}function O(t,e){let n=k.get(t);if(n)ye(t,n,e);else{let s=Y(t);E.set(t,s),n=Q(e??{},s),k.set(t,n),N(`Created LRUCache for namespace '${t}'`)}return n}function Se(t,e,n={}){switch(e.op){case"init":{let s=!k.has(t),i=O(t,e.options);return{namespace:t,isNew:s,max:i.max,version:w(t)}}case"healthCheck":O(t,e.cacheOptions);return;case"destroy":{let s=k.delete(t),i=E.delete(t),r=g.delete(t),o=s||i||r;return o&&p(t),o}case"get":{let i=f(t,e).get(h("cache key",e.key)),r=b(t);return i!==void 0?r.hits+=1:r.misses+=1,i}case"set":return f(t,e).set(h("cache key",e.key),h("cache value",e.value),x({ttl:e.ttl,size:e.size})),b(t).sets+=1,p(t),!0;case"setIfAbsent":{let s=f(t,e),i=h("cache key",e.key);return s.peek(i)!==void 0?!1:(s.set(i,h("cache value",e.value),x({ttl:e.ttl,size:e.size})),b(t).sets+=1,p(t),!0)}case"delete":{let i=f(t,e).delete(h("cache key",e.key));return i&&(b(t).deletes+=1,p(t)),i}case"has":return f(t,e).has(h("cache key",e.key));case"peek":return f(t,e).peek(h("cache key",e.key));case"getRemainingTTL":return f(t,e).getRemainingTTL(h("cache key",e.key));case"clear":f(t,e).clear(),p(t);return;case"mGet":{let s=f(t,e),i=b(t);return e.keys.map(r=>{let o=s.get(h("cache key",r));return o!==void 0?i.hits+=1:i.misses+=1,[r,o]})}case"mSet":{let s=f(t,e),i=b(t),r=e.entries.map(([o,u,a])=>({key:h("cache key",o),value:h("cache value",u),entryOpts:a}));for(let{key:o,value:u,entryOpts:a}of r)s.set(o,u,x({ttl:a?.ttl??e.ttl,size:a?.size??e.size})),i.sets+=1;p(t);return}case"mDelete":{let s=f(t,e),i=b(t),r=e.keys.map(o=>h("cache key",o));for(let o of r)s.delete(o)&&(i.deletes+=1);p(t);return}case"keys":return[...f(t,e).keys()];case"values":return[...f(t,e).values()];case"entries":return[...f(t,e).entries()];case"dump":return f(t,e).dump();case"load":{let s=f(t,e),i=e.entries.map(([r,o])=>{let u=h("cache key",r);return h("cache value",o.value),[u,o]});s.load(i),p(t);return}case"size":return f(t,e).size;case"stats":{let s=f(t,e),i=b(t);return i.size=s.size,{...i}}case"purgeStale":{let s=f(t,e).purgeStale();return s&&p(t),s}case"incr":case"decr":{let s=f(t,e),i=h("cache key",e.key),r=s.peek(i),o=r!==void 0,u=typeof r=="number"?r:0,a=(e.amount??1)*(e.op==="decr"?-1:1),l=u+a,c=e.size??(o?ge(s,i):void 0),d=x(o?{size:c,noUpdateTTL:!0}:{ttl:e.ttl,size:c});return s.set(i,l,d),b(t).sets+=1,p(t),l}case"fetchClaim":{let s=f(t,e),i=h("cache key",e.key),r=we(t),o=Date.now();if(!e.forceRefresh){let a=s.get(i);if(a!==void 0)return{kind:"value",value:a};let l=r.get(i);if(l&&o-l.claimedAt<ve)return{kind:"follower"}}let u=`fetch-${++v.nextFetchToken}`;return r.set(i,{token:u,ownerWorkerId:n.workerId,claimedAt:o}),{kind:"leader",token:u}}case"fetchStore":{let s=f(t,e),i=h("cache key",e.key),r=g.get(t),o=r?.get(i);return!o||o.token!==e.token?!1:(s.set(i,h("cache value",e.value),x({ttl:e.ttl,size:e.size})),r?.delete(i),K(t),b(t).sets+=1,p(t),!0)}case"fetchAbort":{let s=h("cache key",e.key),i=g.get(t),r=i?.get(s);return!r||r.token!==e.token?!1:(i?.delete(s),K(t),!0)}case"max":{let s=f(t,e);if(typeof e.value=="number"&&e.value!==s.max){let i=b(t),r={...J(s),max:e.value},o=Q(r,i);return o.load(s.dump()),k.set(t,o),p(t),o.max}return s.max}case"ttl":{let s=f(t,e),i=s.ttl;return typeof e.value=="number"&&e.value!==i&&(s.ttl=e.value,p(t)),s.ttl}case"allowStale":{let s=f(t,e);return typeof e.value=="boolean"&&(s.allowStale=e.value),s.allowStale}default:{let s=e.op;throw new Error(`unhandled op: ${s}`)}}}var xe=new Set(["destroy","clear","purgeStale","mSet","mDelete","load","max","ttl"]);function Pe(t,e,n){if(xe.has(e.op))return{source:m,push:"l1:invalidate-namespace",namespace:t,version:n};let s=e.key;if(s!=null)return{source:m,push:"l1:invalidate",namespace:t,key:s,version:n}}function Oe(t){for(let e of Object.values(P.default.workers??{}))if(!(!e||!e.isConnected()))try{e.send(t)}catch(n){N(`l1 broadcast to worker ${e.id} failed: %s`,n)}}function M(t,e,n={}){let s=w(t),i=Se(t,e,n),r=w(t);if(r!==s){let o=Pe(t,e,r);o&&Oe(o)}return{value:i,version:r}}function Ce(t,e={}){if(typeof t!="object"||t===null)return A(t,"invalid request: not an object");if(!ee(t))return A(t,"invalid request: missing required fields");try{let{value:n}=M(t.namespace,t,e);return ze(t,n,w(t.namespace))}catch(n){return A(t,n)}}function ze(t,e,n){return{id:t.id,source:m,ok:!0,value:e,version:n}}function A(t,e){return{id:typeof t=="object"&&t!==null&&typeof t.id=="string"?t.id:"",source:m,ok:!1,error:$(e)}}function D(){if(!v.clusterListenerInstalled){v.clusterListenerInstalled=!0,P.default.on("exit",t=>{Le(t.id)}),P.default.on("fork",t=>{X(t)});for(let t of Object.values(P.default.workers??{}))t&&X(t)}}function X(t){t.on("message",e=>{if(!ee(e))return;be(`primary <- worker ${t.id}`,e);let n=Ce(e,{workerId:t.id});if(t.isConnected())try{t.send(n)}catch(s){N(`worker ${t.id} send failed (likely disconnected): %s`,s)}})}function ee(t){return typeof t=="object"&&t!==null&&t.source===m&&typeof t.id=="string"&&typeof t.namespace=="string"&&typeof t.op=="string"}var L=require("timers"),ne=R(require("debug"),1);var te=(0,ne.default)(`${S}-messages`),Re=0;function Ee(t){let e=new Map,n=new Map;t.on("message",i=>{if(Ie(i)){let r=e.get(i.id);if(!r)return;e.delete(i.id),r(i);return}if(B(i)){let r=n.get(i.namespace);if(!r)return;for(let o of r)try{o(i)}catch(u){te("invalidation handler threw: %o",u)}return}});function s(i,r){let o=String(++Re),u={id:o,namespace:i.namespace,source:m,...r};return new Promise((a,l)=>{let c=(0,L.setTimeout)(()=>{e.delete(o),i.failsafe==="reject"?l(new Error("IPC timeout")):a({value:void 0,version:0})},i.timeout);e.set(o,d=>{(0,L.clearTimeout)(c),d.ok?a({value:d.value,version:d.version??0}):l(V(d.error))}),te("worker -> primary",u);try{t.send(u)===!1&&((0,L.clearTimeout)(c),e.delete(o),i.failsafe==="reject"?l(new Error("IPC backpressure")):a({value:void 0,version:0}))}catch(d){(0,L.clearTimeout)(c),e.delete(o),l(d instanceof Error?d:new Error(String(d)))}})}return{async sendToPrimary(i,r){return(await s(i,r)).value},sendToPrimaryWithMeta:(i,r)=>s(i,r),subscribeInvalidations(i,r){let o=n.get(i);return o||(o=new Set,n.set(i,o)),o.add(r),()=>{let u=n.get(i);u&&(u.delete(r),u.size===0&&n.delete(i))}}}}function Ie(t){if(typeof t!="object"||t===null||t.source!==m||typeof t.id!="string"||typeof t.ok!="boolean")return!1;if(t.ok===!1){let e=t.error;if(typeof e!="object"||e===null||typeof e.name!="string"||typeof e.message!="string")return!1}return!0}var F;function _(){if(!F){if(typeof process.send!="function")throw new Error("lru-cache-clustered: worker IPC client requested in a process without `process.send` (not a cluster worker).");let t=process.send.bind(process);F=Ee({send:e=>t(e),on:(e,n)=>process.on(e,n)})}return F}var re=require("lru-cache"),se=new WeakMap,Te=0;function ie(t){let e=se.get(t);return e===void 0&&(e=++Te,se.set(t,e)),e}function W(t){switch(typeof t){case"string":return`s:${t}`;case"number":return`n:${t}`;case"boolean":return`b:${t}`;case"bigint":return`i:${t.toString()}`;case"symbol":throw new Error("L1 does not support symbol keys");case"function":return`f:${ie(t)}`;default:return`o:${ie(t)}`}}var Ve=()=>({enabled:!0,hits:0,misses:0,sets:0,invalidations:0,evictions:0,staleHits:0,size:0,ipcAvoided:0}),I=class{#n;#o;#i=0;#e=Ve();#s;constructor(e){this.#s=e.emit??(()=>{}),this.#o=e.ttl;let n={max:e.max??1e3,ttl:e.ttl,updateAgeOnGet:e.updateAgeOnGet??!0,allowStale:e.allowStale??!1,maxSize:e.maxSize,...e.maxSize!==void 0?{sizeCalculation:()=>1}:{},dispose:(s,i,r)=>{r==="evict"&&(this.#e.evictions+=1,this.#s("evict",{key:s.key??i,reason:"lru"}))}};this.#n=new re.LRUCache(n)}get(e,n=e){let s={},i=this.#n.get(e,{status:s});if(!i){this.#e.misses+=1,this.#s("miss",{key:n});return}if(s.returnedStale&&(this.#e.staleHits+=1,this.#s("stale-hit",{key:i.key})),i.version<this.#i){this.#n.delete(e),this.#e.misses+=1,this.#e.staleHits+=1,this.#s("stale-hit",{key:i.key}),this.#s("miss",{key:n});return}return this.#e.hits+=1,this.#e.ipcAvoided+=1,this.#s("hit",{key:i.key}),i.value}set(e,n,s,i,r=e){if(s<this.#i)return;let o=this.#c(i);o!==!1&&(this.#n.set(e,{value:n,version:s,key:r},o),this.#e.sets+=1,this.#s("set",{key:r,version:s}))}delete(e,n=e,s=!0){this.#n.delete(e)&&(this.#e.invalidations+=1,s&&this.#s("invalidate",{key:n,reason:"self"}))}clear(e=!0){this.#n.size>0&&(this.#e.invalidations+=1),this.#n.clear(),e&&this.#s("invalidate",{key:"*",reason:"clear"})}advanceLatestSeen(e){e>this.#i&&(this.#i=e)}latestSeen(){return this.#i}stats(){return{...this.#e,size:this.#n.size}}destroy(){this.#n.clear()}#c(e){if(e===void 0||!Number.isFinite(e))return;let n=this.#o===void 0?e:Math.min(e,this.#o);return n>0?{ttl:n}:!1}};function oe(t,e,n,s){return async(...i)=>{let r=n(...i);return t.fetch(r,()=>e(...i),s)}}function ae(t,e){let n=o=>e.encode(o),s=o=>e.decode(o);return{cache:t,namespace:t.namespace,ready:t.ready,async get(o,u){let a=await t.get(o,u);return a===void 0?void 0:await s(a)},async set(o,u,a){return t.set(o,await n(u),a)},async setIfAbsent(o,u,a){return t.setIfAbsent(o,await n(u),a)},has:(o,u)=>t.has(o,u),async peek(o,u){let a=await t.peek(o,u);return a===void 0?void 0:await s(a)},delete:o=>t.delete(o),getRemainingTTL:o=>t.getRemainingTTL(o),async mGet(o,u){let a=await t.mGet(o,u),l=new Map;for(let[c,d]of a)l.set(c,d===void 0?void 0:await s(d));return l},async mSet(o,u){let a=[];for(let l of o){let[c,d,G]=l;G===void 0?a.push([c,await n(d)]):a.push([c,await n(d),G])}return t.mSet(a,u)},mDelete:o=>t.mDelete(o),keys:()=>t.keys(),async values(){let o=await t.values(),u=[];for(let a of o)u.push(await s(a));return u},async entries(){let o=await t.entries(),u=[];for(let[a,l]of o)u.push([a,await s(l)]);return u},size:()=>t.size(),async*[Symbol.asyncIterator](){for(let[o,u]of await this.entries())yield[o,u]},clear:()=>t.clear(),destroy:()=>t.destroy(),healthCheck:()=>t.healthCheck(),purgeStale:()=>t.purgeStale(),stats:()=>t.stats(),async fetch(o,u,a){let l=await t.fetch(o,async c=>await n(await u(c)),a);return await s(l)}}}y.default.isPrimary&&D();var Ae=5,Ke=5e3,Ue=1e3,C=new Map,Ne=new Set(["destroy","clear","purgeStale","mSet","mDelete","load","max","ttl"]);function Me(t,e){let n=C.get(t);return n||(n=new Set,C.set(t,n)),n.add(e),()=>{let s=C.get(t);s&&(s.delete(e),s.size===0&&C.delete(t))}}function De(t,e){let n=C.get(t.namespace);if(n)for(let s of n)s!==e&&s(t)}function Fe(t,e){switch(t.op){case"set":case"mSet":case"mDelete":case"clear":case"load":case"incr":case"decr":return!0;case"delete":case"setIfAbsent":case"purgeStale":case"fetchStore":case"destroy":return e===!0;case"max":case"ttl":return typeof t.value=="number";default:return!1}}function _e(t,e,n,s){if(!Fe(e,s))return;if(Ne.has(e.op))return{source:m,push:"l1:invalidate-namespace",namespace:t,version:n};let i=e.key;if(i!=null)return{source:m,push:"l1:invalidate",namespace:t,key:i,version:n}}function We(t,e){if(t===void 0||t===!1)return;let n=t;if(n.enabled===!1)return;if(!n.experimental)throw new Error("localL1 is experimental in v2.1.0. Pass `localL1: { enabled: true, experimental: true }` to opt in.");let s=n.ttl??Math.min((e.ttl??1/0)*.1,Ke),i=e.ttl!==void 0?Math.min(s,e.ttl):s,r=Math.max(100,Math.floor(i)),o=n.methods===void 0?{get:!0,has:!0,fetch:!0}:{get:n.methods.get===!0,has:n.methods.has===!0,fetch:n.methods.fetch===!0};return{max:n.max??Ue,maxSize:n.maxSize,ttl:r,updateAgeOnGet:n.updateAgeOnGet??!0,allowStale:n.allowStale??!1,cacheUndefined:!1,invalidation:n.invalidation??"broadcast",methods:o}}function j(t){if(t!=null)try{return W(t)}catch{return}}var T=class t{namespace;timeout;failsafe;ready;#n;#o=new Map;#i=new ue.EventEmitter;#e;#s;#c;#b;#f;#d;constructor(e={}){this.namespace=e.namespace??"default",this.timeout=e.timeout??100,this.failsafe=e.failsafe==="reject"?"reject":"resolve";let{namespace:n,timeout:s,failsafe:i,noInit:r,localL1:o,...u}=e;this.#n=u;let a=We(e.localL1,u);this.#s=a?.methods??{get:!1,has:!1,fetch:!1},this.#c=a?.invalidation??"broadcast",this.#b=a?.cacheUndefined??!1,a&&(this.#e=new I({max:a.max,maxSize:a.maxSize,ttl:a.ttl,updateAgeOnGet:a.updateAgeOnGet,allowStale:a.allowStale,emit:(l,c)=>{this.#i.emit(`l1:${l}`,{namespace:this.namespace,...c})}})),y.default.isPrimary?(O(this.namespace,this.#n),this.#e&&(this.#e.advanceLatestSeen(w(this.namespace)),this.#h()),this.ready=Promise.resolve(void 0)):e.noInit?this.ready=Promise.resolve(void 0):this.ready=this.#t({op:"init",options:this.#n},"reject").then(l=>{this.#e&&(this.#e.advanceLatestSeen(l.value.version),this.#h())},()=>{})}static async getInstance(e={}){let n=new t({...e,noInit:!0});if(y.default.isWorker){let s=await n.#t({op:"init",options:n.#n},"reject");n.#e&&(n.#e.advanceLatestSeen(s.value.version),n.#h())}return n}static bootstrap(){y.default.isPrimary&&D()}static getAllCaches(){if(y.default.isWorker)throw new Error("LRUCacheClustered.getAllCaches() must not be called from a worker");return k}getCache(){if(y.default.isWorker)throw new Error("LRUCacheClustered.getCache() must not be called from a worker");return k.get(this.namespace)}async get(e,n){let s=this.#e&&this.#s.get&&!n?.bypassL1;if(s){let r=this.#l(e);if(r!==void 0)return r}let i=await this.#t({op:"get",key:e},this.failsafe);return s&&i.value!==void 0&&await this.#a(e,i.value,i.version),i.value}async set(e,n,s){this.#u(e);let i=await this.#t({op:"set",key:e,value:n,ttl:s?.ttl,size:s?.size},this.failsafe);return this.#e&&this.#e.advanceLatestSeen(i.version),this.#e&&s?.updateL1&&i.value===!0&&await this.#a(e,n,i.version),i.value}async delete(e){this.#u(e);let n=await this.#t({op:"delete",key:e},this.failsafe);return this.#e&&this.#e.advanceLatestSeen(n.version),n.value}async has(e,n){return this.#e&&this.#s.has&&!n?.bypassL1&&this.#l(e)!==void 0?!0:(await this.#t({op:"has",key:e},this.failsafe)).value}async peek(e,n){let s=this.#e&&this.#s.get&&!n?.bypassL1;if(s){let r=this.#l(e);if(r!==void 0)return r}let i=await this.#t({op:"peek",key:e},this.failsafe);return s&&i.value!==void 0&&await this.#a(e,i.value,i.version),i.value}async clear(){this.#e?.clear();let e=await this.#t({op:"clear"},this.failsafe);return this.#e&&this.#e.advanceLatestSeen(e.version),e.value}async purgeStale(){this.#e?.clear();let e=await this.#t({op:"purgeStale"},this.failsafe);return this.#e&&this.#e.advanceLatestSeen(e.version),e.value}async mGet(e,n){let s=new Map,i=this.#e&&this.#s.get&&!n?.bypassL1,r=[];if(i)for(let l of e){let c=this.#l(l);c!==void 0?s.set(l,c):r.push(l)}else r.push(...e);if(r.length===0){let l=new Map;for(let c of e)s.has(c)&&l.set(c,s.get(c));return l}let o=await this.#t({op:"mGet",keys:r},this.failsafe),u=[];for(let[l,c]of o.value??[]){let d=c===null?void 0:c;s.set(l,d),i&&d!==void 0&&u.push(this.#a(l,d,o.version))}await Promise.all(u);let a=new Map;for(let l of e)s.has(l)&&a.set(l,s.get(l));return a}async mSet(e,n){this.#e?.clear();let s=[...e].map(r=>r.length===3?[r[0],r[1],r[2]]:[r[0],r[1]]),i=await this.#t({op:"mSet",entries:s,ttl:n?.ttl,size:n?.size},this.failsafe);return this.#e&&this.#e.advanceLatestSeen(i.version),i.value}async mDelete(e){this.#e?.clear();let n=await this.#t({op:"mDelete",keys:e},this.failsafe);return this.#e&&this.#e.advanceLatestSeen(n.version),n.value}keys(){return this.#r({op:"keys"})}values(){return this.#r({op:"values"})}entries(){return this.#r({op:"entries"})}dump(){return this.#r({op:"dump"})}size(){return this.#r({op:"size"})}async incr(e,n,s){this.#u(e);let i=await this.#t({op:"incr",key:e,amount:n,ttl:s?.ttl,size:s?.size},this.failsafe);return this.#e&&this.#e.advanceLatestSeen(i.version),i.value}async decr(e,n,s){this.#u(e);let i=await this.#t({op:"decr",key:e,amount:n,ttl:s?.ttl,size:s?.size},this.failsafe);return this.#e&&this.#e.advanceLatestSeen(i.version),i.value}async allowStale(e){let n=await this.#r({op:"allowStale",value:e});return this.#n.allowStale=n,n}async max(e){let n=await this.#r({op:"max",value:e});return this.#n.max=n,e!==void 0&&this.#e?.clear(),n}async ttl(e){let n=await this.#r({op:"ttl",value:e});return this.#n.ttl=n,e!==void 0&&this.#e?.clear(),n}async getRemainingTTL(e){let n=await this.#r({op:"getRemainingTTL",key:e});return n===null?1/0:n}async setIfAbsent(e,n,s){this.#u(e);let i=await this.#t({op:"setIfAbsent",key:e,value:n,ttl:s?.ttl,size:s?.size},this.failsafe);return this.#e&&this.#e.advanceLatestSeen(i.version),i.value}async load(e){this.#e?.clear();let n=await this.#t({op:"load",entries:e},this.failsafe);return this.#e&&this.#e.advanceLatestSeen(n.version),n.value}async destroy(){return this.#o.clear(),this.#d?.(),this.#d=void 0,this.#e?.destroy(),this.#r({op:"destroy"})}healthCheck(){return this.#m({op:"healthCheck"})}stats(){return this.#r({op:"stats"})}localStats(){return this.#e?.stats()}on(e,n){return this.#i.on(e,n),this}off(e,n){return this.#i.off(e,n),this}once(e,n){return this.#i.once(e,n),this}clearLocal(){this.#e?.clear()}invalidateLocal(e){this.#u(e)}withoutLocal(){let e;return e=new Proxy(this,{get(n,s){if(s==="withoutLocal")return()=>e;if(s==="get")return(r,o)=>n.get(r,{...o,bypassL1:!0});if(s==="has")return(r,o)=>n.has(r,{...o,bypassL1:!0});if(s==="peek")return(r,o)=>n.peek(r,{...o,bypassL1:!0});if(s==="mGet")return(r,o)=>n.mGet(r,{...o,bypassL1:!0});if(s==="fetch")return(r,o,u)=>n.fetch(r,o,{...u,bypassL1:!0});let i=Reflect.get(n,s,n);return typeof i=="function"?i.bind(n):i}}),e}async*[Symbol.asyncIterator](){let e=await this.entries();for(let n of e)yield n}async fetch(e,n,s){let i=this.#e&&this.#s.fetch&&!s?.bypassL1;if(!s?.forceRefresh){if(i){let a=this.#l(e);if(a!==void 0)return a}let u=this.#o.get(e);if(u)return u.promise}let r;r={promise:(async()=>{if(!s?.forceRefresh)if(i){let a=await this.#t({op:"get",key:e},this.failsafe);if(a.value!==void 0)return await this.#a(e,a.value,a.version),a.value}else{let a=await this.get(e,{bypassL1:!0});if(a!==void 0)return a}let u=s?.forceRefresh===!0;for(;;){let a=await this.#m({op:"fetchClaim",key:e,forceRefresh:u});if(a.kind==="value")return a.value;if(a.kind==="leader")try{let c=await n(e),d=await this.#t({op:"fetchStore",key:e,token:a.token,value:c,ttl:s?.ttl,size:s?.size},"reject");return d.value?(i&&await this.#a(e,c,d.version),this.#e&&this.#e.advanceLatestSeen(d.version),c):await this.get(e,{bypassL1:!0})}catch(c){try{await this.#m({op:"fetchAbort",key:e,token:a.token})}catch{}throw c}let l=await this.peek(e,{bypassL1:!i});if(l===void 0){u=!1,await new Promise(c=>setTimeout(c,Ae));continue}return l}})()},this.#o.set(e,r);try{return await r.promise}finally{this.#o.get(e)===r&&this.#o.delete(e)}}#h(){if(!this.#e||this.#c!=="broadcast"||this.#d)return;let e=i=>this.#v(i);this.#f=e;let n=Me(this.namespace,e),s=y.default.isPrimary?void 0:_().subscribeInvalidations(this.namespace,e);this.#d=()=>{n(),s?.(),this.#f=void 0}}#v(e){if(this.#e.advanceLatestSeen(e.version),this.#i.emit("l1:invalidate",{namespace:this.namespace,key:e.push==="l1:invalidate"?e.key:"*",reason:"broadcast"}),e.push==="l1:invalidate")try{this.#e.delete(W(e.key),e.key,!1)}catch{}else this.#e.clear(!1)}async#a(e,n,s){let i=j(e);if(i===void 0)return;let r=await this.#k(e);r!==null&&this.#e.set(i,n,s,r,e)}#l(e){let n=j(e);return n===void 0?void 0:this.#e.get(n,e)}#u(e){if(!this.#e)return;let n=j(e);n!==void 0&&this.#e.delete(n,e)}async#k(e){try{let n=await this.getRemainingTTL(e);return typeof n!="number"||n<=0?null:Number.isFinite(n)?n:void 0}catch{return null}}#p(e,n,s){let i=_e(this.namespace,e,s,n);i&&De(i,this.#f)}#r(e){return this.#t(e,this.failsafe).then(n=>n.value)}#m(e){return this.#t(e,"reject").then(n=>n.value)}async#t(e,n){let s={...e,cacheOptions:this.#n};if(y.default.isPrimary)try{let r=M(this.namespace,s);return this.#p(s,r.value,r.version),{value:r.value,version:r.version}}catch(r){throw r instanceof Error?r:new Error(String(r))}let i=await _().sendToPrimaryWithMeta({namespace:this.namespace,timeout:this.timeout,failsafe:n},s);return this.#p(s,i.value,i.version),i}};var je=T;0&&(module.exports={LRUCacheClustered,LRUCacheForClustersAsPromised,memoize,wrap});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|