@loomwork/live-query 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 +25 -2
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +11 -0
- package/dist/index.js.map +1 -0
- package/dist/liveQuery.d.ts +42 -0
- package/dist/liveQuery.d.ts.map +1 -0
- package/dist/liveQuery.js +114 -0
- package/dist/liveQuery.js.map +1 -0
- package/package.json +62 -3
- package/src/index.ts +7 -0
- package/src/liveQuery.ts +199 -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,26 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @loomwork/live-query — live reads of in-flight executions
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`loadState` folds an execution's state on demand; a **live query** is that plus a subscription:
|
|
4
|
+
re-fold and push the new state each time an event lands. No syscall, no new event type — a read-model
|
|
5
|
+
over `loadState` + `EventStore.subscribe` (P10). See [ADR 0040](../../docs/adr/0040-live-query-and-orchestration.md).
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { liveQuery } from "@loomwork/live-query";
|
|
9
|
+
|
|
10
|
+
const lq = liveQuery({ eventStore, reader: runtime });
|
|
11
|
+
|
|
12
|
+
await lq.snapshot(executionId); // current folded state, or null
|
|
13
|
+
|
|
14
|
+
const unsubscribe = await lq.subscribe(executionId, (state) => {
|
|
15
|
+
render(state); // called now with the current state, then on every new event
|
|
16
|
+
if (state.status === "completed") unsubscribe();
|
|
17
|
+
});
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Updates are **coalesced**: only one re-fold runs at a time, and a burst of events triggers exactly
|
|
21
|
+
one more (latest-wins), so a subscriber never sees stale-then-newer out of order.
|
|
22
|
+
|
|
23
|
+
A wake-up lost across nodes, for example to a full Postgres NOTIFY queue, is not sent later. So each subscription
|
|
24
|
+
also re-reads the log every `pollMs` (default 5 s) until its state is terminal, and a lost wake-up costs that much
|
|
25
|
+
delay. A live subscription costs at most two indexed reads per interval. `pollMs: 0` turns this off, and then a lost
|
|
26
|
+
wake-up is only recovered by that execution's next event.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,KAAK,SAAS,EAAE,KAAK,aAAa,EAAE,KAAK,WAAW,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// @loomwork/live-query — live reads of in-flight executions.
|
|
3
|
+
//
|
|
4
|
+
// `snapshot(id)` folds current state on demand; `subscribe(id, cb)` pushes the state
|
|
5
|
+
// again on every new event. A read-model over loadState + EventStore.subscribe — no
|
|
6
|
+
// syscall, no new event type (P10).
|
|
7
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
8
|
+
exports.liveQuery = void 0;
|
|
9
|
+
var liveQuery_1 = require("./liveQuery");
|
|
10
|
+
Object.defineProperty(exports, "liveQuery", { enumerable: true, get: function () { return liveQuery_1.liveQuery; } });
|
|
11
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA,6DAA6D;AAC7D,EAAE;AACF,qFAAqF;AACrF,oFAAoF;AACpF,oCAAoC;;;AAEpC,yCAA8F;AAA/B,sGAAA,SAAS,OAAA"}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { ExecutionState } from "@loomwork/core";
|
|
2
|
+
import type { EventStore } from "@loomwork/event-runtime";
|
|
3
|
+
/** The runtime capability a live query needs — just the folding read. */
|
|
4
|
+
export interface StateReader {
|
|
5
|
+
loadState(executionId: string, options?: {
|
|
6
|
+
principal?: unknown;
|
|
7
|
+
}): Promise<ExecutionState | null>;
|
|
8
|
+
}
|
|
9
|
+
export interface LiveQuery {
|
|
10
|
+
/** The current folded state (null if the execution is unknown). */
|
|
11
|
+
snapshot(executionId: string): Promise<ExecutionState | null>;
|
|
12
|
+
/**
|
|
13
|
+
* Push the current state now, then again after every subsequent event, until the
|
|
14
|
+
* returned unsubscribe is called. `onState` receives a coalesced latest-wins state;
|
|
15
|
+
* a terminal state is delivered before teardown so callers can stop on completion.
|
|
16
|
+
*/
|
|
17
|
+
subscribe(executionId: string, onState: (state: ExecutionState) => void): Promise<() => void>;
|
|
18
|
+
}
|
|
19
|
+
export interface LiveQueryDeps {
|
|
20
|
+
eventStore: EventStore;
|
|
21
|
+
reader: StateReader;
|
|
22
|
+
/**
|
|
23
|
+
* Reports a BACKGROUND re-fold that failed — a store read that rejected, or an `onState`
|
|
24
|
+
* callback that threw. Those run from the store's subscribe callback with nothing
|
|
25
|
+
* awaiting them, so without this the rejection is unhandled and the process exits.
|
|
26
|
+
*
|
|
27
|
+
* The subscription stays live: one failed re-fold costs that update, and the next event
|
|
28
|
+
* folds from the log again. Unset, failures are swallowed — never rethrown, because
|
|
29
|
+
* there is no caller left to catch them.
|
|
30
|
+
*/
|
|
31
|
+
onError?: (err: unknown) => void;
|
|
32
|
+
/**
|
|
33
|
+
* How often each subscription re-reads the log, in case a wake-up was lost. It stops once the
|
|
34
|
+
* state is terminal, and each quiet pass costs one or two indexed reads, so a live subscription
|
|
35
|
+
* costs at most two reads per interval. `0` turns it off, which means a lost wake-up is only
|
|
36
|
+
* recovered by that execution's next event. Default 5000.
|
|
37
|
+
*/
|
|
38
|
+
pollMs?: number;
|
|
39
|
+
}
|
|
40
|
+
/** Build a {@link LiveQuery} over a store + a state reader (typically the runtime). */
|
|
41
|
+
export declare function liveQuery(deps: LiveQueryDeps): LiveQuery;
|
|
42
|
+
//# sourceMappingURL=liveQuery.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"liveQuery.d.ts","sourceRoot":"","sources":["../src/liveQuery.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAiB,cAAc,EAAE,MAAM,gBAAgB,CAAC;AACpE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAsD1D,yEAAyE;AACzE,MAAM,WAAW,WAAW;IAC1B,SAAS,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CAAC;CACnG;AAED,MAAM,WAAW,SAAS;IACxB,mEAAmE;IACnE,QAAQ,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CAAC;IAC9D;;;;OAIG;IACH,SAAS,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,IAAI,GAAG,OAAO,CAAC,MAAM,IAAI,CAAC,CAAC;CAC/F;AAED,MAAM,WAAW,aAAa;IAC5B,UAAU,EAAE,UAAU,CAAC;IACvB,MAAM,EAAE,WAAW,CAAC;IACpB;;;;;;;;OAQG;IACH,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI,CAAC;IACjC;;;;;OAKG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAUD,uFAAuF;AACvF,wBAAgB,SAAS,CAAC,IAAI,EAAE,aAAa,GAAG,SAAS,CAgGxD"}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.liveQuery = liveQuery;
|
|
4
|
+
const replay_vm_1 = require("@loomwork/replay-vm");
|
|
5
|
+
const DEFAULT_POLL_MS = 5_000;
|
|
6
|
+
const TERMINAL_STATUSES = new Set([
|
|
7
|
+
"completed",
|
|
8
|
+
"failed",
|
|
9
|
+
"cancelled",
|
|
10
|
+
"continued",
|
|
11
|
+
]);
|
|
12
|
+
/** Build a {@link LiveQuery} over a store + a state reader (typically the runtime). */
|
|
13
|
+
function liveQuery(deps) {
|
|
14
|
+
const snapshot = (executionId) => deps.reader.loadState(executionId);
|
|
15
|
+
return {
|
|
16
|
+
snapshot,
|
|
17
|
+
async subscribe(executionId, onState) {
|
|
18
|
+
// Coalesce: only ever one re-fold in flight; if events arrive during a fold,
|
|
19
|
+
// do exactly one more afterwards (latest-wins) so a burst is O(1) extra folds,
|
|
20
|
+
// not one per event, and callers never see stale-then-newer out of order.
|
|
21
|
+
let refolding = false;
|
|
22
|
+
let dirty = false;
|
|
23
|
+
// Per-subscription incremental fold state. `state === null` means "no baseline
|
|
24
|
+
// yet" — the ONLY condition under which a pass does the full `reader.loadState`;
|
|
25
|
+
// every other pass reads just the tail past `tip` and folds it onto `state`.
|
|
26
|
+
let state = null;
|
|
27
|
+
let tip = -1;
|
|
28
|
+
const pump = async () => {
|
|
29
|
+
if (refolding) {
|
|
30
|
+
dirty = true;
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
refolding = true;
|
|
34
|
+
try {
|
|
35
|
+
do {
|
|
36
|
+
dirty = false;
|
|
37
|
+
if (state === null) {
|
|
38
|
+
state = await deps.reader.loadState(executionId);
|
|
39
|
+
if (state !== null)
|
|
40
|
+
tip = state.sequence;
|
|
41
|
+
}
|
|
42
|
+
else {
|
|
43
|
+
const delta = await deps.eventStore.readFrom(executionId, tip + 1);
|
|
44
|
+
if (delta.length === 0) {
|
|
45
|
+
// Nothing new — UNLESS a compaction truncated everything after `tip` with
|
|
46
|
+
// no later event yet to reveal the gap. Only checked when the store has a
|
|
47
|
+
// cheap indexed tip, so an empty wake-up never costs a full read.
|
|
48
|
+
const head = deps.eventStore.head
|
|
49
|
+
? await deps.eventStore.head(executionId)
|
|
50
|
+
: undefined;
|
|
51
|
+
if (head === undefined || head === null || head >= tip)
|
|
52
|
+
continue; // truly nothing new
|
|
53
|
+
state = await deps.reader.loadState(executionId);
|
|
54
|
+
if (state !== null)
|
|
55
|
+
tip = state.sequence;
|
|
56
|
+
}
|
|
57
|
+
else if (delta[0].sequence !== tip + 1 ||
|
|
58
|
+
delta[delta.length - 1].sequence - tip !== delta.length) {
|
|
59
|
+
// Non-contiguous: a compaction truncated events between `tip` and the
|
|
60
|
+
// first surviving one out from under this subscription — or, since ADR 0106
|
|
61
|
+
// keeps an app's pinned-kind events in place, a kept event sits at `tip + 1`
|
|
62
|
+
// and the gap is INSIDE the delta (sequences are unique and sorted, so the
|
|
63
|
+
// delta is contiguous iff its span equals its length: O(1)). Folding `delta`
|
|
64
|
+
// onto `state` here would silently produce a WRONG `ExecutionState` — fall
|
|
65
|
+
// back to a full fold, exactly like the one-time initial load.
|
|
66
|
+
state = await deps.reader.loadState(executionId);
|
|
67
|
+
if (state !== null)
|
|
68
|
+
tip = state.sequence;
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
// `foldEvents` treats `state` as immutable (fresh audit-list ownership per
|
|
72
|
+
// pass), so folding the delta onto the kept state never mutates what a
|
|
73
|
+
// previous `onState` call was handed.
|
|
74
|
+
state = (0, replay_vm_1.foldEvents)(delta, state);
|
|
75
|
+
tip = delta[delta.length - 1].sequence;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
if (state !== null)
|
|
79
|
+
onState(state);
|
|
80
|
+
} while (dirty);
|
|
81
|
+
}
|
|
82
|
+
finally {
|
|
83
|
+
refolding = false;
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
const unsubscribe = await deps.eventStore.subscribe(executionId, (_e) => {
|
|
87
|
+
// Background re-fold: nothing awaits it, so it must never escape as an unhandled
|
|
88
|
+
// rejection. The FIRST fold below is different — the caller awaits `subscribe`, so
|
|
89
|
+
// a failure there is theirs to see and is deliberately left to propagate.
|
|
90
|
+
void pump().catch((err) => deps.onError?.(err));
|
|
91
|
+
});
|
|
92
|
+
// Emit the current state immediately so a subscriber isn't blind until the next event.
|
|
93
|
+
await pump();
|
|
94
|
+
const pollMs = deps.pollMs ?? DEFAULT_POLL_MS;
|
|
95
|
+
if (!(pollMs > 0))
|
|
96
|
+
return unsubscribe;
|
|
97
|
+
const poll = setInterval(() => {
|
|
98
|
+
if (state !== null && TERMINAL_STATUSES.has(state.status)) {
|
|
99
|
+
clearInterval(poll);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (refolding)
|
|
103
|
+
return; // the pass in flight already reads the log
|
|
104
|
+
void pump().catch((err) => deps.onError?.(err));
|
|
105
|
+
}, pollMs);
|
|
106
|
+
poll.unref?.();
|
|
107
|
+
return () => {
|
|
108
|
+
clearInterval(poll);
|
|
109
|
+
unsubscribe();
|
|
110
|
+
};
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
//# sourceMappingURL=liveQuery.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"liveQuery.js","sourceRoot":"","sources":["../src/liveQuery.ts"],"names":[],"mappings":";;AAsGA,8BAgGC;AApMD,mDAAiD;AA2FjD,MAAM,eAAe,GAAG,KAAK,CAAC;AAC9B,MAAM,iBAAiB,GAAwB,IAAI,GAAG,CAAC;IACrD,WAAW;IACX,QAAQ;IACR,WAAW;IACX,WAAW;CACZ,CAAC,CAAC;AAEH,uFAAuF;AACvF,SAAgB,SAAS,C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
4
|
+
"description": "Live queries over in-flight Loom executions — read the current folded state and subscribe to updates as new events land, without a syscall. A read-model over loadState + EventStore.subscribe.",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"types": "./dist/index.d.ts",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"require": "./dist/index.js",
|
|
11
|
+
"default": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"dependencies": {
|
|
15
|
+
"@loomwork/core": "^0.1.0",
|
|
16
|
+
"@loomwork/event-runtime": "^0.1.0",
|
|
17
|
+
"@loomwork/workflow-runtime": "^0.1.0",
|
|
18
|
+
"@loomwork/replay-vm": "^0.1.0"
|
|
19
|
+
},
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"@types/node": "^22.0.0",
|
|
22
|
+
"@types/pg": "^8.11.0",
|
|
23
|
+
"pg": "^8.13.0",
|
|
24
|
+
"typescript": "^5.6.3",
|
|
25
|
+
"vitest": "^2.1.8",
|
|
26
|
+
"zod": "^3.23.8",
|
|
27
|
+
"@loomwork/effect-runtime": "0.1.0",
|
|
28
|
+
"@loomwork/snapshot-runtime": "0.1.0",
|
|
29
|
+
"@loomwork/plugin-postgres": "0.1.0",
|
|
30
|
+
"@loomwork/plugin-content": "0.1.0"
|
|
31
|
+
},
|
|
32
|
+
"license": "Apache-2.0",
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "git+https://github.com/chhetrisushil/loom.git",
|
|
36
|
+
"directory": "packages/live-query"
|
|
37
|
+
},
|
|
38
|
+
"files": [
|
|
39
|
+
"dist",
|
|
40
|
+
"src",
|
|
41
|
+
"!src/**/*.test.ts",
|
|
42
|
+
"!src/**/*.test.tsx",
|
|
43
|
+
"!src/**/__tests__",
|
|
44
|
+
"!src/**/__fixtures__",
|
|
45
|
+
"!src/**/__snapshots__",
|
|
46
|
+
"!src/**/__golden__",
|
|
47
|
+
"LICENSE",
|
|
48
|
+
"NOTICE"
|
|
49
|
+
],
|
|
50
|
+
"publishConfig": {
|
|
51
|
+
"access": "public",
|
|
52
|
+
"tag": "next"
|
|
53
|
+
},
|
|
54
|
+
"engines": {
|
|
55
|
+
"node": ">=20.0.0"
|
|
56
|
+
},
|
|
57
|
+
"scripts": {
|
|
58
|
+
"build": "tsc --build",
|
|
59
|
+
"dev": "tsc --build --watch",
|
|
60
|
+
"test": "vitest run",
|
|
61
|
+
"test:watch": "vitest",
|
|
62
|
+
"clean": "rm -rf dist tsconfig.tsbuildinfo",
|
|
63
|
+
"typecheck:tests": "tsc -p tsconfig.test.json"
|
|
64
|
+
}
|
|
6
65
|
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// @loomwork/live-query — live reads of in-flight executions.
|
|
2
|
+
//
|
|
3
|
+
// `snapshot(id)` folds current state on demand; `subscribe(id, cb)` pushes the state
|
|
4
|
+
// again on every new event. A read-model over loadState + EventStore.subscribe — no
|
|
5
|
+
// syscall, no new event type (P10).
|
|
6
|
+
|
|
7
|
+
export { type LiveQuery, type LiveQueryDeps, type StateReader, liveQuery } from "./liveQuery";
|
package/src/liveQuery.ts
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import type { EventEnvelope, ExecutionState } from "@loomwork/core";
|
|
2
|
+
import type { EventStore } from "@loomwork/event-runtime";
|
|
3
|
+
import { foldEvents } from "@loomwork/replay-vm";
|
|
4
|
+
|
|
5
|
+
// ── Live query over an in-flight execution ────────────────────────────────────
|
|
6
|
+
//
|
|
7
|
+
// Loom's `loadState` already folds an execution's durable state on demand (bounded by
|
|
8
|
+
// snapshots) — that IS a query. A LIVE query is that plus a subscription: re-fold and
|
|
9
|
+
// push the new state each time an event lands. This needs NO syscall and NO new event
|
|
10
|
+
// type — it composes `loadState` with `EventStore.subscribe`, so it stays a read-model
|
|
11
|
+
// concern (P10), never a kernel primitive.
|
|
12
|
+
//
|
|
13
|
+
// INCREMENTAL FOLD — the one-time full load, then deltas only. `loadState` bounds a
|
|
14
|
+
// single fold's I/O with snapshots, but a live subscriber re-folding from genesis on
|
|
15
|
+
// EVERY event is still O(N) rows per event and O(N²) over an execution's lifetime (see
|
|
16
|
+
// `WorkflowRuntime.foldState`'s docstring). So `subscribe` calls `reader.loadState`
|
|
17
|
+
// exactly ONCE per subscription — establishing `state` and `tip` (the last folded
|
|
18
|
+
// sequence) — and every later wake-up instead reads only the tail since `tip`
|
|
19
|
+
// (`eventStore.readFrom(id, tip + 1)`) and folds that delta onto the kept `state` with
|
|
20
|
+
// the kernel's own `foldEvents` (no new fold, no new version — `fold(snapshot, suffix)
|
|
21
|
+
// === fold(events)` is already load-bearing for snapshots/compaction). Total I/O goes
|
|
22
|
+
// from O(N²) to O(N).
|
|
23
|
+
//
|
|
24
|
+
// It reads the delta rather than folding the delivered envelope because delivery can be
|
|
25
|
+
// gapped, duplicated or cross-node — `readFrom` handles all three for free — and because
|
|
26
|
+
// `ContentResolvingEventStore.subscribe` deliberately delivers the RAW ref-bearing event
|
|
27
|
+
// when resolution fails, whereas its read path throws `ContentMissingError` loudly. An
|
|
28
|
+
// empty delta emits nothing; a deleted execution (`readFrom` returns `[]` forever) stays
|
|
29
|
+
// silent, same as today's `null`-skipping.
|
|
30
|
+
//
|
|
31
|
+
// The gate for "still need the one-time full load" is `state === null` — not a separate
|
|
32
|
+
// boolean — because a subscription started before the execution exists must keep asking
|
|
33
|
+
// the reader (cheaply: an empty log) until the reader hands back a real baseline with the
|
|
34
|
+
// executionId/workflowId identity `foldEvents([], undefined)` cannot invent on its own.
|
|
35
|
+
//
|
|
36
|
+
// COMPACTION CAN MOVE THE FLOOR OUT FROM UNDER `tip`. `LogLifecycle.compact` (K10.4)
|
|
37
|
+
// checkpoints a snapshot and then truncates `(0..throughSequence]` out of the log — legal,
|
|
38
|
+
// because `fold(snapshot, suffix) === fold(events)`, but it invalidates `readFrom(tip + 1)`
|
|
39
|
+
// for any subscriber whose `tip` sits behind `throughSequence`: the returned delta either
|
|
40
|
+
// starts PAST `tip + 1` (a gap — the events in between were truncated) or comes back empty
|
|
41
|
+
// while the log's own tip has moved BEHIND ours (nothing left there to read `tip + 1`
|
|
42
|
+
// from). Folding a non-contiguous delta onto stale `state` would silently produce a WRONG
|
|
43
|
+
// `ExecutionState` with no error — so both signals fall back to a full `reader.loadState`
|
|
44
|
+
// (the same one-time-load path as the initial fold) instead, and folding resumes
|
|
45
|
+
// incrementally from ITS tip. The empty-delta check only runs when the store exposes the
|
|
46
|
+
// optional, O(1) `head` — a store without it is tolerated (no fallback full read; the very
|
|
47
|
+
// next non-empty delta still self-heals via the gap check), so this can never turn an
|
|
48
|
+
// empty wake-up into an unbounded read and break the O(N) bound above.
|
|
49
|
+
//
|
|
50
|
+
// A WAKE-UP CAN BE LOST. Cross-node delivery is not guaranteed: a dropped listener or a full
|
|
51
|
+
// Postgres NOTIFY queue costs a wake-up, and a lost one is not sent later. An execution whose last
|
|
52
|
+
// event was the lost one would otherwise never pump again, so a caller waiting to see `completed`
|
|
53
|
+
// would wait forever. So each subscription also pumps on a timer, until its state is terminal. A
|
|
54
|
+
// quiet pump reads only the empty tail past `tip` (the O(N) bound above holds) and emits nothing.
|
|
55
|
+
|
|
56
|
+
/** The runtime capability a live query needs — just the folding read. */
|
|
57
|
+
export interface StateReader {
|
|
58
|
+
loadState(executionId: string, options?: { principal?: unknown }): Promise<ExecutionState | null>;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface LiveQuery {
|
|
62
|
+
/** The current folded state (null if the execution is unknown). */
|
|
63
|
+
snapshot(executionId: string): Promise<ExecutionState | null>;
|
|
64
|
+
/**
|
|
65
|
+
* Push the current state now, then again after every subsequent event, until the
|
|
66
|
+
* returned unsubscribe is called. `onState` receives a coalesced latest-wins state;
|
|
67
|
+
* a terminal state is delivered before teardown so callers can stop on completion.
|
|
68
|
+
*/
|
|
69
|
+
subscribe(executionId: string, onState: (state: ExecutionState) => void): Promise<() => void>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface LiveQueryDeps {
|
|
73
|
+
eventStore: EventStore;
|
|
74
|
+
reader: StateReader;
|
|
75
|
+
/**
|
|
76
|
+
* Reports a BACKGROUND re-fold that failed — a store read that rejected, or an `onState`
|
|
77
|
+
* callback that threw. Those run from the store's subscribe callback with nothing
|
|
78
|
+
* awaiting them, so without this the rejection is unhandled and the process exits.
|
|
79
|
+
*
|
|
80
|
+
* The subscription stays live: one failed re-fold costs that update, and the next event
|
|
81
|
+
* folds from the log again. Unset, failures are swallowed — never rethrown, because
|
|
82
|
+
* there is no caller left to catch them.
|
|
83
|
+
*/
|
|
84
|
+
onError?: (err: unknown) => void;
|
|
85
|
+
/**
|
|
86
|
+
* How often each subscription re-reads the log, in case a wake-up was lost. It stops once the
|
|
87
|
+
* state is terminal, and each quiet pass costs one or two indexed reads, so a live subscription
|
|
88
|
+
* costs at most two reads per interval. `0` turns it off, which means a lost wake-up is only
|
|
89
|
+
* recovered by that execution's next event. Default 5000.
|
|
90
|
+
*/
|
|
91
|
+
pollMs?: number;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const DEFAULT_POLL_MS = 5_000;
|
|
95
|
+
const TERMINAL_STATUSES: ReadonlySet<string> = new Set([
|
|
96
|
+
"completed",
|
|
97
|
+
"failed",
|
|
98
|
+
"cancelled",
|
|
99
|
+
"continued",
|
|
100
|
+
]);
|
|
101
|
+
|
|
102
|
+
/** Build a {@link LiveQuery} over a store + a state reader (typically the runtime). */
|
|
103
|
+
export function liveQuery(deps: LiveQueryDeps): LiveQuery {
|
|
104
|
+
const snapshot = (executionId: string): Promise<ExecutionState | null> =>
|
|
105
|
+
deps.reader.loadState(executionId);
|
|
106
|
+
|
|
107
|
+
return {
|
|
108
|
+
snapshot,
|
|
109
|
+
async subscribe(executionId, onState): Promise<() => void> {
|
|
110
|
+
// Coalesce: only ever one re-fold in flight; if events arrive during a fold,
|
|
111
|
+
// do exactly one more afterwards (latest-wins) so a burst is O(1) extra folds,
|
|
112
|
+
// not one per event, and callers never see stale-then-newer out of order.
|
|
113
|
+
let refolding = false;
|
|
114
|
+
let dirty = false;
|
|
115
|
+
|
|
116
|
+
// Per-subscription incremental fold state. `state === null` means "no baseline
|
|
117
|
+
// yet" — the ONLY condition under which a pass does the full `reader.loadState`;
|
|
118
|
+
// every other pass reads just the tail past `tip` and folds it onto `state`.
|
|
119
|
+
let state: ExecutionState | null = null;
|
|
120
|
+
let tip = -1;
|
|
121
|
+
|
|
122
|
+
const pump = async (): Promise<void> => {
|
|
123
|
+
if (refolding) {
|
|
124
|
+
dirty = true;
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
refolding = true;
|
|
128
|
+
try {
|
|
129
|
+
do {
|
|
130
|
+
dirty = false;
|
|
131
|
+
if (state === null) {
|
|
132
|
+
state = await deps.reader.loadState(executionId);
|
|
133
|
+
if (state !== null) tip = state.sequence;
|
|
134
|
+
} else {
|
|
135
|
+
const delta = await deps.eventStore.readFrom(executionId, tip + 1);
|
|
136
|
+
if (delta.length === 0) {
|
|
137
|
+
// Nothing new — UNLESS a compaction truncated everything after `tip` with
|
|
138
|
+
// no later event yet to reveal the gap. Only checked when the store has a
|
|
139
|
+
// cheap indexed tip, so an empty wake-up never costs a full read.
|
|
140
|
+
const head = deps.eventStore.head
|
|
141
|
+
? await deps.eventStore.head(executionId)
|
|
142
|
+
: undefined;
|
|
143
|
+
if (head === undefined || head === null || head >= tip) continue; // truly nothing new
|
|
144
|
+
state = await deps.reader.loadState(executionId);
|
|
145
|
+
if (state !== null) tip = state.sequence;
|
|
146
|
+
} else if (
|
|
147
|
+
delta[0]!.sequence !== tip + 1 ||
|
|
148
|
+
delta[delta.length - 1]!.sequence - tip !== delta.length
|
|
149
|
+
) {
|
|
150
|
+
// Non-contiguous: a compaction truncated events between `tip` and the
|
|
151
|
+
// first surviving one out from under this subscription — or, since ADR 0106
|
|
152
|
+
// keeps an app's pinned-kind events in place, a kept event sits at `tip + 1`
|
|
153
|
+
// and the gap is INSIDE the delta (sequences are unique and sorted, so the
|
|
154
|
+
// delta is contiguous iff its span equals its length: O(1)). Folding `delta`
|
|
155
|
+
// onto `state` here would silently produce a WRONG `ExecutionState` — fall
|
|
156
|
+
// back to a full fold, exactly like the one-time initial load.
|
|
157
|
+
state = await deps.reader.loadState(executionId);
|
|
158
|
+
if (state !== null) tip = state.sequence;
|
|
159
|
+
} else {
|
|
160
|
+
// `foldEvents` treats `state` as immutable (fresh audit-list ownership per
|
|
161
|
+
// pass), so folding the delta onto the kept state never mutates what a
|
|
162
|
+
// previous `onState` call was handed.
|
|
163
|
+
state = foldEvents(delta, state);
|
|
164
|
+
tip = delta[delta.length - 1]!.sequence;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
if (state !== null) onState(state);
|
|
168
|
+
} while (dirty);
|
|
169
|
+
} finally {
|
|
170
|
+
refolding = false;
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
const unsubscribe = await deps.eventStore.subscribe(executionId, (_e: EventEnvelope) => {
|
|
175
|
+
// Background re-fold: nothing awaits it, so it must never escape as an unhandled
|
|
176
|
+
// rejection. The FIRST fold below is different — the caller awaits `subscribe`, so
|
|
177
|
+
// a failure there is theirs to see and is deliberately left to propagate.
|
|
178
|
+
void pump().catch((err: unknown) => deps.onError?.(err));
|
|
179
|
+
});
|
|
180
|
+
// Emit the current state immediately so a subscriber isn't blind until the next event.
|
|
181
|
+
await pump();
|
|
182
|
+
const pollMs = deps.pollMs ?? DEFAULT_POLL_MS;
|
|
183
|
+
if (!(pollMs > 0)) return unsubscribe;
|
|
184
|
+
const poll = setInterval(() => {
|
|
185
|
+
if (state !== null && TERMINAL_STATUSES.has(state.status)) {
|
|
186
|
+
clearInterval(poll);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
if (refolding) return; // the pass in flight already reads the log
|
|
190
|
+
void pump().catch((err: unknown) => deps.onError?.(err));
|
|
191
|
+
}, pollMs);
|
|
192
|
+
poll.unref?.();
|
|
193
|
+
return () => {
|
|
194
|
+
clearInterval(poll);
|
|
195
|
+
unsubscribe();
|
|
196
|
+
};
|
|
197
|
+
},
|
|
198
|
+
};
|
|
199
|
+
}
|