@swirls/looms 0.15.0 → 0.17.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.
@@ -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-CZwbkhFX.js"></script>
7
+ <script type="module" crossorigin src="./assets/index-Br9tGbPI.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>
@@ -0,0 +1,30 @@
1
+ import { type EventEnvelope } from '@swirls/looms/core';
2
+ /**
3
+ * Keeps a run's durable events on the device, so a store that has followed the run before starts
4
+ * from them and downloads only what was appended since. Ephemeral events are never kept.
5
+ *
6
+ * `key` names one view of one run on one host. A store with a thread filter has its own key.
7
+ */
8
+ export interface EventCache {
9
+ /** The events kept for `key`, in sequence order. Empty when there are none. */
10
+ load(key: string): Promise<readonly EventEnvelope[]>;
11
+ append(key: string, events: readonly EventEnvelope[]): Promise<void>;
12
+ /** Forgets `key`, as when the host's log turns out not to be the one that was kept. */
13
+ clear(key: string): Promise<void>;
14
+ }
15
+ /** An `EventCache` that lives as long as the page. Useful in tests and on hosts with no storage. */
16
+ export declare function memoryEventCache(): EventCache;
17
+ export interface IndexedDbEventCacheOptions {
18
+ /** Database name. Defaults to `looms-events`. */
19
+ name?: string;
20
+ /** How many runs to keep. The ones opened longest ago are dropped first. Defaults to 50. */
21
+ maxRuns?: number;
22
+ /** Defaults to the global `indexedDB`. */
23
+ indexedDB?: IDBFactory;
24
+ }
25
+ /**
26
+ * An `EventCache` in the browser's IndexedDB. Every failure is swallowed: a cache that cannot be
27
+ * read is an empty cache, and one that cannot be written is simply not written, so the store
28
+ * falls back to downloading the log.
29
+ */
30
+ export declare function indexedDbEventCache(options?: IndexedDbEventCacheOptions): EventCache;
@@ -0,0 +1,146 @@
1
+ import { DateTime } from 'effect';
2
+ import { decodeLoomsEvent, encodeLoomsEvent } from '@swirls/looms/core';
3
+ /** An `EventCache` that lives as long as the page. Useful in tests and on hosts with no storage. */
4
+ export function memoryEventCache() {
5
+ const kept = new Map();
6
+ return {
7
+ load: (key) => Promise.resolve(kept.get(key)?.slice() ?? []),
8
+ append: (key, events) => {
9
+ const list = kept.get(key) ?? [];
10
+ list.push(...events);
11
+ kept.set(key, list);
12
+ return Promise.resolve();
13
+ },
14
+ clear: (key) => {
15
+ kept.delete(key);
16
+ return Promise.resolve();
17
+ },
18
+ };
19
+ }
20
+ const EVENTS = 'events';
21
+ const RUNS = 'runs';
22
+ const nothing = () => [];
23
+ const ignore = () => undefined;
24
+ function done(request) {
25
+ // IndexedDB reports through callbacks; this is the one place they become a promise.
26
+ // oxlint-disable-next-line effecttsgo/new-promise
27
+ return new Promise((resolve, reject) => {
28
+ request.addEventListener('success', () => resolve(request.result));
29
+ request.addEventListener('error', () => reject(request.error ?? new Error('IndexedDB failed')));
30
+ });
31
+ }
32
+ function settled(transaction) {
33
+ // oxlint-disable-next-line effecttsgo/new-promise
34
+ return new Promise((resolve, reject) => {
35
+ transaction.addEventListener('complete', () => resolve());
36
+ const fail = () => reject(transaction.error ?? new Error('IndexedDB transaction failed'));
37
+ transaction.addEventListener('error', fail);
38
+ transaction.addEventListener('abort', fail);
39
+ });
40
+ }
41
+ function eventsOf(key) {
42
+ return IDBKeyRange.bound([key, 0], [key, Number.MAX_SAFE_INTEGER]);
43
+ }
44
+ /**
45
+ * An `EventCache` in the browser's IndexedDB. Every failure is swallowed: a cache that cannot be
46
+ * read is an empty cache, and one that cannot be written is simply not written, so the store
47
+ * falls back to downloading the log.
48
+ */
49
+ export function indexedDbEventCache(options = {}) {
50
+ const factory = options.indexedDB ?? globalThis.indexedDB;
51
+ const maxRuns = Math.max(1, options.maxRuns ?? 50);
52
+ let opening;
53
+ const open = () => {
54
+ if (opening) {
55
+ return opening;
56
+ }
57
+ const request = factory.open(options.name ?? 'looms-events', 1);
58
+ request.addEventListener('upgradeneeded', () => {
59
+ const db = request.result;
60
+ if (!db.objectStoreNames.contains(EVENTS)) {
61
+ db.createObjectStore(EVENTS, { keyPath: ['key', 'seq'] });
62
+ }
63
+ if (!db.objectStoreNames.contains(RUNS)) {
64
+ db.createObjectStore(RUNS, { keyPath: 'key' });
65
+ }
66
+ });
67
+ opening = done(request);
68
+ opening.catch(() => {
69
+ opening = undefined;
70
+ });
71
+ return opening;
72
+ };
73
+ /** Drops the runs opened longest ago once more than `maxRuns` are kept. */
74
+ const evict = (db) => {
75
+ const transaction = db.transaction([EVENTS, RUNS], 'readwrite');
76
+ const listed = done(transaction.objectStore(RUNS).getAll());
77
+ return listed.then((runs) => {
78
+ const stale = runs
79
+ .toSorted((a, b) => b.touchedAt - a.touchedAt)
80
+ .slice(maxRuns)
81
+ .map((run) => run.key);
82
+ for (const key of stale) {
83
+ transaction.objectStore(EVENTS).delete(eventsOf(key));
84
+ transaction.objectStore(RUNS).delete(key);
85
+ }
86
+ return settled(transaction);
87
+ });
88
+ };
89
+ const touch = (transaction, key) => {
90
+ transaction
91
+ .objectStore(RUNS)
92
+ .put({ key, touchedAt: DateTime.toEpochMillis(DateTime.nowUnsafe()) });
93
+ };
94
+ return {
95
+ load: (key) => {
96
+ if (!factory) {
97
+ return Promise.resolve([]);
98
+ }
99
+ return open()
100
+ .then((db) => {
101
+ const transaction = db.transaction([EVENTS, RUNS], 'readwrite');
102
+ // Rows are what `append` wrote, which is the wire encoding of an event.
103
+ const read = done(transaction.objectStore(EVENTS).getAll(eventsOf(key)));
104
+ return read.then((rows) => {
105
+ if (rows.length > 0) {
106
+ touch(transaction, key);
107
+ }
108
+ return settled(transaction).then(() => {
109
+ void evict(db).catch(ignore);
110
+ return rows.map((row) => decodeLoomsEvent(row.event, ''));
111
+ });
112
+ });
113
+ })
114
+ .catch(nothing);
115
+ },
116
+ append: (key, events) => {
117
+ if (!factory || events.length === 0) {
118
+ return Promise.resolve();
119
+ }
120
+ return open()
121
+ .then((db) => {
122
+ const transaction = db.transaction([EVENTS, RUNS], 'readwrite');
123
+ const store = transaction.objectStore(EVENTS);
124
+ for (const event of events) {
125
+ store.put({ key, seq: event.seq, event: encodeLoomsEvent(event) });
126
+ }
127
+ touch(transaction, key);
128
+ return settled(transaction);
129
+ })
130
+ .catch(ignore); // Not kept. The store downloads these again next time.
131
+ },
132
+ clear: (key) => {
133
+ if (!factory) {
134
+ return Promise.resolve();
135
+ }
136
+ return open()
137
+ .then((db) => {
138
+ const transaction = db.transaction([EVENTS, RUNS], 'readwrite');
139
+ transaction.objectStore(EVENTS).delete(eventsOf(key));
140
+ transaction.objectStore(RUNS).delete(key);
141
+ return settled(transaction);
142
+ })
143
+ .catch(ignore);
144
+ },
145
+ };
146
+ }
@@ -1,6 +1,8 @@
1
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
+ export { indexedDbEventCache, memoryEventCache, type EventCache, type IndexedDbEventCacheOptions, } from './cache';
4
+ export type { StoreObservation, StoreObserver } from './observer';
3
5
  export { materializeEvents } from './materialize';
