@grafctory/keep 0.0.0-stage → 0.14.2

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.
@@ -0,0 +1,226 @@
1
+ /*
2
+ * Copyright © 2025-2026 Metreeca srl
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { eager } from "@grafctory/blue/value";
17
+ import { error, isNumber, isString } from "@grafctory/core";
18
+ import { resolve } from "@grafctory/core/resource";
19
+ import { equals, immutable } from "@grafctory/core/values";
20
+ /**
21
+ * The form a value read off a state has to take to stand as a path segment: non-empty, with no delimiter or
22
+ * whitespace.
23
+ */
24
+ const SegmentFormat = /^[^\s/?#]+$/;
25
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
26
+ /**
27
+ * Creates a batching request {@link Broker}.
28
+ *
29
+ * Backs {@link createBatchingStore}: the broker queues each submitted request by type and serves the queues in rounds
30
+ * against the supplied handlers, running all four concurrently, until every queue is empty. Within a round, a queue
31
+ * is served as one handler call per plan and per chunk of at most the `limits` declared for its type, the calls
32
+ * running concurrently, at most the `burst` the limits declare at once; see {@link Handler} for the plan each
33
+ * request type shares. Requests issued mid-round, whether forwarded by a handler or freshly submitted, are served
34
+ * in a later round, so a handler must not assume any ordering between its own run and that of another handler.
35
+ *
36
+ * A handler throw fails the whole run: every pending {@link Deferred} is rejected with the originating error, so
37
+ * callers see a deterministic failure rather than a hang.
38
+ *
39
+ * @param handlers The batch handlers, one per request type. Each settles every {@link Deferred} in
40
+ * its batch and may issue nested {@link Broker.detail} / {@link Broker.select} calls while
41
+ * processing; its returned promise must settle only after every owned request, including
42
+ * transitively nested ones, has settled.
43
+ * @param limits The most requests a handler receives in one call, per request type, and the most calls in flight
44
+ *
45
+ * @returns An immutable {@link Broker} surface for enqueuing requests and receiving their
46
+ * materialised results; each call returns a promise that settles when the relevant batch
47
+ * completes
48
+ */
49
+ export function createBroker(handlers, limits = {}) {
50
+ const admit = gate(limits.burst);
51
+ const queues = {
52
+ detect: queue(handlers.detect, () => true, limits.detect),
53
+ detail: queue(handlers.detail, (x, y) => x.shape === y.shape
54
+ && equals(x.model, y.model)
55
+ && equals(x.locale, y.locale), limits.detail),
56
+ select: queue(handlers.select, (x, y) => x.field === y.field && equals(x.query, y.query)
57
+ && equals(x.locale, y.locale)
58
+ && (x.virtual ?? false) === (y.virtual ?? false), limits.select),
59
+ modify: queue(handlers.modify, () => true, limits.modify)
60
+ };
61
+ // Inner surface handed to the handlers: nested calls enqueue without kicking a drain.
62
+ const broker = immutable({
63
+ detect(request) {
64
+ return new Promise((resolve, reject) => queues.detect.items.push({ request, resolve, reject }));
65
+ },
66
+ detail(request) {
67
+ return new Promise((resolve, reject) => queues.detail.items.push({
68
+ request,
69
+ resolve: resolve, // ;(cast) Match<S, T> by handler contract
70
+ reject
71
+ }));
72
+ },
73
+ select(request) {
74
+ return new Promise((resolve, reject) => queues.select.items.push({ request, resolve, reject }));
75
+ },
76
+ modify(request) {
77
+ return new Promise((resolve, reject) => queues.modify.items.push({ request, resolve, reject }));
78
+ }
79
+ });
80
+ // Public surface: every call enqueues through the inner broker and kicks a drain via `process`.
81
+ return immutable({
82
+ detect(request) {
83
+ return process(() => broker.detect(request));
84
+ },
85
+ detail(request) {
86
+ return process(() => broker.detail(request));
87
+ },
88
+ select(request) {
89
+ return process(() => broker.select(request));
90
+ },
91
+ modify(request) {
92
+ return process(() => broker.modify(request));
93
+ }
94
+ });
95
+ // Kicks a drain only when every queue is idle: a running drain keeps its snapshots queued until the
96
+ // step that re-checks the queues, so "all empty" means "no drain in flight". The kick is a microtask,
97
+ // so a synchronous burst of submissions coalesces into one drain. The check runs before `submit`
98
+ // enqueues, or it would always see the request it just pushed.
99
+ function process(submit) {
100
+ if (Object.values(queues).every(queue => queue.items.length === 0)) {
101
+ Promise.resolve().then(async () => {
102
+ // Drain in rounds until every queue is quiescent, all four handlers concurrently per
103
+ // round. Every snapshot stays queued across the `await` and is removed in the same
104
+ // synchronous step as the next idle check, so no submission can ever find the queues empty
105
+ // while the loop is alive; anything pushed mid-round is served next round. A throw leaves
106
+ // the snapshots queued to purge.
107
+ try {
108
+ while (Object.values(queues).some(queue => queue.items.length > 0)) {
109
+ const rounds = Object.values(queues).map(queue => queue.round());
110
+ await Promise.all(rounds.map(round => round.done));
111
+ rounds.forEach(round => round.settle());
112
+ }
113
+ }
114
+ catch (error) {
115
+ // A handler throw poisons the run: purge every queue so pending callers reject
116
+ // instead of hanging; already-settled entries no-op.
117
+ Object.values(queues).forEach(queue => queue.purge(error));
118
+ }
119
+ });
120
+ }
121
+ return submit();
122
+ }
123
+ /**
124
+ * Admits a handler call through the burst gate: at most `limit` calls run at once, a call past the limit starting
125
+ * as soon as an admitted one settles, in admission order; with no limit every call starts at once. An admitted call
126
+ * starts synchronously, so a queue served after another one still snapshots what that one's handlers submitted.
127
+ */
128
+ function gate(limit) {
129
+ if (limit === undefined) {
130
+ return call => call();
131
+ }
132
+ else {
133
+ // the admitted count and the waiting line are the gate's state, updated in place: a gate is a
134
+ // counter by nature, and threading it through every call's promise chain would obscure the one
135
+ // rule it enforces, admission in order (sw-developer:code, genuine state machine)
136
+ const waiting = [];
137
+ let admitted = 0;
138
+ return call => new Promise((resolve, reject) => {
139
+ const start = () => {
140
+ admitted++;
141
+ call().then(resolve, reject).finally(() => {
142
+ admitted--;
143
+ waiting.shift()?.();
144
+ });
145
+ };
146
+ if (admitted < limit) {
147
+ start();
148
+ }
149
+ else {
150
+ waiting.push(start);
151
+ }
152
+ });
153
+ }
154
+ }
155
+ /**
156
+ * The queue of one request type: its pending requests, and the round serving them through `handler` as one
157
+ * call per plan, `alike` telling the requests sharing a plan, and per chunk of at most `limit` requests.
158
+ */
159
+ function queue(handler, alike, limit) {
160
+ const items = [];
161
+ return {
162
+ items,
163
+ // snapshots the queued requests and hands them to the handler, keeping them queued until the round
164
+ // is settled by the drain loop, which removes exactly the snapshot in the same step it re-checks the
165
+ // queues: a queue emptied any earlier would let a submission landing in between kick a second drain
166
+ // over the same snapshot, whose own removal would then drop whatever was queued behind it
167
+ round: () => {
168
+ const batch = items.slice();
169
+ return {
170
+ done: Promise.all(batches(batch).map(call => admit(() => handler(call, broker)))).then(() => undefined),
171
+ settle: () => { items.splice(0, batch.length); }
172
+ };
173
+ },
174
+ purge: error => {
175
+ items.forEach(deferred => deferred.reject(error));
176
+ items.length = 0;
177
+ }
178
+ };
179
+ /**
180
+ * The handler calls serving a batch: one per plan, in order of first request, each split into chunks of at
181
+ * most `limit` requests in submission order, or left whole where the request type declares no limit.
182
+ */
183
+ function batches(batch) {
184
+ const groups = batch.reduce((groups, item) => {
185
+ const group = groups.find(([first]) => alike(first.request, item.request));
186
+ return group === undefined ? [...groups, [item]]
187
+ : groups.map(candidate => candidate === group ? [...group, item] : candidate);
188
+ }, []);
189
+ return groups.flatMap(group => limit === undefined ? [group]
190
+ : Array.from({ length: Math.ceil(group.length / limit) }, (_, index) => group.slice(index * limit, (index + 1) * limit)));
191
+ }
192
+ }
193
+ }
194
+ /**
195
+ * Mints the identifier of a resource created under a collection.
196
+ *
197
+ * Returns an identifier nested under `entry`, matching the identifier {@link ResourceShape.pattern | pattern} declared
198
+ * by the shape, if any. Each `{name}` slot is filled with the like-named member of `state`, or with an opaque segment
199
+ * if the state has no such member. A trailing `/*` slot is always filled with an opaque segment. A root-relative
200
+ * pattern is resolved against `entry`. If the shape declares no pattern, the identifier is an opaque segment under
201
+ * `entry`.
202
+ *
203
+ * @param entry The absolute identifier of the resource collecting the new one
204
+ * @param shape The shape describing the new resource, possibly deferred to break definition cycles
205
+ * @param state The initial state of the new resource
206
+ *
207
+ * @returns The absolute identifier of the new resource
208
+ *
209
+ * @throws {@link !RangeError RangeError} If a member filling a slot is not a single non-empty path segment
210
+ */
211
+ export function mint(entry, shape, state) {
212
+ const { pattern } = eager(shape);
213
+ return pattern === undefined
214
+ ? resolve(entry.endsWith("/") ? entry : `${entry}/`, crypto.randomUUID())
215
+ : resolve(entry, pattern.replace(/\{(\w*)}|(?<=\/)\*$/g, (_, name) => name === undefined ? crypto.randomUUID() : segment(name)));
216
+ /**
217
+ * Reads a pattern slot off the like-named member of the state, or fills it with an opaque segment.
218
+ */
219
+ function segment(name) {
220
+ const value = state[name];
221
+ return value === undefined ? crypto.randomUUID()
222
+ : (isString(value) || isNumber(value)) && SegmentFormat.test(String(value)) ? String(value)
223
+ : error(new RangeError(`illegal identifier segment <${String(value)}> for slot <${name}>`));
224
+ }
225
+ }
226
+ //# sourceMappingURL=batching.core.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batching.core.js","sourceRoot":"","sources":["../../src/clients/batching.core.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE,KAAK,EAAc,MAAM,uBAAuB,CAAC;AAC1D,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAa,MAAM,iBAAiB,CAAC;AACvE,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AACnD,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAM3D;;;GAGG;AACH,MAAM,aAAa,GAAG,aAAa,CAAC;AAGpC,wHAAwH;AAExH;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,UAAU,YAAY,CAAC,QAO5B,EAAE,SAAiB,EAAE;IAErB,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAEjC,MAAM,MAAM,GAAG;QAEd,MAAM,EAAE,KAAK,CACZ,QAAQ,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,CAAC,KAAK,CAAC;gBAC1F,CAAC,CAAC,KAAK,CAAC,IAAI,UAAU,CAAC,+BAA+B,MAAM,CAAC,KAAK,CAAC,eAAe,IAAI,GAAG,CAAC,CAAC,CAAC;IAE/F,CAAC;AAEF,CAAC"}
@@ -0,0 +1,286 @@
1
+ /**
2
+ * Batching store client.
3
+ *
4
+ * Lets a connector serve many concurrent store requests with few backend round-trips. Requests of the same kind are
5
+ * coalesced into a single batch, and the connector supplies one batch {@link Handler} per kind. The resulting
6
+ * {@link StoreClient} adds conditional CRUD semantics on top, so handlers apply each request unconditionally.
7
+ *
8
+ * Four request kinds partition the work, each with its own handler:
9
+ *
10
+ * - **`detect`** — probes whether each {@link Detect} entry exists in the store
11
+ * - **`detail`** — materialises each {@link Detail} resource against its `model`; multi-valued members reached
12
+ * by the model may be handed to the `select` handler through {@link Broker.select}
13
+ * - **`select`** — materialises each {@link Select} collection against its `query`; element resources reached
14
+ * by the query may be handed to the `detail` handler through {@link Broker.detail}
15
+ * - **`modify`** — creates, updates, or deletes each {@link Modify} target, or links it to a collection
16
+ *
17
+ * Retrieval is driven by the requested `model` and `query`, not by the stored graph. A `detail` handler issues a
18
+ * `select` for each multi-valued member its model reaches, and a `select` handler issues a `detail` for each element
19
+ * resource its query reaches. Each request thus descends exactly as deep as its `model` or `query` nests, however
20
+ * deep the underlying graph runs.
21
+ *
22
+ * A connector may declare {@link Limits | caps} matching its backend: the most requests one handler call receives,
23
+ * and the most handler calls in flight at once. A larger accumulation then runs as several smaller batches.
24
+ *
25
+ * > [!IMPORTANT]
26
+ * > Handlers run concurrently and exchange nested requests through the {@link Broker}. A handler must not assume any
27
+ * > ordering between handlers, and must await every nested request it issues before settling the request that
28
+ * > depends on it.
29
+ *
30
+ * @module
31
+ */
32
+ import type { Property, ResourceShape } from "@grafctory/blue/resource";
33
+ import { type Match } from "@grafctory/blue/value";
34
+ import { type Lazy } from "@grafctory/core";
35
+ import type { Tag } from "@grafctory/core/language";
36
+ import type { Query, Slot, Template } from "@grafctory/qest/model";
37
+ import type { Reference, Resource, Value } from "@grafctory/qest/state";
38
+ import type { StoreClient } from "../index.js";
39
+ /**
40
+ * Requests accepted by {@link Broker}.
41
+ */
42
+ export type Request = Detect | Detail | Select | Modify;
43
+ /**
44
+ * Result of running a {@link Request}, narrowed by request variant:
45
+ *
46
+ * - a {@link Detect} resolves to a `boolean` existence flag
47
+ * - a {@link Detail} resolves to the materialised resource, typed by its shape and model
48
+ * - a {@link Select} resolves to the {@link Value | values} its collection holds, untyped since its shape is
49
+ * carried as a value rather than as a type parameter
50
+ * - a {@link Modify} resolves to its mutated entry's {@link Reference}
51
+ *
52
+ * @typeParam R The request whose result type is selected
53
+ */
54
+ export type Response<R extends Request> = R extends Select ? readonly Value[] : R extends Detail<infer T, infer S> ? Match<S, T> : R extends Modify ? Reference : R extends Detect ? boolean : never;
55
+ /**
56
+ * Resource existence request.
57
+ *
58
+ * Carries the `entry` to probe, and resolves to whether that entry exists in the store.
59
+ */
60
+ export type Detect = {
61
+ readonly entry: Reference;
62
+ };
63
+ /**
64
+ * Resource retrieval request.
65
+ *
66
+ * Carries a single resource (`entry` of `shape`), the `model` to materialise it against, and the `locale` priority
67
+ * for coalescing its localised content (QEST §6.2). Resolves to the materialised resource.
68
+ *
69
+ * A `virtual` request materialises a resource derived from the store rather than held in it, and resolves even if
70
+ * `entry` is not stored. Its single-valued members come from whatever `entry` holds. Each multi-valued member the
71
+ * model reaches is retrieved as a `virtual` {@link Select}, while expanded resources are retrieved as held.
72
+ *
73
+ * @typeParam T The resource model selecting the members of the result
74
+ * @typeParam S The shape describing the resource
75
+ */
76
+ export type Detail<T extends Template = Template, S extends Lazy<ResourceShape> = Lazy<ResourceShape>> = {
77
+ /**
78
+ * Whether the resource is derived from the store rather than held in it.
79
+ *
80
+ * @defaultValue `false` (held as it stands)
81
+ */
82
+ readonly virtual?: boolean;
83
+ readonly entry: Reference;
84
+ readonly shape: S;
85
+ readonly model: T;
86
+ readonly locale: readonly Tag[];
87
+ };
88
+ /**
89
+ * Collection retrieval request.
90
+ *
91
+ * Carries a single multi-valued property (`field` on `entry` of `shape`), the `query` describing its values, and the
92
+ * `locale` priority for coalescing its localised content (QEST §6.2). Resolves to the materialised collection: items
93
+ * for a template query, rows for a projection.
94
+ *
95
+ * A `virtual` request materialises the collection from every stored instance of the classes the range of `field`
96
+ * declares, rather than from the resources `entry` links to. The `query` applies to them as to a held collection.
97
+ *
98
+ * @typeParam T The collection query selecting the form of the result
99
+ */
100
+ export type Select<T extends Query<Slot> = Query<Slot>> = {
101
+ /**
102
+ * Whether the collection is derived from the store rather than held in it.
103
+ *
104
+ * @defaultValue `false` (held as it stands)
105
+ */
106
+ readonly virtual?: boolean;
107
+ readonly entry: Reference;
108
+ readonly shape: Lazy<ResourceShape>;
109
+ readonly field: Property;
110
+ readonly query: T;
111
+ readonly locale: readonly Tag[];
112
+ };
113
+ /**
114
+ * Resource mutation request.
115
+ *
116
+ * Carries the `entry` to mutate (of `shape`) and the target `state` to persist. A present `state` creates or updates
117
+ * the entry, and an omitted `state` deletes it. A request carrying a `link` instead adds `item` to the collection
118
+ * held by `entry` under `property`, leaving the rest of the entry unchanged. Resolves to the {@link Reference} of the
119
+ * mutated entry.
120
+ */
121
+ export type Modify = {
122
+ readonly entry: Reference;
123
+ readonly shape: Lazy<ResourceShape>;
124
+ readonly state?: Resource;
125
+ readonly link?: {
126
+ readonly property: Property;
127
+ readonly item: Reference;
128
+ };
129
+ };
130
+ /**
131
+ * Batch handler for a single request type.
132
+ *
133
+ * Supplied by the connector to {@link createBatchingStore}, one per request type. A handler receives requests of its
134
+ * type accumulated since the previous batch, together with a {@link Broker} for issuing nested requests. It settles
135
+ * each {@link Deferred} in the batch with its result or error. The returned promise must resolve only once every
136
+ * request in the batch has settled, including any nested requests issued through the broker.
137
+ *
138
+ * Every batch shares one plan, so a handler reads the plan off any of its requests and never compares them. Every
139
+ * {@link Detail} in a batch names the same `shape`, a structurally equal `model` and an equal `locale`. Every
140
+ * {@link Select} names the same `field`, a structurally equal `query`, an equal `locale` and the same `virtual` flag.
141
+ * A detail batch may mix virtual and held requests, so a detail handler reads `virtual` off each request.
142
+ * {@link Detect} and {@link Modify} batches are not split by plan, and a modify batch keeps submission order. A batch
143
+ * is never empty and never holds more requests than the {@link Limits | limit} declared for its type.
144
+ *
145
+ * @typeParam R The request variant handled
146
+ */
147
+ export type Handler<R extends Request> = {
148
+ (batch: readonly Deferred<R>[], broker: Broker): Promise<void>;
149
+ };
150
+ /**
151
+ * The caps a connector declares on how its {@link Handler | handlers} are called.
152
+ *
153
+ * The caps keep a connector within what its backend accepts: no batch outgrows what the backend takes in one query,
154
+ * and no more handler calls run at once than the backend serves concurrently. An omitted cap sets no limit.
155
+ */
156
+ export type Limits = {
157
+ /**
158
+ * The most {@link Detect} requests one handler call receives; a larger accumulation runs as several batches.
159
+ */
160
+ readonly detect?: number;
161
+ /**
162
+ * The most {@link Detail} requests one handler call receives. A larger accumulation of one plan runs as several
163
+ * batches of that plan, so the cap bounds the entries a backend query has to read at once.
164
+ */
165
+ readonly detail?: number;
166
+ /**
167
+ * The most {@link Select} requests one handler call receives. A larger accumulation of one plan runs as several
168
+ * batches of that plan, so the cap bounds the owners a backend query has to read at once.
169
+ */
170
+ readonly select?: number;
171
+ /**
172
+ * The most {@link Modify} requests one handler call receives. A larger accumulation runs as several batches,
173
+ * which may run concurrently, so submission order holds only within each batch.
174
+ */
175
+ readonly modify?: number;
176
+ /**
177
+ * The most handler calls in flight at once, counted across all request types. A call beyond the cap starts as
178
+ * soon as one in flight settles, so a backend with a connection limit is never asked for more.
179
+ */
180
+ readonly burst?: number;
181
+ };
182
+ /**
183
+ * A queued request paired with its promise-resolution hooks.
184
+ *
185
+ * Each batch a {@link Handler} receives is an array of `Deferred` entries. For each entry, the handler reads the
186
+ * `request` and settles it, calling `resolve` with its result (typed by {@link Response | Response<R>}) or `reject`
187
+ * with an error.
188
+ *
189
+ * @typeParam R The queued request variant: a {@link Detect} probe, a {@link Detail} resource fetch,
190
+ * a {@link Select} collection fetch, or a {@link Modify} mutation
191
+ */
192
+ export type Deferred<R extends Request> = {
193
+ readonly request: R;
194
+ resolve(value: Response<R>): void;
195
+ reject(error: unknown): void;
196
+ };
197
+ /**
198
+ * Request-submission surface over the batching {@link Handler | handlers}.
199
+ *
200
+ * Routes each request (detection, detail, selection, modification) to the handler for its type. Each call queues the
201
+ * request for the next batch and returns a promise that settles with its result. Handlers receive a broker to hand
202
+ * nested work to a sibling handler.
203
+ */
204
+ export type Broker = {
205
+ /**
206
+ * Enqueue a {@link Detect} request.
207
+ *
208
+ * @param request The entry to probe
209
+ *
210
+ * @returns A promise resolving to `true` when the request's entry exists in the store; `false`
211
+ * otherwise
212
+ */
213
+ detect(request: Detect): Promise<boolean>;
214
+ /**
215
+ * Enqueue a {@link Detail} request.
216
+ *
217
+ * Carries no existence precondition: an entry with no stored state resolves to an empty instance of
218
+ * the request's `model` rather than rejecting.
219
+ *
220
+ * @param request The resource and model to materialise
221
+ *
222
+ * @returns A promise resolving to the resource materialised against the request's `model`, settled once the
223
+ * owning batch and any nested requests needed to assemble it have resolved
224
+ */
225
+ detail<S extends Lazy<ResourceShape>, T extends Template>(request: Detail<T, S>): Promise<Match<S, T>>;
226
+ /**
227
+ * Enqueue a {@link Select} request.
228
+ *
229
+ * Carries no existence precondition: an entry with no matching members resolves to an empty
230
+ * collection rather than rejecting.
231
+ *
232
+ * @param request The property and query to materialise
233
+ *
234
+ * @returns A promise resolving to the values the collection holds as the request's `query` narrows them,
235
+ * items for a template and rows for a projection, settled once the owning batch and any nested requests
236
+ * needed to assemble them have resolved
237
+ */
238
+ select<T extends Query<Slot>>(request: Select<T>): Promise<readonly Value[]>;
239
+ /**
240
+ * Enqueue a {@link Modify} request.
241
+ *
242
+ * Mutates unconditionally, with no existence precondition. A present `state` upserts the entry, creating it if
243
+ * absent. An omitted `state` deletes the entry, and is a no-op if the entry is absent.
244
+ *
245
+ * @param request The entry and target state to persist, or the collection link to add
246
+ *
247
+ * @returns A promise resolving to the {@link Reference} of the mutated entry, settled once the owning
248
+ * batch has completed
249
+ */
250
+ modify(request: Modify): Promise<Reference>;
251
+ };
252
+ /**
253
+ * Creates a batching store client backed by a set of request handlers.
254
+ *
255
+ * Coalesces concurrent {@link StoreClient} calls into batches, each served by the matching `handlers` entry. The
256
+ * client adds conditional CRUD semantics on top of the handlers: `create`, `update` and `delete` probe for existence
257
+ * through the `detect` handler before handing the mutation to `modify`. `lookup` probes for existence the same way,
258
+ * except for a `virtual` lookup, which goes straight to the `detail` handler. `create` mints the identifier of the new
259
+ * resource, if its state names none, and links it to the collecting resource as a new collection member.
260
+ *
261
+ * The `modify` handler receives only requests whose `state` carries no `id` other than their `entry`. A request
262
+ * failing this check is rejected on its own, and the rest of the batch still applies. If the `modify` handler throws,
263
+ * the error rejects every request in its batch.
264
+ *
265
+ * @param handlers The batch handlers, one per request type
266
+ * @param options The caps on how `handlers` are called
267
+ *
268
+ * @returns An immutable {@link StoreClient} serving its requests in batches through `handlers`
269
+ *
270
+ * @throws {@link !RangeError RangeError} If an update or insert `state` carries an `id` that differs from its `entry`,
271
+ * or if a create `state` member filling an identifier slot is not a single path segment
272
+ */
273
+ export declare function createBatchingStore(handlers: {
274
+ detect: Handler<Detect>;
275
+ detail: Handler<Detail>;
276
+ select: Handler<Select>;
277
+ modify: Handler<Modify>;
278
+ }, { limit }?: {
279
+ /**
280
+ * The caps on batch size per request type and on handler calls in flight, matched to what the backend accepts.
281
+ *
282
+ * @defaultValue No limit: each handler receives its whole accumulation and every call of a round runs at once
283
+ */
284
+ readonly limit?: Limits;
285
+ }): StoreClient;
286
+ //# sourceMappingURL=batching.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batching.d.ts","sourceRoot":"","sources":["../../src/clients/batching.ts"],"names":[],"mappings":"AAgBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,aAAa,EAA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;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE;IAE7C,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,CAAA;IACvB,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,CAAA;IACvB,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,CAAA;IACvB,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,CAAA;CAEvB,EAAE,EAEF,KAAU,EAEV,GAAE;IAEF;;;;OAIG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAElB,GAAG,WAAW,CAkInB"}
@@ -0,0 +1,112 @@
1
+ /*
2
+ * Copyright © 2025-2026 Metreeca srl
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { blueprint, collection } from "@grafctory/blue/value";
17
+ import { isString } from "@grafctory/core";
18
+ import { immutable } from "@grafctory/core/values";
19
+ import { createBroker, mint } from "./batching.core.js";
20
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
21
+ /**
22
+ * Creates a batching store client backed by a set of request handlers.
23
+ *
24
+ * Coalesces concurrent {@link StoreClient} calls into batches, each served by the matching `handlers` entry. The
25
+ * client adds conditional CRUD semantics on top of the handlers: `create`, `update` and `delete` probe for existence
26
+ * through the `detect` handler before handing the mutation to `modify`. `lookup` probes for existence the same way,
27
+ * except for a `virtual` lookup, which goes straight to the `detail` handler. `create` mints the identifier of the new
28
+ * resource, if its state names none, and links it to the collecting resource as a new collection member.
29
+ *
30
+ * The `modify` handler receives only requests whose `state` carries no `id` other than their `entry`. A request
31
+ * failing this check is rejected on its own, and the rest of the batch still applies. If the `modify` handler throws,
32
+ * the error rejects every request in its batch.
33
+ *
34
+ * @param handlers The batch handlers, one per request type
35
+ * @param options The caps on how `handlers` are called
36
+ *
37
+ * @returns An immutable {@link StoreClient} serving its requests in batches through `handlers`
38
+ *
39
+ * @throws {@link !RangeError RangeError} If an update or insert `state` carries an `id` that differs from its `entry`,
40
+ * or if a create `state` member filling an identifier slot is not a single path segment
41
+ */
42
+ export function createBatchingStore(handlers, { limit = {} } = {}) {
43
+ const broker = createBroker({
44
+ ...handlers,
45
+ async modify(batch, broker) {
46
+ const items = batch.filter(({ request: { entry, state }, reject }) => {
47
+ // reject each request whose state id contradicts its entry on its own, so the
48
+ // rest of the batch still applies and the check stays out of storage-specific handlers
49
+ const matching = state?.id === undefined || state.id === entry;
50
+ if (!matching) {
51
+ reject(new RangeError(`mismatched state id <${String(state?.id)}> for entry <${entry}>`));
52
+ }
53
+ return matching;
54
+ });
55
+ if (items.length > 0) {
56
+ // on backend failure, reject the surviving batch rather than throw: the broker
57
+ // treats a handler throw as a run-wide fault and propagates it to sibling queues
58
+ try {
59
+ await handlers.modify(items, broker);
60
+ }
61
+ catch (error) {
62
+ items.forEach(({ reject }) => reject(error));
63
+ }
64
+ }
65
+ }
66
+ }, limit);
67
+ return immutable({
68
+ async lookup({ virtual = false, entry, shape, model }, { locale = ["und"] } = {}) {
69
+ // a virtual resource is derived rather than held, so it is detailed without probing its presence
70
+ return virtual || await broker.detect({ entry })
71
+ ? broker.detail({ virtual, entry, shape, model, locale })
72
+ : undefined;
73
+ },
74
+ async create({ entry, shape, model, state }) {
75
+ // the new resource is stored under the identifier its state names, or under one minted for it off the
76
+ // blueprint of the collection; either way it is the resource probed for existence and written, not the
77
+ // collection
78
+ const target = collection(shape, model);
79
+ const plan = blueprint(shape, model);
80
+ const { id } = state;
81
+ const child = isString(id) ? id : mint(entry, plan, state);
82
+ // a collection a plain property holds is linked to its new member; one exposed through
83
+ // a foreign property is a view over the member's own link and reaches it on its own
84
+ return await broker.detect({ entry: child }) ? undefined
85
+ : broker.modify({ entry: child, shape: plan, state }).then(created => target.foreign
86
+ ? created
87
+ : broker.modify({ entry, shape, link: { property: target, item: created } }).then(() => created));
88
+ },
89
+ async update({ entry, shape, state }) {
90
+ // the entry identifies the target: a state carrying a different id contradicts it
91
+ const { id } = state;
92
+ if (id !== undefined && id !== entry) {
93
+ throw new RangeError(`mismatched state id <${String(id)}> for entry <${entry}>`);
94
+ }
95
+ return await broker.detect({ entry })
96
+ ? broker.modify({ entry, shape, state })
97
+ : undefined;
98
+ },
99
+ async delete({ entry, shape }) {
100
+ return await broker.detect({ entry })
101
+ ? broker.modify({ entry, shape })
102
+ : undefined;
103
+ },
104
+ insert(insert) {
105
+ return broker.modify(insert);
106
+ },
107
+ remove(remove) {
108
+ return broker.modify(remove);
109
+ }
110
+ });
111
+ }
112
+ //# sourceMappingURL=batching.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batching.js","sourceRoot":"","sources":["../../src/clients/batching.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAmCH,OAAO,EAAE,SAAS,EAAE,UAAU,EAAc,MAAM,uBAAuB,CAAC;AAC1E,OAAO,EAAE,QAAQ,EAA4B,MAAM,iBAAiB,CAAC;AAErE,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAInD,OAAO,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAkRxD,wHAAwH;AAExH;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,UAAU,mBAAmB,CAAC,QAOnC,EAAE,EAEF,KAAK,GAAG,EAAE,KAWP,EAAE;IAEL,MAAM,MAAM,GAAG,YAAY,CAAC;QAE3B,GAAG,QAAQ;QAEX,KAAK,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM;YAEzB,MAAM,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,OAAO,EAAE,E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