@dcsv-io/d2-caching-abstractions 0.1.1

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.
Files changed (51) hide show
  1. package/LICENSE +190 -0
  2. package/README.md +263 -0
  3. package/dist/i-cache-atomic.d.ts +69 -0
  4. package/dist/i-cache-atomic.d.ts.map +1 -0
  5. package/dist/i-cache-atomic.js +5 -0
  6. package/dist/i-cache-atomic.js.map +1 -0
  7. package/dist/i-cache-basic.d.ts +90 -0
  8. package/dist/i-cache-basic.d.ts.map +1 -0
  9. package/dist/i-cache-basic.js +5 -0
  10. package/dist/i-cache-basic.js.map +1 -0
  11. package/dist/i-cache-broadcast.d.ts +47 -0
  12. package/dist/i-cache-broadcast.d.ts.map +1 -0
  13. package/dist/i-cache-broadcast.js +5 -0
  14. package/dist/i-cache-broadcast.js.map +1 -0
  15. package/dist/i-cache-invalidation-backplane.d.ts +73 -0
  16. package/dist/i-cache-invalidation-backplane.d.ts.map +1 -0
  17. package/dist/i-cache-invalidation-backplane.js +5 -0
  18. package/dist/i-cache-invalidation-backplane.js.map +1 -0
  19. package/dist/i-cache-serializer.d.ts +35 -0
  20. package/dist/i-cache-serializer.d.ts.map +1 -0
  21. package/dist/i-cache-serializer.js +5 -0
  22. package/dist/i-cache-serializer.js.map +1 -0
  23. package/dist/i-cache-set.d.ts +59 -0
  24. package/dist/i-cache-set.d.ts.map +1 -0
  25. package/dist/i-cache-set.js +5 -0
  26. package/dist/i-cache-set.js.map +1 -0
  27. package/dist/i-distributed-cache.d.ts +25 -0
  28. package/dist/i-distributed-cache.d.ts.map +1 -0
  29. package/dist/i-distributed-cache.js +5 -0
  30. package/dist/i-distributed-cache.js.map +1 -0
  31. package/dist/i-local-cache.d.ts +18 -0
  32. package/dist/i-local-cache.d.ts.map +1 -0
  33. package/dist/i-local-cache.js +5 -0
  34. package/dist/i-local-cache.js.map +1 -0
  35. package/dist/i-tiered-cache.d.ts +31 -0
  36. package/dist/i-tiered-cache.d.ts.map +1 -0
  37. package/dist/i-tiered-cache.js +5 -0
  38. package/dist/i-tiered-cache.js.map +1 -0
  39. package/dist/index.d.ts +13 -0
  40. package/dist/index.d.ts.map +1 -0
  41. package/dist/index.js +6 -0
  42. package/dist/index.js.map +1 -0
  43. package/dist/input-failures.d.ts +27 -0
  44. package/dist/input-failures.d.ts.map +1 -0
  45. package/dist/input-failures.js +45 -0
  46. package/dist/input-failures.js.map +1 -0
  47. package/dist/local-cache-options.d.ts +40 -0
  48. package/dist/local-cache-options.d.ts.map +1 -0
  49. package/dist/local-cache-options.js +22 -0
  50. package/dist/local-cache-options.js.map +1 -0
  51. package/package.json +31 -0
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+  Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright (c) DCSV
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,263 @@
1
+ <!--
2
+ Copyright (c) DCSV. Licensed under the Apache License, Version 2.0.
3
+ -->
4
+
5
+ # @dcsv-io/d2-caching-abstractions
6
+
7
+ > Parent: [`../README.md`](../README.md) · .NET mirror: `DcsvIo.D2.Caching.Abstractions`
8
+
9
+ Node/BFF authors inject these cache **ports** without pulling Redis, logging, or DI
10
+ wiring into domain-safe code. The package is the TypeScript twin of
11
+ `DcsvIo.D2.Caching.Abstractions`: marker interfaces (`ILocalCache` /
12
+ `IDistributedCache` / `ITieredCache`), fine-grained building blocks
13
+ (`ICacheBasic` / `ICacheAtomic` / `ICacheBroadcast` / `ICacheSet`), plus
14
+ `ICacheInvalidationBackplane`, `ICacheSerializer`, `InputFailures`, and
15
+ `LocalCacheOptions` / `LOCAL_CACHE_DEFAULTS`. Every op returns
16
+ `Promise<D2Result<…>>` / `D2Result<…>` via `@dcsv-io/d2-result`. **No implementations**
17
+ ship here — only contracts and pure helpers.
18
+
19
+ ## Public surface — building blocks
20
+
21
+ Fine-grained interfaces. Implementations declare which they support; marker
22
+ interfaces compose them. Method names are camelCase (drop .NET `Async` suffix);
23
+ cancellation is optional `signal?: AbortSignal`; durations are milliseconds
24
+ (`expirationMs`, `defaultExpirationMs`, remaining TTL from `getTtl`).
25
+
26
+ - **`ICacheBasic`** — `get` / `getMany` / `exists` / `getTtl` / `set` /
27
+ `setMany` / `remove` / `removeMany`
28
+ - **`ICacheAtomic`** — `setNx` / `increment` / `acquireLock` / `releaseLock`
29
+ - **`ICacheBroadcast`** — `setAndBroadcast` / `setManyAndBroadcast` /
30
+ `removeAndBroadcast` / `removeManyAndBroadcast`
31
+ - **`ICacheSet`** — `setAdd` / `setCardinality` / `setRemove` / `setContains`
32
+ (cluster-only — Redis SADD/SCARD/SREM/SISMEMBER)
33
+
34
+ All operations return `D2Result` / `D2Result<T>` (async ops wrap in
35
+ `Promise`). Multi-entry maps use `ReadonlyMap<string, T>` (callers may
36
+ `new Map(Object.entries(record))`).
37
+
38
+ Falsey inputs (missing key, missing keys collection, missing entries map)
39
+ return `validationFailed` with an `InputError` naming the offending parameter
40
+ (built via `InputFailures.required(...)`). Implementations never throw for
41
+ **per-call** caller mistakes — every per-call failure shape is observable on
42
+ the result. Construction-time / DI-registration errors are a different
43
+ lifecycle concern and **do** surface as throws — see the `*AndBroadcast*`
44
+ carve-out below.
45
+
46
+ ## Cache key convention + PII
47
+
48
+ Cache keys follow the `EntityName:{id}` shape (`Session:{userId}`,
49
+ `Jwks:{kid}`, `WhoIs:{ip}`, etc.) (`EntityName:{id}`).
50
+ `LocalCacheOptions.keyPrefix` is a **namespace** prefix layered on top of that
51
+ convention (handy when multiple caches share a process), not a substitute for
52
+ it. **Keep PII out of keys** — keys leak into logs, traces, and store
53
+ inspection. Hash any user-supplied identifier first.
54
+
55
+ ## Marker interfaces
56
+
57
+ What consumers inject. The marker name documents the cache scope at the
58
+ dependency site so the reader sees the parameter and immediately knows the
59
+ behavioral profile, without checking registration.
60
+
61
+ **`ILocalCache`** — composes `ICacheBasic` + `ICacheAtomic`.
62
+ Per-process scope. Atomic ops at process scope. No broadcast (nothing outside
63
+ this process can see local cache state). Use for instance-scoped data: per-
64
+ instance fingerprint cache, per-instance counters, hot in-process lookups.
65
+
66
+ **`IDistributedCache`** — composes `ICacheBasic` + `ICacheAtomic` +
67
+ `ICacheBroadcast` + `ICacheSet`.
68
+ Cluster scope. Atomic ops cluster-wide. Every read hits the remote store
69
+ (no L1). Use when freshness matters more than read speed: rate-limit counters,
70
+ distributed locks, ephemeral session lookups.
71
+
72
+ **`ITieredCache`** — composes `ICacheBasic` + `ICacheAtomic` +
73
+ `ICacheBroadcast`.
74
+ Composed L1+L2. Reads check L1 first / fall through to L2 / populate L1.
75
+ Writes go L2-first (L1 only if L2 succeeded). Atomic ops route through L2 with
76
+ L1 invalidation as side effect. Use for read-heavy entity data where freshness
77
+ within a few seconds is acceptable. **Does NOT compose `ICacheSet`** — set
78
+ primitives are cluster-only and tiered composition would silently hide their
79
+ cluster-wide nature. Callers needing SADD/SCARD inject `IDistributedCache`
80
+ directly.
81
+
82
+ **Shared blocks vs Set:** Basic + Atomic + Broadcast are method-identical on
83
+ `IDistributedCache` and `ITieredCache`. **`ICacheSet` is only on
84
+ `IDistributedCache`** (not full structural identity). The marker distinction
85
+ is behavioral — DI registration determines the concrete implementation; the
86
+ parameter type at the call site tells the reader whether they consume
87
+ "single-tier remote" or "two-tier composed."
88
+
89
+ ## Supporting types
90
+
91
+ **`LocalCacheOptions`** / **`LOCAL_CACHE_DEFAULTS`** / **`createLocalCacheOptions`**
92
+ — `maxEntries` (100_000), `defaultExpirationMs` (3_600_000 / 1h),
93
+ `keyPrefix` (`""`). Factory merges an optional partial over defaults and
94
+ returns a fresh mutable object. No POCO validation (mirrors .NET).
95
+
96
+ **`InputFailures`** — pre-built `validationFailed` factory
97
+ (`required(paramName)` / `required<T>(paramName)`) used by impls so the
98
+ cache surface stays errors-as-values rather than throws for per-call caller
99
+ mistakes. Constructors / DI registration still throw — registration-time
100
+ concern, not per-call input.
101
+
102
+ **`ICacheSerializer`** — pluggable serialization for distributed caches.
103
+ `contentType: string` (free string, e.g. `"application/json"`);
104
+ `serialize` / `deserialize` with `Uint8Array`. This package owns the port only; a default JSON implementation is part of the
105
+ `@dcsv-io/d2-caching-distributed-redis` package surface. Local
106
+ caches store objects directly and do not need this. Impls use `COULD_NOT_BE_SERIALIZED` /
107
+ `COULD_NOT_BE_DESERIALIZED` failure codes.
108
+
109
+ **`ICacheInvalidationBackplane`** — optional pub/sub backplane for
110
+ cross-instance L1 invalidation (`AsyncDisposable`). Tiered consumers
111
+ subscribe at construction; `*AndBroadcast*` writes publish on every send.
112
+ Provider-agnostic — swappable for Redis pub/sub, Postgres LISTEN/NOTIFY,
113
+ in-process for tests.
114
+
115
+ ## Result mapping
116
+
117
+ | Op family | Success / partial | Failure / notes |
118
+ | --- | --- | --- |
119
+ | `get` | hit → `ok(value)` | miss → `notFound`; store down → `serviceUnavailable` |
120
+ | `getMany` | all → `ok(map)`; some → `someFound(partial)` | none → `notFound` |
121
+ | `exists` | `ok(true\|false)` | store down → fail |
122
+ | `getTtl` | remaining ms → `ok(number)`; no expiry → `ok(undefined)` | absent → `notFound` |
123
+ | `set` / `setMany` | `ok` | store down → fail |
124
+ | `remove` / `removeMany` | `ok` (**idempotent**) | store down → fail |
125
+ | `setNx` | wrote → `ok(true)`; exists → `ok(false)` | store down → fail |
126
+ | `increment` | `ok(newValue)`; **TTL applied only on key create; subsequent ops preserve TTL** | type mismatch → `conflict`; store down → fail |
127
+ | `acquireLock` | acquired → `ok(true)`; held → `ok(false)` | **requires** `expirationMs`; store down → fail |
128
+ | `releaseLock` | `ok` (**idempotent** — no-op if not held) | store down → fail |
129
+ | `*AndBroadcast*` | same as plain counterparts | **throws** if no backplane registered (registration error, not D2Result) |
130
+ | `setAdd` | new → `ok(true)`; present → `ok(false)`; **TTL only on set create** | store down → fail |
131
+ | `setCardinality` | `ok(count)`; absent → `ok(0)` | store down → fail |
132
+ | `setRemove` | removed → `ok(true)`; absent → `ok(false)` (**idempotent**) | store down → fail |
133
+ | `setContains` | `ok(true\|false)` | store down → fail |
134
+ | `publishInvalidation` / `Many` | `ok` | backplane error → fail |
135
+ | bad input (falsey key, etc.) | — | `validationFailed` via `InputFailures` (impl duty; ports document) |
136
+
137
+ **Counter width:** `number` (not `bigint`) is the intentional TS ergonomic
138
+ delta vs .NET `long`. Stay within `Number.MAX_SAFE_INTEGER`.
139
+
140
+ ## Broadcast variants — when to use
141
+
142
+ The `*AndBroadcast*` methods write/remove AND publish an invalidation message.
143
+ Other instances' tiered caches subscribe to the backplane and drop their L1
144
+ copies on receipt — keeping cluster L1 caches in sync without polling.
145
+
146
+ **Use the broadcast variant when:**
147
+
148
+ - The data is shared across instances (user profile, org settings, JWKS).
149
+ - A user-initiated remove must be visible cluster-wide quickly.
150
+ - Coordinated state changes that depend on every instance seeing the new state.
151
+
152
+ **Use the plain (non-broadcast) variant when:**
153
+
154
+ - Cache-warming / startup seed.
155
+ - Single-writer-single-reader keys (derived from this instance's process ID).
156
+ - Hot-path writes where the broadcast cost dominates (counter ticks).
157
+ - Refresh writes of effectively-the-same data.
158
+ - Single-instance deployments (don't register a backplane).
159
+ - Short-TTL data where staleness is naturally bounded.
160
+
161
+ ## Invalidation backplane
162
+
163
+ `ICacheInvalidationBackplane` powers `*AndBroadcast*` writes and any other
164
+ "tell every instance to drop K from its L1" flow.
165
+
166
+ ### Everyone acts
167
+
168
+ Every subscriber receives every message — **including messages this instance
169
+ itself published**. There is no sender-ID filter. The cost of self-receive is
170
+ bounded (tiered next-read re-fetch from L2, or a no-op remove).
171
+
172
+ ### Dispose unsubscribes / stops further delivery
173
+
174
+ `subscribe(handler)` returns an `AsyncDisposable`. Disposing a subscription
175
+ **removes that handler from fan-out** and **stops further invalidation key
176
+ delivery** to it. The handler's `AbortSignal` is aborted on dispose
177
+ (accompanies unsubscribe; does not replace it). One handler throw must not
178
+ break delivery to other handlers. Each `subscribe` is independent. Dispose is
179
+ idempotent. Disposing the backplane tears down shared provider resources,
180
+ unsubscribes remaining handlers, and cancels in-flight handler work.
181
+
182
+ ### At-most-once delivery
183
+
184
+ Missed message → next read hits L2. Acceptable for cache invalidation.
185
+
186
+ ```ts
187
+ const subscription = backplane.subscribe(async (key, signal) => {
188
+ // Drop L1 entry for `key`. signal aborts when subscription is disposed.
189
+ await dropLocal(key, signal);
190
+ });
191
+
192
+ // Later:
193
+ await subscription[Symbol.asyncDispose]();
194
+ ```
195
+
196
+ ## Atomic on tiered — how it works
197
+
198
+ `ITieredCache` exposes the same atomic surface as `IDistributedCache` because
199
+ the atomicity guarantee comes from L2 (the cluster source of truth). Pattern:
200
+
201
+ - **`increment`** → L2 atomic increment; on success invalidate L1 + broadcast.
202
+ - **`setNx`** → L2 SetNx; on success write L1 + broadcast; on fail invalidate L1.
203
+ - **`acquireLock` / `releaseLock`** → pure delegation to L2 (lock state is
204
+ coordination, not a cached value).
205
+
206
+ L1 is never authoritative for atomic state. L2 is. L1 just reflects (or
207
+ invalidates). Concrete behavior lands in `@dcsv-io/d2-caching-tiered`.
208
+
209
+ ## Configuration carve-out
210
+
211
+ There is **no** shared `DistributedCacheOptions` in abstractions. Provider-
212
+ specific options (Redis connection string, Sentinel topology, channel name
213
+ for pub/sub, retry config, etc.) live on the implementation package's own
214
+ options class. The few common fields (`defaultExpirationMs`, `keyPrefix`) are
215
+ easier to redeclare per-impl than to inherit. Same for tiered: the tiered
216
+ package declares its own options when there is a real knob to expose.
217
+
218
+ The invalidation channel constant (`d2:cache:invalidations`) lives on the
219
+ Redis package options — abstractions own the **interface only**.
220
+
221
+ ## Usage
222
+
223
+ Inject markers at composition roots; this package registers nothing.
224
+
225
+ ```ts
226
+ import type { ILocalCache, IDistributedCache, ITieredCache } from "@dcsv-io/d2-caching-abstractions";
227
+ import { InputFailures, createLocalCacheOptions } from "@dcsv-io/d2-caching-abstractions";
228
+
229
+ // Domain / handler code depends only on the marker:
230
+ async function loadProfile(cache: ITieredCache, userId: string) {
231
+ return cache.get<Profile>(`Profile:${userId}`);
232
+ }
233
+
234
+ // Impls use InputFailures for per-call validation:
235
+ function guardKey(key: string) {
236
+ if (!key) return InputFailures.required("key");
237
+ return undefined;
238
+ }
239
+
240
+ const localOpts = createLocalCacheOptions({ keyPrefix: "jwks:" });
241
+ ```
242
+
243
+ ## Telemetry
244
+
245
+ **N/A in this package** — abstractions are hook-free. Metrics live in
246
+ **local-default + redis** implementations; **tiered owns structured logs
247
+ (not meters)**.
248
+
249
+ ## Dependencies
250
+
251
+ - `@dcsv-io/d2-result` — every op returns `D2Result` / `D2Result<T>`
252
+ - `@dcsv-io/d2-i18n-keys` — `TK.common.errors.NOT_NULL_VIOLATION` for `InputFailures`
253
+
254
+ No runtime deps beyond those (no DI, no logging, no provider libs). This
255
+ abstraction stays domain-safe so any handler can declare a cache dependency
256
+ without dragging in implementation runtime.
257
+
258
+ ## References
259
+
260
+ - [`local-default/README.md`](../local-default/README.md) — local in-process impl
261
+ - [`distributed-redis/README.md`](../distributed-redis/README.md) — Redis + backplane
262
+ - [`tiered/README.md`](../tiered/README.md) — L1+L2 composition
263
+ - .NET twin: `packages/dotnet/caching/abstractions/`
@@ -0,0 +1,69 @@
1
+ import type { D2Result } from "@dcsv-io/d2-result";
2
+ /**
3
+ * Atomic primitives — set-if-absent, increment, lock acquire/release.
4
+ * Implemented by every cache flavor ({@link ILocalCache},
5
+ * {@link IDistributedCache}, {@link ITieredCache}); the atomicity
6
+ * scope depends on the implementing cache.
7
+ *
8
+ * **Scope per marker:**
9
+ * - {@link ILocalCache}: per-process. Atomicity guaranteed within this
10
+ * instance only.
11
+ * - {@link IDistributedCache}: cluster-wide. Atomicity enforced by the
12
+ * remote store (e.g. Redis SETNX / INCR).
13
+ * - {@link ITieredCache}: cluster-wide. Routes through L2 (the source
14
+ * of truth); L1 is invalidated or refreshed as a side effect.
15
+ *
16
+ * Callers pick the scope by injecting the appropriate marker interface.
17
+ * The same atomic op called via `ILocalCache` coordinates within one
18
+ * process; via `IDistributedCache` or `ITieredCache` it coordinates
19
+ * across the cluster.
20
+ *
21
+ * **Counter width:** `number` (not `bigint`) is an intentional TS
22
+ * ergonomic delta vs .NET `long`. Implementations must stay within
23
+ * `Number.MAX_SAFE_INTEGER`.
24
+ */
25
+ export interface ICacheAtomic {
26
+ /**
27
+ * Sets a value only if the key is not already present (atomic).
28
+ *
29
+ * @returns `ok(true)` if the value was written. `ok(false)` if the
30
+ * key already existed (no write). Failure on backing-store error.
31
+ */
32
+ setNx<T>(key: string, value: T, expirationMs?: number, signal?: AbortSignal): Promise<D2Result<boolean>>;
33
+ /**
34
+ * Atomically increments a numeric counter and returns the new value.
35
+ * Creates the key if absent (initial value = 0 + amount).
36
+ *
37
+ * **TTL-on-create-only:** the optional `expirationMs` is applied
38
+ * **only when the key is created**; subsequent increments on an
39
+ * existing key **preserve the existing TTL**.
40
+ *
41
+ * @param amount - Amount to add (may be negative). Default `1`.
42
+ * @returns `ok(newValue)` on success. `conflict` if the existing key
43
+ * holds a non-numeric value (Redis WRONGTYPE parity). Failure on
44
+ * backing-store error.
45
+ */
46
+ increment(key: string, amount?: number, expirationMs?: number, signal?: AbortSignal): Promise<D2Result<number>>;
47
+ /**
48
+ * Attempts to acquire a lock on the given key. The caller-supplied
49
+ * `lockId` identifies the holder and is required for release. Locks
50
+ * expire automatically after `expirationMs` to prevent indefinite
51
+ * hold by a crashed process.
52
+ *
53
+ * @param expirationMs - **Required** lock TTL in milliseconds —
54
+ * locks must auto-expire (matches .NET `TimeSpan expiration` with
55
+ * no default).
56
+ * @returns `ok(true)` on acquisition. `ok(false)` if the lock is
57
+ * held by someone else. Failure on backing-store error.
58
+ */
59
+ acquireLock(key: string, lockId: string, expirationMs: number, signal?: AbortSignal): Promise<D2Result<boolean>>;
60
+ /**
61
+ * Releases a lock previously acquired with {@link acquireLock}.
62
+ * Releasing a lock you don't hold (or one that's already expired) is
63
+ * a no-op rather than an error — release is **idempotent**.
64
+ *
65
+ * @returns `ok`; failure on backing-store error.
66
+ */
67
+ releaseLock(key: string, lockId: string, signal?: AbortSignal): Promise<D2Result>;
68
+ }
69
+ //# sourceMappingURL=i-cache-atomic.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"i-cache-atomic.d.ts","sourceRoot":"","sources":["../src/i-cache-atomic.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAEnD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,WAAW,YAAY;IAC3B;;;;;OAKG;IACH,KAAK,CAAC,CAAC,EACL,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,CAAC,EACR,YAAY,CAAC,EAAE,MAAM,EACrB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC;IAE9B;;;;;;;;;;;;OAYG;IACH,SAAS,CACP,GAAG,EAAE,MAAM,EACX,MAAM,CAAC,EAAE,MAAM,EACf,YAAY,CAAC,EAAE,MAAM,EACrB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;IAE7B;;;;;;;;;;;OAWG;IACH,WAAW,CACT,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,MAAM,EACpB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC;IAE9B;;;;;;OAMG;IACH,WAAW,CACT,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,MAAM,EACd,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,QAAQ,CAAC,CAAC;CACtB"}
@@ -0,0 +1,5 @@
1
+ // -----------------------------------------------------------------------
2
+ // Copyright (c) DCSV. Licensed under the Apache License, Version 2.0.
3
+ // -----------------------------------------------------------------------
4
+ export {};
5
+ //# sourceMappingURL=i-cache-atomic.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"i-cache-atomic.js","sourceRoot":"","sources":["../src/i-cache-atomic.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,sEAAsE;AACtE,0EAA0E"}
@@ -0,0 +1,90 @@
1
+ import type { D2Result } from "@dcsv-io/d2-result";
2
+ /**
3
+ * Core read + write surface common to every cache flavor (local,
4
+ * distributed, tiered). Every method returns `D2Result` / `D2Result<T>`.
5
+ * Cache misses surface as `notFound`; partial bulk hits as `someFound`
6
+ * (callers discriminate via `success` / `isPartialSuccess` / `errorCode`).
7
+ * Generic infrastructure failures (couldn't reach the backing store,
8
+ * serializer threw, etc.) surface as `serviceUnavailable` /
9
+ * `unhandledException`.
10
+ *
11
+ * Falsey inputs (missing key, missing keys collection, missing entries
12
+ * map) return `validationFailed` with an `InputError` naming the
13
+ * offending parameter (built via `InputFailures.required(...)`).
14
+ * Implementations never throw for **per-call** caller mistakes —
15
+ * every per-call failure shape is observable on the result.
16
+ *
17
+ * **Behavior per marker:**
18
+ * - {@link ILocalCache}: in-process reads/writes. Sub-microsecond per op.
19
+ * - {@link IDistributedCache}: every read and write hits the remote store.
20
+ * No L1 buffer. Predictable freshness, network-bound latency.
21
+ * - {@link ITieredCache}: reads check L1 first / fall through to L2 /
22
+ * populate L1. Writes go L2-first — L1 only writes if L2 succeeded —
23
+ * so partial-write states are impossible and the result is binary
24
+ * (success or the L2 failure bubbled up).
25
+ *
26
+ * **PII:** keep PII out of cache **keys** — keys leak into logs, traces,
27
+ * and store inspection tooling. Hash user-supplied identifiers first.
28
+ */
29
+ export interface ICacheBasic {
30
+ /**
31
+ * Reads a single value by key.
32
+ *
33
+ * @returns `ok(value)` on hit, `notFound` on miss, failure on
34
+ * backing-store error.
35
+ */
36
+ get<T>(key: string, signal?: AbortSignal): Promise<D2Result<T>>;
37
+ /**
38
+ * Reads many keys in one round-trip.
39
+ *
40
+ * @returns `ok(map)` when every key hit, `someFound(partial)` when
41
+ * some hit and some missed, `notFound` when none hit, or a failure
42
+ * on backing-store error. Callers may build the input via
43
+ * `new Map(Object.entries(record))` when they hold a record.
44
+ */
45
+ getMany<T>(keys: readonly string[], signal?: AbortSignal): Promise<D2Result<ReadonlyMap<string, T>>>;
46
+ /**
47
+ * Returns whether a key is currently present.
48
+ *
49
+ * @returns `ok(true|false)`; failure on backing-store error.
50
+ */
51
+ exists(key: string, signal?: AbortSignal): Promise<D2Result<boolean>>;
52
+ /**
53
+ * Returns the remaining TTL for a key in milliseconds.
54
+ *
55
+ * @returns `notFound` if the key is absent. `ok(undefined)` if the key
56
+ * exists with no expiration set. `ok(ms)` with the remaining time
57
+ * when expiration is set. Failure on backing-store error.
58
+ */
59
+ getTtl(key: string, signal?: AbortSignal): Promise<D2Result<number | undefined>>;
60
+ /**
61
+ * Writes (or overwrites) a value.
62
+ *
63
+ * @param expirationMs - Optional TTL in milliseconds; omitted means
64
+ * use the cache's default.
65
+ * @returns `ok` on success; failure on backing-store error.
66
+ */
67
+ set<T>(key: string, value: T, expirationMs?: number, signal?: AbortSignal): Promise<D2Result>;
68
+ /**
69
+ * Writes many entries in one round-trip.
70
+ *
71
+ * @param entries - Key/value pairs to store (`ReadonlyMap`).
72
+ * @param expirationMs - Optional TTL applied to every entry.
73
+ * @returns `ok` on success; failure on backing-store error.
74
+ */
75
+ setMany<T>(entries: ReadonlyMap<string, T>, expirationMs?: number, signal?: AbortSignal): Promise<D2Result>;
76
+ /**
77
+ * Removes a key. **Idempotent** — succeeds whether the key existed
78
+ * or not.
79
+ *
80
+ * @returns `ok`; failure on backing-store error.
81
+ */
82
+ remove(key: string, signal?: AbortSignal): Promise<D2Result>;
83
+ /**
84
+ * Removes many keys. **Idempotent**.
85
+ *
86
+ * @returns `ok`; failure on backing-store error.
87
+ */
88
+ removeMany(keys: readonly string[], signal?: AbortSignal): Promise<D2Result>;
89
+ }
90
+ //# sourceMappingURL=i-cache-basic.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"i-cache-basic.d.ts","sourceRoot":"","sources":["../src/i-cache-basic.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAEnD;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,WAAW,WAAW;IAC1B;;;;;OAKG;IACH,GAAG,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;IAEhE;;;;;;;OAOG;IACH,OAAO,CAAC,CAAC,EACP,IAAI,EAAE,SAAS,MAAM,EAAE,EACvB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IAE7C;;;;OAIG;IACH,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC;IAEtE;;;;;;OAMG;IACH,MAAM,CACJ,GAAG,EAAE,MAAM,EACX,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,QAAQ,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC,CAAC;IAEzC;;;;;;OAMG;IACH,GAAG,CAAC,CAAC,EACH,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,CAAC,EACR,YAAY,CAAC,EAAE,MAAM,EACrB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,QAAQ,CAAC,CAAC;IAErB;;;;;;OAMG;IACH,OAAO,CAAC,CAAC,EACP,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,CAAC,CAAC,EAC/B,YAAY,CAAC,EAAE,MAAM,EACrB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,QAAQ,CAAC,CAAC;IAErB;;;;;OAKG;IACH,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IAE7D;;;;OAIG;IACH,UAAU,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CAC9E"}
@@ -0,0 +1,5 @@
1
+ // -----------------------------------------------------------------------
2
+ // Copyright (c) DCSV. Licensed under the Apache License, Version 2.0.
3
+ // -----------------------------------------------------------------------
4
+ export {};
5
+ //# sourceMappingURL=i-cache-basic.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"i-cache-basic.js","sourceRoot":"","sources":["../src/i-cache-basic.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,sEAAsE;AACtE,0EAA0E"}