@prisma-next/middleware-cache 0.9.0-dev.6

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/LICENSE ADDED
@@ -0,0 +1,201 @@
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
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2026] [Prisma Data, Inc]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,152 @@
1
+ # @prisma-next/middleware-cache
2
+
3
+ A family-agnostic, opt-in caching middleware for Prisma Next runtimes.
4
+
5
+ Built on the `intercept` hook on `RuntimeMiddleware` (added in TML-2143 M1): on a cache hit, the middleware short-circuits execution and returns the cached rows; the driver is never invoked. On a cache miss, the middleware buffers rows from the driver and commits them to the store on successful completion.
6
+
7
+ The package depends only on `@prisma-next/framework-components/runtime` — no SQL or Mongo runtime dependency. Cache keys come from `RuntimeMiddlewareContext.contentHash(exec)`, which the family runtime populates, so SQL and Mongo runtimes both work out of the box.
8
+
9
+ ## Responsibilities
10
+
11
+ - Provide an opt-in caching `RuntimeMiddleware` that short-circuits repeated reads via the `intercept` hook.
12
+ - Define the `cacheAnnotation` handle (read-only) that lane terminals (SQL DSL `.annotate(...)`, ORM read terminals) use to attach per-query cache parameters (`ttl`, `skip`, `key`).
13
+ - Resolve the cache key per execution: per-query `cacheAnnotation({ key })` override, otherwise `RuntimeMiddlewareContext.contentHash(exec)` from the family runtime.
14
+ - Buffer driver rows on a miss and commit to the `CacheStore` only on successful completion (`completed: true && source: 'driver'`).
15
+ - Bypass the cache when `RuntimeMiddlewareContext.scope` is `'connection'` or `'transaction'`.
16
+ - Ship a default in-memory LRU-with-TTL `CacheStore` and expose the `CacheStore` interface for pluggable backends (Redis, Memcached, etc.).
17
+
18
+ ## Dependencies
19
+
20
+ - `@prisma-next/framework-components/runtime` — the only production dependency. Provides `RuntimeMiddleware`, `RuntimeMiddlewareContext` (with `contentHash` and `scope`), `defineAnnotation`, `AfterExecuteResult`, and the orchestrator integration via `runWithMiddleware`.
21
+
22
+ The package does **not** depend on `@prisma-next/sql-runtime`, `@prisma-next/mongo-runtime`, or any target adapter. It does not import `node:crypto` — hashing the canonical execution identity is the family runtime's responsibility (via `@prisma-next/utils/hash-identity` in the SQL and Mongo runtimes today).
23
+
24
+
25
+ ## Quick start
26
+
27
+ ```typescript
28
+ import postgres from '@prisma-next/postgres/runtime';
29
+ import {
30
+ cacheAnnotation,
31
+ createCacheMiddleware,
32
+ } from '@prisma-next/middleware-cache';
33
+ import type { Contract } from './contract.d';
34
+ import contractJson from './contract.json' with { type: 'json' };
35
+
36
+ const db = postgres<Contract>({
37
+ contractJson,
38
+ url: process.env['DATABASE_URL']!,
39
+ middleware: [createCacheMiddleware({ maxEntries: 1000 })],
40
+ });
41
+
42
+ // First call: hits the database, caches the raw rows.
43
+ const first = await db.orm.User.first({ id: 1 }, (meta) =>
44
+ meta.annotate(cacheAnnotation({ ttl: 60_000 })),
45
+ );
46
+
47
+ // Second call with the identical plan: served from cache, driver
48
+ // not invoked.
49
+ const second = await db.orm.User.first({ id: 1 }, (meta) =>
50
+ meta.annotate(cacheAnnotation({ ttl: 60_000 })),
51
+ );
52
+
53
+ // Un-annotated queries are never cached — caching is strictly opt-in.
54
+ const fresh = await db.orm.User.first({ id: 1 }); // always hits the DB
55
+ ```
56
+
57
+ ## Opt-in by annotation
58
+
59
+ The cache middleware acts only on plans that carry a `cacheAnnotation` payload with a `ttl` set:
60
+
61
+ | Annotation state | Behavior |
62
+ |---|---|
63
+ | No `cacheAnnotation` on the plan | Pass through; never cached. |
64
+ | `cacheAnnotation({ })` (no `ttl`) | Pass through; never cached. |
65
+ | `cacheAnnotation({ skip: true })` | Pass through; never cached. |
66
+ | `cacheAnnotation({ ttl })` | Cache lookup; commit on miss + success. |
67
+ | `cacheAnnotation({ ttl, key })` | As above, but use the supplied key verbatim. |
68
+
69
+ The annotation is **read-only**: it declares `applicableTo: ['read']`, so the lane gate (TML-2143 M2) rejects passing it to write terminals at both type and runtime levels. "Cache a mutation" is structurally impossible without an `as any` cast bypass at both the type and runtime levels — the cache middleware itself ships without any mutation classifier.
70
+
71
+ ```typescript
72
+ // ✓ ORM read terminal accepts the read-only annotation via the meta callback.
73
+ await db.orm.User.first({ id }, (meta) => meta.annotate(cacheAnnotation({ ttl: 60_000 })));
74
+
75
+ // ✓ Bare-configurator form on `first` — pass `undefined` as the filter to
76
+ // attach an annotation without narrowing further. Also valid: chain
77
+ // `.where(...)` before `.first(undefined, ...)`.
78
+ await db.orm.User.first(undefined, (meta) => meta.annotate(cacheAnnotation({ ttl: 60_000 })));
79
+
80
+ // ✗ Type error: write terminal rejects read-only annotation.
81
+ await db.orm.User.create(input, (meta) => meta.annotate(cacheAnnotation({ ttl: 60_000 })));
82
+
83
+ // ✓ SQL DSL: chainable on select / grouped builders.
84
+ const plan = db.sql
85
+ .from(tables.user)
86
+ .select({ id: tables.user.columns.id })
87
+ .annotate(cacheAnnotation({ ttl: 60_000 }))
88
+ .build();
89
+ ```
90
+
91
+ ## Cache key composition
92
+
93
+ Two-tier resolution:
94
+
95
+ 1. **Per-query override.** `cacheAnnotation({ key })` — the supplied string is used verbatim. The cache middleware does **not** rehash user-supplied keys; the caller is responsible for keeping the string bounded in size and free of sensitive data they do not want flowing into debug logs, Redis `KEYS` output, persistence dumps, or any user-supplied `CacheStore`. User-supplied keys also bypass the storage-hash discrimination below — if you fix a key, prefix it with something tied to your schema version (e.g. `` `${storageHash}:my-key` ``) to avoid serving stale-schema entries after a migration.
96
+ 2. **Default.** `RuntimeMiddlewareContext.contentHash(exec)` — the family runtime owns this. The SQL and Mongo runtimes today compose `meta.storageHash + '|' + …` and pipe the result through `hashContent` (SHA-512), producing a bounded, opaque digest of the form `sha512:HEXDIGEST`. The cache middleware uses the returned string directly as the `Map<string, …>` key.
97
+
98
+ Two consequences worth pinning (both properties of the **default** key path — user-supplied keys above opt out of both):
99
+
100
+ - **Storage-hash discrimination.** A schema migration changes `meta.storageHash`, which changes `contentHash`, which invalidates cached entries automatically. Stale-schema reads cannot leak across migrations.
101
+ - **AST rewrites are part of the key.** Middleware that rewrite the plan via `beforeCompile` (e.g. soft-delete) run **upstream** of the cache. The cache sees the post-lowering plan, so the rewritten SQL is part of the content hash. Adding or removing a `beforeCompile` middleware changes which entries hit.
102
+
103
+ ## `CacheStore` pluggability
104
+
105
+ The default in-memory store is per-process and **not** coherent across replicas. For shared caching, supply a custom `CacheStore`:
106
+
107
+ ```typescript
108
+ import type { CacheStore, CachedEntry } from '@prisma-next/middleware-cache';
109
+
110
+ const redis: CacheStore = {
111
+ async get(key) {
112
+ const raw = await redisClient.get(key);
113
+ return raw ? (JSON.parse(raw) as CachedEntry) : undefined;
114
+ },
115
+ async set(key, entry, ttlMs) {
116
+ await redisClient.set(key, JSON.stringify(entry), 'PX', ttlMs);
117
+ },
118
+ };
119
+
120
+ const middleware = createCacheMiddleware({ store: redis });
121
+ ```
122
+
123
+ The interface is intentionally minimal — `get` returns the entry if present and not expired (implementations gating on TTL should treat expired as absent), `set` writes the entry under the key with the per-call `ttlMs`. Both are async to leave room for I/O-backed stores; the default in-memory store completes synchronously and wraps results in `Promise.resolve` for type conformance.
124
+
125
+ ## Transaction-scope guard
126
+
127
+ The middleware bypasses the cache entirely when `RuntimeMiddlewareContext.scope` is `'connection'` or `'transaction'`. Only top-level `runtime.execute` (`scope === 'runtime'`) consults the store.
128
+
129
+ This avoids two surprises:
130
+
131
+ - Inside a transaction, the caller expects read-after-write coherence with their own writes — the cache cannot meaningfully serve those reads without tracking the transaction's pending writes, which is out of scope for this milestone.
132
+ - On a checked-out connection (`runtime.connection().execute(...)`), the caller has explicitly stepped outside the shared runtime surface and likely does not expect the global cache to inject results.
133
+
134
+ ## TTL and LRU semantics
135
+
136
+ The default `createInMemoryCacheStore({ maxEntries, clock? })`:
137
+
138
+ - **TTL.** Each entry is committed with the per-query `ttl` (in milliseconds). The store evaluates expiry against its injected clock (defaults to `Date.now`); reads of expired entries return `undefined` and drop the entry as a side effect.
139
+ - **LRU.** Iteration order is the LRU order. Reads and writes both bump recency. When the live count would exceed `maxEntries`, the oldest entry is evicted.
140
+ - **Failure handling.** The middleware commits to the store only when `afterExecute` reports `completed: true && source: 'driver'`. Driver errors mid-stream and middleware-served executions never populate the cache.
141
+
142
+ ## Caveats
143
+
144
+ - **Default store is not coherent across replicas.** Multiple processes / pods do not share state. Use a custom `CacheStore` (Redis, etc.) for cross-process coherence.
145
+ - **Concurrent misses both populate the store.** Two concurrent first-time reads of the same key both run the driver and both commit; last writer wins. Single-flight / coalescing semantics are deferred to a follow-up.
146
+ - **Reads of stale-on-arrival entries.** With a custom replicated store, a follower may serve a stale entry for a brief window after the writer commits. Use the storage-hash discrimination plus a sensible TTL.
147
+ - **No invalidation beyond TTL.** Entries are not invalidated by writes; tag-based or event-based invalidation is out of scope for this milestone. If a write invalidates a cached read, choose a TTL short enough to bound the staleness window, or pass `cacheAnnotation({ skip: true })` on the read that needs to be authoritative.
148
+
149
+ ## See also
150
+
151
+ - [Runtime & Middleware Framework](../../../docs/architecture%20docs/subsystems/4.%20Runtime%20&%20Middleware%20Framework.md) for the SPI and middleware lifecycle (including the `intercept` hook the cache uses).
152
+ - [ADR 204 — Single-tier runtime](../../../docs/architecture%20docs/adrs/ADR%20204%20-%20Single-tier%20runtime.md) for why the cache middleware is family-agnostic by construction.
@@ -0,0 +1,219 @@
1
+ import * as _$_prisma_next_framework_components_runtime0 from "@prisma-next/framework-components/runtime";
2
+ import { CrossFamilyMiddleware } from "@prisma-next/framework-components/runtime";
3
+
4
+ //#region src/cache-annotation.d.ts
5
+ /**
6
+ * Payload accepted when calling the `cacheAnnotation` handle.
7
+ *
8
+ * - `ttl` — Time-to-live for the cached entry, in milliseconds. When
9
+ * omitted, the cache middleware passes the query through untouched —
10
+ * presence of the annotation alone is not sufficient to enable caching.
11
+ * This makes the cache strictly opt-in per query.
12
+ * - `skip` — When `true`, the cache middleware passes the query through
13
+ * untouched even if a `ttl` is set. Useful for selectively bypassing
14
+ * the cache on a per-call basis without removing the annotation
15
+ * entirely (e.g. a "force refresh" knob in user code).
16
+ * - `key` — Per-query override of the cache key. When supplied, replaces
17
+ * the default `RuntimeMiddlewareContext.contentHash(exec)` digest.
18
+ * The supplied string is stored as-is — the cache middleware does
19
+ * **not** rehash it, so the caller is responsible for ensuring the
20
+ * string is bounded in size and free of sensitive data they do not
21
+ * want flowing into logs / Redis `KEYS` / persistence dumps.
22
+ */
23
+ interface CachePayload {
24
+ readonly ttl?: number;
25
+ readonly skip?: boolean;
26
+ readonly key?: string;
27
+ }
28
+ /**
29
+ * Read-only annotation handle for the cache middleware.
30
+ *
31
+ * Declared with `applicableTo: ['read']`. Write terminals supply
32
+ * `K = 'write'` to the type-level `ValidAnnotations<'write', As>` gate
33
+ * (and the runtime `assertAnnotationsApplicable(annotations, 'write', ...)`
34
+ * check); the join `K extends Kinds` fails for this annotation, making
35
+ * "cache a mutation" structurally impossible without an `as any` cast
36
+ * bypass at both type *and* runtime levels.
37
+ *
38
+ * Stored under namespace `'cache'` in `plan.meta.annotations`. The cache
39
+ * middleware reads it via `cacheAnnotation.read(plan)`.
40
+ *
41
+ * @example
42
+ * ```typescript
43
+ * import { cacheAnnotation } from '@prisma-next/middleware-cache';
44
+ *
45
+ * // ORM read terminal — accepts the read-only annotation via the meta callback.
46
+ * const user = await db.User.first(
47
+ * { id },
48
+ * (meta) => meta.annotate(cacheAnnotation({ ttl: 60_000 })),
49
+ * );
50
+ *
51
+ * // SQL DSL select builder — chainable.
52
+ * const plan = db.sql
53
+ * .from(tables.user)
54
+ * .annotate(cacheAnnotation({ ttl: 60_000 }))
55
+ * .select({ id: tables.user.columns.id })
56
+ * .build();
57
+ * ```
58
+ */
59
+ declare const cacheAnnotation: _$_prisma_next_framework_components_runtime0.AnnotationHandle<CachePayload, "read">;
60
+ //#endregion
61
+ //#region src/cache-store.d.ts
62
+ /**
63
+ * A cached set of rows produced by a single execution.
64
+ *
65
+ * - `rows` are stored raw (undecoded). The SQL runtime's `decodeRow` pass
66
+ * wraps the orchestrator output, so intercepted rows go through the
67
+ * same codec decoding as driver rows on the way to the consumer. The
68
+ * cache stores wire-format values; decoding happens once per consumer
69
+ * read regardless of where the rows came from.
70
+ * - `storedAt` is the clock value at the moment the entry was committed
71
+ * to the store. It is informational metadata for callers (debugging,
72
+ * telemetry) and is **not** used by the in-memory store itself for
73
+ * expiry — TTL is driven by the store's own clock plus the `ttlMs`
74
+ * passed to `set`. Custom stores may use it differently.
75
+ */
76
+ interface CachedEntry {
77
+ readonly rows: readonly Record<string, unknown>[];
78
+ readonly storedAt: number;
79
+ }
80
+ /**
81
+ * Pluggable cache backend used by the cache middleware.
82
+ *
83
+ * The default implementation is an in-memory LRU with TTL produced by
84
+ * `createInMemoryCacheStore`. Users can supply Redis, Memcached, or any
85
+ * other backend by implementing this interface.
86
+ *
87
+ * The interface is intentionally minimal:
88
+ *
89
+ * - `get` returns the entry if it exists and has not expired, or
90
+ * `undefined` otherwise. Implementations that gate on TTL should
91
+ * treat an expired entry as absent (return `undefined`) and may
92
+ * evict it as a side effect.
93
+ * - `set` writes the entry under the key with an associated TTL in
94
+ * milliseconds. Implementations may evict other entries to make
95
+ * room (LRU, LFU, etc.) and may treat the operation as fire-and-
96
+ * forget at scale; the cache middleware does not rely on `set`
97
+ * completing before subsequent `get`s.
98
+ *
99
+ * Both methods are async to leave the door open for I/O-backed stores
100
+ * (Redis, S3, etc.). The default in-memory store completes
101
+ * synchronously and wraps the result in `Promise.resolve` for type
102
+ * conformance.
103
+ */
104
+ interface CacheStore {
105
+ get(key: string): Promise<CachedEntry | undefined>;
106
+ set(key: string, entry: CachedEntry, ttlMs: number): Promise<void>;
107
+ }
108
+ /**
109
+ * Options accepted by `createInMemoryCacheStore`.
110
+ *
111
+ * - `maxEntries` — hard cap on the number of live entries. Once the cap
112
+ * is exceeded, the least recently used entry is evicted. Reads and
113
+ * writes both count as "uses" for ordering purposes.
114
+ * - `clock` — injectable time source for TTL math. Defaults to
115
+ * `Date.now`. Tests inject a controlled clock to verify expiry without
116
+ * real-time waits.
117
+ */
118
+ interface InMemoryCacheStoreOptions {
119
+ readonly maxEntries: number;
120
+ readonly clock?: () => number;
121
+ }
122
+ /**
123
+ * Default cache backend. An LRU with per-entry TTL, backed by a `Map`.
124
+ *
125
+ * Eviction policy:
126
+ *
127
+ * - On `set` of a fresh key whose insertion would push the live count
128
+ * above `maxEntries`, the least recently used entry is evicted.
129
+ * Setting an existing key updates the entry in place and refreshes its
130
+ * recency without changing the live count.
131
+ * - On `get` of an existing key, recency is bumped (so the entry is no
132
+ * longer the LRU candidate).
133
+ * - On `get` of an expired entry, the entry is removed from the map and
134
+ * `undefined` is returned. The slot becomes available for new writes
135
+ * without counting against `maxEntries`.
136
+ *
137
+ * `Map` insertion order is the LRU order: the first key is the LRU
138
+ * candidate; the last key is the most recently used. Bumping recency is
139
+ * a delete-then-set on the underlying map.
140
+ *
141
+ * The default store is **not** coherent across processes or replicas —
142
+ * each process holds its own Map. Users who need a shared cache supply
143
+ * their own `CacheStore` (Redis, Memcached, etc.).
144
+ */
145
+ declare function createInMemoryCacheStore(options: InMemoryCacheStoreOptions): CacheStore;
146
+ //#endregion
147
+ //#region src/cache-middleware.d.ts
148
+ /**
149
+ * Options accepted by `createCacheMiddleware`.
150
+ *
151
+ * - `store` — pluggable cache backend. Defaults to an in-process LRU
152
+ * produced by `createInMemoryCacheStore`. Users supply Redis,
153
+ * Memcached, or any other backend by implementing the `CacheStore`
154
+ * interface.
155
+ * - `maxEntries` — only consulted when `store` is omitted. Sets the
156
+ * `maxEntries` cap on the default in-memory store. Defaults to 1000.
157
+ * - `clock` — injectable time source for `storedAt` stamping on
158
+ * committed entries. Defaults to `Date.now`. Tests inject a controlled
159
+ * clock to make commit-time observable. Note: TTL math lives inside
160
+ * the store, not the middleware — supplying a clock here only affects
161
+ * the `storedAt` field on committed `CachedEntry` values.
162
+ */
163
+ interface CacheMiddlewareOptions {
164
+ readonly store?: CacheStore;
165
+ readonly maxEntries?: number;
166
+ readonly clock?: () => number;
167
+ }
168
+ /**
169
+ * Creates a family-agnostic caching middleware.
170
+ *
171
+ * The middleware uses three hooks:
172
+ *
173
+ * - `intercept` — on each execution, checks the cache. On a hit, returns
174
+ * the cached raw rows; the runtime skips `beforeExecute`, `runDriver`,
175
+ * and `onRow`, and yields the cached rows to the consumer (which, in
176
+ * the SQL runtime, sees them after the standard `decodeRow` pass —
177
+ * i.e. the cache stores wire-format values). On a miss, records a
178
+ * pending buffer keyed on the `exec` object identity and returns
179
+ * `undefined` (passthrough).
180
+ * - `onRow` — on the miss path, appends each row yielded by the driver
181
+ * to the pending buffer.
182
+ * - `afterExecute` — on the miss path, commits the buffer to the store
183
+ * if and only if `result.completed === true && result.source === 'driver'`.
184
+ * Failed executions and middleware-served executions never populate
185
+ * the cache. The pending buffer is cleared in all branches so a stale
186
+ * `WeakMap` entry cannot leak between executions sharing an `exec`.
187
+ *
188
+ * The middleware bypasses the cache entirely when:
189
+ * - the plan has no `cache` annotation, or
190
+ * - the annotation has `skip: true`, or
191
+ * - the annotation has no `ttl`, or
192
+ * - `ctx.scope !== 'runtime'` (connection / transaction scopes opt out).
193
+ *
194
+ * Returns a cross-family `RuntimeMiddleware` (no `familyId` /
195
+ * `targetId`). The package depends only on
196
+ * `@prisma-next/framework-components/runtime`; cache keys come from
197
+ * `ctx.contentHash(exec)`, populated by the family runtime, so SQL and
198
+ * Mongo runtimes both work out of the box.
199
+ *
200
+ * @example
201
+ * ```typescript
202
+ * import { createCacheMiddleware, cacheAnnotation } from '@prisma-next/middleware-cache';
203
+ *
204
+ * const db = postgres({
205
+ * contractJson,
206
+ * url: process.env['DATABASE_URL']!,
207
+ * middleware: [createCacheMiddleware({ maxEntries: 1000 })],
208
+ * });
209
+ *
210
+ * const user = await db.User.first(
211
+ * { id },
212
+ * (meta) => meta.annotate(cacheAnnotation({ ttl: 60_000 })),
213
+ * );
214
+ * ```
215
+ */
216
+ declare function createCacheMiddleware(options?: CacheMiddlewareOptions): CrossFamilyMiddleware;
217
+ //#endregion
218
+ export { type CacheMiddlewareOptions, type CachePayload, type CacheStore, type CachedEntry, type InMemoryCacheStoreOptions, cacheAnnotation, createCacheMiddleware, createInMemoryCacheStore };
219
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/cache-annotation.ts","../src/cache-store.ts","../src/cache-middleware.ts"],"mappings":";;;;;;;;AAoBA;;;;;;;;;AAqCA;;;;;UArCiB,YAAA;EAAA,SACN,GAAA;EAAA,SACA,IAAA;EAAA,SACA,GAAA;AAAA;;;;;;;;ACoBX;;;;;;;;;;;;;;;;;;;;;AAeA;;;cDDa,eAAA,EAAe,4CAAA,CAAA,gBAAA,CAAA,YAAA;;;;;;;AArC5B;;;;;;;;;AAqCA;UC3CiB,WAAA;EAAA,SACN,IAAA,WAAe,MAAA;EAAA,SACf,QAAA;AAAA;;;;AAFX;;;;;;;;;AA6BA;;;;;;;;;;;;UAAiB,UAAA;EACf,GAAA,CAAI,GAAA,WAAc,OAAA,CAAQ,WAAA;EAC1B,GAAA,CAAI,GAAA,UAAa,KAAA,EAAO,WAAA,EAAa,KAAA,WAAgB,OAAA;AAAA;;;;;;AAavD;;;;;UAAiB,yBAAA;EAAA,SACN,UAAA;EAAA,SACA,KAAA;AAAA;;;;;;;;;ACpCX;;;;;;;;;;AAwHA;;;;;iBDrDgB,wBAAA,CAAyB,OAAA,EAAS,yBAAA,GAA4B,UAAA;;;;;ADvE9E;;;;;;;;;AAqCA;;;;UEjCiB,sBAAA;EAAA,SACN,KAAA,GAAQ,UAAA;EAAA,SACR,UAAA;EAAA,SACA,KAAA;AAAA;;;;;;;;;ADgBX;;;;;;;;;;;;;;;;;;;;;AAeA;;;;;AAiCA;;;;;;;;;;;;ACnEA;;iBAwHgB,qBAAA,CAAsB,OAAA,GAAU,sBAAA,GAAyB,qBAAA"}