@loomwork/projection-runtime 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +8 -0
- package/README.md +64 -2
- package/dist/InMemoryProjectionRuntime.d.ts +70 -0
- package/dist/InMemoryProjectionRuntime.d.ts.map +1 -0
- package/dist/InMemoryProjectionRuntime.js +305 -0
- package/dist/InMemoryProjectionRuntime.js.map +1 -0
- package/dist/esm/InMemoryProjectionRuntime.js +301 -0
- package/dist/esm/InMemoryProjectionRuntime.js.map +1 -0
- package/dist/esm/index.js +2 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/types.js +2 -0
- package/dist/esm/types.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -0
- package/dist/types.d.ts +61 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/package.json +59 -3
- package/src/InMemoryProjectionRuntime.ts +384 -0
- package/src/index.ts +5 -0
- package/src/projectionStorm.bench.ts +146 -0
- package/src/types.ts +73 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,65 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @loomwork/projection-runtime — in-memory read models folded from events
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A projection folds an execution's events into a small state object that a UI or another reader can
|
|
4
|
+
query and subscribe to. This package holds the `Projection` and `ProjectionRuntime` types and the one
|
|
5
|
+
implementation, `InMemoryProjectionRuntime`. `defineConfig` creates one for you when you do not pass
|
|
6
|
+
`projectionRuntime`, registers your `projections`, and feeds it every event, so most apps use it through
|
|
7
|
+
`@loomwork/app` and the renderers rather than constructing it. Reach for it directly in tests, or when you
|
|
8
|
+
wire a surface of your own.
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
import { InMemoryProjectionRuntime } from "@loomwork/projection-runtime";
|
|
12
|
+
import type { EventEnvelope } from "@loomwork/core";
|
|
13
|
+
|
|
14
|
+
const runtime = new InMemoryProjectionRuntime({ coalesceNotifications: true });
|
|
15
|
+
|
|
16
|
+
runtime.register<{ completed: number }>({
|
|
17
|
+
id: "progress",
|
|
18
|
+
version: "1", // bump when the fold's meaning changes (ADR 0095)
|
|
19
|
+
initialState: { completed: 0 },
|
|
20
|
+
handlers: { STEP_COMPLETED: (state) => ({ completed: state.completed + 1 }) },
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
declare const event: EventEnvelope; // normally from EventStore.subscribe, or defineConfig's feed
|
|
24
|
+
runtime.handleEvent(event);
|
|
25
|
+
|
|
26
|
+
const stop = runtime.subscribeSelector<{ completed: number }, number>(
|
|
27
|
+
"progress",
|
|
28
|
+
event.executionId,
|
|
29
|
+
(state) => state.completed,
|
|
30
|
+
(completed) => console.log("completed steps:", completed)
|
|
31
|
+
);
|
|
32
|
+
stop();
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Surface
|
|
36
|
+
|
|
37
|
+
- **Types.** `Projection` (`id`, `initialState`, `handlers` or an event-type-gated `lazy` loader, optional
|
|
38
|
+
`version`) and `ProjectionRuntime`.
|
|
39
|
+
- **Reads.** `getState(projectionId, executionId)` returns `initialState` for an execution it has seen no
|
|
40
|
+
events for, and throws for a projection that was never registered.
|
|
41
|
+
- **Subscriptions.** `subscribe` fires on every change. `subscribeSelector` fires only when a selected
|
|
42
|
+
slice changes (`Object.is` by default, or your `isEqual`), and not on subscribe (ADR 0068).
|
|
43
|
+
- **Feeding.** `handleEvent(event)` and `seedState(...)`. `forget(executionId)` drops a finished
|
|
44
|
+
execution's state and subscribers.
|
|
45
|
+
|
|
46
|
+
## Behaviour that surprises people
|
|
47
|
+
|
|
48
|
+
- **State lives in memory.** Nothing here persists it, and a new process starts from `initialState`.
|
|
49
|
+
- **Retention is bounded.** `maxExecutions` (default 10,000) keeps the most recently touched executions.
|
|
50
|
+
An evicted execution reads as `initialState` again, but an execution with a live subscriber is skipped
|
|
51
|
+
by eviction (the scan gives up after 64 candidates, so the cap can be exceeded).
|
|
52
|
+
- **Notifications are synchronous by default.** `coalesceNotifications: true` flushes once per
|
|
53
|
+
microtask with the latest state, so a burst of events reaches subscribers once.
|
|
54
|
+
- **A lazy projection loads its fold code on the first matching event.** If that load fails, the
|
|
55
|
+
projection is abandoned and its buffered events are dropped; the buffer is capped at 10,000.
|
|
56
|
+
|
|
57
|
+
## Status / See also
|
|
58
|
+
|
|
59
|
+
Unpublished for now: inside this repo use `workspace:*`; from a sibling checkout use a `link:` override
|
|
60
|
+
(see [AGENTS.md](../../AGENTS.md)).
|
|
61
|
+
|
|
62
|
+
- [ADR 0068](../../docs/adr/0068-projection-selector-subscription.md): selector subscriptions.
|
|
63
|
+
- [ADR 0095](../../docs/adr/0095-binding-semantics-pin.md): the declared `version` and pin checks.
|
|
64
|
+
- API reference: section "`@loomwork/projection-runtime`" in [docs/api-reference.org](../../docs/api-reference.org).
|
|
65
|
+
- Guides: [docs/user-guide.md](../../docs/user-guide.md), [docs/README.md](../../docs/README.md).
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { EventEnvelope } from "@loomwork/core";
|
|
2
|
+
import type { Projection, ProjectionRuntime } from "./types";
|
|
3
|
+
export interface InMemoryProjectionRuntimeConfig {
|
|
4
|
+
/**
|
|
5
|
+
* Coalesce subscriber notifications. When true, instead of notifying
|
|
6
|
+
* synchronously on every event, dirty keys are collected and flushed once per
|
|
7
|
+
* microtask with each projection's LATEST state. A streaming burst of N events
|
|
8
|
+
* (e.g. one LLM token per event) collapses from N subscriber calls to 1 per
|
|
9
|
+
* affected key, cutting downstream re-renders without changing final state.
|
|
10
|
+
*
|
|
11
|
+
* Off by default: notifications stay synchronous, preserving exact current
|
|
12
|
+
* semantics and adding zero overhead unless explicitly enabled.
|
|
13
|
+
*/
|
|
14
|
+
coalesceNotifications?: boolean;
|
|
15
|
+
/**
|
|
16
|
+
* Bound how many distinct executions' projection states are retained (LRU by last touch).
|
|
17
|
+
* Prevents unbounded growth in a long-lived server: an execution evicted here reverts to
|
|
18
|
+
* `initialState` on the next `getState` (graceful). Default 10_000; set higher/lower to taste.
|
|
19
|
+
*/
|
|
20
|
+
maxExecutions?: number;
|
|
21
|
+
}
|
|
22
|
+
export declare class InMemoryProjectionRuntime implements ProjectionRuntime {
|
|
23
|
+
private readonly projections;
|
|
24
|
+
private readonly states;
|
|
25
|
+
private readonly subscribers;
|
|
26
|
+
private readonly selectorSubscribers;
|
|
27
|
+
private readonly coalesce;
|
|
28
|
+
private readonly dirtyKeys;
|
|
29
|
+
private flushScheduled;
|
|
30
|
+
private readonly maxExecutions;
|
|
31
|
+
private readonly execOrder;
|
|
32
|
+
constructor(config?: InMemoryProjectionRuntimeConfig);
|
|
33
|
+
/** Drop all retained state + subscribers for an execution (e.g. after it completes). */
|
|
34
|
+
forget(executionId: string): void;
|
|
35
|
+
/** True if anything is currently subscribed to any projection of this execution. */
|
|
36
|
+
private hasSubscribers;
|
|
37
|
+
/**
|
|
38
|
+
* Drop an execution's retained STATE only — never its subscriber registries.
|
|
39
|
+
*
|
|
40
|
+
* The distinction is the whole point. `forget` is an explicit "this execution is done"
|
|
41
|
+
* from a caller who knows it; eviction is a cache decision the caller never made, and
|
|
42
|
+
* dropping a live subscriber's registry there does not degrade — it disconnects. The
|
|
43
|
+
* handler set is captured by closure in `subscribe`, so once the map entry is gone
|
|
44
|
+
* `notify` looks up a key that no longer exists and that subscriber never fires again.
|
|
45
|
+
*/
|
|
46
|
+
private evictState;
|
|
47
|
+
private touch;
|
|
48
|
+
private stateKey;
|
|
49
|
+
register<TState>(projection: Projection<TState>): void;
|
|
50
|
+
getState<TState>(projectionId: string, executionId: string): TState;
|
|
51
|
+
subscribe<TState>(projectionId: string, executionId: string, handler: (state: TState) => void): () => void;
|
|
52
|
+
subscribeSelector<TState, TSlice>(projectionId: string, executionId: string, selector: (state: TState) => TSlice, handler: (slice: TSlice) => void, isEqual?: (a: TSlice, b: TSlice) => boolean): () => void;
|
|
53
|
+
private peekState;
|
|
54
|
+
handleEvent(event: EventEnvelope): void;
|
|
55
|
+
/** Fold one event into a projection's state via the matching handler, then notify. */
|
|
56
|
+
private apply;
|
|
57
|
+
seedState(projectionId: string, executionId: string, state: unknown): void;
|
|
58
|
+
/**
|
|
59
|
+
* ADR 0095 — the declared `version` of every registered projection that has one.
|
|
60
|
+
*
|
|
61
|
+
* Projections that declare nothing are ABSENT rather than present-and-empty: the caller
|
|
62
|
+
* compares this against what an artifact recorded, and a key mapped to `""` would compare
|
|
63
|
+
* equal to another empty declaration and read as a verified match.
|
|
64
|
+
*/
|
|
65
|
+
pins(): Readonly<Record<string, string>>;
|
|
66
|
+
private notify;
|
|
67
|
+
private flush;
|
|
68
|
+
private emit;
|
|
69
|
+
}
|
|
70
|
+
//# sourceMappingURL=InMemoryProjectionRuntime.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"InMemoryProjectionRuntime.d.ts","sourceRoot":"","sources":["../src/InMemoryProjectionRuntime.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,KAAK,EAAE,UAAU,EAAqB,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAkDhF,MAAM,WAAW,+BAA+B;IAC9C;;;;;;;;;OASG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,qBAAa,yBAA0B,YAAW,iBAAiB;IACjE,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAuC;IACnE,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA8B;IACrD,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAoD;IAGhF,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAyC;IAE7E,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAU;IACnC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAqB;IAC/C,OAAO,CAAC,cAAc,CAAS;IAG/B,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAS;IACvC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA2B;gBAEzC,MAAM,CAAC,EAAE,+BAA+B;IAKpD,wFAAwF;IACxF,MAAM,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI;IAUjC,oFAAoF;IACpF,OAAO,CAAC,cAAc;IAQtB;;;;;;;;OAQG;IACH,OAAO,CAAC,UAAU;IAOlB,OAAO,CAAC,KAAK;IAqBb,OAAO,CAAC,QAAQ;IAIhB,QAAQ,CAAC,MAAM,EAAE,UAAU,EAAE,UAAU,CAAC,MAAM,CAAC,GAAG,IAAI;IAkBtD,QAAQ,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM;IAYnE,SAAS,CAAC,MAAM,EACd,YAAY,EAAE,MAAM,EACpB,WAAW,EAAE,MAAM,EACnB,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,GAC/B,MAAM,IAAI;IAoBb,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAC9B,YAAY,EAAE,MAAM,EACpB,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,EACnC,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,EAChC,OAAO,GAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,OAAmB,GACrD,MAAM,IAAI;IA4Bb,OAAO,CAAC,SAAS;IAMjB,WAAW,CAAC,KAAK,EAAE,aAAa,GAAG,IAAI;IA4CvC,sFAAsF;IACtF,OAAO,CAAC,KAAK;IAsBb,SAAS,CAAC,YAAY,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI;IAM1E;;;;;;OAMG;IACH,IAAI,IAAI,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAUxC,OAAO,CAAC,MAAM;IAad,OAAO,CAAC,KAAK;IAWb,OAAO,CAAC,IAAI;CAsBb"}
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.InMemoryProjectionRuntime = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Cap on how many matching events a lazy projection buffers while its fold code loads. A local
|
|
6
|
+
* `import()` resolves in well under this window; exceeding it means the load is stuck or broken,
|
|
7
|
+
* so we stop buffering (the projection is a read-model, rebuildable from the log) rather than
|
|
8
|
+
* grow memory without bound. Generous so normal bursts never hit it.
|
|
9
|
+
*/
|
|
10
|
+
const LAZY_BUFFER_LIMIT = 10_000;
|
|
11
|
+
/**
|
|
12
|
+
* How many least-recently-touched executions eviction will step over looking for an
|
|
13
|
+
* unsubscribed one. Bounds the per-event cost of `touch`; see its comment for why giving up
|
|
14
|
+
* (and sitting one entry over the cap) is the right failure direction.
|
|
15
|
+
*/
|
|
16
|
+
const EVICTION_SCAN_LIMIT = 64;
|
|
17
|
+
class InMemoryProjectionRuntime {
|
|
18
|
+
projections = new Map();
|
|
19
|
+
states = new Map();
|
|
20
|
+
subscribers = new Map();
|
|
21
|
+
// Selector-subscribers, keyed like `subscribers`. Kept separate so whole-state
|
|
22
|
+
// subscription stays a zero-overhead fast path when no selector-subscribers exist.
|
|
23
|
+
selectorSubscribers = new Map();
|
|
24
|
+
coalesce;
|
|
25
|
+
dirtyKeys = new Set();
|
|
26
|
+
flushScheduled = false;
|
|
27
|
+
// Insertion order = LRU order over distinct executions, for the retention bound.
|
|
28
|
+
maxExecutions;
|
|
29
|
+
execOrder = new Map();
|
|
30
|
+
constructor(config) {
|
|
31
|
+
this.coalesce = config?.coalesceNotifications ?? false;
|
|
32
|
+
this.maxExecutions = config?.maxExecutions ?? 10_000;
|
|
33
|
+
}
|
|
34
|
+
/** Drop all retained state + subscribers for an execution (e.g. after it completes). */
|
|
35
|
+
forget(executionId) {
|
|
36
|
+
for (const projectionId of this.projections.keys()) {
|
|
37
|
+
const key = this.stateKey(projectionId, executionId);
|
|
38
|
+
this.states.delete(key);
|
|
39
|
+
this.subscribers.delete(key);
|
|
40
|
+
this.selectorSubscribers.delete(key);
|
|
41
|
+
}
|
|
42
|
+
this.execOrder.delete(executionId);
|
|
43
|
+
}
|
|
44
|
+
/** True if anything is currently subscribed to any projection of this execution. */
|
|
45
|
+
hasSubscribers(executionId) {
|
|
46
|
+
for (const projectionId of this.projections.keys()) {
|
|
47
|
+
const key = this.stateKey(projectionId, executionId);
|
|
48
|
+
if (this.subscribers.has(key) || this.selectorSubscribers.has(key))
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Drop an execution's retained STATE only — never its subscriber registries.
|
|
55
|
+
*
|
|
56
|
+
* The distinction is the whole point. `forget` is an explicit "this execution is done"
|
|
57
|
+
* from a caller who knows it; eviction is a cache decision the caller never made, and
|
|
58
|
+
* dropping a live subscriber's registry there does not degrade — it disconnects. The
|
|
59
|
+
* handler set is captured by closure in `subscribe`, so once the map entry is gone
|
|
60
|
+
* `notify` looks up a key that no longer exists and that subscriber never fires again.
|
|
61
|
+
*/
|
|
62
|
+
evictState(executionId) {
|
|
63
|
+
for (const projectionId of this.projections.keys()) {
|
|
64
|
+
this.states.delete(this.stateKey(projectionId, executionId));
|
|
65
|
+
}
|
|
66
|
+
this.execOrder.delete(executionId);
|
|
67
|
+
}
|
|
68
|
+
touch(executionId) {
|
|
69
|
+
this.execOrder.delete(executionId);
|
|
70
|
+
this.execOrder.set(executionId, true);
|
|
71
|
+
if (this.execOrder.size <= this.maxExecutions)
|
|
72
|
+
return;
|
|
73
|
+
// Evict least-recently-touched first, but SKIP anything with a live subscriber:
|
|
74
|
+
// evicting a state someone is folding into resets it to `initialState`, which is
|
|
75
|
+
// corruption rather than a cache miss (the same rule `AgentSurfaceRuntime` follows).
|
|
76
|
+
//
|
|
77
|
+
// The scan is bounded rather than exhaustive: if the oldest entries are all subscribed,
|
|
78
|
+
// giving up costs one over-cap entry, while scanning on would make `touch` — which runs
|
|
79
|
+
// once per event — O(retained). Over the cap is the safe direction; `forget` is the
|
|
80
|
+
// explicit remedy.
|
|
81
|
+
let examined = 0;
|
|
82
|
+
for (const candidate of this.execOrder.keys()) {
|
|
83
|
+
if (examined++ >= EVICTION_SCAN_LIMIT)
|
|
84
|
+
return;
|
|
85
|
+
if (this.hasSubscribers(candidate))
|
|
86
|
+
continue;
|
|
87
|
+
this.evictState(candidate);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
stateKey(projectionId, executionId) {
|
|
92
|
+
return `${projectionId}::${executionId}`;
|
|
93
|
+
}
|
|
94
|
+
register(projection) {
|
|
95
|
+
const active = {
|
|
96
|
+
id: projection.id,
|
|
97
|
+
initialState: projection.initialState,
|
|
98
|
+
...(projection.version !== undefined && { version: projection.version }),
|
|
99
|
+
loading: false,
|
|
100
|
+
buffer: [],
|
|
101
|
+
...(projection.handlers !== undefined && {
|
|
102
|
+
handlers: projection.handlers,
|
|
103
|
+
}),
|
|
104
|
+
...(projection.lazy !== undefined && {
|
|
105
|
+
eventTypes: new Set(projection.lazy.eventTypes),
|
|
106
|
+
load: projection.lazy.load,
|
|
107
|
+
}),
|
|
108
|
+
};
|
|
109
|
+
this.projections.set(projection.id, active);
|
|
110
|
+
}
|
|
111
|
+
getState(projectionId, executionId) {
|
|
112
|
+
const key = this.stateKey(projectionId, executionId);
|
|
113
|
+
if (this.states.has(key)) {
|
|
114
|
+
return this.states.get(key);
|
|
115
|
+
}
|
|
116
|
+
const projection = this.projections.get(projectionId);
|
|
117
|
+
if (!projection) {
|
|
118
|
+
throw new Error(`Projection "${projectionId}" is not registered`);
|
|
119
|
+
}
|
|
120
|
+
return projection.initialState;
|
|
121
|
+
}
|
|
122
|
+
subscribe(projectionId, executionId, handler) {
|
|
123
|
+
const key = this.stateKey(projectionId, executionId);
|
|
124
|
+
if (!this.subscribers.has(key)) {
|
|
125
|
+
this.subscribers.set(key, new Set());
|
|
126
|
+
}
|
|
127
|
+
const handlers = this.subscribers.get(key);
|
|
128
|
+
const wrapper = (s) => handler(s);
|
|
129
|
+
handlers.add(wrapper);
|
|
130
|
+
return () => {
|
|
131
|
+
handlers.delete(wrapper);
|
|
132
|
+
// Only retire the map entry if it is still OUR set. After an explicit `forget`, a later
|
|
133
|
+
// subscriber installs a fresh set under the same key; without this identity check a
|
|
134
|
+
// stale unsubscribe would empty its own orphaned set and then delete the live one,
|
|
135
|
+
// silently disconnecting a subscriber that did nothing wrong.
|
|
136
|
+
if (handlers.size === 0 && this.subscribers.get(key) === handlers) {
|
|
137
|
+
this.subscribers.delete(key);
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
subscribeSelector(projectionId, executionId, selector, handler, isEqual = Object.is) {
|
|
142
|
+
const key = this.stateKey(projectionId, executionId);
|
|
143
|
+
let set = this.selectorSubscribers.get(key);
|
|
144
|
+
if (!set) {
|
|
145
|
+
set = new Set();
|
|
146
|
+
this.selectorSubscribers.set(key, set);
|
|
147
|
+
}
|
|
148
|
+
const sel = selector;
|
|
149
|
+
const entry = {
|
|
150
|
+
selector: sel,
|
|
151
|
+
isEqual: isEqual,
|
|
152
|
+
handler: handler,
|
|
153
|
+
// Seed from current state so change-only holds from the first event on.
|
|
154
|
+
last: sel(this.peekState(projectionId, executionId)),
|
|
155
|
+
};
|
|
156
|
+
set.add(entry);
|
|
157
|
+
return () => {
|
|
158
|
+
set.delete(entry);
|
|
159
|
+
// Same identity check as `subscribe` — never retire a set that is no longer ours.
|
|
160
|
+
if (set.size === 0 && this.selectorSubscribers.get(key) === set) {
|
|
161
|
+
this.selectorSubscribers.delete(key);
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
// Current state without throwing for an unregistered/unseen projection (unlike
|
|
166
|
+
// getState) — used to seed a selector-subscription's `last`. resolve-by-path
|
|
167
|
+
// selectors are null-safe, so an absent state seeds cleanly to `undefined`.
|
|
168
|
+
peekState(projectionId, executionId) {
|
|
169
|
+
const key = this.stateKey(projectionId, executionId);
|
|
170
|
+
if (this.states.has(key))
|
|
171
|
+
return this.states.get(key);
|
|
172
|
+
return this.projections.get(projectionId)?.initialState;
|
|
173
|
+
}
|
|
174
|
+
handleEvent(event) {
|
|
175
|
+
for (const [, projection] of this.projections) {
|
|
176
|
+
if (projection.handlers !== undefined) {
|
|
177
|
+
// Eager (or an already-loaded lazy) projection — fold synchronously as before.
|
|
178
|
+
this.apply(projection, projection.handlers, event);
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
// Lazy projection: gate on the compiler-recorded event types WITHOUT loading the
|
|
182
|
+
// fold code. A non-matching event never touches this projection (0 code loaded).
|
|
183
|
+
// A projection whose load already failed permanently is skipped (no buffer, no retry).
|
|
184
|
+
if (projection.loadFailed === true)
|
|
185
|
+
continue;
|
|
186
|
+
if (projection.eventTypes?.has(event.eventType) !== true)
|
|
187
|
+
continue;
|
|
188
|
+
// First matching event: buffer it (and any that arrive during load), kick the
|
|
189
|
+
// one-time import, and drain the buffer in arrival order once the code is ready.
|
|
190
|
+
// Bounded so a stuck/broken load can't grow the buffer without limit.
|
|
191
|
+
if (projection.buffer.length < LAZY_BUFFER_LIMIT)
|
|
192
|
+
projection.buffer.push(event);
|
|
193
|
+
if (!projection.loading) {
|
|
194
|
+
projection.loading = true;
|
|
195
|
+
projection.load()
|
|
196
|
+
.then((handlers) => {
|
|
197
|
+
projection.handlers = handlers;
|
|
198
|
+
projection.eventTypes = undefined; // resolved — the eager path takes over
|
|
199
|
+
projection.loading = false;
|
|
200
|
+
const buffered = projection.buffer;
|
|
201
|
+
projection.buffer = [];
|
|
202
|
+
for (const buf of buffered)
|
|
203
|
+
this.apply(projection, handlers, buf);
|
|
204
|
+
})
|
|
205
|
+
.catch((err) => {
|
|
206
|
+
// A chunk load failure is not transient (missing/broken module). Abandon the
|
|
207
|
+
// projection: free the buffer and stop retrying, rather than leak memory and
|
|
208
|
+
// re-import on every matching event. The read-model can be rebuilt from the log.
|
|
209
|
+
projection.loading = false;
|
|
210
|
+
projection.loadFailed = true;
|
|
211
|
+
projection.buffer = [];
|
|
212
|
+
console.warn(`[loom] projection "${projection.id}" failed to load its fold code — it will not update: ${String(err)}`);
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
this.touch(event.executionId);
|
|
217
|
+
}
|
|
218
|
+
/** Fold one event into a projection's state via the matching handler, then notify. */
|
|
219
|
+
apply(projection, handlers, event) {
|
|
220
|
+
// Own-key lookup: the fold map is user-authored and the event type is caller-controlled,
|
|
221
|
+
// so `handlers["__proto__"]` would resolve to `Object.prototype` — truthy, defeating the
|
|
222
|
+
// `!handler` guard, and then called as a function. Mirrors `getHandler` in @loomwork/replay-vm.
|
|
223
|
+
if (!Object.hasOwn(handlers, event.eventType))
|
|
224
|
+
return;
|
|
225
|
+
const handler = handlers[event.eventType];
|
|
226
|
+
if (typeof handler !== "function")
|
|
227
|
+
return;
|
|
228
|
+
const key = this.stateKey(projection.id, event.executionId);
|
|
229
|
+
// One `get` on the hot path (this runs per event per projection); `has` is consulted only
|
|
230
|
+
// in the rare case where the retained state is itself `undefined`.
|
|
231
|
+
const retained = this.states.get(key);
|
|
232
|
+
const currentState = retained !== undefined || this.states.has(key) ? retained : projection.initialState;
|
|
233
|
+
const nextState = handler(currentState, event);
|
|
234
|
+
this.states.set(key, nextState);
|
|
235
|
+
this.notify(key, nextState);
|
|
236
|
+
}
|
|
237
|
+
seedState(projectionId, executionId, state) {
|
|
238
|
+
const key = this.stateKey(projectionId, executionId);
|
|
239
|
+
this.states.set(key, state);
|
|
240
|
+
this.touch(executionId);
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* ADR 0095 — the declared `version` of every registered projection that has one.
|
|
244
|
+
*
|
|
245
|
+
* Projections that declare nothing are ABSENT rather than present-and-empty: the caller
|
|
246
|
+
* compares this against what an artifact recorded, and a key mapped to `""` would compare
|
|
247
|
+
* equal to another empty declaration and read as a verified match.
|
|
248
|
+
*/
|
|
249
|
+
pins() {
|
|
250
|
+
// No prototype: a projection registered as `__proto__` would otherwise set one instead
|
|
251
|
+
// of adding a key, and vanish from every comparison without a finding.
|
|
252
|
+
const pins = Object.create(null);
|
|
253
|
+
for (const [id, projection] of this.projections) {
|
|
254
|
+
if (projection.version !== undefined)
|
|
255
|
+
pins[id] = projection.version;
|
|
256
|
+
}
|
|
257
|
+
return pins;
|
|
258
|
+
}
|
|
259
|
+
notify(key, state) {
|
|
260
|
+
if (!this.coalesce) {
|
|
261
|
+
this.emit(key, state);
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
// Defer: mark dirty and flush once per microtask with the latest state.
|
|
265
|
+
this.dirtyKeys.add(key);
|
|
266
|
+
if (!this.flushScheduled) {
|
|
267
|
+
this.flushScheduled = true;
|
|
268
|
+
queueMicrotask(() => this.flush());
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
flush() {
|
|
272
|
+
this.flushScheduled = false;
|
|
273
|
+
const keys = Array.from(this.dirtyKeys);
|
|
274
|
+
this.dirtyKeys.clear();
|
|
275
|
+
for (const key of keys) {
|
|
276
|
+
// Read the current state so subscribers always see the latest value even
|
|
277
|
+
// when many events for the same key arrived within the batch.
|
|
278
|
+
this.emit(key, this.states.get(key));
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
emit(key, state) {
|
|
282
|
+
const handlers = this.subscribers.get(key);
|
|
283
|
+
if (handlers) {
|
|
284
|
+
for (const handler of handlers) {
|
|
285
|
+
handler(state);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
// Selector-subscribers: recompute each slice against the latest state and fire
|
|
289
|
+
// only those whose slice actually changed — so an unrelated slice's update never
|
|
290
|
+
// wakes this subscriber. Snapshot the set so an unsubscribe during iteration
|
|
291
|
+
// (a handler tearing itself down) can't mutate the live set mid-loop.
|
|
292
|
+
const selectors = this.selectorSubscribers.get(key);
|
|
293
|
+
if (selectors) {
|
|
294
|
+
for (const entry of [...selectors]) {
|
|
295
|
+
const next = entry.selector(state);
|
|
296
|
+
if (!entry.isEqual(entry.last, next)) {
|
|
297
|
+
entry.last = next;
|
|
298
|
+
entry.handler(next);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
exports.InMemoryProjectionRuntime = InMemoryProjectionRuntime;
|
|
305
|
+
//# sourceMappingURL=InMemoryProjectionRuntime.js.map
|