4
6
  export { emptyTables, type MaterializedTables, type RunRow, type ThreadRow } from './tables';
5
7
  export type { LoomsRegister, RegisteredEvent, AnyEventEnvelope } from '@swirls/looms/core';
6
- export { LoomsProvider, useRunStore, useProjection, useRunSelector, useRunSummary, useRunEvents, useThreadTree, useEventCounts, useEventBySeq, useLatestEvent, useLiveFold, type LoomsProviderProps, type UseRunStoreOptions, type RunSummary, } from './react';
8
+ export { LoomsProvider, preloadRunStore, useRunStore, useProjection, useRunSelector, useRunSummary, useRunEvents, useThreadTree, useEventCounts, useEventBySeq, useLatestEvent, useLiveFold, type LoomsProviderProps, type PreloadRunStoreOptions, type RunStoreOptions, type UseRunStoreOptions, type RunSummary, } from './react';
@@ -1,5 +1,6 @@
1
1
  export { createLoomsStore, isPendingEvent, } from './store.js';
2
2
  export { defineLiveFold, foldLive, EventIndex, eventThreadKey, } from './derived.js';
3
+ export { indexedDbEventCache, memoryEventCache, } from './cache.js';
3
4
  export { materializeEvents } from './materialize.js';
4
5
  export { emptyTables } from './tables.js';
