@swirls/looms 0.14.0 → 0.15.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/CHANGELOG.md +10 -0
- package/dist/actor/cell.d.ts +3 -9
- package/dist/actor/host.d.ts +2 -4
- package/dist/cloudflare/durable-object.d.ts +5 -17
- package/dist/core/event-codec.js +3 -0
- package/dist/debugger/app/assets/{index-CtGiJU8b.js → index-CZwbkhFX.js} +3 -3
- package/dist/debugger/app/assets/routes-CSuFE23L.js +47 -0
- package/dist/debugger/app/index.html +1 -1
- package/dist/react/derived.d.ts +5 -2
- package/dist/react/derived.js +27 -4
- package/dist/react/index.d.ts +1 -1
- package/dist/react/index.js +1 -1
- package/dist/react/react.d.ts +16 -4
- package/dist/react/react.js +20 -10
- package/dist/react/store.d.ts +43 -1
- package/dist/react/store.js +201 -24
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/looms.d.ts +2 -4
- package/dist/runtime/runtime.d.ts +1 -1
- package/dist/runtime/runtime.js +7 -1
- package/dist/runtime/server/http.d.ts +6 -0
- package/dist/runtime/server/http.js +13 -0
- package/dist/runtime/server/routes/runs.js +22 -5
- package/dist/runtime/types.d.ts +15 -8
- package/package.json +1 -1
- package/dist/debugger/app/assets/routes-Bg0vNEOr.js +0 -47
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
<meta charset="UTF-8" />
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
6
|
<title>Looms debugger</title>
|
|
7
|
-
<script type="module" crossorigin src="./assets/index-
|
|
7
|
+
<script type="module" crossorigin src="./assets/index-CZwbkhFX.js"></script>
|
|
8
8
|
<link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-CbXtAM7H.js">
|
|
9
9
|
<link rel="stylesheet" crossorigin href="./assets/index-CO5gIvV8.css">
|
|
10
10
|
</head>
|
package/dist/react/derived.d.ts
CHANGED
|
@@ -30,8 +30,11 @@ export declare function foldLive<S, TEvent extends AnyEventEnvelope = Registered
|
|
|
30
30
|
export declare class ProjectionCache {
|
|
31
31
|
private projectionCache;
|
|
32
32
|
private foldCache;
|
|
33
|
-
|
|
33
|
+
private projectionOverlay;
|
|
34
|
+
private foldOverlay;
|
|
35
|
+
/** `pending` are events shown before the host confirms them; they fold after `events`. */
|
|
36
|
+
project<S>(definition: ProjectionDefinition<S>, events: readonly EventEnvelope[], pending?: readonly EventEnvelope[], pendingVersion?: number): S;
|
|
34
37
|
/** A retry can supersede events already folded, so a batch containing one refolds from scratch. */
|
|
35
|
-
fold<S, TEvent extends AnyEventEnvelope = RegisteredEvent>(definition: LiveFoldDefinition<S, TEvent>, events: readonly TEvent[]): S;
|
|
38
|
+
fold<S, TEvent extends AnyEventEnvelope = RegisteredEvent>(definition: LiveFoldDefinition<S, TEvent>, events: readonly TEvent[], pending?: readonly TEvent[], pendingVersion?: number): S;
|
|
36
39
|
clear(): void;
|
|
37
40
|
}
|
package/dist/react/derived.js
CHANGED
|
@@ -30,18 +30,41 @@ function advanceCache(cache, definition, events, compute, canAppend = () => true
|
|
|
30
30
|
cache.set(definition, { state, upTo: events.length });
|
|
31
31
|
return state;
|
|
32
32
|
}
|
|
33
|
+
/**
|
|
34
|
+
* Folds events not yet confirmed on top of the confirmed state. The confirmed fold stays
|
|
35
|
+
* incremental; the overlay is refolded only when the confirmed state or the pending set changes.
|
|
36
|
+
*/
|
|
37
|
+
function overlay(cache, definition, base, pending, pendingVersion, compute) {
|
|
38
|
+
if (pending.length === 0) {
|
|
39
|
+
return base;
|
|
40
|
+
}
|
|
41
|
+
const cached = cache.get(definition);
|
|
42
|
+
if (cached && cached.base === base && cached.pending === pendingVersion) {
|
|
43
|
+
return cached.state;
|
|
44
|
+
}
|
|
45
|
+
const state = compute(definition, pending, base);
|
|
46
|
+
cache.set(definition, { base, pending: pendingVersion, state });
|
|
47
|
+
return state;
|
|
48
|
+
}
|
|
33
49
|
export class ProjectionCache {
|
|
34
50
|
projectionCache = new WeakMap();
|
|
35
51
|
foldCache = new WeakMap();
|
|
36
|
-
|
|
37
|
-
|
|
52
|
+
projectionOverlay = new WeakMap();
|
|
53
|
+
foldOverlay = new WeakMap();
|
|
54
|
+
/** `pending` are events shown before the host confirms them; they fold after `events`. */
|
|
55
|
+
project(definition, events, pending = [], pendingVersion = 0) {
|
|
56
|
+
const base = advanceCache(this.projectionCache, definition, events, project);
|
|
57
|
+
return overlay(this.projectionOverlay, definition, base, pending, pendingVersion, project);
|
|
38
58
|
}
|
|
39
59
|
/** A retry can supersede events already folded, so a batch containing one refolds from scratch. */
|
|
40
|
-
fold(definition, events) {
|
|
41
|
-
|
|
60
|
+
fold(definition, events, pending = [], pendingVersion = 0) {
|
|
61
|
+
const base = advanceCache(this.foldCache, definition, events, foldFrom, hasNoRetries);
|
|
62
|
+
return overlay(this.foldOverlay, definition, base, pending, pendingVersion, foldFrom);
|
|
42
63
|
}
|
|
43
64
|
clear() {
|
|
44
65
|
this.projectionCache = new WeakMap();
|
|
45
66
|
this.foldCache = new WeakMap();
|
|
67
|
+
this.projectionOverlay = new WeakMap();
|
|
68
|
+
this.foldOverlay = new WeakMap();
|
|
46
69
|
}
|
|
47
70
|
}
|
package/dist/react/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { createLoomsStore, type LoomsClientStore, type LoomsClientStoreOptions, type LoomsConnectionStatus, type LoomsStoreQuery, type CoalesceOption, type StoreListener, } from './store';
|
|
1
|
+
export { createLoomsStore, isPendingEvent, type CommitOptions, type LoomsClientStore, type LoomsClientStoreOptions, type LoomsConnectionStatus, type LoomsStoreQuery, type CoalesceOption, type StoreListener, } from './store';
|
|
2
2
|
export { defineLiveFold, foldLive, EventIndex, eventThreadKey, type LiveFoldDefinition, } from './derived';
|
|
3
3
|
export { materializeEvents } from './materialize';
|
|
4
4
|
export { emptyTables, type MaterializedTables, type RunRow, type ThreadRow } from './tables';
|
package/dist/react/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { createLoomsStore, } from './store.js';
|
|
1
|
+
export { createLoomsStore, isPendingEvent, } from './store.js';
|
|
2
2
|
export { defineLiveFold, foldLive, EventIndex, eventThreadKey, } from './derived.js';
|
|
3
3
|
export { materializeEvents } from './materialize.js';
|
|
4
4
|
export { emptyTables } from './tables.js';
|
package/dist/react/react.d.ts
CHANGED
|
@@ -1,20 +1,27 @@
|
|
|
1
1
|
import { type ReactNode } from 'react';
|
|
2
2
|
import { type AnyEventEnvelope, type ProjectionDefinition, type RegisteredEvent, type RunAttributes, type RunLaunchSource, type RunStatus, type SubscriptionTransport, type ThreadTree } from '@swirls/looms/core';
|
|
3
3
|
import { defineLiveFold, foldLive, type LiveFoldDefinition } from './derived';
|
|
4
|
-
import { createLoomsStore, type CoalesceOption, type LoomsClientStore, type LoomsConnectionStatus } from './store';
|
|
4
|
+
import { createLoomsStore, isPendingEvent, type CoalesceOption, type LoomsClientStore, type LoomsConnectionStatus } from './store';
|
|
5
5
|
export interface LoomsProviderProps {
|
|
6
6
|
children: ReactNode;
|
|
7
7
|
endpoint?: string;
|
|
8
8
|
coalesce?: CoalesceOption;
|
|
9
9
|
transport?: SubscriptionTransport;
|
|
10
|
+
/**
|
|
11
|
+
* How long a run's store stays connected and in memory after the last component using it
|
|
12
|
+
* unmounts. Returning to the run within that time shows it at once, with no download. Defaults
|
|
13
|
+
* to five seconds.
|
|
14
|
+
*/
|
|
15
|
+
retainMs?: number;
|
|
10
16
|
}
|
|
11
17
|
interface ProviderContextValue {
|
|
12
18
|
endpoint: string;
|
|
13
19
|
coalesce?: CoalesceOption;
|
|
14
20
|
transport?: SubscriptionTransport;
|
|
21
|
+
retainMs?: number;
|
|
15
22
|
}
|
|
16
23
|
/** Root provider that supplies the Looms host endpoint to run stores. */
|
|
17
|
-
export declare function LoomsProvider({ children, endpoint, coalesce, transport, }: LoomsProviderProps): import("react").FunctionComponentElement<import("react").ProviderProps<ProviderContextValue>>;
|
|
24
|
+
export declare function LoomsProvider({ children, endpoint, coalesce, transport, retainMs, }: LoomsProviderProps): import("react").FunctionComponentElement<import("react").ProviderProps<ProviderContextValue>>;
|
|
18
25
|
export interface UseRunStoreOptions {
|
|
19
26
|
endpoint?: string;
|
|
20
27
|
reconnectDelayMs?: number;
|
|
@@ -22,6 +29,9 @@ export interface UseRunStoreOptions {
|
|
|
22
29
|
transport?: SubscriptionTransport;
|
|
23
30
|
threadId?: string;
|
|
24
31
|
includeEphemeral?: boolean;
|
|
32
|
+
/** See `LoomsClientStoreOptions.fromSeq`. Read once, when the store is first created. */
|
|
33
|
+
fromSeq?: number;
|
|
34
|
+
retainMs?: number;
|
|
25
35
|
}
|
|
26
36
|
/**
|
|
27
37
|
* Acquires a non-subscribing handle to the run store.
|
|
@@ -47,6 +57,8 @@ export interface RunSummary {
|
|
|
47
57
|
readonly launchedBy: RunLaunchSource | undefined;
|
|
48
58
|
readonly attributes: RunAttributes;
|
|
49
59
|
readonly connection: LoomsConnectionStatus;
|
|
60
|
+
/** False while the store is still catching up to the log, when empty state means "loading". */
|
|
61
|
+
readonly synced: boolean;
|
|
50
62
|
}
|
|
51
63
|
/** Lightweight subscription to top-level run metadata and connection status. */
|
|
52
64
|
export declare function useRunSummary<TEvent extends AnyEventEnvelope = RegisteredEvent>(store: LoomsClientStore<TEvent>): RunSummary;
|
|
@@ -64,8 +76,8 @@ export declare function useEventBySeq<TEvent extends AnyEventEnvelope = Register
|
|
|
64
76
|
export declare function useLatestEvent<TEvent extends AnyEventEnvelope = RegisteredEvent>(store: LoomsClientStore<TEvent>, type: string): TEvent | undefined;
|
|
65
77
|
/** Subscribe to a live fold, which includes ephemeral events. */
|
|
66
78
|
export declare function useLiveFold<S, TEvent extends AnyEventEnvelope = RegisteredEvent>(store: LoomsClientStore<TEvent>, fold: LiveFoldDefinition<S, TEvent>): S;
|
|
67
|
-
export { createLoomsStore };
|
|
79
|
+
export { createLoomsStore, isPendingEvent };
|
|
68
80
|
export { defineLiveFold, foldLive };
|
|
69
|
-
export type { LoomsClientStore, LoomsClientStoreOptions, LoomsConnectionStatus, LoomsStoreQuery, CoalesceOption, StoreListener, } from './store';
|
|
81
|
+
export type { LoomsClientStore, CommitOptions, LoomsClientStoreOptions, LoomsConnectionStatus, LoomsStoreQuery, CoalesceOption, StoreListener, } from './store';
|
|
70
82
|
export type { LiveFoldDefinition } from './derived';
|
|
71
83
|
export type { LoomsRegister, RegisteredEvent, AnyEventEnvelope } from '@swirls/looms/core';
|
package/dist/react/react.js
CHANGED
|
@@ -2,9 +2,9 @@ import { Effect, Fiber } from 'effect';
|
|
|
2
2
|
import { createContext, createElement, useCallback, useContext, useEffect, useMemo, useRef, useSyncExternalStore, } from 'react';
|
|
3
3
|
import { isTerminalStatus, sameStringRecord, threadTree, toThreadTree, } from '@swirls/looms/core';
|
|
4
4
|
import { defineLiveFold, foldLive } from './derived.js';
|
|
5
|
-
import { createLoomsStore, } from './store.js';
|
|
5
|
+
import { createLoomsStore, isPendingEvent, } from './store.js';
|
|
6
6
|
const LoomsContext = createContext({ endpoint: '' });
|
|
7
|
-
const
|
|
7
|
+
const DEFAULT_RETAIN_MS = 5_000;
|
|
8
8
|
const registry = new Map();
|
|
9
9
|
function registryKey(runId, identity) {
|
|
10
10
|
return [
|
|
@@ -23,8 +23,8 @@ function disposeEntry(key) {
|
|
|
23
23
|
entry.store.dispose();
|
|
24
24
|
registry.delete(key);
|
|
25
25
|
}
|
|
26
|
-
function scheduleDisposal(key) {
|
|
27
|
-
return Effect.runFork(Effect.sleep(
|
|
26
|
+
function scheduleDisposal(key, retainMs) {
|
|
27
|
+
return Effect.runFork(Effect.sleep(retainMs).pipe(Effect.andThen(Effect.sync(() => disposeEntry(key)))));
|
|
28
28
|
}
|
|
29
29
|
function peekStore(runId, identity) {
|
|
30
30
|
const key = registryKey(runId, identity);
|
|
@@ -40,11 +40,15 @@ function peekStore(runId, identity) {
|
|
|
40
40
|
transport: identity.transport,
|
|
41
41
|
threadId: identity.threadId,
|
|
42
42
|
includeEphemeral: identity.includeEphemeral,
|
|
43
|
+
fromSeq: identity.fromSeq,
|
|
43
44
|
});
|
|
45
|
+
const retainMs = Math.max(0, identity.retainMs ?? DEFAULT_RETAIN_MS);
|
|
44
46
|
registry.set(key, {
|
|
45
47
|
store,
|
|
46
48
|
refs: 0,
|
|
47
|
-
|
|
49
|
+
retainMs,
|
|
50
|
+
// A store that is peeked at and never mounted is not kept for the full retention.
|
|
51
|
+
disposal: scheduleDisposal(key, Math.min(retainMs, DEFAULT_RETAIN_MS)),
|
|
48
52
|
});
|
|
49
53
|
return store;
|
|
50
54
|
}
|
|
@@ -69,12 +73,12 @@ function releaseStore(runId, identity) {
|
|
|
69
73
|
}
|
|
70
74
|
entry.refs = Math.max(0, entry.refs - 1);
|
|
71
75
|
if (entry.refs === 0 && entry.disposal === undefined) {
|
|
72
|
-
entry.disposal = scheduleDisposal(key);
|
|
76
|
+
entry.disposal = scheduleDisposal(key, entry.retainMs);
|
|
73
77
|
}
|
|
74
78
|
}
|
|
75
79
|
/** Root provider that supplies the Looms host endpoint to run stores. */
|
|
76
|
-
export function LoomsProvider({ children, endpoint = '', coalesce, transport, }) {
|
|
77
|
-
const value = useMemo(() => ({ endpoint, coalesce, transport }), [endpoint, coalesce, transport]);
|
|
80
|
+
export function LoomsProvider({ children, endpoint = '', coalesce, transport, retainMs, }) {
|
|
81
|
+
const value = useMemo(() => ({ endpoint, coalesce, transport, retainMs }), [endpoint, coalesce, transport, retainMs]);
|
|
78
82
|
return createElement(LoomsContext.Provider, { value, children });
|
|
79
83
|
}
|
|
80
84
|
/**
|
|
@@ -90,6 +94,8 @@ export function useRunStore(runId, options) {
|
|
|
90
94
|
const transport = options?.transport ?? context.transport;
|
|
91
95
|
const threadId = options?.threadId;
|
|
92
96
|
const includeEphemeral = options?.includeEphemeral;
|
|
97
|
+
const fromSeq = options?.fromSeq;
|
|
98
|
+
const retainMs = options?.retainMs ?? context.retainMs;
|
|
93
99
|
const identity = {
|
|
94
100
|
endpoint,
|
|
95
101
|
reconnectDelayMs,
|
|
@@ -97,6 +103,8 @@ export function useRunStore(runId, options) {
|
|
|
97
103
|
transport,
|
|
98
104
|
threadId,
|
|
99
105
|
includeEphemeral,
|
|
106
|
+
fromSeq,
|
|
107
|
+
retainMs,
|
|
100
108
|
};
|
|
101
109
|
const store = peekStore(runId, identity);
|
|
102
110
|
useEffect(() => {
|
|
@@ -141,7 +149,8 @@ function shallowEqualSummary(a, b) {
|
|
|
141
149
|
a.startedAt === b.startedAt &&
|
|
142
150
|
a.launchedBy === b.launchedBy &&
|
|
143
151
|
sameStringRecord(a.attributes, b.attributes) &&
|
|
144
|
-
a.connection === b.connection
|
|
152
|
+
a.connection === b.connection &&
|
|
153
|
+
a.synced === b.synced);
|
|
145
154
|
}
|
|
146
155
|
/** Lightweight subscription to top-level run metadata and connection status. */
|
|
147
156
|
export function useRunSummary(store) {
|
|
@@ -159,6 +168,7 @@ export function useRunSummary(store) {
|
|
|
159
168
|
launchedBy: run?.launchedBy ?? undefined,
|
|
160
169
|
attributes: run?.attributes ?? {},
|
|
161
170
|
connection: s.status(),
|
|
171
|
+
synced: s.synced(),
|
|
162
172
|
};
|
|
163
173
|
}, []);
|
|
164
174
|
return useRunSelector(store, selector, shallowEqualSummary);
|
|
@@ -194,5 +204,5 @@ export function useLiveFold(store, fold) {
|
|
|
194
204
|
const getSnapshot = useCallback(() => store.fold(fold), [store, fold]);
|
|
195
205
|
return useStoreSnapshot(store, getSnapshot);
|
|
196
206
|
}
|
|
197
|
-
export { createLoomsStore };
|
|
207
|
+
export { createLoomsStore, isPendingEvent };
|
|
198
208
|
export { defineLiveFold, foldLive };
|
package/dist/react/store.d.ts
CHANGED
|
@@ -7,6 +7,33 @@ export type { CoalesceOption } from './notify';
|
|
|
7
7
|
/** Fired after the store version bumps. Re-read via `events()` / `getState()` / `query`. */
|
|
8
8
|
export type StoreListener = () => void;
|
|
9
9
|
export type LoomsConnectionStatus = 'connecting' | 'live' | 'reconnecting';
|
|
10
|
+
/** True for an event shown optimistically that the host has not confirmed yet. */
|
|
11
|
+
export declare function isPendingEvent(event: {
|
|
12
|
+
readonly seq: number;
|
|
13
|
+
}): boolean;
|
|
14
|
+
export interface CommitOptions {
|
|
15
|
+
/**
|
|
16
|
+
* Show the events at once, before the host confirms them. They are folded after every confirmed
|
|
17
|
+
* event, replaced by the host's own copies when those arrive, and removed if the commit fails,
|
|
18
|
+
* in which case `commit` rejects. Defaults to the store's `optimistic` option.
|
|
19
|
+
*/
|
|
20
|
+
optimistic?: boolean;
|
|
21
|
+
/**
|
|
22
|
+
* Identifies this commit to the host, which ignores a repeat of it. An optimistic commit is
|
|
23
|
+
* matched to its confirmed events by this key; one is generated when it is left out.
|
|
24
|
+
*/
|
|
25
|
+
idempotencyKey?: string;
|
|
26
|
+
/**
|
|
27
|
+
* Sends the commit somewhere other than the run's signal route, such as a route of your own that
|
|
28
|
+
* signs the events. It must signal the run with the `idempotencyKey` it is given, or an
|
|
29
|
+
* optimistic commit cannot be matched to what the host records.
|
|
30
|
+
*/
|
|
31
|
+
send?: (commit: {
|
|
32
|
+
readonly events: readonly EventInput[];
|
|
33
|
+
readonly idempotencyKey: string | undefined;
|
|
34
|
+
readonly signal: AbortSignal;
|
|
35
|
+
}) => Promise<void>;
|
|
36
|
+
}
|
|
10
37
|
export interface LoomsClientStoreOptions {
|
|
11
38
|
/** Run id for this client store. */
|
|
12
39
|
storeId: string;
|
|
@@ -27,6 +54,14 @@ export interface LoomsClientStoreOptions {
|
|
|
27
54
|
threadId?: string;
|
|
28
55
|
includeEphemeral?: boolean;
|
|
29
56
|
webSocket?: SubscriptionSocketConstructor;
|
|
57
|
+
/**
|
|
58
|
+
* First sequence number to follow. Use it with state you already hold up to `fromSeq - 1`, such
|
|
59
|
+
* as a projection the host served, so the store does not download the log behind it. Events
|
|
60
|
+
* before it are never seen: `events()`, projections and the run summary cover only what follows.
|
|
61
|
+
*/
|
|
62
|
+
fromSeq?: number;
|
|
63
|
+
/** Whether `commit` shows its events before the host confirms them. Defaults to false. */
|
|
64
|
+
optimistic?: boolean;
|
|
30
65
|
}
|
|
31
66
|
export interface LoomsStoreQuery<TEvent extends AnyEventEnvelope = RegisteredEvent> {
|
|
32
67
|
events: (options?: {
|
|
@@ -44,6 +79,11 @@ export interface LoomsClientStore<TEvent extends AnyEventEnvelope = RegisteredEv
|
|
|
44
79
|
storeId: string;
|
|
45
80
|
version: () => number;
|
|
46
81
|
status: () => LoomsConnectionStatus;
|
|
82
|
+
/**
|
|
83
|
+
* True once the store holds everything the log had when the subscription opened. Until then an
|
|
84
|
+
* empty projection means "still loading", not "nothing there".
|
|
85
|
+
*/
|
|
86
|
+
synced: () => boolean;
|
|
47
87
|
getState: () => MaterializedTables;
|
|
48
88
|
events: (options?: {
|
|
49
89
|
threadId?: string;
|
|
@@ -53,7 +93,9 @@ export interface LoomsClientStore<TEvent extends AnyEventEnvelope = RegisteredEv
|
|
|
53
93
|
project<S>(definition: ProjectionDefinition<S>): S;
|
|
54
94
|
fold<S>(definition: LiveFoldDefinition<S, TEvent>): S;
|
|
55
95
|
flush: () => void;
|
|
56
|
-
|
|
96
|
+
/** Events shown optimistically that the host has not confirmed yet. */
|
|
97
|
+
pending: () => readonly TEvent[];
|
|
98
|
+
commit: (event: EventInput | readonly EventInput[], options?: CommitOptions) => Promise<void>;
|
|
57
99
|
sync: () => Promise<void>;
|
|
58
100
|
dispose: () => void;
|
|
59
101
|
}
|
package/dist/react/store.js
CHANGED
|
@@ -1,11 +1,24 @@
|
|
|
1
1
|
import { Data, Effect, Fiber, Option, Predicate, Schema } from 'effect';
|
|
2
2
|
import { absoluteHttpBase } from '@swirls/looms/client';
|
|
3
|
-
import { decodeLoomsEvent, readSubscriptionData, stringifyJson, } from '@swirls/looms/core';
|
|
3
|
+
import { createEvent, createEventId, decodeLoomsEvent, readSubscriptionData, stringifyJson, } from '@swirls/looms/core';
|
|
4
4
|
import { EventIndex, ProjectionCache } from './derived.js';
|
|
5
5
|
import { materializeEvents } from './materialize.js';
|
|
6
6
|
import { createNotifyScheduler } from './notify.js';
|
|
7
7
|
import { consumeSseStreamEffect } from './sse.js';
|
|
8
8
|
import { emptyTables } from './tables.js';
|
|
9
|
+
/**
|
|
10
|
+
* Sequence numbers at or above this belong to events the store is showing before the host has
|
|
11
|
+
* confirmed them. They sort after every confirmed event.
|
|
12
|
+
*/
|
|
13
|
+
const PENDING_SEQ_BASE = 2 ** 52;
|
|
14
|
+
/** How long a commit the host accepted may stay unconfirmed before the store stops showing it. */
|
|
15
|
+
const PENDING_SETTLE_MS = 10_000;
|
|
16
|
+
/** True for an event shown optimistically that the host has not confirmed yet. */
|
|
17
|
+
export function isPendingEvent(event) {
|
|
18
|
+
return event.seq >= PENDING_SEQ_BASE;
|
|
19
|
+
}
|
|
20
|
+
/** How long a filtered subscription's opening replay must be quiet to count as caught up. */
|
|
21
|
+
const SYNC_QUIET_MS = 250;
|
|
9
22
|
class LoomsStoreError extends Data.TaggedError('LoomsStoreError') {
|
|
10
23
|
constructor(message, cause) {
|
|
11
24
|
super({ cause, message });
|
|
@@ -49,7 +62,13 @@ export function createLoomsStore(options) {
|
|
|
49
62
|
let version = 0;
|
|
50
63
|
let status = 'connecting';
|
|
51
64
|
let tables = emptyTables();
|
|
52
|
-
let fromSeq = 1;
|
|
65
|
+
let fromSeq = Math.max(1, Math.trunc(options.fromSeq ?? 1));
|
|
66
|
+
// A filtered subscription may never be sent the event at the tail, so it also counts as caught
|
|
67
|
+
// up once the opening replay goes quiet.
|
|
68
|
+
const filtered = options.threadId !== undefined || options.includeEphemeral === false;
|
|
69
|
+
let synced = false;
|
|
70
|
+
let syncTail;
|
|
71
|
+
let quietFiber;
|
|
53
72
|
let disposed = false;
|
|
54
73
|
let live = false;
|
|
55
74
|
let liveStarted = false;
|
|
@@ -58,7 +77,13 @@ export function createLoomsStore(options) {
|
|
|
58
77
|
let socket;
|
|
59
78
|
let reconnectFiber;
|
|
60
79
|
let syncing = null;
|
|
61
|
-
const
|
|
80
|
+
const pendingCommits = [];
|
|
81
|
+
let pendingEvents = Object.freeze([]);
|
|
82
|
+
let pendingVersion = 0;
|
|
83
|
+
let pendingSeq = PENDING_SEQ_BASE;
|
|
84
|
+
let visible;
|
|
85
|
+
const visibleByThread = new Map();
|
|
86
|
+
const confirmedEvents = () => {
|
|
62
87
|
if (!eventsSnapshotDirty) {
|
|
63
88
|
return eventsSnapshot;
|
|
64
89
|
}
|
|
@@ -66,6 +91,43 @@ export function createLoomsStore(options) {
|
|
|
66
91
|
eventsSnapshotDirty = false;
|
|
67
92
|
return eventsSnapshot;
|
|
68
93
|
};
|
|
94
|
+
/** `base` with the pending events after it. Stable while neither has changed. */
|
|
95
|
+
const withPending = (base, cached, threadId) => {
|
|
96
|
+
if (cached && cached.base === base && cached.pending === pendingVersion) {
|
|
97
|
+
return cached;
|
|
98
|
+
}
|
|
99
|
+
const extra = threadId
|
|
100
|
+
? pendingEvents.filter((event) => event.threadId === threadId)
|
|
101
|
+
: pendingEvents;
|
|
102
|
+
return {
|
|
103
|
+
base,
|
|
104
|
+
pending: pendingVersion,
|
|
105
|
+
value: extra.length === 0 ? base : Object.freeze([...base, ...extra]),
|
|
106
|
+
};
|
|
107
|
+
};
|
|
108
|
+
/** What readers see: every confirmed event, then the ones still waiting to be confirmed. */
|
|
109
|
+
const publishedEvents = () => {
|
|
110
|
+
visible = withPending(confirmedEvents(), visible);
|
|
111
|
+
return visible.value;
|
|
112
|
+
};
|
|
113
|
+
const setPending = () => {
|
|
114
|
+
pendingEvents = Object.freeze(pendingCommits.flatMap((commit) => commit.events));
|
|
115
|
+
pendingVersion += 1;
|
|
116
|
+
version += 1;
|
|
117
|
+
};
|
|
118
|
+
const dropPending = (commit) => {
|
|
119
|
+
const index = pendingCommits.indexOf(commit);
|
|
120
|
+
if (index === -1) {
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
pendingCommits.splice(index, 1);
|
|
124
|
+
if (commit.settle !== undefined) {
|
|
125
|
+
Effect.runFork(Fiber.interrupt(commit.settle));
|
|
126
|
+
commit.settle = undefined;
|
|
127
|
+
}
|
|
128
|
+
setPending();
|
|
129
|
+
return true;
|
|
130
|
+
};
|
|
69
131
|
const notify = createNotifyScheduler(coalesce, () => {
|
|
70
132
|
publishedEvents();
|
|
71
133
|
for (const listener of listeners) {
|
|
@@ -80,6 +142,35 @@ export function createLoomsStore(options) {
|
|
|
80
142
|
version += 1;
|
|
81
143
|
notify.schedule();
|
|
82
144
|
};
|
|
145
|
+
const cancelQuiet = () => {
|
|
146
|
+
if (quietFiber !== undefined) {
|
|
147
|
+
Effect.runFork(Fiber.interrupt(quietFiber));
|
|
148
|
+
quietFiber = undefined;
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
const markSynced = () => {
|
|
152
|
+
cancelQuiet();
|
|
153
|
+
if (synced) {
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
synced = true;
|
|
157
|
+
version += 1;
|
|
158
|
+
notify.schedule();
|
|
159
|
+
};
|
|
160
|
+
/** Called when the subscription reports its bounds and after each batch that follows. */
|
|
161
|
+
const checkSynced = () => {
|
|
162
|
+
if (synced || syncTail === undefined) {
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
if (fromSeq > syncTail) {
|
|
166
|
+
markSynced();
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
if (filtered) {
|
|
170
|
+
cancelQuiet();
|
|
171
|
+
quietFiber = Effect.runFork(Effect.sleep(SYNC_QUIET_MS).pipe(Effect.andThen(Effect.sync(markSynced))));
|
|
172
|
+
}
|
|
173
|
+
};
|
|
83
174
|
const applyBatch = (batch) => {
|
|
84
175
|
const fresh = [];
|
|
85
176
|
for (const event of batch) {
|
|
@@ -91,6 +182,7 @@ export function createLoomsStore(options) {
|
|
|
91
182
|
fromSeq = Math.max(fromSeq, event.seq + 1);
|
|
92
183
|
}
|
|
93
184
|
if (fresh.length === 0) {
|
|
185
|
+
checkSynced();
|
|
94
186
|
return;
|
|
95
187
|
}
|
|
96
188
|
tables = materializeEvents(fresh, tables);
|
|
@@ -100,7 +192,17 @@ export function createLoomsStore(options) {
|
|
|
100
192
|
eventsSnapshotDirty = true;
|
|
101
193
|
eventIndex.append(fresh);
|
|
102
194
|
version += 1;
|
|
195
|
+
// The host's copy of an optimistic commit takes the place of the provisional one.
|
|
196
|
+
for (const event of fresh) {
|
|
197
|
+
const confirmed = event.idempotencyKey
|
|
198
|
+
? pendingCommits.find((commit) => commit.key === event.idempotencyKey)
|
|
199
|
+
: undefined;
|
|
200
|
+
if (confirmed) {
|
|
201
|
+
dropPending(confirmed);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
103
204
|
notify.schedule();
|
|
205
|
+
checkSynced();
|
|
104
206
|
};
|
|
105
207
|
const applyLiveData = (data) => {
|
|
106
208
|
const read = readSubscriptionData(data, options.storeId);
|
|
@@ -112,6 +214,9 @@ export function createLoomsStore(options) {
|
|
|
112
214
|
fromSeq = read.head;
|
|
113
215
|
return 'resync';
|
|
114
216
|
case 'hello':
|
|
217
|
+
syncTail = read.tail;
|
|
218
|
+
checkSynced();
|
|
219
|
+
return 'continue';
|
|
115
220
|
case 'ignore':
|
|
116
221
|
return 'continue';
|
|
117
222
|
default: {
|
|
@@ -349,8 +454,11 @@ export function createLoomsStore(options) {
|
|
|
349
454
|
startLive();
|
|
350
455
|
}
|
|
351
456
|
const readEvents = (filterOptions) => {
|
|
352
|
-
|
|
353
|
-
|
|
457
|
+
const threadId = filterOptions?.threadId;
|
|
458
|
+
if (threadId) {
|
|
459
|
+
const slice = withPending(eventIndex.getByThread(threadId), visibleByThread.get(threadId), threadId);
|
|
460
|
+
visibleByThread.set(threadId, slice);
|
|
461
|
+
return slice.value;
|
|
354
462
|
}
|
|
355
463
|
return publishedEvents();
|
|
356
464
|
};
|
|
@@ -358,6 +466,7 @@ export function createLoomsStore(options) {
|
|
|
358
466
|
storeId: options.storeId,
|
|
359
467
|
version: () => version,
|
|
360
468
|
status: () => status,
|
|
469
|
+
synced: () => synced,
|
|
361
470
|
/**
|
|
362
471
|
* Live mutable materialized tables. Re-read after each version bump;
|
|
363
472
|
* do not hold Map/array references across notifies.
|
|
@@ -372,7 +481,7 @@ export function createLoomsStore(options) {
|
|
|
372
481
|
bySeq: (seq) => eventIndex.getBySeq(seq),
|
|
373
482
|
startedAt: () => eventIndex.getStartedAt(),
|
|
374
483
|
latest: (type) => eventIndex.getLatest(type),
|
|
375
|
-
fold: (def) => projectionCache.fold(def,
|
|
484
|
+
fold: (def) => projectionCache.fold(def, confirmedEvents(), pendingEvents, pendingVersion),
|
|
376
485
|
},
|
|
377
486
|
subscribe: (listener) => {
|
|
378
487
|
listeners.add(listener);
|
|
@@ -384,34 +493,102 @@ export function createLoomsStore(options) {
|
|
|
384
493
|
listeners.delete(listener);
|
|
385
494
|
};
|
|
386
495
|
},
|
|
387
|
-
project: (definition) => projectionCache.project(definition,
|
|
388
|
-
fold: (definition) => projectionCache.fold(definition,
|
|
496
|
+
project: (definition) => projectionCache.project(definition, confirmedEvents(), pendingEvents, pendingVersion),
|
|
497
|
+
fold: (definition) => projectionCache.fold(definition, confirmedEvents(), pendingEvents, pendingVersion),
|
|
498
|
+
pending: () => pendingEvents,
|
|
389
499
|
flush: notify.flush,
|
|
390
500
|
sync: () => sync().then(() => {
|
|
391
501
|
notify.flush();
|
|
392
502
|
}),
|
|
393
|
-
commit: (event) =>
|
|
394
|
-
const
|
|
395
|
-
|
|
503
|
+
commit: (event, commitOptions) => {
|
|
504
|
+
const inputs = Array.isArray(event) ? event : [event];
|
|
505
|
+
const optimistic = commitOptions?.optimistic ?? options.optimistic ?? false;
|
|
506
|
+
const key = commitOptions?.idempotencyKey ?? (optimistic ? createEventId() : undefined);
|
|
507
|
+
let shown;
|
|
508
|
+
if (optimistic && key !== undefined && inputs.length > 0) {
|
|
509
|
+
const rootThreadId = tables.runs.get(options.storeId)?.rootThreadId ?? null;
|
|
510
|
+
shown = {
|
|
511
|
+
key,
|
|
512
|
+
settle: undefined,
|
|
513
|
+
events: inputs.map((input) => {
|
|
514
|
+
pendingSeq += 1;
|
|
515
|
+
return createEvent(options.storeId, {
|
|
516
|
+
...input,
|
|
517
|
+
threadId: input.threadId === undefined ? rootThreadId : input.threadId,
|
|
518
|
+
origin: input.origin ?? { type: 'external' },
|
|
519
|
+
idempotencyKey: input.idempotencyKey ?? key,
|
|
520
|
+
}, { seq: pendingSeq });
|
|
521
|
+
}),
|
|
522
|
+
};
|
|
523
|
+
pendingCommits.push(shown);
|
|
524
|
+
setPending();
|
|
525
|
+
notify.schedule();
|
|
526
|
+
notify.flush();
|
|
527
|
+
}
|
|
528
|
+
const post = (signal) => {
|
|
529
|
+
if (commitOptions?.send) {
|
|
530
|
+
return commitOptions.send({ events: inputs, idempotencyKey: key, signal });
|
|
531
|
+
}
|
|
532
|
+
const body = key === undefined
|
|
533
|
+
? Array.isArray(event)
|
|
534
|
+
? { events: inputs }
|
|
535
|
+
: event
|
|
536
|
+
: { events: inputs, idempotencyKey: key };
|
|
537
|
+
// The log is what the UI renders, so the answer is wanted as soon as the events are
|
|
538
|
+
// committed, not once the run has finished acting on them.
|
|
539
|
+
return fetchFn(`${endpoint}/runs/${encodeURIComponent(options.storeId)}/events?respond=async`, {
|
|
396
540
|
method: 'POST',
|
|
397
541
|
headers: { 'content-type': 'application/json' },
|
|
398
|
-
body: stringifyJson(
|
|
542
|
+
body: stringifyJson(body),
|
|
399
543
|
signal,
|
|
400
|
-
})
|
|
401
|
-
|
|
544
|
+
}).then((res) => res.ok
|
|
545
|
+
? undefined
|
|
546
|
+
: res.text().then((text) => {
|
|
547
|
+
throw new LoomsStoreError(`Run signal failed: ${res.status} ${text}`);
|
|
548
|
+
}));
|
|
549
|
+
};
|
|
550
|
+
return Effect.runPromise(Effect.gen(function* () {
|
|
551
|
+
yield* Effect.tryPromise({
|
|
552
|
+
try: post,
|
|
553
|
+
catch: (cause) => cause instanceof LoomsStoreError
|
|
554
|
+
? cause
|
|
555
|
+
: new LoomsStoreError('Run signal failed', cause),
|
|
556
|
+
});
|
|
557
|
+
if (!live) {
|
|
558
|
+
yield* Effect.promise(sync);
|
|
559
|
+
}
|
|
560
|
+
return undefined;
|
|
561
|
+
}).pipe(Effect.tapError(() => Effect.sync(() => {
|
|
562
|
+
// Roll back: the events were never recorded.
|
|
563
|
+
if (shown && dropPending(shown)) {
|
|
564
|
+
notify.schedule();
|
|
565
|
+
notify.flush();
|
|
566
|
+
}
|
|
567
|
+
})))).then(() => {
|
|
568
|
+
const accepted = shown;
|
|
569
|
+
if (accepted && pendingCommits.includes(accepted)) {
|
|
570
|
+
// The host took the commit, so its events are on their way. If none ever carries this
|
|
571
|
+
// key (the host recorded something else, or nothing), stop showing ours.
|
|
572
|
+
accepted.settle = Effect.runFork(Effect.sleep(PENDING_SETTLE_MS).pipe(Effect.andThen(Effect.promise(sync)), Effect.andThen(Effect.sync(() => {
|
|
573
|
+
accepted.settle = undefined;
|
|
574
|
+
if (dropPending(accepted)) {
|
|
575
|
+
notify.schedule();
|
|
576
|
+
}
|
|
577
|
+
}))));
|
|
578
|
+
}
|
|
579
|
+
notify.flush();
|
|
402
580
|
});
|
|
403
|
-
|
|
404
|
-
const text = yield* Effect.promise(() => res.text());
|
|
405
|
-
return yield* new LoomsStoreError(`Run signal failed: ${res.status} ${text}`);
|
|
406
|
-
}
|
|
407
|
-
if (!live) {
|
|
408
|
-
yield* Effect.promise(sync);
|
|
409
|
-
}
|
|
410
|
-
notify.flush();
|
|
411
|
-
return undefined;
|
|
412
|
-
})),
|
|
581
|
+
},
|
|
413
582
|
dispose: () => {
|
|
414
583
|
disposed = true;
|
|
584
|
+
cancelQuiet();
|
|
585
|
+
for (const commit of pendingCommits.splice(0)) {
|
|
586
|
+
if (commit.settle !== undefined) {
|
|
587
|
+
Effect.runFork(Fiber.interrupt(commit.settle));
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
pendingEvents = Object.freeze([]);
|
|
591
|
+
visibleByThread.clear();
|
|
415
592
|
notify.cancel();
|
|
416
593
|
stopLive();
|
|
417
594
|
listeners.clear();
|
package/dist/runtime/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { createRuntime, createTimeoutScheduler, DuplicateEffectDispatchError, ForkConflictError, MaxWakeIterationsError, RunNotFinishedError, RunNotFoundError, RunOverloadedError, RunTerminalError, StartRunConflictError, type CreateRuntimeOptions, type EffectWorker, type EffectWorkerDeadlines, type EffectWorkerTask, type LoomsRuntime, type RunOperationalStatus, type RegisteredDefinition, type StartRunArgs, type WakeError, type WakeScheduler, type WorkerCallback, type WorkerCallbackInput, type WorkerCallbackResult, } from './runtime';
|
|
1
|
+
export { createRuntime, createTimeoutScheduler, DuplicateEffectDispatchError, ForkConflictError, MaxWakeIterationsError, RunNotFinishedError, RunNotFoundError, RunOverloadedError, RunTerminalError, StartRunConflictError, type CreateRuntimeOptions, type EffectWorker, type EffectWorkerDeadlines, type EffectWorkerTask, type LoomsRuntime, type RunSignalOptions, type RunOperationalStatus, type RegisteredDefinition, type StartRunArgs, type WakeError, type WakeScheduler, type WorkerCallback, type WorkerCallbackInput, type WorkerCallbackResult, } from './runtime';
|
|
2
2
|
export { listEffectPlacements } from './worker-effect-dispatch';
|
|
3
3
|
export { createLooms, type Looms, type CreateLoomsOptions, type StartResult } from './looms';
|
|
4
4
|
export { loadSubscriptionOpening, readSubscriptionBounds } from './subscription';
|
package/dist/runtime/looms.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type AnyRuntimeModule, type DebuggerHost, type DefinitionInput, type DefinitionRef, type DefinitionResolver, type EventEnvelope, type EventInput, type BlobStore, type EventStore, type EventStoreTrimCoverage, type JsonValue, type SnapshotStore, type ProjectionDefinition, type HasRequiredAttributes, type ReplayStep, type RunAttributeFields, type RunAttributesOption, type RunLauncher, type RunState } from '@swirls/looms/core';
|
|
2
2
|
import type { RuntimeObserver } from './observer';
|
|
3
|
-
import { type EffectWorker, type LoomsRuntime, type RunOperationalStatus, type StartRunArgs, type WakeScheduler, type WorkerCallbackInput, type WorkerCallbackResult } from './runtime';
|
|
3
|
+
import { type EffectWorker, type LoomsRuntime, type RunSignalOptions, type RunOperationalStatus, type StartRunArgs, type WakeScheduler, type WorkerCallbackInput, type WorkerCallbackResult } from './runtime';
|
|
4
4
|
import { type Authorize, type RunningServer } from './server';
|
|
5
5
|
export interface CreateLoomsOptions<Fields extends RunAttributeFields = RunAttributeFields> {
|
|
6
6
|
/** Runtime modules to enable. Pass `agent()`, `workflow()`, `approval()`, and/or your own. */
|
|
@@ -112,9 +112,7 @@ export interface Looms<Fields extends RunAttributeFields = RunAttributeFields> {
|
|
|
112
112
|
fromSeq?: number;
|
|
113
113
|
limit?: number;
|
|
114
114
|
}): Promise<EventEnvelope[]>;
|
|
115
|
-
signal(runId: string, events: ReadonlyArray<EventInput>, options?:
|
|
116
|
-
idempotencyKey?: string;
|
|
117
|
-
}): Promise<RunState>;
|
|
115
|
+
signal(runId: string, events: ReadonlyArray<EventInput>, options?: RunSignalOptions): Promise<RunState>;
|
|
118
116
|
wake(runId: string): Promise<RunState>;
|
|
119
117
|
rescanTimers(): Promise<number>;
|
|
120
118
|
recoverDeadlines(): Promise<number>;
|