@prisma/orm-extension-middleware-cache 8.0.0-rc.18-dev.27 → 8.0.0-rc.18-dev.29
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/README.md +14 -3
- package/dist/index.d.mts +40 -8
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +39 -5
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -14,13 +14,14 @@ import {
|
|
|
14
14
|
createCacheMiddleware,
|
|
15
15
|
createInMemoryCacheStore,
|
|
16
16
|
deriveKeyFromContentHash,
|
|
17
|
+
invalidateAnnotation,
|
|
17
18
|
type CacheStore,
|
|
18
19
|
} from '@prisma/orm-extension-middleware-cache';
|
|
19
20
|
```
|
|
20
21
|
|
|
21
22
|
## Responsibilities
|
|
22
23
|
|
|
23
|
-
A read-through cache middleware. An annotated ORM call, such as `db.orm.public.User.first(...)`, is cached as a whole: on a hit the middleware supplies the call's result and the ORM sends no statement; on a miss it stores the value the call returned. An annotated statement, such as a SQL builder query, is cached as rows: on a hit it returns the cached rows and never invokes the driver; on a miss it buffers the driver's rows and stores them when the read completes. A read opts in with `cacheAnnotation({ key?, meta?, bypass? })`: `key` names the entry; otherwise an ORM call is keyed by its content hash, a digest of the terminal method and the statement it sends, and a statement by the `deriveKey` option (default: the family runtime's content hash, `deriveKeyFromContentHash`); `meta` is handed to the store with the entry; `bypass: true` skips the cache for that call. A read inside a transaction or on a held connection, such as a Supabase role session, is neither served nor stored.
|
|
24
|
+
A read-through cache middleware. An annotated ORM call, such as `db.orm.public.User.first(...)`, is cached as a whole: on a hit the middleware supplies the call's result and the ORM sends no statement; on a miss it stores the value the call returned. An annotated statement, such as a SQL builder query, is cached as rows: on a hit it returns the cached rows and never invokes the driver; on a miss it buffers the driver's rows and stores them when the read completes. A read opts in with `cacheAnnotation({ key?, meta?, bypass? })`: `key` names the entry; otherwise an ORM call is keyed by its content hash, a digest of the terminal method and the statement it sends, and a statement by the `deriveKey` option (default: the family runtime's content hash, `deriveKeyFromContentHash`); `meta` is handed to the store with the entry; `bypass: true` skips the cache for that call. A read inside a transaction or on a held connection, such as a Supabase role session, is neither served nor stored. A write annotated with `invalidateAnnotation({ keys?, meta? })` removes those entries once its effects are final.
|
|
24
25
|
|
|
25
26
|
How long an entry lives is the store's policy. The default store, `createInMemoryCacheStore({ maxEntries?, ttlMs?, clock? })`, keeps up to 1000 values for 60 seconds each; `ttlMs: Infinity` never expires. A key's version is kept for `ttlMs` after the `unset` that moved it. Versions are not bounded by `maxEntries`. A forgotten version reads as 0, so with a finite `ttlMs` a read that takes longer than `ttlMs` and overlaps an `invalidate` can store stale rows. With `ttlMs: Infinity`, the versions of invalidated keys are never forgotten and grow with the number of distinct keys invalidated. A `maxEntries` that is not a positive integer or a `ttlMs` that is not positive throws `RUNTIME.ARGUMENT_INVALID`. Implement the `CacheStore` interface to use Redis, Memcached, or any other backend.
|
|
26
27
|
|
|
@@ -110,10 +111,20 @@ await cache.invalidate({ keys: ['user-1'] });
|
|
|
110
111
|
|
|
111
112
|
A read that missed before an `invalidate` and finishes after it does not store its rows. Its `store.get` returned an empty entry with, say, version 3; the `unset` moves the key to version 4; `store.set(entry, rows)` then returns `false`. This works across processes that share a store, because the store owns the version. Call `invalidate` after the write has committed: inside a transaction, another request can put the old rows back in the cache before the commit. An error from the store propagates.
|
|
112
113
|
|
|
114
|
+
A write can carry its invalidation instead. `invalidateAnnotation({ keys?, meta? })` takes the same `InvalidationTarget<TMeta>` as `invalidate`, and the middleware makes the same call from the runtime's `activityFinalized` event, once the write's effects are final:
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
await db.orm.public.User.where({ id: 1 }).update({ name: 'Alicia' }, (meta) =>
|
|
118
|
+
meta.annotate(invalidateAnnotation({ keys: ['user-1'] })),
|
|
119
|
+
);
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
It applies to writes only: every SQL ORM write terminal and every SQL builder insert, update and delete accepts it, and a read rejects it at compile time and at run time. Outside a transaction it invalidates right after the write ends, after the write's own transaction when the ORM call runs one, such as an update with a relation callback or a create on a multi-table-inheritance variant. Inside `db.transaction(fn)` it invalidates when the transaction ends; until then the entry is still served. A rolled-back write does not invalidate. An `unknown` outcome, such as a failed write or a `COMMIT` that errored, does, since the write may have landed. Several annotated writes in one transaction each invalidate when it ends. The middleware reads the annotation from whatever activity carries it, an ORM call, an annotated builder statement or any client activity, and does not check the kind or the transaction. An error from `unset` is passed to `ctx.log.error` with the event `middleware.activityFinalized.error` and swallowed; the write has already happened. `postgres()`, `sqlite()` and `supabase()` drop these events unless the application passes `log`, for example `postgres({ contract: contractFromJson<Contract>(contractJson), url, middleware: [cache], log: console })`, so pass it to see a failed invalidation. So on a store that cannot act on `meta`, such as the default store, an annotation with `meta` removes nothing, not even its `keys`, and each such write only logs `RUNTIME.CACHE_STORE_META_UNSUPPORTED`. The write's promise, and `db.transaction(fn)`'s, resolve only after `store.unset` has settled, so a custom store must time out its own `unset`. A write whose activity never finalizes, such as a builder write whose row iterator is dropped without `return()`, or a process that stops between the commit and the invalidation, does not invalidate; its entries stay until they expire. The Mongo ORM's write methods take no annotations, so on Mongo call `invalidate` after the write. Because the middleware implements `activityFinalized`, a runtime that uses it keeps every transaction's finished statements until the transaction ends, whether or not any write is annotated: measured on Postgres, about 2.9 KB per statement, about 55 MB for a transaction of 20,000 statements, all released at the commit. Split a long batch import into several transactions, or run it on a client without the cache middleware.
|
|
123
|
+
|
|
113
124
|
A tag scheme is a store policy: `cacheAnnotation({ meta: { tags: ['users'] } })` on the read, a store that indexes `meta.tags` in `set`, and `cache.invalidate({ meta: { tags: ['users'] } })` after the write.
|
|
114
125
|
|
|
115
126
|
## Scope
|
|
116
127
|
|
|
117
|
-
The middleware is a read-through cache with a control surface: keys and `deriveKey`, `meta`, `bypass`, `invalidate`, and the `CacheStore` interface. It carries data between the annotations and the store and never interprets it. Lifetime and the meaning of `meta` are the store's; deciding what
|
|
128
|
+
The middleware is a read-through cache with a control surface: keys and `deriveKey`, `meta`, `bypass`, `invalidate` and `invalidateAnnotation`, and the `CacheStore` interface. It carries data between the annotations and the store and never interprets it. Lifetime and the meaning of `meta` are the store's; the middleware decides when the invalidation a write carries runs, once the write's effects are final; deciding what a write should invalidate, for example by table, request coalescing and routing between several stores belong in extensions built on these primitives.
|
|
118
129
|
|
|
119
|
-
|
|
130
|
+
Serve-stale strategies such as stale-while-revalidate need the hit-or-miss decision, which only the middleware makes.
|
package/dist/index.d.mts
CHANGED
|
@@ -54,6 +54,37 @@ type CacheAnnotationHandle = (<TMeta = unknown>(options: CacheAnnotationOptions<
|
|
|
54
54
|
* ```
|
|
55
55
|
*/
|
|
56
56
|
declare const cacheAnnotation: CacheAnnotationHandle;
|
|
57
|
+
/**
|
|
58
|
+
* What to invalidate: the argument of the cache middleware's `invalidate`, and the payload of `invalidateAnnotation`, which the middleware passes to the same call once the write's effects are final.
|
|
59
|
+
*
|
|
60
|
+
* `TMeta` is the shape of `meta`; pass the store's `TMeta` so the two agree.
|
|
61
|
+
*/
|
|
62
|
+
interface InvalidationTarget<TMeta = unknown> {
|
|
63
|
+
readonly keys?: readonly string[];
|
|
64
|
+
readonly meta?: TMeta;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* The type of `invalidateAnnotation`: a call generic in `TMeta`, plus the read-only `namespace`,
|
|
68
|
+
* `applicableTo` and `read` of the underlying annotation handle.
|
|
69
|
+
*/
|
|
70
|
+
type InvalidateAnnotationHandle = (<TMeta = unknown>(options: InvalidationTarget<TMeta>) => AnnotationValue<InvalidationTarget, 'write'>) & {
|
|
71
|
+
readonly namespace: string;
|
|
72
|
+
readonly applicableTo: ReadonlySet<'write'>;
|
|
73
|
+
readonly read: AnnotationHandle<InvalidationTarget, 'write'>['read'];
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* Marks a write whose cache entries the cache middleware invalidates once the write's effects are final: right after the write outside a transaction, or when the outermost enclosing transaction ends. It does not invalidate when the write is rolled back, and does when the outcome is unknown. It applies to writes only: a read terminal refuses it at compile time and at run time.
|
|
77
|
+
*
|
|
78
|
+
* `TMeta` types `meta` for this call only. Nothing ties it to the store's `TMeta`, so a store package should export a wrapper typed with its own meta, such as `(o: InvalidationTarget<TagMeta>) => invalidateAnnotation<TagMeta>(o)`.
|
|
79
|
+
*
|
|
80
|
+
* @example
|
|
81
|
+
* ```typescript
|
|
82
|
+
* await db.orm.public.User.where({ id: 1 }).update({ name: 'Alicia' }, (meta) =>
|
|
83
|
+
* meta.annotate(invalidateAnnotation({ keys: ['user-1'] })),
|
|
84
|
+
* );
|
|
85
|
+
* ```
|
|
86
|
+
*/
|
|
87
|
+
declare const invalidateAnnotation: InvalidateAnnotationHandle;
|
|
57
88
|
//#endregion
|
|
58
89
|
//#region src/cache-store.d.ts
|
|
59
90
|
/**
|
|
@@ -185,13 +216,12 @@ interface CacheMiddlewareOptions<TMeta = unknown> {
|
|
|
185
216
|
* its conditional `store.set` returns `false`. This holds across processes that share a store. An
|
|
186
217
|
* error from the store propagates.
|
|
187
218
|
*
|
|
219
|
+
* A write annotated with `invalidateAnnotation({ keys, meta })` makes the same call from `activityFinalized`, once the write's effects are final, unless they were rolled back.
|
|
220
|
+
*
|
|
188
221
|
* `TMeta` is the store's meta type, which `invalidate`'s `meta` must have.
|
|
189
222
|
*/
|
|
190
223
|
type CacheMiddleware<TMeta = unknown> = CrossFamilyMiddleware & {
|
|
191
|
-
readonly invalidate: (target:
|
|
192
|
-
readonly keys?: readonly string[];
|
|
193
|
-
readonly meta?: TMeta;
|
|
194
|
-
}) => Promise<void>;
|
|
224
|
+
readonly invalidate: (target: InvalidationTarget<TMeta>) => Promise<void>;
|
|
195
225
|
};
|
|
196
226
|
/**
|
|
197
227
|
* The default `deriveKey`: the family runtime's content hash of the plan, which covers the
|
|
@@ -199,7 +229,7 @@ type CacheMiddleware<TMeta = unknown> = CrossFamilyMiddleware & {
|
|
|
199
229
|
*/
|
|
200
230
|
declare function deriveKeyFromContentHash(exec: ExecutionPlan, ctx: ActivityContext): Promise<string>;
|
|
201
231
|
/**
|
|
202
|
-
* Creates a read-through cache middleware that works with every family runtime.
|
|
232
|
+
* Creates a read-through cache middleware that works with every family runtime. It also invalidates entries for writes annotated with `invalidateAnnotation`.
|
|
203
233
|
*
|
|
204
234
|
* It caches an activity that carries `cacheAnnotation` without `bypass` and runs in runtime scope,
|
|
205
235
|
* outside any transaction: never on a held connection, whose session may change what a read
|
|
@@ -221,6 +251,7 @@ declare function deriveKeyFromContentHash(exec: ExecutionPlan, ctx: ActivityCont
|
|
|
221
251
|
* `succeeded` with a result (`null` is a result), calls `store.set(entry, value)` with the entry
|
|
222
252
|
* `store.get` returned, which stores only if the key's version has not moved. If an `unset` moved
|
|
223
253
|
* it meanwhile, `set` returns `false` and the middleware logs `middleware.cache.store-skipped`.
|
|
254
|
+
* - `activityFinalized` — for any activity that carries `invalidateAnnotation`, whatever its kind or transaction, calls `invalidate` with the annotation's `keys` and `meta`, unless the outcome is `rolled-back`. An `unknown` outcome invalidates, since the write may have landed. A store error is thrown, and the runtime logs it.
|
|
224
255
|
*
|
|
225
256
|
* @example
|
|
226
257
|
* ```typescript
|
|
@@ -231,11 +262,12 @@ declare function deriveKeyFromContentHash(exec: ExecutionPlan, ctx: ActivityCont
|
|
|
231
262
|
* { id: 1 },
|
|
232
263
|
* (meta) => meta.annotate(cacheAnnotation({ key: 'user-1' })),
|
|
233
264
|
* );
|
|
234
|
-
* await db.orm.public.User.where({ id: 1 }).update({ name: 'Alicia' })
|
|
235
|
-
*
|
|
265
|
+
* await db.orm.public.User.where({ id: 1 }).update({ name: 'Alicia' }, (meta) =>
|
|
266
|
+
* meta.annotate(invalidateAnnotation({ keys: ['user-1'] })),
|
|
267
|
+
* );
|
|
236
268
|
* ```
|
|
237
269
|
*/
|
|
238
270
|
declare function createCacheMiddleware<TMeta = unknown>(options?: CacheMiddlewareOptions<TMeta>): CacheMiddleware<TMeta>;
|
|
239
271
|
//#endregion
|
|
240
|
-
export { type CacheAnnotationHandle, type CacheAnnotationOptions, type CacheEntry, type CacheMiddleware, type CacheMiddlewareOptions, type CacheStore, type CachedRows, type CachedValue, type InMemoryCacheStoreOptions, cacheAnnotation, createCacheMiddleware, createInMemoryCacheStore, deriveKeyFromContentHash };
|
|
272
|
+
export { type CacheAnnotationHandle, type CacheAnnotationOptions, type CacheEntry, type CacheMiddleware, type CacheMiddlewareOptions, type CacheStore, type CachedRows, type CachedValue, type InMemoryCacheStoreOptions, type InvalidateAnnotationHandle, type InvalidationTarget, cacheAnnotation, createCacheMiddleware, createInMemoryCacheStore, deriveKeyFromContentHash, invalidateAnnotation };
|
|
241
273
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../../3-extensions/middleware-cache/dist/index.d.mts"],"mappings":";;;;;;;;;;;;;;;UAcU,uBAAuB;WACtB;WACA,OAAO;WACP;;;;;;KAMN,0BAA0B,iBAAiB,SAAS,uBAAuB,WAAW,gBAAgB;WAChG;WACA,cAAc;WACd,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA4BpB,iBAAiB;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../../3-extensions/middleware-cache/dist/index.d.mts"],"mappings":";;;;;;;;;;;;;;;UAcU,uBAAuB;WACtB;WACA,OAAO;WACP;;;;;;KAMN,0BAA0B,iBAAiB,SAAS,uBAAuB,WAAW,gBAAgB;WAChG;WACA,cAAc;WACd,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA4BpB,iBAAiB;;;;;;UAMrB,mBAAmB;WAClB;WACA,OAAO;;;;;;KAMb,+BAA+B,iBAAiB,SAAS,mBAAmB,WAAW,gBAAgB;WACjG;WACA,cAAc;WACd,MAAM,iBAAiB;;;;;;;;;;;;;;cAcpB,sBAAsB;;;;;;;KAO/B,sBAAsB;;;;KAItB;WACM;WACA,MAAM;;WAEN;WACA;;;;;;;;;;;;UAYD,WAAW,iBAAiB,SAAS;WACpC;WACA,MAAM;WACN;WACA;aACE;;aAEA;aACA,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAgCV,WAAW,iBAAiB,SAAS;EAC7C,IAAI;aACO;aACA,MAAM;MACb,QAAQ,WAAW,OAAO;EAC9B,IAAI,OAAO,WAAW,OAAO,SAAS,OAAO,SAAS;EACtD,MAAM;aACK;aACA,MAAM;MACb;;;;;;;;;;;;;;;UAeI;WACC;WACA;WACA;;;;;iBAKM,yBAAyB,iBAAiB,UAAU,4BAA4B,WAAW,OAAO;;;;;;;;;;;;;;;;;;;UAmBzG,uBAAuB;WACtB,QAAQ,WAAW,OAAO;WAC1B,aAAa,MAAM,eAAe,KAAK,6BAA6B;;;;;;;;;;;;;;;KAe1E,gBAAgB,mBAAmB;WAC7B,aAAa,QAAQ,mBAAmB,WAAW;;;;;;iBAM7C,yBAAyB,MAAM,eAAe,KAAK,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAwCrE,sBAAsB,iBAAiB,UAAU,uBAAuB,SAAS,gBAAgB"}
|
package/dist/index.mjs
CHANGED
|
@@ -42,6 +42,32 @@ function withTypedMeta(handle) {
|
|
|
42
42
|
read: handle.read
|
|
43
43
|
}));
|
|
44
44
|
}
|
|
45
|
+
/**
|
|
46
|
+
* Marks a write whose cache entries the cache middleware invalidates once the write's effects are final: right after the write outside a transaction, or when the outermost enclosing transaction ends. It does not invalidate when the write is rolled back, and does when the outcome is unknown. It applies to writes only: a read terminal refuses it at compile time and at run time.
|
|
47
|
+
*
|
|
48
|
+
* `TMeta` types `meta` for this call only. Nothing ties it to the store's `TMeta`, so a store package should export a wrapper typed with its own meta, such as `(o: InvalidationTarget<TagMeta>) => invalidateAnnotation<TagMeta>(o)`.
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* ```typescript
|
|
52
|
+
* await db.orm.public.User.where({ id: 1 }).update({ name: 'Alicia' }, (meta) =>
|
|
53
|
+
* meta.annotate(invalidateAnnotation({ keys: ['user-1'] })),
|
|
54
|
+
* );
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
const invalidateAnnotation = withTypedInvalidateMeta(defineAnnotation()({
|
|
58
|
+
namespace: "cache-invalidate",
|
|
59
|
+
applicableTo: ["write"]
|
|
60
|
+
}));
|
|
61
|
+
function withTypedInvalidateMeta(handle) {
|
|
62
|
+
function invalidateAnnotationWithMeta(options) {
|
|
63
|
+
return handle(options);
|
|
64
|
+
}
|
|
65
|
+
return Object.freeze(Object.assign(invalidateAnnotationWithMeta, {
|
|
66
|
+
namespace: handle.namespace,
|
|
67
|
+
applicableTo: handle.applicableTo,
|
|
68
|
+
read: handle.read
|
|
69
|
+
}));
|
|
70
|
+
}
|
|
45
71
|
const typedArraySlice = Reflect.get(Object.getPrototypeOf(Uint8Array.prototype), "slice");
|
|
46
72
|
/**
|
|
47
73
|
* A copy of the plain structure of `value`: plain and null-prototype objects, arrays, `Map`, `Set`,
|
|
@@ -113,7 +139,7 @@ function copyStored(value) {
|
|
|
113
139
|
}
|
|
114
140
|
}
|
|
115
141
|
function metaUnsupported() {
|
|
116
|
-
return structuredError("RUNTIME.CACHE_STORE_META_UNSUPPORTED", "The in-memory cache store cannot remove entries by meta because it does not index meta
|
|
142
|
+
return structuredError("RUNTIME.CACHE_STORE_META_UNSUPPORTED", "The in-memory cache store cannot remove entries by meta because it does not index meta, so it removed nothing, not even the keys passed with it", { fix: "Use a CacheStore that indexes meta in set and unset, or pass only keys." });
|
|
117
143
|
}
|
|
118
144
|
function invalidOption(argument, received, expected) {
|
|
119
145
|
return structuredError("RUNTIME.ARGUMENT_INVALID", `createInMemoryCacheStore: ${argument} must be ${expected}`, {
|
|
@@ -233,7 +259,7 @@ function valueToStore(miss, result) {
|
|
|
233
259
|
} : void 0;
|
|
234
260
|
}
|
|
235
261
|
/**
|
|
236
|
-
* Creates a read-through cache middleware that works with every family runtime.
|
|
262
|
+
* Creates a read-through cache middleware that works with every family runtime. It also invalidates entries for writes annotated with `invalidateAnnotation`.
|
|
237
263
|
*
|
|
238
264
|
* It caches an activity that carries `cacheAnnotation` without `bypass` and runs in runtime scope,
|
|
239
265
|
* outside any transaction: never on a held connection, whose session may change what a read
|
|
@@ -255,6 +281,7 @@ function valueToStore(miss, result) {
|
|
|
255
281
|
* `succeeded` with a result (`null` is a result), calls `store.set(entry, value)` with the entry
|
|
256
282
|
* `store.get` returned, which stores only if the key's version has not moved. If an `unset` moved
|
|
257
283
|
* it meanwhile, `set` returns `false` and the middleware logs `middleware.cache.store-skipped`.
|
|
284
|
+
* - `activityFinalized` — for any activity that carries `invalidateAnnotation`, whatever its kind or transaction, calls `invalidate` with the annotation's `keys` and `meta`, unless the outcome is `rolled-back`. An `unknown` outcome invalidates, since the write may have landed. A store error is thrown, and the runtime logs it.
|
|
258
285
|
*
|
|
259
286
|
* @example
|
|
260
287
|
* ```typescript
|
|
@@ -265,8 +292,9 @@ function valueToStore(miss, result) {
|
|
|
265
292
|
* { id: 1 },
|
|
266
293
|
* (meta) => meta.annotate(cacheAnnotation({ key: 'user-1' })),
|
|
267
294
|
* );
|
|
268
|
-
* await db.orm.public.User.where({ id: 1 }).update({ name: 'Alicia' })
|
|
269
|
-
*
|
|
295
|
+
* await db.orm.public.User.where({ id: 1 }).update({ name: 'Alicia' }, (meta) =>
|
|
296
|
+
* meta.annotate(invalidateAnnotation({ keys: ['user-1'] })),
|
|
297
|
+
* );
|
|
270
298
|
* ```
|
|
271
299
|
*/
|
|
272
300
|
function createCacheMiddleware(options) {
|
|
@@ -333,6 +361,11 @@ function createCacheMiddleware(options) {
|
|
|
333
361
|
meta: target.meta
|
|
334
362
|
});
|
|
335
363
|
}
|
|
364
|
+
async function activityFinalized(activity, result) {
|
|
365
|
+
if (result.outcome === "rolled-back") return;
|
|
366
|
+
const target = invalidateAnnotation.read(activity);
|
|
367
|
+
if (target !== void 0) await invalidate(target);
|
|
368
|
+
}
|
|
336
369
|
return {
|
|
337
370
|
name: "cache",
|
|
338
371
|
intercept: {
|
|
@@ -341,10 +374,11 @@ function createCacheMiddleware(options) {
|
|
|
341
374
|
},
|
|
342
375
|
onRow,
|
|
343
376
|
activityEnded,
|
|
377
|
+
activityFinalized,
|
|
344
378
|
invalidate
|
|
345
379
|
};
|
|
346
380
|
}
|
|
347
381
|
//#endregion
|
|
348
|
-
export { cacheAnnotation, createCacheMiddleware, createInMemoryCacheStore, deriveKeyFromContentHash };
|
|
382
|
+
export { cacheAnnotation, createCacheMiddleware, createInMemoryCacheStore, deriveKeyFromContentHash, invalidateAnnotation };
|
|
349
383
|
|
|
350
384
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../3-extensions/middleware-cache/dist/index.mjs"],"sourcesContent":["import { defineAnnotation } from \"@internal/framework-components/runtime\";\nimport { blindCast } from \"@internal/utils/casts\";\nimport { structuredError } from \"@internal/utils/structured-error\";\n//#region src/cache-annotation.ts\n/**\n* Marks a read for the cache middleware. It applies to reads only: a write terminal refuses it at\n* compile time and at run time. The middleware reads it from a statement plan's `meta.annotations.cache`, or from the annotations of a client activity, such as an ORM read, which is then cached as a whole.\n*\n* `TMeta` types `meta` for this call only. Nothing ties it to the store's `TMeta`, so a store\n* package should export a wrapper typed with its own meta, such as\n* `(o: CacheAnnotationOptions<TagMeta>) => cacheAnnotation<TagMeta>(o)`.\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.orm.public.User.first(\n* { id },\n* (meta) => meta.annotate(cacheAnnotation({ key: `user-${id}` })),\n* );\n*\n* // SQL DSL select builder — chainable.\n* const plan = db.sql\n* .from(tables.user)\n* .annotate(cacheAnnotation({}))\n* .select({ id: tables.user.columns.id })\n* .build();\n* ```\n*/\nconst cacheAnnotation = withTypedMeta(defineAnnotation()({\n\tnamespace: \"cache\",\n\tapplicableTo: [\"read\"]\n}));\nfunction withTypedMeta(handle) {\n\tfunction cacheAnnotationWithMeta(options) {\n\t\treturn handle(options);\n\t}\n\treturn Object.freeze(Object.assign(cacheAnnotationWithMeta, {\n\t\tnamespace: handle.namespace,\n\t\tapplicableTo: handle.applicableTo,\n\t\tread: handle.read\n\t}));\n}\n//#endregion\n//#region src/cache-store.ts\nconst typedArraySlice = Reflect.get(Object.getPrototypeOf(Uint8Array.prototype), \"slice\");\n/**\n* A copy of the plain structure of `value`: plain and null-prototype objects, arrays, `Map`, `Set`,\n* `Date`, `RegExp`, `ArrayBuffer`, typed arrays and `DataView` are copied, and every other value,\n* such as a class instance or a function, is kept by reference. A typed array is copied with\n* `TypedArray.prototype.slice`, which keeps its class, so a `Buffer` copies to a `Buffer` with its\n* own memory; a `DataView` copies to a plain `DataView`; an array copies to its elements only, with\n* holes read as `undefined`. Shared references and cycles are kept.\n*/\nfunction copyValue(value, copies = /* @__PURE__ */ new Map()) {\n\tif (typeof value !== \"object\" || value === null) return value;\n\tconst known = copies.get(value);\n\tif (known !== void 0) return blindCast(known);\n\tconst copy = copyObject(value, copies);\n\tcopies.set(value, copy);\n\treturn blindCast(copy);\n}\nfunction copyObject(value, copies) {\n\tif (value instanceof DataView) {\n\t\tconst start = value.byteOffset;\n\t\treturn new DataView(value.buffer.slice(start, start + value.byteLength));\n\t}\n\tif (ArrayBuffer.isView(value)) return typedArraySlice.call(value);\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (prototype === ArrayBuffer.prototype && value instanceof ArrayBuffer) return value.slice(0);\n\tif (prototype === Date.prototype && value instanceof Date) return new Date(value.getTime());\n\tif (prototype === RegExp.prototype && value instanceof RegExp) return new RegExp(value.source, value.flags);\n\tif (prototype === Map.prototype && value instanceof Map) {\n\t\tconst copy = /* @__PURE__ */ new Map();\n\t\tcopies.set(value, copy);\n\t\tfor (const [key, entry] of value) copy.set(copyValue(key, copies), copyValue(entry, copies));\n\t\treturn copy;\n\t}\n\tif (prototype === Set.prototype && value instanceof Set) {\n\t\tconst copy = /* @__PURE__ */ new Set();\n\t\tcopies.set(value, copy);\n\t\tfor (const entry of value) copy.add(copyValue(entry, copies));\n\t\treturn copy;\n\t}\n\tif (prototype === Array.prototype && Array.isArray(value)) {\n\t\tconst copy = [];\n\t\tcopies.set(value, copy);\n\t\tfor (const entry of value) copy.push(copyValue(entry, copies));\n\t\treturn copy;\n\t}\n\tif (prototype !== Object.prototype && prototype !== null) return value;\n\tconst copy = Object.create(prototype);\n\tcopies.set(value, copy);\n\tfor (const key of Reflect.ownKeys(value)) if (Object.prototype.propertyIsEnumerable.call(value, key)) copy[key] = copyValue(Reflect.get(value, key), copies);\n\treturn copy;\n}\n/** Statement rows hold driver values, such as BSON `ObjectId`s, that this package cannot copy. So the array and each row object are copied, each row keeping its prototype, and the driver's values are kept by reference and shared with every hit. */\nfunction copyRows(rows) {\n\treturn rows.map((row) => {\n\t\tconst copy = Object.create(Object.getPrototypeOf(row));\n\t\treturn Object.assign(copy, row);\n\t});\n}\nfunction copyStored(value) {\n\tswitch (value.kind) {\n\t\tcase \"statement-rows\": return {\n\t\t\tkind: \"statement-rows\",\n\t\t\trows: copyRows(value.rows)\n\t\t};\n\t\tcase \"call-result\": return {\n\t\t\tkind: \"call-result\",\n\t\t\tresult: copyValue(value.result)\n\t\t};\n\t}\n}\nfunction metaUnsupported() {\n\treturn structuredError(\"RUNTIME.CACHE_STORE_META_UNSUPPORTED\", \"The in-memory cache store cannot remove entries by meta because it does not index meta\", { fix: \"Invalidate by keys, or supply a CacheStore that indexes meta in set and unset.\" });\n}\nfunction invalidOption(argument, received, expected) {\n\treturn structuredError(\"RUNTIME.ARGUMENT_INVALID\", `createInMemoryCacheStore: ${argument} must be ${expected}`, {\n\t\tfix: `Pass ${argument} as ${expected}, or leave it unset for the default.`,\n\t\tmeta: {\n\t\t\thelper: \"createInMemoryCacheStore\",\n\t\t\targument,\n\t\t\treceived\n\t\t}\n\t});\n}\n/**\n* The default cache store: a least-recently-used map of `CachedValue` with one lifetime for every value, local to the process. Statement rows are copied one level deep on `set` and `get`: the array, and each row object with its prototype. The driver's values in them are kept by reference and shared with every hit; the runtime decodes them on each hit, and a codec that returns its wire value unchanged, such as a date or byte-array codec, hands that shared object to the caller. A call result has its plain structure copied on `set` and on every `get`: plain and null-prototype objects, arrays (their elements only; holes read as `undefined`), `Map`, `Set`, `Date`, `RegExp`, `ArrayBuffer`, typed arrays (a subclass such as Node's `Buffer` keeps its class) and `DataView` (copied as a plain `DataView`). Every other value in it, such as a class instance (a Temporal value, a BSON value, an error) or a function, is shared by reference. So after `set` returns, a change to the plain structure of the value `set` was given, or of a value `get` returned, reaches no later `get`; a change made to a shared value, or made before `set`, does. It never refuses a value: `set` returns `false` only when the version moved. A key's version is kept for `ttlMs` after the `unset` that moved it (see `InMemoryCacheStoreOptions`). It ignores `meta` in `get` and `set`, and its `unset` rejects any `meta`, including `null`, before changing anything. It throws `RUNTIME.ARGUMENT_INVALID` for a `maxEntries` or `ttlMs` outside the ranges above.\n*/\nfunction createInMemoryCacheStore(options) {\n\tconst maxEntries = options?.maxEntries ?? 1e3;\n\tconst ttlMs = options?.ttlMs ?? 6e4;\n\tconst clock = options?.clock ?? Date.now;\n\tif (!Number.isInteger(maxEntries) || maxEntries <= 0) throw invalidOption(\"maxEntries\", maxEntries, \"a positive integer\");\n\tif (!(ttlMs > 0)) throw invalidOption(\"ttlMs\", ttlMs, \"a positive number of milliseconds, or Infinity\");\n\tconst records = /* @__PURE__ */ new Map();\n\tconst versions = /* @__PURE__ */ new Map();\n\tfunction forgetExpiredVersions() {\n\t\tconst now = clock();\n\t\tfor (const [key, record] of versions) {\n\t\t\tif (now < record.expiresAt) return;\n\t\t\tversions.delete(key);\n\t\t}\n\t}\n\tfunction versionOf(key) {\n\t\tforgetExpiredVersions();\n\t\treturn versions.get(key)?.version ?? 0;\n\t}\n\tfunction liveRecord(key) {\n\t\tconst record = records.get(key);\n\t\tif (record === void 0) return;\n\t\trecords.delete(key);\n\t\tif (clock() >= record.expiresAt) return;\n\t\trecords.set(key, record);\n\t\treturn record;\n\t}\n\tasync function get(target) {\n\t\tconst record = liveRecord(target.key);\n\t\treturn {\n\t\t\tkey: target.key,\n\t\t\tmeta: target.meta,\n\t\t\tversion: versionOf(target.key),\n\t\t\tdata: record === void 0 ? { empty: true } : {\n\t\t\t\tempty: false,\n\t\t\t\tvalue: copyStored(record.value)\n\t\t\t}\n\t\t};\n\t}\n\tasync function set(entry, value) {\n\t\tif (entry.version !== versionOf(entry.key)) return false;\n\t\trecords.delete(entry.key);\n\t\trecords.set(entry.key, {\n\t\t\tvalue: copyStored(value),\n\t\t\texpiresAt: clock() + ttlMs\n\t\t});\n\t\tfor (const leastRecentlyUsed of records.keys()) {\n\t\t\tif (records.size <= maxEntries) break;\n\t\t\trecords.delete(leastRecentlyUsed);\n\t\t}\n\t\treturn true;\n\t}\n\tasync function unset(target) {\n\t\tif (target.meta !== void 0) throw metaUnsupported();\n\t\tfor (const key of target.keys ?? []) {\n\t\t\trecords.delete(key);\n\t\t\tconst version = versionOf(key) + 1;\n\t\t\tversions.delete(key);\n\t\t\tversions.set(key, {\n\t\t\t\tversion,\n\t\t\t\texpiresAt: clock() + ttlMs\n\t\t\t});\n\t\t}\n\t}\n\treturn {\n\t\tget,\n\t\tset,\n\t\tunset\n\t};\n}\n//#endregion\n//#region src/cache-middleware.ts\n/**\n* The default `deriveKey`: the family runtime's content hash of the plan, which covers the\n* statement, its parameters and the storage hash.\n*/\nfunction deriveKeyFromContentHash(exec, ctx) {\n\treturn ctx.contentHash(exec);\n}\nconst pendingMiss = Symbol(\"cache.pendingMiss\");\nfunction pendingOf(ctx) {\n\tconst miss = ctx.state(pendingMiss)[\"miss\"];\n\treturn isPendingMiss(miss) ? miss : void 0;\n}\nfunction isPendingMiss(value) {\n\treturn typeof value === \"object\" && value !== null && \"entry\" in value && \"buffer\" in value;\n}\nfunction hasTag(value, tag) {\n\treturn value.kind === tag;\n}\nfunction cacheable(ctx) {\n\treturn ctx.scope === \"runtime\" && !ctx.inTransaction();\n}\n/** The value a pending miss stores when its activity ends this way, or `undefined` to store nothing. */\nfunction valueToStore(miss, result) {\n\tif (result.outcome !== \"succeeded\") return void 0;\n\tif (result.kind === \"statement\") return result.source === \"driver\" && miss.buffer !== void 0 ? {\n\t\tkind: \"statement-rows\",\n\t\trows: miss.buffer\n\t} : void 0;\n\tif (result.kind === \"transaction\") return void 0;\n\treturn result.source === \"client\" && result.result !== void 0 ? {\n\t\tkind: \"call-result\",\n\t\tresult: result.result\n\t} : void 0;\n}\n/**\n* Creates a read-through cache middleware that works with every family runtime.\n*\n* It caches an activity that carries `cacheAnnotation` without `bypass` and runs in runtime scope,\n* outside any transaction: never on a held connection, whose session may change what a read\n* returns, and never inside a transaction, which must read its own uncommitted writes. Two kinds\n* of activity are cached:\n*\n* - A statement whose plan carries the annotation, such as an annotated SQL builder query. Its key\n* is the annotation's `key`, else `deriveKey(exec, ctx)`; its value is the raw rows.\n* - A client activity that carries the annotation, such as an annotated ORM read. Its key is the\n* annotation's `key`, else `await activity.contentHash()`; its value is the result the client\n* ended the activity with. It is served as a whole, so a hit sends no statement.\n*\n* The middleware tags each stored value `statement-rows` or `call-result` and serves `statement-rows` only to a statement and `call-result` only to a client activity; under the same key, a value with the other tag is a miss, and the read stores its own value in its place. A key therefore belongs to one query and one terminal method: an ORM call served another method's result under a shared key fails with `ORM.INTERCEPTED_RESULT_INVALID` or returns the wrong shape.\n*\n* - `intercept.onQuery` and `intercept.onActivity` — on a hit, return the stored rows or result,\n* and nothing runs. On a miss, record the pending entry.\n* - `onRow` — collects each row of a statement miss.\n* - `activityEnded` — when the driver completed the statement, or the client ended the call\n* `succeeded` with a result (`null` is a result), calls `store.set(entry, value)` with the entry\n* `store.get` returned, which stores only if the key's version has not moved. If an `unset` moved\n* it meanwhile, `set` returns `false` and the middleware logs `middleware.cache.store-skipped`.\n*\n* @example\n* ```typescript\n* const cache = createCacheMiddleware();\n* const db = postgres({ contract, url, middleware: [cache] });\n*\n* const user = await db.orm.public.User.first(\n* { id: 1 },\n* (meta) => meta.annotate(cacheAnnotation({ key: 'user-1' })),\n* );\n* await db.orm.public.User.where({ id: 1 }).update({ name: 'Alicia' });\n* await cache.invalidate({ keys: ['user-1'] });\n* ```\n*/\nfunction createCacheMiddleware(options) {\n\tconst store = options?.store ?? createInMemoryCacheStore();\n\tconst deriveKey = options?.deriveKey ?? deriveKeyFromContentHash;\n\tasync function lookUp(tag, key, meta, ctx, buffer) {\n\t\tconst entry = await store.get({\n\t\t\tkey,\n\t\t\tmeta\n\t\t});\n\t\tif (!entry.data.empty && hasTag(entry.data.value, tag)) {\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 entry.data.value;\n\t\t}\n\t\tctx.state(pendingMiss)[\"miss\"] = {\n\t\t\tentry,\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 onQuery(exec, ctx) {\n\t\tif (!cacheable(ctx)) return;\n\t\tconst annotation = cacheAnnotation.read(exec);\n\t\tif (annotation === void 0 || annotation.bypass === true) return;\n\t\tconst value = await lookUp(\"statement-rows\", annotation.key ?? await deriveKey(exec, ctx), annotation.meta, ctx, []);\n\t\treturn value === void 0 ? void 0 : { rows: value.rows };\n\t}\n\tasync function onActivity(activity, ctx) {\n\t\tif (!cacheable(ctx)) return;\n\t\tconst annotation = cacheAnnotation.read(activity);\n\t\tif (annotation === void 0 || annotation.bypass === true) return;\n\t\tconst value = await lookUp(\"call-result\", annotation.key ?? await activity.contentHash(), annotation.meta, ctx, void 0);\n\t\treturn value === void 0 ? void 0 : { result: value.result };\n\t}\n\tasync function onRow(row, _exec, ctx) {\n\t\tpendingOf(ctx)?.buffer?.push(row);\n\t}\n\tasync function activityEnded(_activity, result, ctx) {\n\t\tconst miss = pendingOf(ctx);\n\t\tif (miss === void 0) return;\n\t\tdelete ctx.state(pendingMiss)[\"miss\"];\n\t\tconst value = valueToStore(miss, result);\n\t\tif (value === void 0) return;\n\t\tconst stored = await store.set(miss.entry, value);\n\t\tctx.log.debug?.({\n\t\t\tevent: stored ? \"middleware.cache.store\" : \"middleware.cache.store-skipped\",\n\t\t\tmiddleware: \"cache\",\n\t\t\tkey: miss.entry.key\n\t\t});\n\t}\n\tasync function invalidate(target) {\n\t\tconst keys = target.keys !== void 0 && target.keys.length > 0 ? target.keys : void 0;\n\t\tif (keys === void 0 && target.meta === void 0) return;\n\t\tawait store.unset({\n\t\t\tkeys,\n\t\t\tmeta: target.meta\n\t\t});\n\t}\n\treturn {\n\t\tname: \"cache\",\n\t\tintercept: {\n\t\t\tonQuery,\n\t\t\tonActivity\n\t\t},\n\t\tonRow,\n\t\tactivityEnded,\n\t\tinvalidate\n\t};\n}\n//#endregion\nexport { cacheAnnotation, createCacheMiddleware, createInMemoryCacheStore, deriveKeyFromContentHash };\n\n//# sourceMappingURL=index.mjs.map"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAM,kBAAkB,cAAc,iBAAiB,CAAC,CAAC;CACxD,WAAW;CACX,cAAc,CAAC,MAAM;AACtB,CAAC,CAAC;AACF,SAAS,cAAc,QAAQ;CAC9B,SAAS,wBAAwB,SAAS;EACzC,OAAO,OAAO,OAAO;CACtB;CACA,OAAO,OAAO,OAAO,OAAO,OAAO,yBAAyB;EAC3D,WAAW,OAAO;EAClB,cAAc,OAAO;EACrB,MAAM,OAAO;CACd,CAAC,CAAC;AACH;AAGA,MAAM,kBAAkB,QAAQ,IAAI,OAAO,eAAe,WAAW,SAAS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A,eAAe,cAAc,WAAW,QAAQ,KAAK;EACpD,MAAM,OAAO,UAAU,GAAG;EAC1B,IAAI,SAAS,KAAK,GAAG;EACrB,OAAO,IAAI,MAAM,WAAW,CAAC,CAAC;EAC9B,MAAM,QAAQ,aAAa,MAAM,MAAM;EACvC,IAAI,UAAU,KAAK,GAAG;EACtB,MAAM,SAAS,MAAM,MAAM,IAAI,KAAK,OAAO,KAAK;EAChD,IAAI,IAAI,QAAQ;GACf,OAAO,SAAS,2BAA2B;GAC3C,YAAY;GACZ,KAAK,KAAK,MAAM;EACjB,CAAC;CACF;CACA,eAAe,WAAW,QAAQ;EACjC,MAAM,OAAO,OAAO,SAAS,KAAK,KAAK,OAAO,KAAK,SAAS,IAAI,OAAO,OAAO,KAAK;EACnF,IAAI,SAAS,KAAK,KAAK,OAAO,SAAS,KAAK,GAAG;EAC/C,MAAM,MAAM,MAAM;GACjB;GACA,MAAM,OAAO;EACd,CAAC;CACF;CACA,OAAO;EACN,MAAM;EACN,WAAW;GACV;GACA;EACD;EACA;EACA;EACA;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../3-extensions/middleware-cache/dist/index.mjs"],"sourcesContent":["import { defineAnnotation } from \"@internal/framework-components/runtime\";\nimport { blindCast } from \"@internal/utils/casts\";\nimport { structuredError } from \"@internal/utils/structured-error\";\n//#region src/cache-annotation.ts\n/**\n* Marks a read for the cache middleware. It applies to reads only: a write terminal refuses it at\n* compile time and at run time. The middleware reads it from a statement plan's `meta.annotations.cache`, or from the annotations of a client activity, such as an ORM read, which is then cached as a whole.\n*\n* `TMeta` types `meta` for this call only. Nothing ties it to the store's `TMeta`, so a store\n* package should export a wrapper typed with its own meta, such as\n* `(o: CacheAnnotationOptions<TagMeta>) => cacheAnnotation<TagMeta>(o)`.\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.orm.public.User.first(\n* { id },\n* (meta) => meta.annotate(cacheAnnotation({ key: `user-${id}` })),\n* );\n*\n* // SQL DSL select builder — chainable.\n* const plan = db.sql\n* .from(tables.user)\n* .annotate(cacheAnnotation({}))\n* .select({ id: tables.user.columns.id })\n* .build();\n* ```\n*/\nconst cacheAnnotation = withTypedMeta(defineAnnotation()({\n\tnamespace: \"cache\",\n\tapplicableTo: [\"read\"]\n}));\nfunction withTypedMeta(handle) {\n\tfunction cacheAnnotationWithMeta(options) {\n\t\treturn handle(options);\n\t}\n\treturn Object.freeze(Object.assign(cacheAnnotationWithMeta, {\n\t\tnamespace: handle.namespace,\n\t\tapplicableTo: handle.applicableTo,\n\t\tread: handle.read\n\t}));\n}\n/**\n* Marks a write whose cache entries the cache middleware invalidates once the write's effects are final: right after the write outside a transaction, or when the outermost enclosing transaction ends. It does not invalidate when the write is rolled back, and does when the outcome is unknown. It applies to writes only: a read terminal refuses it at compile time and at run time.\n*\n* `TMeta` types `meta` for this call only. Nothing ties it to the store's `TMeta`, so a store package should export a wrapper typed with its own meta, such as `(o: InvalidationTarget<TagMeta>) => invalidateAnnotation<TagMeta>(o)`.\n*\n* @example\n* ```typescript\n* await db.orm.public.User.where({ id: 1 }).update({ name: 'Alicia' }, (meta) =>\n* meta.annotate(invalidateAnnotation({ keys: ['user-1'] })),\n* );\n* ```\n*/\nconst invalidateAnnotation = withTypedInvalidateMeta(defineAnnotation()({\n\tnamespace: \"cache-invalidate\",\n\tapplicableTo: [\"write\"]\n}));\nfunction withTypedInvalidateMeta(handle) {\n\tfunction invalidateAnnotationWithMeta(options) {\n\t\treturn handle(options);\n\t}\n\treturn Object.freeze(Object.assign(invalidateAnnotationWithMeta, {\n\t\tnamespace: handle.namespace,\n\t\tapplicableTo: handle.applicableTo,\n\t\tread: handle.read\n\t}));\n}\n//#endregion\n//#region src/cache-store.ts\nconst typedArraySlice = Reflect.get(Object.getPrototypeOf(Uint8Array.prototype), \"slice\");\n/**\n* A copy of the plain structure of `value`: plain and null-prototype objects, arrays, `Map`, `Set`,\n* `Date`, `RegExp`, `ArrayBuffer`, typed arrays and `DataView` are copied, and every other value,\n* such as a class instance or a function, is kept by reference. A typed array is copied with\n* `TypedArray.prototype.slice`, which keeps its class, so a `Buffer` copies to a `Buffer` with its\n* own memory; a `DataView` copies to a plain `DataView`; an array copies to its elements only, with\n* holes read as `undefined`. Shared references and cycles are kept.\n*/\nfunction copyValue(value, copies = /* @__PURE__ */ new Map()) {\n\tif (typeof value !== \"object\" || value === null) return value;\n\tconst known = copies.get(value);\n\tif (known !== void 0) return blindCast(known);\n\tconst copy = copyObject(value, copies);\n\tcopies.set(value, copy);\n\treturn blindCast(copy);\n}\nfunction copyObject(value, copies) {\n\tif (value instanceof DataView) {\n\t\tconst start = value.byteOffset;\n\t\treturn new DataView(value.buffer.slice(start, start + value.byteLength));\n\t}\n\tif (ArrayBuffer.isView(value)) return typedArraySlice.call(value);\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (prototype === ArrayBuffer.prototype && value instanceof ArrayBuffer) return value.slice(0);\n\tif (prototype === Date.prototype && value instanceof Date) return new Date(value.getTime());\n\tif (prototype === RegExp.prototype && value instanceof RegExp) return new RegExp(value.source, value.flags);\n\tif (prototype === Map.prototype && value instanceof Map) {\n\t\tconst copy = /* @__PURE__ */ new Map();\n\t\tcopies.set(value, copy);\n\t\tfor (const [key, entry] of value) copy.set(copyValue(key, copies), copyValue(entry, copies));\n\t\treturn copy;\n\t}\n\tif (prototype === Set.prototype && value instanceof Set) {\n\t\tconst copy = /* @__PURE__ */ new Set();\n\t\tcopies.set(value, copy);\n\t\tfor (const entry of value) copy.add(copyValue(entry, copies));\n\t\treturn copy;\n\t}\n\tif (prototype === Array.prototype && Array.isArray(value)) {\n\t\tconst copy = [];\n\t\tcopies.set(value, copy);\n\t\tfor (const entry of value) copy.push(copyValue(entry, copies));\n\t\treturn copy;\n\t}\n\tif (prototype !== Object.prototype && prototype !== null) return value;\n\tconst copy = Object.create(prototype);\n\tcopies.set(value, copy);\n\tfor (const key of Reflect.ownKeys(value)) if (Object.prototype.propertyIsEnumerable.call(value, key)) copy[key] = copyValue(Reflect.get(value, key), copies);\n\treturn copy;\n}\n/** Statement rows hold driver values, such as BSON `ObjectId`s, that this package cannot copy. So the array and each row object are copied, each row keeping its prototype, and the driver's values are kept by reference and shared with every hit. */\nfunction copyRows(rows) {\n\treturn rows.map((row) => {\n\t\tconst copy = Object.create(Object.getPrototypeOf(row));\n\t\treturn Object.assign(copy, row);\n\t});\n}\nfunction copyStored(value) {\n\tswitch (value.kind) {\n\t\tcase \"statement-rows\": return {\n\t\t\tkind: \"statement-rows\",\n\t\t\trows: copyRows(value.rows)\n\t\t};\n\t\tcase \"call-result\": return {\n\t\t\tkind: \"call-result\",\n\t\t\tresult: copyValue(value.result)\n\t\t};\n\t}\n}\nfunction metaUnsupported() {\n\treturn structuredError(\"RUNTIME.CACHE_STORE_META_UNSUPPORTED\", \"The in-memory cache store cannot remove entries by meta because it does not index meta, so it removed nothing, not even the keys passed with it\", { fix: \"Use a CacheStore that indexes meta in set and unset, or pass only keys.\" });\n}\nfunction invalidOption(argument, received, expected) {\n\treturn structuredError(\"RUNTIME.ARGUMENT_INVALID\", `createInMemoryCacheStore: ${argument} must be ${expected}`, {\n\t\tfix: `Pass ${argument} as ${expected}, or leave it unset for the default.`,\n\t\tmeta: {\n\t\t\thelper: \"createInMemoryCacheStore\",\n\t\t\targument,\n\t\t\treceived\n\t\t}\n\t});\n}\n/**\n* The default cache store: a least-recently-used map of `CachedValue` with one lifetime for every value, local to the process. Statement rows are copied one level deep on `set` and `get`: the array, and each row object with its prototype. The driver's values in them are kept by reference and shared with every hit; the runtime decodes them on each hit, and a codec that returns its wire value unchanged, such as a date or byte-array codec, hands that shared object to the caller. A call result has its plain structure copied on `set` and on every `get`: plain and null-prototype objects, arrays (their elements only; holes read as `undefined`), `Map`, `Set`, `Date`, `RegExp`, `ArrayBuffer`, typed arrays (a subclass such as Node's `Buffer` keeps its class) and `DataView` (copied as a plain `DataView`). Every other value in it, such as a class instance (a Temporal value, a BSON value, an error) or a function, is shared by reference. So after `set` returns, a change to the plain structure of the value `set` was given, or of a value `get` returned, reaches no later `get`; a change made to a shared value, or made before `set`, does. It never refuses a value: `set` returns `false` only when the version moved. A key's version is kept for `ttlMs` after the `unset` that moved it (see `InMemoryCacheStoreOptions`). It ignores `meta` in `get` and `set`, and its `unset` rejects any `meta`, including `null`, before changing anything. It throws `RUNTIME.ARGUMENT_INVALID` for a `maxEntries` or `ttlMs` outside the ranges above.\n*/\nfunction createInMemoryCacheStore(options) {\n\tconst maxEntries = options?.maxEntries ?? 1e3;\n\tconst ttlMs = options?.ttlMs ?? 6e4;\n\tconst clock = options?.clock ?? Date.now;\n\tif (!Number.isInteger(maxEntries) || maxEntries <= 0) throw invalidOption(\"maxEntries\", maxEntries, \"a positive integer\");\n\tif (!(ttlMs > 0)) throw invalidOption(\"ttlMs\", ttlMs, \"a positive number of milliseconds, or Infinity\");\n\tconst records = /* @__PURE__ */ new Map();\n\tconst versions = /* @__PURE__ */ new Map();\n\tfunction forgetExpiredVersions() {\n\t\tconst now = clock();\n\t\tfor (const [key, record] of versions) {\n\t\t\tif (now < record.expiresAt) return;\n\t\t\tversions.delete(key);\n\t\t}\n\t}\n\tfunction versionOf(key) {\n\t\tforgetExpiredVersions();\n\t\treturn versions.get(key)?.version ?? 0;\n\t}\n\tfunction liveRecord(key) {\n\t\tconst record = records.get(key);\n\t\tif (record === void 0) return;\n\t\trecords.delete(key);\n\t\tif (clock() >= record.expiresAt) return;\n\t\trecords.set(key, record);\n\t\treturn record;\n\t}\n\tasync function get(target) {\n\t\tconst record = liveRecord(target.key);\n\t\treturn {\n\t\t\tkey: target.key,\n\t\t\tmeta: target.meta,\n\t\t\tversion: versionOf(target.key),\n\t\t\tdata: record === void 0 ? { empty: true } : {\n\t\t\t\tempty: false,\n\t\t\t\tvalue: copyStored(record.value)\n\t\t\t}\n\t\t};\n\t}\n\tasync function set(entry, value) {\n\t\tif (entry.version !== versionOf(entry.key)) return false;\n\t\trecords.delete(entry.key);\n\t\trecords.set(entry.key, {\n\t\t\tvalue: copyStored(value),\n\t\t\texpiresAt: clock() + ttlMs\n\t\t});\n\t\tfor (const leastRecentlyUsed of records.keys()) {\n\t\t\tif (records.size <= maxEntries) break;\n\t\t\trecords.delete(leastRecentlyUsed);\n\t\t}\n\t\treturn true;\n\t}\n\tasync function unset(target) {\n\t\tif (target.meta !== void 0) throw metaUnsupported();\n\t\tfor (const key of target.keys ?? []) {\n\t\t\trecords.delete(key);\n\t\t\tconst version = versionOf(key) + 1;\n\t\t\tversions.delete(key);\n\t\t\tversions.set(key, {\n\t\t\t\tversion,\n\t\t\t\texpiresAt: clock() + ttlMs\n\t\t\t});\n\t\t}\n\t}\n\treturn {\n\t\tget,\n\t\tset,\n\t\tunset\n\t};\n}\n//#endregion\n//#region src/cache-middleware.ts\n/**\n* The default `deriveKey`: the family runtime's content hash of the plan, which covers the\n* statement, its parameters and the storage hash.\n*/\nfunction deriveKeyFromContentHash(exec, ctx) {\n\treturn ctx.contentHash(exec);\n}\nconst pendingMiss = Symbol(\"cache.pendingMiss\");\nfunction pendingOf(ctx) {\n\tconst miss = ctx.state(pendingMiss)[\"miss\"];\n\treturn isPendingMiss(miss) ? miss : void 0;\n}\nfunction isPendingMiss(value) {\n\treturn typeof value === \"object\" && value !== null && \"entry\" in value && \"buffer\" in value;\n}\nfunction hasTag(value, tag) {\n\treturn value.kind === tag;\n}\nfunction cacheable(ctx) {\n\treturn ctx.scope === \"runtime\" && !ctx.inTransaction();\n}\n/** The value a pending miss stores when its activity ends this way, or `undefined` to store nothing. */\nfunction valueToStore(miss, result) {\n\tif (result.outcome !== \"succeeded\") return void 0;\n\tif (result.kind === \"statement\") return result.source === \"driver\" && miss.buffer !== void 0 ? {\n\t\tkind: \"statement-rows\",\n\t\trows: miss.buffer\n\t} : void 0;\n\tif (result.kind === \"transaction\") return void 0;\n\treturn result.source === \"client\" && result.result !== void 0 ? {\n\t\tkind: \"call-result\",\n\t\tresult: result.result\n\t} : void 0;\n}\n/**\n* Creates a read-through cache middleware that works with every family runtime. It also invalidates entries for writes annotated with `invalidateAnnotation`.\n*\n* It caches an activity that carries `cacheAnnotation` without `bypass` and runs in runtime scope,\n* outside any transaction: never on a held connection, whose session may change what a read\n* returns, and never inside a transaction, which must read its own uncommitted writes. Two kinds\n* of activity are cached:\n*\n* - A statement whose plan carries the annotation, such as an annotated SQL builder query. Its key\n* is the annotation's `key`, else `deriveKey(exec, ctx)`; its value is the raw rows.\n* - A client activity that carries the annotation, such as an annotated ORM read. Its key is the\n* annotation's `key`, else `await activity.contentHash()`; its value is the result the client\n* ended the activity with. It is served as a whole, so a hit sends no statement.\n*\n* The middleware tags each stored value `statement-rows` or `call-result` and serves `statement-rows` only to a statement and `call-result` only to a client activity; under the same key, a value with the other tag is a miss, and the read stores its own value in its place. A key therefore belongs to one query and one terminal method: an ORM call served another method's result under a shared key fails with `ORM.INTERCEPTED_RESULT_INVALID` or returns the wrong shape.\n*\n* - `intercept.onQuery` and `intercept.onActivity` — on a hit, return the stored rows or result,\n* and nothing runs. On a miss, record the pending entry.\n* - `onRow` — collects each row of a statement miss.\n* - `activityEnded` — when the driver completed the statement, or the client ended the call\n* `succeeded` with a result (`null` is a result), calls `store.set(entry, value)` with the entry\n* `store.get` returned, which stores only if the key's version has not moved. If an `unset` moved\n* it meanwhile, `set` returns `false` and the middleware logs `middleware.cache.store-skipped`.\n* - `activityFinalized` — for any activity that carries `invalidateAnnotation`, whatever its kind or transaction, calls `invalidate` with the annotation's `keys` and `meta`, unless the outcome is `rolled-back`. An `unknown` outcome invalidates, since the write may have landed. A store error is thrown, and the runtime logs it.\n*\n* @example\n* ```typescript\n* const cache = createCacheMiddleware();\n* const db = postgres({ contract, url, middleware: [cache] });\n*\n* const user = await db.orm.public.User.first(\n* { id: 1 },\n* (meta) => meta.annotate(cacheAnnotation({ key: 'user-1' })),\n* );\n* await db.orm.public.User.where({ id: 1 }).update({ name: 'Alicia' }, (meta) =>\n* meta.annotate(invalidateAnnotation({ keys: ['user-1'] })),\n* );\n* ```\n*/\nfunction createCacheMiddleware(options) {\n\tconst store = options?.store ?? createInMemoryCacheStore();\n\tconst deriveKey = options?.deriveKey ?? deriveKeyFromContentHash;\n\tasync function lookUp(tag, key, meta, ctx, buffer) {\n\t\tconst entry = await store.get({\n\t\t\tkey,\n\t\t\tmeta\n\t\t});\n\t\tif (!entry.data.empty && hasTag(entry.data.value, tag)) {\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 entry.data.value;\n\t\t}\n\t\tctx.state(pendingMiss)[\"miss\"] = {\n\t\t\tentry,\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 onQuery(exec, ctx) {\n\t\tif (!cacheable(ctx)) return;\n\t\tconst annotation = cacheAnnotation.read(exec);\n\t\tif (annotation === void 0 || annotation.bypass === true) return;\n\t\tconst value = await lookUp(\"statement-rows\", annotation.key ?? await deriveKey(exec, ctx), annotation.meta, ctx, []);\n\t\treturn value === void 0 ? void 0 : { rows: value.rows };\n\t}\n\tasync function onActivity(activity, ctx) {\n\t\tif (!cacheable(ctx)) return;\n\t\tconst annotation = cacheAnnotation.read(activity);\n\t\tif (annotation === void 0 || annotation.bypass === true) return;\n\t\tconst value = await lookUp(\"call-result\", annotation.key ?? await activity.contentHash(), annotation.meta, ctx, void 0);\n\t\treturn value === void 0 ? void 0 : { result: value.result };\n\t}\n\tasync function onRow(row, _exec, ctx) {\n\t\tpendingOf(ctx)?.buffer?.push(row);\n\t}\n\tasync function activityEnded(_activity, result, ctx) {\n\t\tconst miss = pendingOf(ctx);\n\t\tif (miss === void 0) return;\n\t\tdelete ctx.state(pendingMiss)[\"miss\"];\n\t\tconst value = valueToStore(miss, result);\n\t\tif (value === void 0) return;\n\t\tconst stored = await store.set(miss.entry, value);\n\t\tctx.log.debug?.({\n\t\t\tevent: stored ? \"middleware.cache.store\" : \"middleware.cache.store-skipped\",\n\t\t\tmiddleware: \"cache\",\n\t\t\tkey: miss.entry.key\n\t\t});\n\t}\n\tasync function invalidate(target) {\n\t\tconst keys = target.keys !== void 0 && target.keys.length > 0 ? target.keys : void 0;\n\t\tif (keys === void 0 && target.meta === void 0) return;\n\t\tawait store.unset({\n\t\t\tkeys,\n\t\t\tmeta: target.meta\n\t\t});\n\t}\n\tasync function activityFinalized(activity, result) {\n\t\tif (result.outcome === \"rolled-back\") return;\n\t\tconst target = invalidateAnnotation.read(activity);\n\t\tif (target !== void 0) await invalidate(target);\n\t}\n\treturn {\n\t\tname: \"cache\",\n\t\tintercept: {\n\t\t\tonQuery,\n\t\t\tonActivity\n\t\t},\n\t\tonRow,\n\t\tactivityEnded,\n\t\tactivityFinalized,\n\t\tinvalidate\n\t};\n}\n//#endregion\nexport { cacheAnnotation, createCacheMiddleware, createInMemoryCacheStore, deriveKeyFromContentHash, invalidateAnnotation };\n\n//# sourceMappingURL=index.mjs.map"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAM,kBAAkB,cAAc,iBAAiB,CAAC,CAAC;CACxD,WAAW;CACX,cAAc,CAAC,MAAM;AACtB,CAAC,CAAC;AACF,SAAS,cAAc,QAAQ;CAC9B,SAAS,wBAAwB,SAAS;EACzC,OAAO,OAAO,OAAO;CACtB;CACA,OAAO,OAAO,OAAO,OAAO,OAAO,yBAAyB;EAC3D,WAAW,OAAO;EAClB,cAAc,OAAO;EACrB,MAAM,OAAO;CACd,CAAC,CAAC;AACH;;;;;;;;;;;;;AAaA,MAAM,uBAAuB,wBAAwB,iBAAiB,CAAC,CAAC;CACvE,WAAW;CACX,cAAc,CAAC,OAAO;AACvB,CAAC,CAAC;AACF,SAAS,wBAA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18-dev.29",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -9,12 +9,12 @@
|
|
|
9
9
|
"dist"
|
|
10
10
|
],
|
|
11
11
|
"dependencies": {
|
|
12
|
-
"@prisma/orm-framework": "8.0.0-rc.18-dev.
|
|
12
|
+
"@prisma/orm-framework": "8.0.0-rc.18-dev.29"
|
|
13
13
|
},
|
|
14
14
|
"devDependencies": {
|
|
15
|
-
"@internal/middleware-cache": "8.0.0-rc.18-dev.
|
|
16
|
-
"@repo/tsconfig": "8.0.0-rc.18-dev.
|
|
17
|
-
"@repo/tsdown": "8.0.0-rc.18-dev.
|
|
15
|
+
"@internal/middleware-cache": "8.0.0-rc.18-dev.29",
|
|
16
|
+
"@repo/tsconfig": "8.0.0-rc.18-dev.29",
|
|
17
|
+
"@repo/tsdown": "8.0.0-rc.18-dev.29",
|
|
18
18
|
"tsdown": "0.22.14",
|
|
19
19
|
"typescript": "5.9.3"
|
|
20
20
|
},
|