5
- export { LoomsProvider, useRunStore, useProjection, useRunSelector, useRunSummary, useRunEvents, useThreadTree, useEventCounts, useEventBySeq, useLatestEvent, useLiveFold, } from './react.js';
6
+ export { LoomsProvider, preloadRunStore, useRunStore, useProjection, useRunSelector, useRunSummary, useRunEvents, useThreadTree, useEventCounts, useEventBySeq, useLatestEvent, useLiveFold, } from './react.js';
@@ -0,0 +1,44 @@
1
+ /**
2
+ * What a client store reports about how the run felt to use: how long it took to show, and how
3
+ * long each write took to be acknowledged and then confirmed. Durations are in milliseconds.
4
+ */
5
+ export type StoreObservation = {
6
+ /** The store holds everything the log had when it connected. Reported once per store. */
7
+ readonly type: 'store.synced';
8
+ readonly runId: string;
9
+ readonly at: number;
10
+ /** From the store's creation. */
11
+ readonly durationMs: number;
12
+ readonly eventCount: number;
13
+ /** How many of those events came from the device's cache and were not downloaded. */
14
+ readonly cachedEvents: number;
15
+ } | {
16
+ readonly type: 'store.connection';
17
+ readonly runId: string;
18
+ readonly at: number;
19
+ readonly status: 'connecting' | 'live' | 'reconnecting';
20
+ } | {
21
+ /** The host answered a commit. */
22
+ readonly type: 'commit.acked';
23
+ readonly runId: string;
24
+ readonly at: number;
25
+ readonly durationMs: number;
26
+ readonly eventCount: number;
27
+ readonly optimistic: boolean;
28
+ } | {
29
+ /** The host's copy of an optimistic commit arrived on the event stream. */
30
+ readonly type: 'commit.confirmed';
31
+ readonly runId: string;
32
+ readonly at: number;
33
+ /** From the call to `commit`. */
34
+ readonly durationMs: number;
35
+ } | {
36
+ readonly type: 'commit.failed';
37
+ readonly runId: string;
38
+ readonly at: number;
39
+ readonly durationMs: number;
40
+ readonly message: string;
41
+ };
42
+ export interface StoreObserver {
43
+ observe(observation: StoreObservation): void;
44
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,6 +1,8 @@
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
+ import type { EventCache } from './cache';
3
4
  import { defineLiveFold, foldLive, type LiveFoldDefinition } from './derived';
5
+ import type { StoreObserver } from './observer';
4
6
  import { createLoomsStore, isPendingEvent, type CoalesceOption, type LoomsClientStore, type LoomsConnectionStatus } from './store';
5
7
  export interface LoomsProviderProps {
6
8
  children: ReactNode;
@@ -13,15 +15,21 @@ export interface LoomsProviderProps {
13
15
  * to five seconds.
14
16
  */
15
17
  retainMs?: number;
18
+ /** Keeps each run's durable events on the device. See `indexedDbEventCache`. */
19
+ cache?: EventCache;
20
+ /** Told how long each run took to show and how long each commit took. */
21
+ observer?: StoreObserver;
16
22
  }
17
23
  interface ProviderContextValue {
18
24
  endpoint: string;
19
25
  coalesce?: CoalesceOption;
20
26
  transport?: SubscriptionTransport;
21
27
  retainMs?: number;
28
+ cache?: EventCache;
29
+ observer?: StoreObserver;
22
30
  }
23
31
  /** Root provider that supplies the Looms host endpoint to run stores. */
24
- export declare function LoomsProvider({ children, endpoint, coalesce, transport, retainMs, }: LoomsProviderProps): import("react").FunctionComponentElement<import("react").ProviderProps<ProviderContextValue>>;
32
+ export declare function LoomsProvider({ children, endpoint, coalesce, transport, retainMs, cache, observer, }: LoomsProviderProps): import("react").FunctionComponentElement<import("react").ProviderProps<ProviderContextValue>>;
25
33
  export interface UseRunStoreOptions {
26
34
  endpoint?: string;
27
35
  reconnectDelayMs?: number;
@@ -33,6 +41,39 @@ export interface UseRunStoreOptions {
33
41
  fromSeq?: number;
34
42
  retainMs?: number;
35
43
  }
44
+ /**
45
+ * Everything that decides which store a run gets when there is no provider to supply part of
46
+ * it. Inside React the provider gives `endpoint`, `coalesce`, `transport`, `retainMs`, `cache`
47
+ * and `observer`; outside it the caller passes them.
48
+ */
49
+ export interface RunStoreOptions extends UseRunStoreOptions {
50
+ /** Keeps the run's durable events on the device. See `indexedDbEventCache`. */
51
+ cache?: EventCache;
52
+ /** Told how long the run took to show and how long each commit took. */
53
+ observer?: StoreObserver;
54
+ }
55
+ export interface PreloadRunStoreOptions extends RunStoreOptions {
56
+ /** Stops waiting. The promise rejects with the signal's reason and the store is let go. */
57
+ signal?: AbortSignal;
58
+ }
59
+ /**
60
+ * Opens a run's store outside React and resolves with it once it has caught up to the log,
61
+ * which is when `store.synced()` turns true.
62
+ *
63
+ * This is for code that runs before a page renders, such as a route loader: await it, and the
64
+ * components that then call `useRunStore` for the same run get this store, already filled,
65
+ * instead of connecting and replaying the log on screen.
66
+ *
67
+ * A store is found by its endpoint, run, transport, thread and `includeEphemeral`, so pass the
68
+ * same values the provider is given, or the hook will open a second store. Sharing one options
69
+ * object between `LoomsProvider` and this call is the simplest way. `cache`, `observer` and
70
+ * `fromSeq` are taken from whichever of the two opens the store first.
71
+ *
72
+ * The store is held while this waits and then kept for `retainMs`, like one whose last
73
+ * component unmounted, so a page has that long to take it over. With no `signal` it waits for
74
+ * as long as the log takes to arrive.
75
+ */
76
+ export declare function preloadRunStore(runId: string, options?: PreloadRunStoreOptions): Promise<LoomsClientStore>;
36
77
  /**
37
78
  * Acquires a non-subscribing handle to the run store.
38
79
  * Retains the store in memory while mounted; does NOT trigger component re-renders.
@@ -41,6 +41,8 @@ function peekStore(runId, identity) {
41
41
  threadId: identity.threadId,
42
42
  includeEphemeral: identity.includeEphemeral,
43
43
  fromSeq: identity.fromSeq,
44
+ cache: identity.cache,
45
+ observer: identity.observer,
44
46
  });
45
47
  const retainMs = Math.max(0, identity.retainMs ?? DEFAULT_RETAIN_MS);
46
48
  registry.set(key, {
@@ -77,10 +79,61 @@ function releaseStore(runId, identity) {
77
79
  }
78
80
  }
79
81
  /** Root provider that supplies the Looms host endpoint to run stores. */
80
- export function LoomsProvider({ children, endpoint = '', coalesce, transport, retainMs, }) {
81
- const value = useMemo(() => ({ endpoint, coalesce, transport, retainMs }), [endpoint, coalesce, transport, retainMs]);
82
+ export function LoomsProvider({ children, endpoint = '', coalesce, transport, retainMs, cache, observer, }) {
83
+ const value = useMemo(() => ({ endpoint, coalesce, transport, retainMs, cache, observer }), [endpoint, coalesce, transport, retainMs, cache, observer]);
82
84
  return createElement(LoomsContext.Provider, { value, children });
83
85
  }
86
+ /**
87
+ * Opens a run's store outside React and resolves with it once it has caught up to the log,
88
+ * which is when `store.synced()` turns true.
89
+ *
90
+ * This is for code that runs before a page renders, such as a route loader: await it, and the
91
+ * components that then call `useRunStore` for the same run get this store, already filled,
92
+ * instead of connecting and replaying the log on screen.
93
+ *
94
+ * A store is found by its endpoint, run, transport, thread and `includeEphemeral`, so pass the
95
+ * same values the provider is given, or the hook will open a second store. Sharing one options
96
+ * object between `LoomsProvider` and this call is the simplest way. `cache`, `observer` and
97
+ * `fromSeq` are taken from whichever of the two opens the store first.
98
+ *
99
+ * The store is held while this waits and then kept for `retainMs`, like one whose last
100
+ * component unmounted, so a page has that long to take it over. With no `signal` it waits for
101
+ * as long as the log takes to arrive.
102
+ */
103
+ export function preloadRunStore(runId, options = {}) {
104
+ const { signal, ...rest } = options;
105
+ const identity = { ...rest, endpoint: rest.endpoint ?? '' };
106
+ if (signal?.aborted) {
107
+ return Promise.reject(signal.reason);
108
+ }
109
+ const { promise, resolve, reject } = Promise.withResolvers();
110
+ retainStore(runId, identity);
111
+ const store = peekStore(runId, identity);
112
+ let done = false;
113
+ // A store calls a new listener at once, which is before there is anything to unsubscribe.
114
+ let unsubscribe;
115
+ const finish = (settle) => {
116
+ if (done) {
117
+ return;
118
+ }
119
+ done = true;
120
+ unsubscribe?.();
121
+ signal?.removeEventListener('abort', onAbort);
122
+ releaseStore(runId, identity);
123
+ settle();
124
+ };
125
+ const onAbort = () => finish(() => reject(signal?.reason));
126
+ unsubscribe = store.subscribe(() => {
127
+ if (store.synced()) {
128
+ finish(() => resolve(store));
129
+ }
130
+ });
131
+ if (done) {
132
+ unsubscribe();
133
+ }
134
+ signal?.addEventListener('abort', onAbort, { once: true });
135
+ return promise;
136
+ }
84
137
  /**
85
138
  * Acquires a non-subscribing handle to the run store.
86
139
  * Retains the store in memory while mounted; does NOT trigger component re-renders.
@@ -105,6 +158,8 @@ export function useRunStore(runId, options) {
105
158
  includeEphemeral,
106
159
  fromSeq,
107
160
  retainMs,
161
+ cache: context.cache,
162
+ observer: context.observer,
108
163
  };
109
164
  const store = peekStore(runId, identity);
110
165
  useEffect(() => {
@@ -1,7 +1,9 @@
1
1
  import { type SubscriptionSocketConstructor } from '@swirls/looms/client';
2
2
  import { type AnyEventEnvelope, type EventInput, type ProjectionDefinition, type RegisteredEvent, type SubscriptionTransport } from '@swirls/looms/core';
3
+ import type { EventCache } from './cache';
3
4
  import { type LiveFoldDefinition } from './derived';
4
5
  import { type CoalesceOption } from './notify';
6
+ import type { StoreObserver } from './observer';
5
7
  import { type MaterializedTables } from './tables';
6
8
  export type { CoalesceOption } from './notify';
7
9
  /** Fired after the store version bumps. Re-read via `events()` / `getState()` / `query`. */
@@ -62,6 +64,13 @@ export interface LoomsClientStoreOptions {
62
64
  fromSeq?: number;
63
65
  /** Whether `commit` shows its events before the host confirms them. Defaults to false. */
64
66
  optimistic?: boolean;
67
+ /**
68
+ * Keeps the run's durable events on the device. A store that has followed the run before starts
69
+ * from them and downloads only what was appended since. Not used together with `fromSeq`.
70
+ */
71
+ cache?: EventCache;
72
+ /** Told how long the run took to show and how long each commit took. */
73
+ observer?: StoreObserver;
65
74
  }
66
75
  export interface LoomsStoreQuery<TEvent extends AnyEventEnvelope = RegisteredEvent> {
67
76
  events: (options?: {
@@ -1,4 +1,4 @@
1
- import { Data, Effect, Fiber, Option, Predicate, Schema } from 'effect';
1
+ import { Data, DateTime, Effect, Fiber, Option, Predicate, Schema } from 'effect';
2
2
  import { absoluteHttpBase } from '@swirls/looms/client';
3
3
  import { createEvent, createEventId, decodeLoomsEvent, readSubscriptionData, stringifyJson, } from '@swirls/looms/core';
4
4
  import { EventIndex, ProjectionCache } from './derived.js';
@@ -19,6 +19,9 @@ export function isPendingEvent(event) {
19
19
  }
20
20
  /** How long a filtered subscription's opening replay must be quiet to count as caught up. */
21
21
  const SYNC_QUIET_MS = 250;
22
+ function nowMs() {
23
+ return DateTime.toEpochMillis(DateTime.nowUnsafe());
24
+ }
22
25
  class LoomsStoreError extends Data.TaggedError('LoomsStoreError') {
23
26
  constructor(message, cause) {
24
27
  super({ cause, message });
@@ -57,6 +60,22 @@ export function createLoomsStore(options) {
57
60
  const seenIds = new Set();
58
61
  const projectionCache = new ProjectionCache();
59
62
  const eventIndex = new EventIndex();
63
+ const createdAt = nowMs();
64
+ const observe = (observation) => {
65
+ try {
66
+ options.observer?.observe(observation);
67
+ }
68
+ catch {
69
+ // An observer must never break the store it watches.
70
+ }
71
+ };
72
+ // The cache holds a whole view of the run, so a store that starts partway through has none.
73
+ const cache = options.fromSeq === undefined || options.fromSeq <= 1 ? options.cache : undefined;
74
+ const cacheKey = [endpoint, options.storeId, options.threadId ?? ''].join('|');
75
+ let cacheWrites = Promise.resolve();
76
+ let cachedEvents = 0;
77
+ let hydrated = cache === undefined;
78
+ let hydrating;
60
79
  let eventsSnapshot = Object.freeze([]);
61
80
  let eventsSnapshotDirty = false;
62
81
  let version = 0;
@@ -115,11 +134,20 @@ export function createLoomsStore(options) {
115
134
  pendingVersion += 1;
116
135
  version += 1;
117
136
  };
118
- const dropPending = (commit) => {
137
+ const dropPending = (commit, confirmed = false) => {
119
138
  const index = pendingCommits.indexOf(commit);
120
139
  if (index === -1) {
121
140
  return false;
122
141
  }
142
+ if (confirmed) {
143
+ const at = nowMs();
144
+ observe({
145
+ type: 'commit.confirmed',
146
+ runId: options.storeId,
147
+ at,
148
+ durationMs: at - commit.startedAt,
149
+ });
150
+ }
123
151
  pendingCommits.splice(index, 1);
124
152
  if (commit.settle !== undefined) {
125
153
  Effect.runFork(Fiber.interrupt(commit.settle));
@@ -139,6 +167,7 @@ export function createLoomsStore(options) {
139
167
  return;
140
168
  }
141
169
  status = next;
170
+ observe({ type: 'store.connection', runId: options.storeId, at: nowMs(), status: next });
142
171
  version += 1;
143
172
  notify.schedule();
144
173
  };
@@ -154,6 +183,15 @@ export function createLoomsStore(options) {
154
183
  return;
155
184
  }
156
185
  synced = true;
186
+ const at = nowMs();
187
+ observe({
188
+ type: 'store.synced',
189
+ runId: options.storeId,
190
+ at,
191
+ durationMs: at - createdAt,
192
+ eventCount: events.length,
193
+ cachedEvents,
194
+ });
157
195
  version += 1;
158
196
  notify.schedule();
159
197
  };
@@ -171,7 +209,7 @@ export function createLoomsStore(options) {
171
209
  quietFiber = Effect.runFork(Effect.sleep(SYNC_QUIET_MS).pipe(Effect.andThen(Effect.sync(markSynced))));
172
210
  }
173
211
  };
174
- const applyBatch = (batch) => {
212
+ const applyBatch = (batch, fromCache = false) => {
175
213
  const fresh = [];
176
214
  for (const event of batch) {
177
215
  if (event.seq < fromSeq || seenIds.has(event.id)) {
@@ -198,12 +236,35 @@ export function createLoomsStore(options) {
198
236
  ? pendingCommits.find((commit) => commit.key === event.idempotencyKey)
199
237
  : undefined;
200
238
  if (confirmed) {
201
- dropPending(confirmed);
239
+ dropPending(confirmed, true);
240
+ }
241
+ }
242
+ if (cache && !fromCache) {
243
+ const durable = fresh.filter((event) => !event.ephemeral);
244
+ if (durable.length > 0) {
245
+ cacheWrites = cacheWrites.then(() => cache.append(cacheKey, durable)).catch(() => undefined);
202
246
  }
203
247
  }
204
248
  notify.schedule();
205
249
  checkSynced();
206
250
  };
251
+ /** Drops everything the store holds, when what the cache supplied is not the host's log. */
252
+ const forgetCache = () => {
253
+ events.length = 0;
254
+ seenIds.clear();
255
+ eventIndex.clear();
256
+ projectionCache.clear();
257
+ tables = emptyTables();
258
+ eventsSnapshotDirty = true;
259
+ cachedEvents = 0;
260
+ synced = false;
261
+ syncTail = undefined;
262
+ version += 1;
263
+ if (cache) {
264
+ cacheWrites = cacheWrites.then(() => cache.clear(cacheKey)).catch(() => undefined);
265
+ }
266
+ notify.schedule();
267
+ };
207
268
  const applyLiveData = (data) => {
208
269
  const read = readSubscriptionData(data, options.storeId);
209
270
  switch (read.kind) {
@@ -214,6 +275,12 @@ export function createLoomsStore(options) {
214
275
  fromSeq = read.head;
215
276
  return 'resync';
216
277
  case 'hello':
278
+ // The cache is ahead of the host's log, so it was kept from a different one.
279
+ if (cachedEvents > 0 && read.tail < fromSeq - 1) {
280
+ forgetCache();
281
+ fromSeq = 1;
282
+ return 'resync';
283
+ }
217
284
  syncTail = read.tail;
218
285
  checkSynced();
219
286
  return 'continue';
@@ -450,8 +517,32 @@ export function createLoomsStore(options) {
450
517
  liveAbort?.abort();
451
518
  liveAbort = undefined;
452
519
  };
520
+ /** Starts following the run, after first loading whatever the device kept of it. */
521
+ const begin = () => {
522
+ if (hydrated || !cache) {
523
+ startLive();
524
+ return;
525
+ }
526
+ hydrating ??= cache
527
+ .load(cacheKey)
528
+ .then((kept) => {
529
+ if (disposed || events.length > 0) {
530
+ return;
531
+ }
532
+ applyBatch(kept.slice(), true);
533
+ cachedEvents = events.length;
534
+ })
535
+ .catch(() => undefined)
536
+ .then(() => {
537
+ hydrated = true;
538
+ hydrating = undefined;
539
+ if (!disposed) {
540
+ startLive();
541
+ }
542
+ });
543
+ };
453
544
  if (options.storeId) {
454
- startLive();
545
+ begin();
455
546
  }
456
547
  const readEvents = (filterOptions) => {
457
548
  const threadId = filterOptions?.threadId;
@@ -487,7 +578,7 @@ export function createLoomsStore(options) {
487
578
  listeners.add(listener);
488
579
  listener();
489
580
  if (disposed) {
490
- startLive();
581
+ begin();
491
582
  }
492
583
  return () => {
493
584
  listeners.delete(listener);
@@ -504,11 +595,13 @@ export function createLoomsStore(options) {
504
595
  const inputs = Array.isArray(event) ? event : [event];
505
596
  const optimistic = commitOptions?.optimistic ?? options.optimistic ?? false;
506
597
  const key = commitOptions?.idempotencyKey ?? (optimistic ? createEventId() : undefined);
598
+ const startedAt = nowMs();
507
599
  let shown;
508
600
  if (optimistic && key !== undefined && inputs.length > 0) {
509
601
  const rootThreadId = tables.runs.get(options.storeId)?.rootThreadId ?? null;
510
602
  shown = {
511
603
  key,
604
+ startedAt,
512
605
  settle: undefined,
513
606
  events: inputs.map((input) => {
514
607
  pendingSeq += 1;
@@ -558,13 +651,30 @@ export function createLoomsStore(options) {
558
651
  yield* Effect.promise(sync);
559
652
  }
560
653
  return undefined;
561
- }).pipe(Effect.tapError(() => Effect.sync(() => {
654
+ }).pipe(Effect.tapError((error) => Effect.sync(() => {
655
+ const at = nowMs();
656
+ observe({
657
+ type: 'commit.failed',
658
+ runId: options.storeId,
659
+ at,
660
+ durationMs: at - startedAt,
661
+ message: error.message,
662
+ });
562
663
  // Roll back: the events were never recorded.
563
664
  if (shown && dropPending(shown)) {
564
665
  notify.schedule();
565
666
  notify.flush();
566
667
  }
567
668
  })))).then(() => {
669
+ const at = nowMs();
670
+ observe({
671
+ type: 'commit.acked',
672
+ runId: options.storeId,
673
+ at,
674
+ durationMs: at - startedAt,
675
+ eventCount: inputs.length,
676
+ optimistic: shown !== undefined,
677
+ });
568
678
  const accepted = shown;
569
679
  if (accepted && pendingCommits.includes(accepted)) {
570
680
  // The host took the commit, so its events are on their way. If none ever carries this