@prisma/orm-extension-middleware-cache 0.16.0-dev.36
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 +201 -0
- package/README.md +23 -0
- package/dist/index.d.mts +219 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +243 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +43 -0
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,23 @@
|
|
|
1
|
+
# @prisma/orm-extension-middleware-cache
|
|
2
|
+
|
|
3
|
+
Opt-in query caching for Prisma Next runtimes, for both the SQL and Mongo families.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pnpm add @prisma/orm-extension-middleware-cache
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
The whole surface is the package root:
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { cache, cacheAnnotation, type CacheStore } from '@prisma/orm-extension-middleware-cache';
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Responsibilities
|
|
16
|
+
|
|
17
|
+
A runtime middleware that short-circuits repeated reads: on a hit it returns cached rows and never invokes the driver; on a miss it buffers the driver's rows and commits them to the store only when the execution completes successfully. Cache keys come from the family runtime's content hash of the execution, or from a per-query `cacheAnnotation({ key })` override; `ttl` and `skip` are per-query too. Connection- and transaction-scoped executions bypass the cache.
|
|
18
|
+
|
|
19
|
+
It ships an in-memory LRU-with-TTL store and exposes the `CacheStore` interface so Redis, Memcached, or any other backend can be dropped in.
|
|
20
|
+
|
|
21
|
+
## Dependencies
|
|
22
|
+
|
|
23
|
+
`@prisma/orm-framework` at an exact lockstep version, and nothing else. It depends on no family runtime and no target, which is why one middleware serves every database.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { CrossFamilyMiddleware } from "@prisma/orm-framework/components/runtime";
|
|
2
|
+
//#region ../../../3-extensions/middleware-cache/dist/index.d.mts
|
|
3
|
+
//#region src/cache-annotation.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Payload accepted when calling the `cacheAnnotation` handle.
|
|
6
|
+
*
|
|
7
|
+
* - `ttl` — Time-to-live for the cached entry, in milliseconds. When
|
|
8
|
+
* omitted, the cache middleware passes the query through untouched —
|
|
9
|
+
* presence of the annotation alone is not sufficient to enable caching.
|
|
10
|
+
* This makes the cache strictly opt-in per query.
|
|
11
|
+
* - `skip` — When `true`, the cache middleware passes the query through
|
|
12
|
+
* untouched even if a `ttl` is set. Useful for selectively bypassing
|
|
13
|
+
* the cache on a per-call basis without removing the annotation
|
|
14
|
+
* entirely (e.g. a "force refresh" knob in user code).
|
|
15
|
+
* - `key` — Per-query override of the cache key. When supplied, replaces
|
|
16
|
+
* the default `RuntimeMiddlewareContext.contentHash(exec)` digest.
|
|
17
|
+
* The supplied string is stored as-is — the cache middleware does
|
|
18
|
+
* **not** rehash it, so the caller is responsible for ensuring the
|
|
19
|
+
* string is bounded in size and free of sensitive data they do not
|
|
20
|
+
* want flowing into logs / Redis `KEYS` / persistence dumps.
|
|
21
|
+
*/
|
|
22
|
+
interface CachePayload {
|
|
23
|
+
readonly ttl?: number;
|
|
24
|
+
readonly skip?: boolean;
|
|
25
|
+
readonly key?: string;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Read-only annotation handle for the cache middleware.
|
|
29
|
+
*
|
|
30
|
+
* Declared with `applicableTo: ['read']`. Write terminals supply
|
|
31
|
+
* `K = 'write'` to the type-level `ValidAnnotations<'write', As>` gate
|
|
32
|
+
* (and the runtime `assertAnnotationsApplicable(annotations, 'write', ...)`
|
|
33
|
+
* check); the join `K extends Kinds` fails for this annotation, making
|
|
34
|
+
* "cache a mutation" structurally impossible without an `as any` cast
|
|
35
|
+
* bypass at both type *and* runtime levels.
|
|
36
|
+
*
|
|
37
|
+
* Stored under namespace `'cache'` in `plan.meta.annotations`. The cache
|
|
38
|
+
* middleware reads it via `cacheAnnotation.read(plan)`.
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```typescript
|
|
42
|
+
* import { cacheAnnotation } from '@internal/middleware-cache';
|
|
43
|
+
*
|
|
44
|
+
* // ORM read terminal — accepts the read-only annotation via the meta callback.
|
|
45
|
+
* const user = await db.User.first(
|
|
46
|
+
* { id },
|
|
47
|
+
* (meta) => meta.annotate(cacheAnnotation({ ttl: 60_000 })),
|
|
48
|
+
* );
|
|
49
|
+
*
|
|
50
|
+
* // SQL DSL select builder — chainable.
|
|
51
|
+
* const plan = db.sql
|
|
52
|
+
* .from(tables.user)
|
|
53
|
+
* .annotate(cacheAnnotation({ ttl: 60_000 }))
|
|
54
|
+
* .select({ id: tables.user.columns.id })
|
|
55
|
+
* .build();
|
|
56
|
+
* ```
|
|
57
|
+
*/
|
|
58
|
+
declare const cacheAnnotation: import("@prisma/orm-framework/components/runtime").AnnotationHandle<CachePayload, "read">;
|
|
59
|
+
//#endregion
|
|
60
|
+
//#region src/cache-store.d.ts
|
|
61
|
+
/**
|
|
62
|
+
* A cached set of rows produced by a single execution.
|
|
63
|
+
*
|
|
64
|
+
* - `rows` are stored raw (undecoded). The SQL runtime's `decodeRow` pass
|
|
65
|
+
* wraps the orchestrator output, so intercepted rows go through the
|
|
66
|
+
* same codec decoding as driver rows on the way to the consumer. The
|
|
67
|
+
* cache stores wire-format values; decoding happens once per consumer
|
|
68
|
+
* read regardless of where the rows came from.
|
|
69
|
+
* - `storedAt` is the clock value at the moment the entry was committed
|
|
70
|
+
* to the store. It is informational metadata for callers (debugging,
|
|
71
|
+
* telemetry) and is **not** used by the in-memory store itself for
|
|
72
|
+
* expiry — TTL is driven by the store's own clock plus the `ttlMs`
|
|
73
|
+
* passed to `set`. Custom stores may use it differently.
|
|
74
|
+
*/
|
|
75
|
+
interface CachedEntry {
|
|
76
|
+
readonly rows: readonly Record<string, unknown>[];
|
|
77
|
+
readonly storedAt: number;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Pluggable cache backend used by the cache middleware.
|
|
81
|
+
*
|
|
82
|
+
* The default implementation is an in-memory LRU with TTL produced by
|
|
83
|
+
* `createInMemoryCacheStore`. Users can supply Redis, Memcached, or any
|
|
84
|
+
* other backend by implementing this interface.
|
|
85
|
+
*
|
|
86
|
+
* The interface is intentionally minimal:
|
|
87
|
+
*
|
|
88
|
+
* - `get` returns the entry if it exists and has not expired, or
|
|
89
|
+
* `undefined` otherwise. Implementations that gate on TTL should
|
|
90
|
+
* treat an expired entry as absent (return `undefined`) and may
|
|
91
|
+
* evict it as a side effect.
|
|
92
|
+
* - `set` writes the entry under the key with an associated TTL in
|
|
93
|
+
* milliseconds. Implementations may evict other entries to make
|
|
94
|
+
* room (LRU, LFU, etc.) and may treat the operation as fire-and-
|
|
95
|
+
* forget at scale; the cache middleware does not rely on `set`
|
|
96
|
+
* completing before subsequent `get`s.
|
|
97
|
+
*
|
|
98
|
+
* Both methods are async to leave the door open for I/O-backed stores
|
|
99
|
+
* (Redis, S3, etc.). The default in-memory store completes
|
|
100
|
+
* synchronously and wraps the result in `Promise.resolve` for type
|
|
101
|
+
* conformance.
|
|
102
|
+
*/
|
|
103
|
+
interface CacheStore {
|
|
104
|
+
get(key: string): Promise<CachedEntry | undefined>;
|
|
105
|
+
set(key: string, entry: CachedEntry, ttlMs: number): Promise<void>;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Options accepted by `createInMemoryCacheStore`.
|
|
109
|
+
*
|
|
110
|
+
* - `maxEntries` — hard cap on the number of live entries. Once the cap
|
|
111
|
+
* is exceeded, the least recently used entry is evicted. Reads and
|
|
112
|
+
* writes both count as "uses" for ordering purposes.
|
|
113
|
+
* - `clock` — injectable time source for TTL math. Defaults to
|
|
114
|
+
* `Date.now`. Tests inject a controlled clock to verify expiry without
|
|
115
|
+
* real-time waits.
|
|
116
|
+
*/
|
|
117
|
+
interface InMemoryCacheStoreOptions {
|
|
118
|
+
readonly maxEntries: number;
|
|
119
|
+
readonly clock?: () => number;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Default cache backend. An LRU with per-entry TTL, backed by a `Map`.
|
|
123
|
+
*
|
|
124
|
+
* Eviction policy:
|
|
125
|
+
*
|
|
126
|
+
* - On `set` of a fresh key whose insertion would push the live count
|
|
127
|
+
* above `maxEntries`, the least recently used entry is evicted.
|
|
128
|
+
* Setting an existing key updates the entry in place and refreshes its
|
|
129
|
+
* recency without changing the live count.
|
|
130
|
+
* - On `get` of an existing key, recency is bumped (so the entry is no
|
|
131
|
+
* longer the LRU candidate).
|
|
132
|
+
* - On `get` of an expired entry, the entry is removed from the map and
|
|
133
|
+
* `undefined` is returned. The slot becomes available for new writes
|
|
134
|
+
* without counting against `maxEntries`.
|
|
135
|
+
*
|
|
136
|
+
* `Map` insertion order is the LRU order: the first key is the LRU
|
|
137
|
+
* candidate; the last key is the most recently used. Bumping recency is
|
|
138
|
+
* a delete-then-set on the underlying map.
|
|
139
|
+
*
|
|
140
|
+
* The default store is **not** coherent across processes or replicas —
|
|
141
|
+
* each process holds its own Map. Users who need a shared cache supply
|
|
142
|
+
* their own `CacheStore` (Redis, Memcached, etc.).
|
|
143
|
+
*/
|
|
144
|
+
declare function createInMemoryCacheStore(options: InMemoryCacheStoreOptions): CacheStore;
|
|
145
|
+
//#endregion
|
|
146
|
+
//#region src/cache-middleware.d.ts
|
|
147
|
+
/**
|
|
148
|
+
* Options accepted by `createCacheMiddleware`.
|
|
149
|
+
*
|
|
150
|
+
* - `store` — pluggable cache backend. Defaults to an in-process LRU
|
|
151
|
+
* produced by `createInMemoryCacheStore`. Users supply Redis,
|
|
152
|
+
* Memcached, or any other backend by implementing the `CacheStore`
|
|
153
|
+
* interface.
|
|
154
|
+
* - `maxEntries` — only consulted when `store` is omitted. Sets the
|
|
155
|
+
* `maxEntries` cap on the default in-memory store. Defaults to 1000.
|
|
156
|
+
* - `clock` — injectable time source for `storedAt` stamping on
|
|
157
|
+
* committed entries. Defaults to `Date.now`. Tests inject a controlled
|
|
158
|
+
* clock to make commit-time observable. Note: TTL math lives inside
|
|
159
|
+
* the store, not the middleware — supplying a clock here only affects
|
|
160
|
+
* the `storedAt` field on committed `CachedEntry` values.
|
|
161
|
+
*/
|
|
162
|
+
interface CacheMiddlewareOptions {
|
|
163
|
+
readonly store?: CacheStore;
|
|
164
|
+
readonly maxEntries?: number;
|
|
165
|
+
readonly clock?: () => number;
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Creates a family-agnostic caching middleware.
|
|
169
|
+
*
|
|
170
|
+
* The middleware uses three hooks:
|
|
171
|
+
*
|
|
172
|
+
* - `intercept` — on each execution, checks the cache. On a hit, returns
|
|
173
|
+
* the cached raw rows; the runtime skips `runDriver` and `onRow`
|
|
174
|
+
* (`beforeExecute` is not affected — it has already run for every
|
|
175
|
+
* middleware before any `intercept` is consulted) and yields the
|
|
176
|
+
* cached rows to the consumer (which, in the SQL runtime, sees them
|
|
177
|
+
* after the standard `decodeRow` pass — i.e. the cache stores
|
|
178
|
+
* wire-format values). On a miss, records a pending buffer keyed on
|
|
179
|
+
* the `exec` object identity and returns `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
|
+
* `@internal/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 '@internal/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":["../../../../3-extensions/middleware-cache/dist/index.d.mts"],"mappings":";;;;;;;;;;;;;;;;;;;;;UAoBU;WACC;WACA;WACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAiCG,kEAAkE,iBAAiB;;;;;;;;;;;;;;;;;UAiBvF;WACC,eAAe;WACf;;;;;;;;;;;;;;;;;;;;;;;;;;UA0BD;EACR,IAAI,cAAc,QAAQ;EAC1B,IAAI,aAAa,OAAO,aAAa,gBAAgB;;;;;;;;;;;;UAY7C;WACC;WACA;;;;;;;;;;;;;;;;;;;;;;;;;iBAyBM,yBAAyB,SAAS,4BAA4B;;;;;;;;;;;;;;;;;;UAkBrE;WACC,QAAQ;WACR;WACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAmDM,sBAAsB,UAAU,yBAAyB"}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { defineAnnotation } from "@prisma/orm-framework/components/runtime";
|
|
2
|
+
//#region ../../../3-extensions/middleware-cache/dist/index.mjs
|
|
3
|
+
/**
|
|
4
|
+
* Read-only annotation handle for the cache middleware.
|
|
5
|
+
*
|
|
6
|
+
* Declared with `applicableTo: ['read']`. Write terminals supply
|
|
7
|
+
* `K = 'write'` to the type-level `ValidAnnotations<'write', As>` gate
|
|
8
|
+
* (and the runtime `assertAnnotationsApplicable(annotations, 'write', ...)`
|
|
9
|
+
* check); the join `K extends Kinds` fails for this annotation, making
|
|
10
|
+
* "cache a mutation" structurally impossible without an `as any` cast
|
|
11
|
+
* bypass at both type *and* runtime levels.
|
|
12
|
+
*
|
|
13
|
+
* Stored under namespace `'cache'` in `plan.meta.annotations`. The cache
|
|
14
|
+
* middleware reads it via `cacheAnnotation.read(plan)`.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```typescript
|
|
18
|
+
* import { cacheAnnotation } from '@internal/middleware-cache';
|
|
19
|
+
*
|
|
20
|
+
* // ORM read terminal — accepts the read-only annotation via the meta callback.
|
|
21
|
+
* const user = await db.User.first(
|
|
22
|
+
* { id },
|
|
23
|
+
* (meta) => meta.annotate(cacheAnnotation({ ttl: 60_000 })),
|
|
24
|
+
* );
|
|
25
|
+
*
|
|
26
|
+
* // SQL DSL select builder — chainable.
|
|
27
|
+
* const plan = db.sql
|
|
28
|
+
* .from(tables.user)
|
|
29
|
+
* .annotate(cacheAnnotation({ ttl: 60_000 }))
|
|
30
|
+
* .select({ id: tables.user.columns.id })
|
|
31
|
+
* .build();
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
const cacheAnnotation = defineAnnotation()({
|
|
35
|
+
namespace: "cache",
|
|
36
|
+
applicableTo: ["read"]
|
|
37
|
+
});
|
|
38
|
+
/**
|
|
39
|
+
* Default cache backend. An LRU with per-entry TTL, backed by a `Map`.
|
|
40
|
+
*
|
|
41
|
+
* Eviction policy:
|
|
42
|
+
*
|
|
43
|
+
* - On `set` of a fresh key whose insertion would push the live count
|
|
44
|
+
* above `maxEntries`, the least recently used entry is evicted.
|
|
45
|
+
* Setting an existing key updates the entry in place and refreshes its
|
|
46
|
+
* recency without changing the live count.
|
|
47
|
+
* - On `get` of an existing key, recency is bumped (so the entry is no
|
|
48
|
+
* longer the LRU candidate).
|
|
49
|
+
* - On `get` of an expired entry, the entry is removed from the map and
|
|
50
|
+
* `undefined` is returned. The slot becomes available for new writes
|
|
51
|
+
* without counting against `maxEntries`.
|
|
52
|
+
*
|
|
53
|
+
* `Map` insertion order is the LRU order: the first key is the LRU
|
|
54
|
+
* candidate; the last key is the most recently used. Bumping recency is
|
|
55
|
+
* a delete-then-set on the underlying map.
|
|
56
|
+
*
|
|
57
|
+
* The default store is **not** coherent across processes or replicas —
|
|
58
|
+
* each process holds its own Map. Users who need a shared cache supply
|
|
59
|
+
* their own `CacheStore` (Redis, Memcached, etc.).
|
|
60
|
+
*/
|
|
61
|
+
function createInMemoryCacheStore(options) {
|
|
62
|
+
const maxEntries = options.maxEntries;
|
|
63
|
+
const clock = options.clock ?? Date.now;
|
|
64
|
+
const map = /* @__PURE__ */ new Map();
|
|
65
|
+
function get(key) {
|
|
66
|
+
const record = map.get(key);
|
|
67
|
+
if (record === void 0) return Promise.resolve(void 0);
|
|
68
|
+
if (clock() >= record.expiresAt) {
|
|
69
|
+
map.delete(key);
|
|
70
|
+
return Promise.resolve(void 0);
|
|
71
|
+
}
|
|
72
|
+
map.delete(key);
|
|
73
|
+
map.set(key, record);
|
|
74
|
+
return Promise.resolve(record.entry);
|
|
75
|
+
}
|
|
76
|
+
function set(key, entry, ttlMs) {
|
|
77
|
+
const expiresAt = clock() + ttlMs;
|
|
78
|
+
if (map.has(key)) map.delete(key);
|
|
79
|
+
map.set(key, {
|
|
80
|
+
entry,
|
|
81
|
+
expiresAt
|
|
82
|
+
});
|
|
83
|
+
while (map.size > maxEntries) {
|
|
84
|
+
const oldest = map.keys().next();
|
|
85
|
+
if (oldest.done) break;
|
|
86
|
+
map.delete(oldest.value);
|
|
87
|
+
}
|
|
88
|
+
return Promise.resolve();
|
|
89
|
+
}
|
|
90
|
+
return {
|
|
91
|
+
get,
|
|
92
|
+
set
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Default `maxEntries` for the built-in in-memory store. Bounded so a
|
|
97
|
+
* runaway producer cannot exhaust process memory; users who need
|
|
98
|
+
* different bounds supply a custom `CacheStore`.
|
|
99
|
+
*/
|
|
100
|
+
const DEFAULT_MAX_ENTRIES = 1e3;
|
|
101
|
+
/**
|
|
102
|
+
* Reads the cache payload from the plan, if present and branded.
|
|
103
|
+
*
|
|
104
|
+
* Returns `undefined` when:
|
|
105
|
+
* - the plan has no `meta.annotations`, or
|
|
106
|
+
* - the `cache` namespace key is absent, or
|
|
107
|
+
* - the value under `cache` is not a branded `AnnotationValue` (the
|
|
108
|
+
* `cacheAnnotation.read` defensive check covers this).
|
|
109
|
+
*/
|
|
110
|
+
function readCachePayload(plan) {
|
|
111
|
+
return cacheAnnotation.read(plan);
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Computes the cache key for an execution.
|
|
115
|
+
*
|
|
116
|
+
* Two-tier resolution:
|
|
117
|
+
*
|
|
118
|
+
* 1. Per-query override: `cacheAnnotation({ key })` — the supplied
|
|
119
|
+
* string is used verbatim. Not rehashed; the user is responsible for
|
|
120
|
+
* keeping the string bounded and free of sensitive data.
|
|
121
|
+
* 2. Default: `ctx.contentHash(exec)` — the family runtime owns this and
|
|
122
|
+
* returns an opaque, bounded digest (SHA-512 in the SQL and Mongo
|
|
123
|
+
* runtimes today).
|
|
124
|
+
*
|
|
125
|
+
* The returned string is consumed directly as the `Map<string, …>` key
|
|
126
|
+
* by the underlying `CacheStore`; the cache middleware does not perform
|
|
127
|
+
* any further transformation.
|
|
128
|
+
*/
|
|
129
|
+
async function resolveCacheKey(payload, exec, ctx) {
|
|
130
|
+
if (payload.key !== void 0) return payload.key;
|
|
131
|
+
return ctx.contentHash(exec);
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Creates a family-agnostic caching middleware.
|
|
135
|
+
*
|
|
136
|
+
* The middleware uses three hooks:
|
|
137
|
+
*
|
|
138
|
+
* - `intercept` — on each execution, checks the cache. On a hit, returns
|
|
139
|
+
* the cached raw rows; the runtime skips `runDriver` and `onRow`
|
|
140
|
+
* (`beforeExecute` is not affected — it has already run for every
|
|
141
|
+
* middleware before any `intercept` is consulted) and yields the
|
|
142
|
+
* cached rows to the consumer (which, in the SQL runtime, sees them
|
|
143
|
+
* after the standard `decodeRow` pass — i.e. the cache stores
|
|
144
|
+
* wire-format values). On a miss, records a pending buffer keyed on
|
|
145
|
+
* the `exec` object identity and returns `undefined` (passthrough).
|
|
146
|
+
* - `onRow` — on the miss path, appends each row yielded by the driver
|
|
147
|
+
* to the pending buffer.
|
|
148
|
+
* - `afterExecute` — on the miss path, commits the buffer to the store
|
|
149
|
+
* if and only if `result.completed === true && result.source === 'driver'`.
|
|
150
|
+
* Failed executions and middleware-served executions never populate
|
|
151
|
+
* the cache. The pending buffer is cleared in all branches so a stale
|
|
152
|
+
* `WeakMap` entry cannot leak between executions sharing an `exec`.
|
|
153
|
+
*
|
|
154
|
+
* The middleware bypasses the cache entirely when:
|
|
155
|
+
* - the plan has no `cache` annotation, or
|
|
156
|
+
* - the annotation has `skip: true`, or
|
|
157
|
+
* - the annotation has no `ttl`, or
|
|
158
|
+
* - `ctx.scope !== 'runtime'` (connection / transaction scopes opt out).
|
|
159
|
+
*
|
|
160
|
+
* Returns a cross-family `RuntimeMiddleware` (no `familyId` /
|
|
161
|
+
* `targetId`). The package depends only on
|
|
162
|
+
* `@internal/framework-components/runtime`; cache keys come from
|
|
163
|
+
* `ctx.contentHash(exec)`, populated by the family runtime, so SQL and
|
|
164
|
+
* Mongo runtimes both work out of the box.
|
|
165
|
+
*
|
|
166
|
+
* @example
|
|
167
|
+
* ```typescript
|
|
168
|
+
* import { createCacheMiddleware, cacheAnnotation } from '@internal/middleware-cache';
|
|
169
|
+
*
|
|
170
|
+
* const db = postgres({
|
|
171
|
+
* contractJson,
|
|
172
|
+
* url: process.env['DATABASE_URL']!,
|
|
173
|
+
* middleware: [createCacheMiddleware({ maxEntries: 1000 })],
|
|
174
|
+
* });
|
|
175
|
+
*
|
|
176
|
+
* const user = await db.User.first(
|
|
177
|
+
* { id },
|
|
178
|
+
* (meta) => meta.annotate(cacheAnnotation({ ttl: 60_000 })),
|
|
179
|
+
* );
|
|
180
|
+
* ```
|
|
181
|
+
*/
|
|
182
|
+
function createCacheMiddleware(options) {
|
|
183
|
+
const store = options?.store ?? createInMemoryCacheStore({ maxEntries: options?.maxEntries ?? DEFAULT_MAX_ENTRIES });
|
|
184
|
+
const clock = options?.clock ?? Date.now;
|
|
185
|
+
const pending = /* @__PURE__ */ new WeakMap();
|
|
186
|
+
async function intercept(exec, ctx) {
|
|
187
|
+
if (ctx.scope !== "runtime") return;
|
|
188
|
+
const payload = readCachePayload(exec);
|
|
189
|
+
if (payload === void 0) return;
|
|
190
|
+
if (payload.skip === true) return;
|
|
191
|
+
if (payload.ttl === void 0) return;
|
|
192
|
+
const key = await resolveCacheKey(payload, exec, ctx);
|
|
193
|
+
const hit = await store.get(key);
|
|
194
|
+
if (hit !== void 0) {
|
|
195
|
+
ctx.log.debug?.({
|
|
196
|
+
event: "middleware.cache.hit",
|
|
197
|
+
middleware: "cache",
|
|
198
|
+
key
|
|
199
|
+
});
|
|
200
|
+
return { rows: hit.rows };
|
|
201
|
+
}
|
|
202
|
+
pending.set(exec, {
|
|
203
|
+
key,
|
|
204
|
+
ttlMs: payload.ttl,
|
|
205
|
+
buffer: []
|
|
206
|
+
});
|
|
207
|
+
ctx.log.debug?.({
|
|
208
|
+
event: "middleware.cache.miss",
|
|
209
|
+
middleware: "cache",
|
|
210
|
+
key
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
async function onRow(row, exec, _ctx) {
|
|
214
|
+
const slot = pending.get(exec);
|
|
215
|
+
if (slot === void 0) return;
|
|
216
|
+
slot.buffer.push(row);
|
|
217
|
+
}
|
|
218
|
+
async function afterExecute(exec, result, ctx) {
|
|
219
|
+
const slot = pending.get(exec);
|
|
220
|
+
if (slot === void 0) return;
|
|
221
|
+
pending.delete(exec);
|
|
222
|
+
if (!result.completed || result.source !== "driver") return;
|
|
223
|
+
await store.set(slot.key, {
|
|
224
|
+
rows: slot.buffer,
|
|
225
|
+
storedAt: clock()
|
|
226
|
+
}, slot.ttlMs);
|
|
227
|
+
ctx.log.debug?.({
|
|
228
|
+
event: "middleware.cache.store",
|
|
229
|
+
middleware: "cache",
|
|
230
|
+
key: slot.key
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
return {
|
|
234
|
+
name: "cache",
|
|
235
|
+
intercept,
|
|
236
|
+
onRow,
|
|
237
|
+
afterExecute
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
//#endregion
|
|
241
|
+
export { cacheAnnotation, createCacheMiddleware, createInMemoryCacheStore };
|
|
242
|
+
|
|
243
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../3-extensions/middleware-cache/dist/index.mjs"],"sourcesContent":["import { defineAnnotation } from \"@internal/framework-components/runtime\";\n//#region src/cache-annotation.ts\n/**\n* Read-only annotation handle for the cache middleware.\n*\n* Declared with `applicableTo: ['read']`. Write terminals supply\n* `K = 'write'` to the type-level `ValidAnnotations<'write', As>` gate\n* (and the runtime `assertAnnotationsApplicable(annotations, 'write', ...)`\n* check); the join `K extends Kinds` fails for this annotation, making\n* \"cache a mutation\" structurally impossible without an `as any` cast\n* bypass at both type *and* runtime levels.\n*\n* Stored under namespace `'cache'` in `plan.meta.annotations`. The cache\n* middleware reads it via `cacheAnnotation.read(plan)`.\n*\n* @example\n* ```typescript\n* import { cacheAnnotation } from '@internal/middleware-cache';\n*\n* // ORM read terminal — accepts the read-only annotation via the meta callback.\n* const user = await db.User.first(\n* { id },\n* (meta) => meta.annotate(cacheAnnotation({ ttl: 60_000 })),\n* );\n*\n* // SQL DSL select builder — chainable.\n* const plan = db.sql\n* .from(tables.user)\n* .annotate(cacheAnnotation({ ttl: 60_000 }))\n* .select({ id: tables.user.columns.id })\n* .build();\n* ```\n*/\nconst cacheAnnotation = defineAnnotation()({\n\tnamespace: \"cache\",\n\tapplicableTo: [\"read\"]\n});\n//#endregion\n//#region src/cache-store.ts\n/**\n* Default cache backend. An LRU with per-entry TTL, backed by a `Map`.\n*\n* Eviction policy:\n*\n* - On `set` of a fresh key whose insertion would push the live count\n* above `maxEntries`, the least recently used entry is evicted.\n* Setting an existing key updates the entry in place and refreshes its\n* recency without changing the live count.\n* - On `get` of an existing key, recency is bumped (so the entry is no\n* longer the LRU candidate).\n* - On `get` of an expired entry, the entry is removed from the map and\n* `undefined` is returned. The slot becomes available for new writes\n* without counting against `maxEntries`.\n*\n* `Map` insertion order is the LRU order: the first key is the LRU\n* candidate; the last key is the most recently used. Bumping recency is\n* a delete-then-set on the underlying map.\n*\n* The default store is **not** coherent across processes or replicas —\n* each process holds its own Map. Users who need a shared cache supply\n* their own `CacheStore` (Redis, Memcached, etc.).\n*/\nfunction createInMemoryCacheStore(options) {\n\tconst maxEntries = options.maxEntries;\n\tconst clock = options.clock ?? Date.now;\n\tconst map = /* @__PURE__ */ new Map();\n\tfunction get(key) {\n\t\tconst record = map.get(key);\n\t\tif (record === void 0) return Promise.resolve(void 0);\n\t\tif (clock() >= record.expiresAt) {\n\t\t\tmap.delete(key);\n\t\t\treturn Promise.resolve(void 0);\n\t\t}\n\t\tmap.delete(key);\n\t\tmap.set(key, record);\n\t\treturn Promise.resolve(record.entry);\n\t}\n\tfunction set(key, entry, ttlMs) {\n\t\tconst expiresAt = clock() + ttlMs;\n\t\tif (map.has(key)) map.delete(key);\n\t\tmap.set(key, {\n\t\t\tentry,\n\t\t\texpiresAt\n\t\t});\n\t\twhile (map.size > maxEntries) {\n\t\t\tconst oldest = map.keys().next();\n\t\t\tif (oldest.done) break;\n\t\t\tmap.delete(oldest.value);\n\t\t}\n\t\treturn Promise.resolve();\n\t}\n\treturn {\n\t\tget,\n\t\tset\n\t};\n}\n//#endregion\n//#region src/cache-middleware.ts\n/**\n* Default `maxEntries` for the built-in in-memory store. Bounded so a\n* runaway producer cannot exhaust process memory; users who need\n* different bounds supply a custom `CacheStore`.\n*/\nconst DEFAULT_MAX_ENTRIES = 1e3;\n/**\n* Reads the cache payload from the plan, if present and branded.\n*\n* Returns `undefined` when:\n* - the plan has no `meta.annotations`, or\n* - the `cache` namespace key is absent, or\n* - the value under `cache` is not a branded `AnnotationValue` (the\n* `cacheAnnotation.read` defensive check covers this).\n*/\nfunction readCachePayload(plan) {\n\treturn cacheAnnotation.read(plan);\n}\n/**\n* Computes the cache key for an execution.\n*\n* Two-tier resolution:\n*\n* 1. Per-query override: `cacheAnnotation({ key })` — the supplied\n* string is used verbatim. Not rehashed; the user is responsible for\n* keeping the string bounded and free of sensitive data.\n* 2. Default: `ctx.contentHash(exec)` — the family runtime owns this and\n* returns an opaque, bounded digest (SHA-512 in the SQL and Mongo\n* runtimes today).\n*\n* The returned string is consumed directly as the `Map<string, …>` key\n* by the underlying `CacheStore`; the cache middleware does not perform\n* any further transformation.\n*/\nasync function resolveCacheKey(payload, exec, ctx) {\n\tif (payload.key !== void 0) return payload.key;\n\treturn ctx.contentHash(exec);\n}\n/**\n* Creates a family-agnostic caching middleware.\n*\n* The middleware uses three hooks:\n*\n* - `intercept` — on each execution, checks the cache. On a hit, returns\n* the cached raw rows; the runtime skips `runDriver` and `onRow`\n* (`beforeExecute` is not affected — it has already run for every\n* middleware before any `intercept` is consulted) and yields the\n* cached rows to the consumer (which, in the SQL runtime, sees them\n* after the standard `decodeRow` pass — i.e. the cache stores\n* wire-format values). On a miss, records a pending buffer keyed on\n* the `exec` object identity and returns `undefined` (passthrough).\n* - `onRow` — on the miss path, appends each row yielded by the driver\n* to the pending buffer.\n* - `afterExecute` — on the miss path, commits the buffer to the store\n* if and only if `result.completed === true && result.source === 'driver'`.\n* Failed executions and middleware-served executions never populate\n* the cache. The pending buffer is cleared in all branches so a stale\n* `WeakMap` entry cannot leak between executions sharing an `exec`.\n*\n* The middleware bypasses the cache entirely when:\n* - the plan has no `cache` annotation, or\n* - the annotation has `skip: true`, or\n* - the annotation has no `ttl`, or\n* - `ctx.scope !== 'runtime'` (connection / transaction scopes opt out).\n*\n* Returns a cross-family `RuntimeMiddleware` (no `familyId` /\n* `targetId`). The package depends only on\n* `@internal/framework-components/runtime`; cache keys come from\n* `ctx.contentHash(exec)`, populated by the family runtime, so SQL and\n* Mongo runtimes both work out of the box.\n*\n* @example\n* ```typescript\n* import { createCacheMiddleware, cacheAnnotation } from '@internal/middleware-cache';\n*\n* const db = postgres({\n* contractJson,\n* url: process.env['DATABASE_URL']!,\n* middleware: [createCacheMiddleware({ maxEntries: 1000 })],\n* });\n*\n* const user = await db.User.first(\n* { id },\n* (meta) => meta.annotate(cacheAnnotation({ ttl: 60_000 })),\n* );\n* ```\n*/\nfunction createCacheMiddleware(options) {\n\tconst store = options?.store ?? createInMemoryCacheStore({ maxEntries: options?.maxEntries ?? DEFAULT_MAX_ENTRIES });\n\tconst clock = options?.clock ?? Date.now;\n\tconst pending = /* @__PURE__ */ new WeakMap();\n\tasync function intercept(exec, ctx) {\n\t\tif (ctx.scope !== \"runtime\") return;\n\t\tconst payload = readCachePayload(exec);\n\t\tif (payload === void 0) return;\n\t\tif (payload.skip === true) return;\n\t\tif (payload.ttl === void 0) return;\n\t\tconst key = await resolveCacheKey(payload, exec, ctx);\n\t\tconst hit = await store.get(key);\n\t\tif (hit !== void 0) {\n\t\t\tctx.log.debug?.({\n\t\t\t\tevent: \"middleware.cache.hit\",\n\t\t\t\tmiddleware: \"cache\",\n\t\t\t\tkey\n\t\t\t});\n\t\t\treturn { rows: hit.rows };\n\t\t}\n\t\tpending.set(exec, {\n\t\t\tkey,\n\t\t\tttlMs: payload.ttl,\n\t\t\tbuffer: []\n\t\t});\n\t\tctx.log.debug?.({\n\t\t\tevent: \"middleware.cache.miss\",\n\t\t\tmiddleware: \"cache\",\n\t\t\tkey\n\t\t});\n\t}\n\tasync function onRow(row, exec, _ctx) {\n\t\tconst slot = pending.get(exec);\n\t\tif (slot === void 0) return;\n\t\tslot.buffer.push(row);\n\t}\n\tasync function afterExecute(exec, result, ctx) {\n\t\tconst slot = pending.get(exec);\n\t\tif (slot === void 0) return;\n\t\tpending.delete(exec);\n\t\tif (!result.completed || result.source !== \"driver\") return;\n\t\tawait store.set(slot.key, {\n\t\t\trows: slot.buffer,\n\t\t\tstoredAt: clock()\n\t\t}, slot.ttlMs);\n\t\tctx.log.debug?.({\n\t\t\tevent: \"middleware.cache.store\",\n\t\t\tmiddleware: \"cache\",\n\t\t\tkey: slot.key\n\t\t});\n\t}\n\treturn {\n\t\tname: \"cache\",\n\t\tintercept,\n\t\tonRow,\n\t\tafterExecute\n\t};\n}\n//#endregion\nexport { cacheAnnotation, createCacheMiddleware, createInMemoryCacheStore };\n\n//# sourceMappingURL=index.mjs.map"],"mappings":"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"}
|
package/package.json
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@prisma/orm-extension-middleware-cache",
|
|
3
|
+
"version": "0.16.0-dev.36",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"sideEffects": false,
|
|
7
|
+
"description": "Family-agnostic caching middleware for Prisma Next runtimes",
|
|
8
|
+
"files": [
|
|
9
|
+
"dist"
|
|
10
|
+
],
|
|
11
|
+
"dependencies": {
|
|
12
|
+
"@prisma/orm-framework": "0.16.0-dev.36"
|
|
13
|
+
},
|
|
14
|
+
"devDependencies": {
|
|
15
|
+
"@internal/middleware-cache": "0.16.0-dev.36",
|
|
16
|
+
"@repo/tsconfig": "0.16.0-dev.36",
|
|
17
|
+
"@repo/tsdown": "0.16.0-dev.36",
|
|
18
|
+
"tsdown": "0.22.14",
|
|
19
|
+
"typescript": "5.9.3"
|
|
20
|
+
},
|
|
21
|
+
"peerDependencies": {
|
|
22
|
+
"typescript": ">=5.9"
|
|
23
|
+
},
|
|
24
|
+
"peerDependenciesMeta": {
|
|
25
|
+
"typescript": {
|
|
26
|
+
"optional": true
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"exports": {
|
|
30
|
+
".": "./dist/index.mjs",
|
|
31
|
+
"./package.json": "./package.json"
|
|
32
|
+
},
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "https://github.com/prisma/prisma.git",
|
|
36
|
+
"directory": "packages/9-public/@prisma/orm-extension-middleware-cache"
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"build": "tsdown",
|
|
40
|
+
"lint": "biome check . --error-on-warnings",
|
|
41
|
+
"clean": "rm -rf dist src-gen"
|
|
42
|
+
}
|
|
43
|
+
}
|