experimental-a2 0.21.1 → 0.23.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 +32 -0
- package/dist/{actor-HnGmrOZZ.d.ts → actor-CqibLgjQ.d.ts} +13 -5
- package/dist/actor-CqibLgjQ.d.ts.map +1 -0
- package/dist/actor-client.d.ts +1 -1
- package/dist/actor-react.d.ts +1 -1
- package/dist/actor-react.js +1 -1
- package/dist/actor-shared-DFET5q16.js.map +1 -1
- package/dist/actor.d.ts +1 -1
- package/dist/actor.js +3 -3
- package/dist/{ai-CvEnqVfo.d.ts → ai-DAu77CDr.d.ts} +2 -2
- package/dist/{ai-CvEnqVfo.d.ts.map → ai-DAu77CDr.d.ts.map} +1 -1
- package/dist/{ai-CzE672Q3.js → ai-EEfKyc-z.js} +2 -2
- package/dist/{ai-CzE672Q3.js.map → ai-EEfKyc-z.js.map} +1 -1
- package/dist/ai-client.d.ts +1 -1
- package/dist/ai-client.js +2 -2
- package/dist/ai-fx.d.ts +4 -2
- package/dist/ai-fx.d.ts.map +1 -1
- package/dist/ai-fx.js +234 -62
- package/dist/ai-fx.js.map +1 -1
- package/dist/{ai-harness-Bfk-Lycn.d.ts → ai-harness-DTjkAr2T.d.ts} +2 -2
- package/dist/{ai-harness-Bfk-Lycn.d.ts.map → ai-harness-DTjkAr2T.d.ts.map} +1 -1
- package/dist/ai-harness-dQeJaR1t.js.map +1 -1
- package/dist/ai-pi.d.ts +1 -1
- package/dist/ai-pi.js +1 -1
- package/dist/ai-react.d.ts +1 -1
- package/dist/ai-react.js +2 -2
- package/dist/ai-server.d.ts +3 -3
- package/dist/ai-server.d.ts.map +1 -1
- package/dist/ai-server.js +10 -4
- package/dist/ai-server.js.map +1 -1
- package/dist/ai.d.ts +1 -1
- package/dist/ai.js +1 -1
- package/dist/{client-9IeTsiAs.js → client-BQS4i_V9.js} +27 -4
- package/dist/client-BQS4i_V9.js.map +1 -0
- package/dist/client-CUMbS_38.d.ts.map +1 -1
- package/dist/client.js +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/{internal-Bc4PvfHk.js → internal-CvsrprnU.js} +32 -15
- package/dist/{internal-Bc4PvfHk.js.map → internal-CvsrprnU.js.map} +1 -1
- package/dist/react.js +1 -1
- package/dist/{runtime-consumer-BWmht60z.js → runtime-consumer-CIeL33wj.js} +2 -2
- package/dist/{runtime-consumer-BWmht60z.js.map → runtime-consumer-CIeL33wj.js.map} +1 -1
- package/dist/scheduler-qstash.d.ts +2 -2
- package/dist/scheduler-qstash.js +2 -2
- package/dist/scheduler-vercel.d.ts +2 -2
- package/dist/scheduler-vercel.js +2 -2
- package/dist/{server-DvIB8kj5.js → server-DtFrWxi3.js} +30 -8
- package/dist/server-DtFrWxi3.js.map +1 -0
- package/dist/{server-BshFZ0eL.d.ts → server-qgez0Xny.d.ts} +3 -3
- package/dist/{server-BshFZ0eL.d.ts.map → server-qgez0Xny.d.ts.map} +1 -1
- package/dist/server.d.ts +2 -2
- package/dist/server.js +1 -1
- package/dist/{session-clear-Bk_29eEw.d.ts → session-clear-D1PFe7xl.d.ts} +2 -2
- package/dist/session-clear-D1PFe7xl.d.ts.map +1 -0
- package/dist/{store-Z2qjw50n.d.ts → store-D0MhBvg6.d.ts} +15 -6
- package/dist/store-D0MhBvg6.d.ts.map +1 -0
- package/dist/store-N8PXxDAS.js.map +1 -1
- package/dist/store-memory.d.ts +1 -1
- package/dist/store-memory.d.ts.map +1 -1
- package/dist/store-memory.js +15 -17
- package/dist/store-memory.js.map +1 -1
- package/dist/{store-polling-DYNyxCev.js → store-polling-BZt2Rf3D.js} +2 -2
- package/dist/{store-polling-DYNyxCev.js.map → store-polling-BZt2Rf3D.js.map} +1 -1
- package/dist/store-postgres.d.ts +1 -1
- package/dist/store-postgres.d.ts.map +1 -1
- package/dist/store-postgres.js +31 -40
- package/dist/store-postgres.js.map +1 -1
- package/dist/store-presence-polling-JuAy2Ck2.js +111 -0
- package/dist/store-presence-polling-JuAy2Ck2.js.map +1 -0
- package/dist/store-redis-http.d.ts +1 -1
- package/dist/store-redis-http.js +3 -3
- package/dist/{store-redis-notify-IiVdlYHc.js → store-redis-notify-CBDVJxA_.js} +545 -399
- package/dist/store-redis-notify-CBDVJxA_.js.map +1 -0
- package/dist/store-redis.d.ts +1 -1
- package/dist/store-redis.d.ts.map +1 -1
- package/dist/store-redis.js +3 -4
- package/dist/store-redis.js.map +1 -1
- package/dist/store-sqlite.d.ts +1 -1
- package/dist/store-sqlite.d.ts.map +1 -1
- package/dist/store-sqlite.js +16 -18
- package/dist/store-sqlite.js.map +1 -1
- package/dist/store-valkey.d.ts +33 -0
- package/dist/store-valkey.d.ts.map +1 -0
- package/dist/store-valkey.js +218 -0
- package/dist/store-valkey.js.map +1 -0
- package/dist/stream-buffer-DrTyiIuo.js +57 -0
- package/dist/stream-buffer-DrTyiIuo.js.map +1 -0
- package/dist/{wire-CZGqNZRx.js → wire-CV-Z7wz-.js} +3 -3
- package/dist/{wire-CZGqNZRx.js.map → wire-CV-Z7wz-.js.map} +1 -1
- package/docs/actors/01-introduction.mdx +5 -2
- package/docs/agents/03-conversations.mdx +9 -8
- package/docs/agents/04-harnesses.mdx +7 -4
- package/docs/client/03-presence.mdx +1 -0
- package/docs/reference/01-core.mdx +4 -2
- package/docs/reference/02-server.mdx +5 -1
- package/docs/reference/04-ai.mdx +13 -4
- package/docs/reference/06-errors.mdx +1 -1
- package/docs/server/01-consumers.mdx +4 -1
- package/docs/server/06-guarantees.mdx +7 -4
- package/docs/stores/01-overview.mdx +1 -0
- package/docs/stores/02-redis.mdx +18 -10
- package/docs/stores/03-redis-http.mdx +6 -4
- package/docs/stores/04-postgres.mdx +2 -2
- package/docs/stores/07-valkey.mdx +97 -0
- package/docs/upgrades/01-overview.mdx +1 -0
- package/docs/upgrades/78-0-22.mdx +115 -0
- package/examples/playground/app/a0/sandbox.ts +58 -13
- package/examples/playground/app/a2slack/db/a2.ts +7 -4
- package/examples/playground/app/a2slack/db/migrations/0004_a2_session_event_ids.sql +2 -0
- package/examples/playground/app/a2slack/db/migrations/meta/0004_snapshot.json +1165 -0
- package/examples/playground/app/a2slack/db/migrations/meta/_journal.json +8 -1
- package/examples/playground/app/chat/server.ts +2 -2
- package/examples/playground/lib/store.ts +1 -1
- package/examples/playground/package.json +1 -1
- package/package.json +8 -2
- package/sql/postgres/drizzle-schema.ts +7 -4
- package/sql/postgres/schema.sql +24 -3
- package/src/actor-shared.ts +10 -2
- package/src/ai-agent.ts +13 -0
- package/src/ai-fx.ts +365 -78
- package/src/ai-harness.ts +7 -0
- package/src/client.ts +19 -2
- package/src/deterministic-id.ts +1 -1
- package/src/internal.ts +42 -11
- package/src/libfx.d.ts +2 -0
- package/src/presence-recovery.ts +18 -11
- package/src/presence-tombstones.ts +52 -0
- package/src/push-envelope.ts +2 -2
- package/src/server.ts +49 -15
- package/src/store-memory.ts +24 -32
- package/src/store-postgres.ts +43 -53
- package/src/store-presence-polling.ts +59 -34
- package/src/store-redis-core.ts +595 -439
- package/src/store-redis-notify.ts +82 -28
- package/src/store-redis.ts +2 -3
- package/src/store-sqlite.ts +34 -40
- package/src/store-valkey.ts +376 -0
- package/src/store.ts +14 -5
- package/dist/actor-HnGmrOZZ.d.ts.map +0 -1
- package/dist/client-9IeTsiAs.js.map +0 -1
- package/dist/server-DvIB8kj5.js.map +0 -1
- package/dist/session-clear-Bk_29eEw.d.ts.map +0 -1
- package/dist/store-Z2qjw50n.d.ts.map +0 -1
- package/dist/store-presence-polling-CzQ0wdtM.js +0 -94
- package/dist/store-presence-polling-CzQ0wdtM.js.map +0 -1
- package/dist/store-redis-notify-IiVdlYHc.js.map +0 -1
- package/dist/stream-buffer-Cx7AAPGq.js +0 -23
- package/dist/stream-buffer-Cx7AAPGq.js.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { c as ContractEvent, d as PresenceDefs, f as PresenceMap, g as WithPresence, m as PresenceSnapshot, o as AppendInput, p as PresencePatch, r as RegisteredReducer, s as Contract, t as Reducer, u as EventDefs } from "./reducer-CYPHsSmd.js";
|
|
2
|
-
import { t as A2Store } from "./store-
|
|
3
|
-
import { t as SessionCleared } from "./session-clear-
|
|
2
|
+
import { t as A2Store } from "./store-D0MhBvg6.js";
|
|
3
|
+
import { t as SessionCleared } from "./session-clear-D1PFe7xl.js";
|
|
4
4
|
import { i as A2Telemetry } from "./telemetry-CWwsh-Gx.js";
|
|
5
5
|
//#region src/session-socket.d.ts
|
|
6
6
|
/**
|
|
@@ -450,4 +450,4 @@ type ServerOptions<D extends EventDefs, P extends PresenceDefs = Record<never, n
|
|
|
450
450
|
declare function createServer<D extends EventDefs, P extends PresenceDefs = Record<never, never>, R extends RegisteredReducer<D, P> | undefined = RegisteredReducer<D, P> | undefined, const C extends readonly unknown[] = readonly Consumer<D>[]>(options: ServerOptions<D, P, R, C>): A2Server<D, P, R>;
|
|
451
451
|
//#endregion
|
|
452
452
|
export { SessionSchedule as A, SchedulerTask as B, SessionConsumeOptions as C, SessionPresence as D, SessionDispatch as E, deliverSchedulerClear as F, UpgradeWebSocket as G, A2PushEvent as H, ScheduledEvent as I, A2Socket as K, SchedulerAppendTask as L, consumer as M, createServer as N, SessionRedriveOptions as O, deliverSchedulerAppend as P, SchedulerClearTask as R, SessionClearResult as S, SessionDeadLetters as T, A2PushPresence as U, A2Operation as V, ServerFetchOptions as W, ServerConsumers as _, ConsumerAppend as a, SessionAppend as b, ConsumerOptions as c, DeadLetter as d, DrainableServer as f, ScheduleTiming as g, ScheduleDelay as h, Consumer as i, StateOptions as j, SessionRedriveResult as k, ConsumerResult as l, LaneContext as m, A2Server as n, ConsumerContext as o, InlineConsumer as p, AbortSpec as r, ConsumerLane as s, A2Scheduler as t, ConsumerSpec as u, ServerOptions as v, SessionConsumeResult as w, SessionClearOptions as x, Session as y, SchedulerDrainTask as z };
|
|
453
|
-
//# sourceMappingURL=server-
|
|
453
|
+
//# sourceMappingURL=server-qgez0Xny.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-
|
|
1
|
+
{"version":3,"file":"server-qgez0Xny.d.ts","names":[],"sources":["../src/session-socket.ts","../src/server-fetch.ts","../src/scheduler-task.ts","../src/server.ts"],"mappings":";;;;;;;;;;;;KA2CY;EACV,KAAK;EACL,GAAG,kBAAkB,WAAW;EAChC,GAAG,gBAAgB;EACnB,GAAG,gBAAgB,WAAW;EAC9B,MAAM,eAAe;;;EAGrB;;;;KCjBG,mBAAmB,UAAU,oBACzB,wBAAwB;KAE5B,wBAAwB,UAAU,gBAAgB,YAClD,WAAW,2BAA0B;KAG9B,YAAY,UAAU,YAAY;WACnC,MAAM,mBAAmB;WACzB;WACA;;KAGC,eAAe,UAAU,eAAe;WACzC;WACA,QAAQ,wBAAwB;WAChC;WACA;;KAGC,YACV,UAAU,YAAY,WACtB,UAAU,eAAe;WAGZ;WACA;WACA;WACA;WACA;;WAGA;WACA;WACA;WACA;WACA;;WAGA;WACA;WACA,iBAAiB,YAAY;WAC7B,WAAW,eAAe;WAC1B;;KAGH,oBACV,SAAS,QAAQ,sBACd,WAAW,QAAQ;KAEZ,mBACV,UAAU,YAAY,WACtB,UAAU,eAAe;EAEzB,aAAa,WAAW,YAAY,GAAG,iBAAiB;EACxD,mBAAmB;;EAEnB;;;;;KC1FU;EACV;EACA;EACA;;;KAIU;EACV;EACA;EACA;EACA;;EAEA;;;KAIU;EACV;EACA;;EAEA;EACA;EACA;;EAEA;EACA,iBAAiB;;EAEjB;;;KAIU;EACV;EACA;;EAEA;EACA;EACA;;EAEA;;EAEA;;;KAIU,gBACV,qBAAqB,sBAAsB;;;KCgCxC,YAAY,uBAAuB,YAEpC;EAAY,oBAAoB;IAC9B;;KAiCM,gBACV,UAAU,WACV,gBAAgB,mBAAmB,YACnC,UAAU,eAAe,sBACzB;;EAGA,OAAO,cAAc,GAAG;;EAExB;;EAEA,SAAS,QAAQ,GAAG,eAAe,IAAI,GAAG;;EAE1C,QAAQ;;KAG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Map, m as PresenceSnapshot, o as AppendInput, p as PresencePatch, s as Contract, u as EventDefs } from "./reducer-CYPHsSmd.js";
|
|
2
|
-
import { a as EventCause, c as PresenceRow, d as StoreStateRead, f as StoredEvent, i as Event, l as StoreAppendResult, n as AppendEvent, o as FailAttemptResult, r as Clock, s as IdSource, t as A2Store, u as StoreClaimAvailableResult } from "./store-
|
|
3
|
-
import { A as SessionSchedule, B as SchedulerTask, C as SessionConsumeOptions, D as SessionPresence, E as SessionDispatch, F as deliverSchedulerClear, G as UpgradeWebSocket, H as A2PushEvent, I as ScheduledEvent, K as A2Socket, L as SchedulerAppendTask, M as consumer, N as createServer, O as SessionRedriveOptions, P as deliverSchedulerAppend, R as SchedulerClearTask, S as SessionClearResult, T as SessionDeadLetters, U as A2PushPresence, V as A2Operation, W as ServerFetchOptions, _ as ServerConsumers, a as ConsumerAppend, b as SessionAppend, c as ConsumerOptions, d as DeadLetter, f as DrainableServer, g as ScheduleTiming, h as ScheduleDelay, i as Consumer, j as StateOptions, k as SessionRedriveResult, l as ConsumerResult, m as LaneContext, n as A2Server, o as ConsumerContext, p as InlineConsumer, r as AbortSpec, s as ConsumerLane, t as A2Scheduler, u as ConsumerSpec, v as ServerOptions, w as SessionConsumeResult, x as SessionClearOptions, y as Session, z as SchedulerDrainTask } from "./server-
|
|
2
|
+
import { a as EventCause, c as PresenceRow, d as StoreStateRead, f as StoredEvent, i as Event, l as StoreAppendResult, n as AppendEvent, o as FailAttemptResult, r as Clock, s as IdSource, t as A2Store, u as StoreClaimAvailableResult } from "./store-D0MhBvg6.js";
|
|
3
|
+
import { A as SessionSchedule, B as SchedulerTask, C as SessionConsumeOptions, D as SessionPresence, E as SessionDispatch, F as deliverSchedulerClear, G as UpgradeWebSocket, H as A2PushEvent, I as ScheduledEvent, K as A2Socket, L as SchedulerAppendTask, M as consumer, N as createServer, O as SessionRedriveOptions, P as deliverSchedulerAppend, R as SchedulerClearTask, S as SessionClearResult, T as SessionDeadLetters, U as A2PushPresence, V as A2Operation, W as ServerFetchOptions, _ as ServerConsumers, a as ConsumerAppend, b as SessionAppend, c as ConsumerOptions, d as DeadLetter, f as DrainableServer, g as ScheduleTiming, h as ScheduleDelay, i as Consumer, j as StateOptions, k as SessionRedriveResult, l as ConsumerResult, m as LaneContext, n as A2Server, o as ConsumerContext, p as InlineConsumer, r as AbortSpec, s as ConsumerLane, t as A2Scheduler, u as ConsumerSpec, v as ServerOptions, w as SessionConsumeResult, x as SessionClearOptions, y as Session, z as SchedulerDrainTask } from "./server-qgez0Xny.js";
|
|
4
4
|
export { type A2Operation, type A2PushEvent, type A2PushPresence, A2Scheduler, A2Server, type A2Socket, type A2Store, AbortSpec, type AppendEvent, type AppendInput, type Clock, Consumer, ConsumerAppend, ConsumerContext, ConsumerLane, ConsumerOptions, ConsumerResult, ConsumerSpec, type Contract, type ContractEvent, DeadLetter, DrainableServer, type Event, type EventCause, type EventDefs, type FailAttemptResult, type IdSource, InlineConsumer, LaneContext, type PresenceDefs, type PresenceMap, type PresencePatch, type PresenceRow, type PresenceSnapshot, ScheduleDelay, ScheduleTiming, type ScheduledEvent, type SchedulerAppendTask, type SchedulerClearTask, type SchedulerDrainTask, type SchedulerTask, ServerConsumers, type ServerFetchOptions, ServerOptions, Session, SessionAppend, SessionClearOptions, SessionClearResult, SessionConsumeOptions, SessionConsumeResult, SessionDeadLetters, SessionDispatch, SessionPresence, SessionRedriveOptions, SessionRedriveResult, SessionSchedule, StateOptions, type StoreAppendResult, type StoreClaimAvailableResult, type StoreStateRead, type StoredEvent, type UpgradeWebSocket, consumer, createServer, deliverSchedulerAppend, deliverSchedulerClear };
|
package/dist/server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as deliverSchedulerClear, n as createServer, r as deliverSchedulerAppend, t as consumer } from "./server-
|
|
1
|
+
import { i as deliverSchedulerClear, n as createServer, r as deliverSchedulerAppend, t as consumer } from "./server-DtFrWxi3.js";
|
|
2
2
|
export { consumer, createServer, deliverSchedulerAppend, deliverSchedulerClear };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as Event } from "./store-
|
|
1
|
+
import { i as Event } from "./store-D0MhBvg6.js";
|
|
2
2
|
//#region src/session-clear.d.ts
|
|
3
3
|
/** Reserved type of the marker a clear appends. */
|
|
4
4
|
declare const CLEAR_EVENT_TYPE = "a2.cleared";
|
|
@@ -9,4 +9,4 @@ type SessionCleared = Event & {
|
|
|
9
9
|
};
|
|
10
10
|
//#endregion
|
|
11
11
|
export { SessionCleared as t };
|
|
12
|
-
//# sourceMappingURL=session-clear-
|
|
12
|
+
//# sourceMappingURL=session-clear-D1PFe7xl.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session-clear-D1PFe7xl.d.ts","names":[],"sources":["../src/session-clear.ts"],"mappings":";;;cAOa;;KAGD,iBAAiB;EAC3B,aAAa;EACb"}
|
|
@@ -270,6 +270,8 @@ interface A2Store {
|
|
|
270
270
|
* lost — return the existing rows as success. If only *some* ids
|
|
271
271
|
* exist, the caller mixed an already-sent batch with fresh events —
|
|
272
272
|
* always a caller bug — so throw `A2Error('PARTIAL_DUPLICATE_BATCH')`.
|
|
273
|
+
* Ids are unique per session: the same id in another session names a
|
|
274
|
+
* different event and plays no part in these checks.
|
|
273
275
|
*
|
|
274
276
|
* In the same atomic operation, each event's `targets` start cursor work:
|
|
275
277
|
* a lane target queues the event in that consumer's lane, a null lane
|
|
@@ -487,18 +489,25 @@ interface A2Store {
|
|
|
487
489
|
presence?: {
|
|
488
490
|
/**
|
|
489
491
|
* Field-wise last-writer-wins merge of one participant's values:
|
|
490
|
-
* a field whose
|
|
491
|
-
* sender's stamp) is left untouched
|
|
492
|
-
*
|
|
492
|
+
* a field whose unexpired entry has a strictly newer `at` (the
|
|
493
|
+
* sender's stamp) is left untouched. `null` deletes the value but
|
|
494
|
+
* keeps a tombstone with its `at`, which takes part in the merge
|
|
495
|
+
* like a value until it expires, so a set older than the delete
|
|
496
|
+
* still loses when it arrives later. Every applied write, value or
|
|
497
|
+
* tombstone, refreshes that field's expiry to the storage's own
|
|
493
498
|
* clock plus `ttlMs` — the sender stamp orders writes but never
|
|
494
|
-
* anchors their lifetime.
|
|
499
|
+
* anchors their lifetime. `subscribe` delivers applied writes only,
|
|
500
|
+
* a delete as `null`.
|
|
495
501
|
*/
|
|
496
502
|
set(ns: string, participant: string, values: Record<string, unknown | null>, meta: {
|
|
497
503
|
seen: number;
|
|
498
504
|
at: Date;
|
|
499
505
|
ttlMs: number;
|
|
500
506
|
}): Promise<void>;
|
|
501
|
-
/**
|
|
507
|
+
/**
|
|
508
|
+
* The current map, pruned of rows at or past their `expiresAt`.
|
|
509
|
+
* Tombstones never appear.
|
|
510
|
+
*/
|
|
502
511
|
read(ns: string): Promise<PresenceRow[]>;
|
|
503
512
|
/**
|
|
504
513
|
* Adapter-managed patch delivery. Without it, live feeds re-read
|
|
@@ -520,4 +529,4 @@ interface A2Store {
|
|
|
520
529
|
}
|
|
521
530
|
//#endregion
|
|
522
531
|
export { EventCause as a, PresenceRow as c, StoreStateRead as d, StoredEvent as f, Event as i, StoreAppendResult as l, AppendEvent as n, FailAttemptResult as o, Clock as r, IdSource as s, A2Store as t, StoreClaimAvailableResult as u };
|
|
523
|
-
//# sourceMappingURL=store-
|
|
532
|
+
//# sourceMappingURL=store-D0MhBvg6.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store-D0MhBvg6.d.ts","names":[],"sources":["../src/store.ts"],"mappings":";;;KAaY;EACV;EACA;EACA;;EAEA;EACA;EACA,WAAW;;;KAID;EACV;;EAEA;EACA;EACA;;EAEA;;;KAIU,cAAc;;EAExB,OAAO;;;;;;;;;KAUG;EACV;EACA;;EAEA,gBAAgB;;EAEhB,eAAe;;EAEf;;EAEA;;;;;EAKA,gBAAgB;;;;;EAKhB;;EAEA,cAAc;;EAEd;;EAEA;;EAEA,UAAU;;;KAIA,eAAe;;EAEzB;;EAEA;;;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C7B,QAAQ;;;;;;;;EASX,eAAe;IACb;IACA;IACA;IACA;IACA,mBAAmB;IACnB,qBAAqB;;;;;;;;;IASrB;;;;;IAKA;MACE,QAAQ;;;;;;;;;;EAWZ,YAAY;IACV;IACA;IACA,kBAAkB;MAAY;;IAC9B;IACA;MACE,QAAQ;;;;;;;;EASZ,gBAAgB;IACd;IACA;IACA;IACA;IACA;IACA,QAAQ;IACR,qBAAqB;MACnB,QAAQ;;;;;;;;;EAUZ,YAAY;IACV;IACA;IACA;IACA;IACA;IACA;IACA;IACA;MACE,QAAQ;;;;;;;;EASZ,UACE,mBACA,qBACA;IAAY;IAAuB;MAClC,QAAQ;;;;;;;;EASX,YACE,mBAAmB,yBACnB,sBACC,QAAQ;;;;;;;;EASX,aACE,mBACA,qBACA,oBAAoB,uBACnB;;;;;;;EAQH;;;;;;;;;;;;;IAaE,IACE,YACA,qBACA,QAAQ,gCACR;MAAQ;MAAc,IAAI;MAAM;QAC/B;;;;;IAMH,KAAK,aAAa,QAAQ;;;;;;IAO1B,WAAW,YAAY,UAAU,OAAO;;;;;;;;;EAU1C,OACE,mBACA;IAAS;MACR,cAAc"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store-N8PXxDAS.js","names":[],"sources":["../src/store.ts"],"sourcesContent":["/**\n * The A2Store interface — the storage contract every store backend\n * implements. See specs/a2-implementation.md §2–3.\n *\n * This is the whole storage contract: append, read, consumer cursors,\n * failure markers, snapshots, and the live stream. The scheduler\n * needs nothing extra — the armed queue message is its own state, and\n * the store is the only thing it consults.\n */\n\nimport type { PresencePatch } from './contract.ts'\n\n/** A stored event, as the public API exposes it. */\nexport type Event = {\n id: string\n type: string\n payload: unknown\n /** Position in the session's event log, from 1. */\n index: number\n sessionId: string\n createdAt: Date\n}\n\n/** The consumer attempt whose append first persisted a child event. */\nexport type EventCause = {\n consumer: string\n /** The cursor's lane; null for a concurrent consumer's cursor of one event. */\n lane: string | null\n index: number\n attempt: number\n /** Size of one named consumer append, used to reject truncated retries. */\n batchSize?: number\n}\n\n/** What the store persists: immutable event history and its causal edge. */\nexport type StoredEvent = Event & {\n /** Same-session consumer attempt that appended this event; null means root. */\n cause: EventCause | null\n}\n\n/**\n * Where a consumer's cursor stands on its head event. A cursor is one record\n * per (session, consumer, lane): a log cursor for a consumer with one string\n * lane, a lane cursor per lane for a lane function, and a cursor per event\n * (lane null) for a concurrent consumer. Its attempt and failure fields\n * describe the current head and reset when the cursor moves past it.\n */\nexport type HeadDispatch = {\n consumer: string\n lane: string | null\n /** Adapter clock time recorded by the first durable claim of this head. */\n firstClaimedAt: Date | null\n /** Adapter clock time recorded by the most recent durable claim of this head. */\n lastClaimedAt: Date | null\n /** Durable claims of this head, including claims abandoned by hard kills. */\n attemptCount: number\n /** Current holder; null when the head is not claimed. */\n claimHolder: string | null\n /**\n * Adapter clock expiry for the current claim, or, with no holder, the end\n * of a failed attempt's retry hold.\n */\n claimExpiresAt: Date | null\n /**\n * Failed attempts on this head: caught failures, and lapsed claims a later\n * claim took over. This alone drives dead-lettering.\n */\n failureCount: number\n /** Adapter clock time recorded by the most recent caught failure. */\n lastFailedAt: Date | null\n /** Attempt that produced the most recent caught failure. */\n lastFailedAttempt: number | null\n /** The last failure, stringified. */\n lastError: string | null\n /** Adapter clock time recorded when dead-lettered; null otherwise. */\n failedAt: Date | null\n}\n\n/** Where one cursor stands: its position, its head, and the head's dispatch state. */\nexport type StoredCursor = HeadDispatch & {\n /** The last index this cursor finished; a log cursor counts from the latest clear marker. */\n position: number\n /** The event it runs next; null when it has nothing to run. */\n head: number | null\n}\n\n/** A cursor's head event together with its dispatch state. */\nexport type HeadEvent = StoredEvent &\n HeadDispatch & {\n /** Latest clear marker, on claimed heads of a cleared session. */\n clearIndex?: number\n }\n\n/** Names one cursor head: the consumer, its lane, and the head's index. */\nexport type HeadRef = {\n consumer: string\n lane: string | null\n index: number\n}\n\n/**\n * A consumer the caller serves. Work for consumers it does not name is\n * neither pending nor claimed, so a removed consumer's cursors wait for its\n * name to return.\n */\nexport type StoreConsumer = {\n name: string\n /**\n * Set for a consumer with one string lane. Its cursor keeps one position\n * over the log and runs the next event whose type is in `types` (null:\n * every type). A missing cursor is created by the first append that\n * carries one of those types: at the start of the log with `backfill`,\n * otherwise just before that append.\n */\n log?: {\n lane: string\n types: readonly string[] | null\n backfill: boolean\n }\n}\n\n/**\n * One live presence value, as `A2Store.presence.read` returns it. The\n * row is the LWW unit — one participant's one field. `at` is the\n * sender's stamp, the LWW comparator. `expiresAt` is the storage's\n * own clock at the applied set plus its `ttlMs` — never derived from\n * the sender stamp; a row is live strictly before it.\n */\nexport type PresenceRow = {\n participant: string\n field: string\n value: unknown\n seen: number\n at: Date\n expiresAt: Date\n}\n\n/** One consistent cache-plus-tail read for a reducer fold. */\nexport type StoreStateRead = {\n /** The current head checkpoint, even when an older historical snapshot is selected. */\n headIndex: number | null\n /** The greatest cached fold at or before the requested snapshot frontier. */\n snapshot: { index: number; state: unknown } | null\n /** Immutable events strictly after `snapshot.index`, or the full log on a miss. */\n events: Event[]\n /** Latest clear marker; omitted when the session was never cleared. */\n clearIndex?: number\n}\n\nexport type StoreSnapshotWrite = {\n index: number\n state: unknown\n /** Unfinished cursor heads that durably retain this exact checkpoint. */\n pins?: readonly HeadRef[]\n}\n\nexport type StoreStateReadRequest = {\n sessionId: string\n throughIndex?: number\n snapshotThroughIndex?: number\n}\n\n/** The result of atomically claiming every currently eligible head. */\nexport type StoreClaimAvailableResult =\n | {\n outcome: 'claimed'\n events: HeadEvent[]\n /** The session's head when the claim was made: how far behind each event is. */\n head?: number\n }\n | { outcome: 'busy'; retryAt: Date }\n | { outcome: 'settled' }\n\n/** A completion may lose to a newer claim or an earlier completion. */\nexport type CompleteAttemptResult =\n { outcome: 'completed'; events: StoredEvent[] } | { outcome: 'superseded' }\n\n/** The result of one claim-renewal heartbeat, both lists in head order. */\nexport type RenewClaimsResult = {\n /** Listed claims that remain owned by the holder. */\n renewed: HeadRef[]\n /** Listed claims a newer attempt has durably taken, or whose cursor moved on. */\n superseded: HeadRef[]\n}\n\n/** The result of atomically recording a caught failure. */\nexport type FailAttemptResult = {\n outcome: 'failed' | 'dead_lettered' | 'superseded'\n failureCount: number\n}\n\n/** A consumer an appended event starts work for, with its resolved lane. */\nexport type EventTarget = {\n consumer: string\n /** The lane a lane function resolved; null runs the event concurrently. */\n lane: string | null\n}\n\n/** Input to `A2Store.append` — already validated by the machine. */\nexport type AppendEvent = {\n type: string\n payload: unknown\n /** Caller-supplied idempotency key; generated when absent. */\n id?: string\n /** Internal causal edge supplied atomically by consumer `session.append`. */\n cause?: EventCause\n /**\n * Lane-function and concurrent consumers this event starts work for,\n * resolved before persistence. Log-cursor consumers are matched by type\n * from `StoreConsumer.log` instead.\n */\n targets?: readonly EventTarget[]\n}\n\n/** A consumer-returned event with the deterministic id retries require. */\nexport type ReturnedEvent = AppendEvent & { id: string }\n\n/** The rows written by an append and the session's pending state. */\nexport type StoreAppendResult = {\n events: StoredEvent[]\n /**\n * Whether a served consumer has a live head in this session: one that is\n * not dead-lettered. An append whose own batch starts work for a served\n * consumer may report true without checking that work is runnable.\n */\n hasPending: boolean\n}\n\nexport type StoreClearOptions = {\n sessionId: string\n ifLastIndex?: number\n /** The clearing consumer's attempt, fenced like a consumer append. */\n cause?: EventCause\n}\n\nexport type StoreClearResult = {\n cleared: boolean\n /** The head after the operation. */\n index: number\n /** The latest clear marker after the operation, or 0. */\n clearIndex: number\n}\n\nexport type StoreReclaimResult = { deleted: number; done: boolean }\n\nexport type StoreRedriveOptions = {\n sessionId: string\n consumer: string\n index: number\n /** `retry` clears the dead letter; `skip` moves the cursor past it. */\n action: 'retry' | 'skip'\n consumers?: readonly StoreConsumer[]\n}\n\nexport type StoreRedriveResult = {\n /** Whether the head was dead-lettered and this operation resolved it. */\n redriven: boolean\n /** Whether a served consumer has a live head in this session: one that is not dead-lettered. */\n hasPending: boolean\n}\n\n/**\n * An injectable clock. Adapters take one so tests can drive claim\n * expiry, failure timestamps, and (later) stuck-session detection\n * deterministically — against real storage, no mocking.\n */\nexport type Clock = {\n now(): Date\n}\n\n/** An injectable id source for generated event ids. */\nexport type IdSource = () => string\n\nexport const SYSTEM_CLOCK: Clock = {\n now: () => new Date(),\n}\n\nexport const RANDOM_IDS: IdSource = () => crypto.randomUUID()\n\n/**\n * Cursor rules every operation shares:\n *\n * - `consumers` names the consumers the caller serves. Omitted, every cursor\n * counts and no log cursor is created or advanced by type.\n * - A cursor's head is the next event it runs: the lowest unfinished event of\n * its lane, the event itself for a concurrent cursor, or for a log cursor\n * the next event after its position whose type it takes. The clear marker\n * is never a head.\n * - A head is eligible when no live claim or retry hold owns it, it is not\n * dead-lettered, and it lies above the latest clear marker.\n * - Moving a cursor past its head resets the head's attempt and failure\n * fields and releases snapshot pins on it.\n */\nexport interface A2Store {\n /**\n * Accepts a batch; the batch is atomic — one transaction, consecutive\n * `index`es, all-or-nothing. The idempotency key covers the whole\n * operation, not each item: if *every* event's `id` already exists in\n * this session, this is a retry of a committed batch whose ack was\n * lost — return the existing rows as success. If only *some* ids\n * exist, the caller mixed an already-sent batch with fresh events —\n * always a caller bug — so throw `A2Error('PARTIAL_DUPLICATE_BATCH')`.\n *\n * In the same atomic operation, each event's `targets` start cursor work:\n * a lane target queues the event in that consumer's lane, a null lane\n * creates a cursor for that event alone. Each log consumer in `consumers`\n * whose types the batch carries gets its cursor created or, when idle, a\n * head: the next event after its position that it takes, which may\n * precede the batch when an appender that doesn't serve it wrote in\n * between. `hasPending` reflects the whole session for the served consumers,\n * including older work and idempotent retries.\n *\n * An event carrying `cause` is a consumer append, fenced by attempt\n * currency: accept it only while the cause's cursor still has\n * `cause.index` as its head, `cause.attempt` is that head's latest\n * attempt, and the head is not dead-lettered; otherwise throw\n * `A2Error('SUPERSEDED_ATTEMPT')` and write nothing. The check is part of\n * this atomic operation and must serialize against a concurrent\n * `claimAvailable` — an unlocked read of the cursor admits write skew. The\n * idempotent-replay path runs first, so a batch whose ids all exist\n * replays regardless of the current attempt.\n *\n * Clearing stores (a2-implementation.md §17.2) fence one level earlier:\n * a `cause` at or below the latest clear marker throws\n * `SUPERSEDED_ATTEMPT`, an `originIndex` there throws `SESSION_CLEARED`,\n * and ids whose rows lie below the marker are free to reuse.\n */\n append(\n sessionId: string,\n events: AppendEvent[],\n options?: {\n originIndex?: number\n consumers?: readonly StoreConsumer[]\n },\n ): Promise<StoreAppendResult>\n\n /**\n * Optional with `reclaim`. Serialized with `append`: checks\n * `ifLastIndex` against the head and the latest marker, then appends a\n * clear marker at the next index without touching existing rows.\n * Afterwards every event at or below the marker is superseded: no head\n * lies there, and every log cursor's position counts from the marker.\n */\n clear?(options: StoreClearOptions): Promise<StoreClearResult>\n\n /**\n * Deletes one bounded batch of rows below the latest clear marker, with\n * their cursor records, id records, and cached folds. `done` once nothing\n * remains below it. Never waits on a lock that other operations hold.\n */\n reclaim?(sessionId: string): Promise<StoreReclaimResult>\n\n /**\n * Optional with `redrive`. The session's dead-lettered heads above the\n * latest clear marker, in event order, then by consumer name.\n */\n deadLetters?(sessionId: string): Promise<HeadEvent[]>\n\n /**\n * Optional with `deadLetters`. Atomically resolves the consumer's\n * dead-lettered head at `index` above the latest clear marker; anything\n * else is untouched and reports `redriven: false`. `retry` clears\n * `failedAt` and `failureCount`, so the head is claimable again with a\n * fresh failure budget, keeping its claim history and last failure. `skip`\n * moves the cursor past the head with no completion. Both serialize with\n * `claimAvailable` and the consumer-append fence. `hasPending` is read in\n * the same step.\n */\n redrive?(options: StoreRedriveOptions): Promise<StoreRedriveResult>\n\n /**\n * Brings one log consumer's cursor up to date without an append, for\n * `session.consume()`. A missing cursor is created: with `backfill`, at\n * the latest clear marker, taking the first event of its types after it;\n * otherwise at the head, with nothing to run. When the session has nothing\n * after its latest clear (or was never written), a missing cursor stays\n * missing: nothing is written, and the cursor comes back idle at the\n * marker, so a consume of an unknown session leaves no trace. That is\n * exact with `backfill`; without it, the consumer starts at the first\n * consume or serving append that finds events. An\n * idle cursor takes the next event of its types after its position, so it\n * finds events appended by deployments that don't serve it. A cursor with\n * a head, claimed or not, is left as it is. Records the consumer's types,\n * as an append would, and returns the cursor and the session's head.\n */\n wakeLog(options: {\n sessionId: string\n consumer: StoreConsumer & { log: NonNullable<StoreConsumer['log']> }\n }): Promise<{ cursor: StoredCursor; head: number }>\n\n /**\n * The session's cursors: every log and lane cursor, and every concurrent\n * cursor that still has a head, by consumer, then lane (concurrent cursors\n * last, by head). Lane and concurrent cursors whose work lies at or below\n * the latest clear marker are not listed.\n */\n cursors(sessionId: string): Promise<StoredCursor[]>\n\n /** Events for one session, oldest first. Bounds form `(afterIndex, throughIndex]`. */\n read(\n sessionId: string,\n opts?: { afterIndex?: number; throughIndex?: number },\n ): Promise<StoredEvent[]>\n\n /** Public history without causal edges; core falls back to read when absent. */\n readHistory?(\n sessionId: string,\n opts?: { afterIndex?: number; throughIndex?: number },\n ): Promise<Event[]>\n\n /**\n * Atomically claims every eligible head of the served consumers. A live\n * claim or retry hold produces `busy` only when it is the sole remaining\n * obstacle to actionable work. Claimed heads are returned in event order,\n * then by consumer name. Excluded heads stay unclaimed and keep blocking\n * their lane.\n */\n claimAvailable(options: {\n sessionId: string\n holder: string\n ttlMs: number\n expiresAtMs?: number\n exclude?: readonly HeadRef[]\n consumers?: readonly StoreConsumer[]\n /**\n * Taking over a lapsed claim (one whose holder is still recorded, never\n * completed or failed) adds one to `failureCount`. When that reaches\n * `maxFailures`, the head dead-letters instead of being claimed: it\n * comes back in `events` with `failedAt` set and no claim. Its\n * `attemptCount` still advances, fencing the lapsed attempt, and its\n * `lastFailedAttempt` is unchanged.\n */\n maxFailures?: number\n /**\n * Claims only heads at or below this index: a head past it is neither\n * claimed nor reported `busy`, and stays claimable without it.\n */\n through?: number\n }): Promise<StoreClaimAvailableResult>\n\n /**\n * Renews the listed live claims still owned by `holder`. Each listed claim\n * carries the attempt the holder owns. `renewed` lists the claims that\n * remain owned after the operation; `superseded` lists the claims whose\n * head a newer attempt has durably taken, or whose cursor has moved past\n * it. An expired claim no successor has taken appears in neither list — its\n * attempt may still complete (`completeAttempt` is the fence), so it is\n * not reported as lost. Renewal never revives an expired claim.\n */\n renewClaims(options: {\n sessionId: string\n holder: string\n claims: readonly (HeadRef & { attempt: number })[]\n ttlMs: number\n expiresAtMs?: number\n }): Promise<RenewClaimsResult>\n\n /**\n * Atomically completes one current attempt: appends its returned events\n * (with their own targets, waking the served log consumers) and moves the\n * cursor past its head. Retrying a committed completion with the same\n * attempt and deterministic child ids returns the existing children. A\n * stale attempt never appends.\n */\n completeAttempt(options: {\n sessionId: string\n consumer: string\n lane: string | null\n index: number\n attempt: number\n events: ReturnedEvent[]\n consumers?: readonly StoreConsumer[]\n }): Promise<CompleteAttemptResult>\n\n /**\n * Atomically records a caught failure for one claimed attempt. A stale\n * attempt cannot poison a finished head or a newer attempt. Accepted\n * failures record the operation's clock time. A failure that does not\n * dead-letter releases the claim and, with `retryAfterMs`, keeps the head\n * unclaimable for that long: its claim expiry is set with no holder, so\n * `claimAvailable` reports it `busy` until then.\n */\n failAttempt(options: {\n sessionId: string\n consumer: string\n lane: string | null\n index: number\n attempt: number\n error: string\n maxFailures: number\n retryAfterMs?: number\n }): Promise<FailAttemptResult>\n\n /**\n * Reads a reducer snapshot and its event tail as one consistent adapter\n * operation. On a cache miss, `snapshot` is null and `events` is the full\n * log. The snapshot is untrusted; core may reject it and issue a full\n * `read()` when its state schema no longer accepts the cached value.\n * Operational failures propagate without falling back to a full-log read.\n */\n readState(\n sessionId: string,\n reducerName: string,\n options?: { throughIndex?: number; snapshotThroughIndex?: number },\n ): Promise<StoreStateRead>\n\n /**\n * Optional batched `readState` — one consistent snapshot-plus-tail read\n * per session id, aligned positionally with the input (duplicates\n * allowed). Each element has its own frontier; the batch makes no\n * cross-session consistency claim. Core falls back to parallel\n * `readState` calls when absent.\n */\n readStates?(\n requests: readonly StoreStateReadRequest[],\n reducerName: string,\n ): Promise<StoreStateRead[]>\n\n /**\n * Atomically writes disposable reducer checkpoints. The greatest index\n * advances the head cache. Older checkpoints survive only while at least\n * one listed cursor head is still unfinished; moving that cursor past it\n * or dead-lettering it releases the pin and collects unreferenced\n * historical checkpoints.\n */\n putSnapshots(\n sessionId: string,\n reducerName: string,\n snapshots: readonly StoreSnapshotWrite[],\n ): Promise<void>\n\n /**\n * Optional ephemeral-plane capability (specs/a2-implementation.md\n * §15.1) — optional like snapshots are. Values arrive already\n * validated by core; adapters store them opaquely. Presence never\n * touches the event log: no index, no history row, no recovery arm.\n */\n presence?: {\n /**\n * Field-wise last-writer-wins merge of one participant's values:\n * a field whose existing row has a strictly newer `at` (the\n * sender's stamp) is left untouched; `null` deletes the row. Every\n * applied write refreshes that field's expiry to the storage's own\n * clock plus `ttlMs` — the sender stamp orders writes but never\n * anchors their lifetime.\n */\n set(\n ns: string,\n participant: string,\n values: Record<string, unknown | null>,\n meta: { seen: number; at: Date; ttlMs: number },\n ): Promise<void>\n\n /** The current map, pruned of rows at or past their `expiresAt`. */\n read(ns: string): Promise<PresenceRow[]>\n\n /**\n * Adapter-managed patch delivery. Without it, live feeds re-read\n * presence on their poll cadence. HTTP Redis uses adaptive polling\n * here when its endpoint does not support subscriptions.\n */\n subscribe?(ns: string, onPatch: (patch: PresencePatch) => void): () => void\n }\n\n /**\n * A live feed of one session's events, starting after `startAfter`\n * (exclusive). Transport is the backend's choice — in-process pub/sub,\n * polling, LISTEN/NOTIFY — callers never branch on which. The iterable\n * ends when the consumer calls `return()` (e.g. a disconnecting SSE\n * client) and must deliver events appended after subscription.\n */\n stream(\n sessionId: string,\n opts?: { startAfter?: number },\n ): AsyncIterable<Event>\n}\n"],"mappings":";AAiRA,MAAa,eAAsB,EACjC,2BAAW,IAAI,KAAK,EACtB;AAEA,MAAa,mBAA6B,OAAO,WAAW"}
|
|
1
|
+
{"version":3,"file":"store-N8PXxDAS.js","names":[],"sources":["../src/store.ts"],"sourcesContent":["/**\n * The A2Store interface — the storage contract every store backend\n * implements. See specs/a2-implementation.md §2–3.\n *\n * This is the whole storage contract: append, read, consumer cursors,\n * failure markers, snapshots, and the live stream. The scheduler\n * needs nothing extra — the armed queue message is its own state, and\n * the store is the only thing it consults.\n */\n\nimport type { PresencePatch } from './contract.ts'\n\n/** A stored event, as the public API exposes it. */\nexport type Event = {\n id: string\n type: string\n payload: unknown\n /** Position in the session's event log, from 1. */\n index: number\n sessionId: string\n createdAt: Date\n}\n\n/** The consumer attempt whose append first persisted a child event. */\nexport type EventCause = {\n consumer: string\n /** The cursor's lane; null for a concurrent consumer's cursor of one event. */\n lane: string | null\n index: number\n attempt: number\n /** Size of one named consumer append, used to reject truncated retries. */\n batchSize?: number\n}\n\n/** What the store persists: immutable event history and its causal edge. */\nexport type StoredEvent = Event & {\n /** Same-session consumer attempt that appended this event; null means root. */\n cause: EventCause | null\n}\n\n/**\n * Where a consumer's cursor stands on its head event. A cursor is one record\n * per (session, consumer, lane): a log cursor for a consumer with one string\n * lane, a lane cursor per lane for a lane function, and a cursor per event\n * (lane null) for a concurrent consumer. Its attempt and failure fields\n * describe the current head and reset when the cursor moves past it.\n */\nexport type HeadDispatch = {\n consumer: string\n lane: string | null\n /** Adapter clock time recorded by the first durable claim of this head. */\n firstClaimedAt: Date | null\n /** Adapter clock time recorded by the most recent durable claim of this head. */\n lastClaimedAt: Date | null\n /** Durable claims of this head, including claims abandoned by hard kills. */\n attemptCount: number\n /** Current holder; null when the head is not claimed. */\n claimHolder: string | null\n /**\n * Adapter clock expiry for the current claim, or, with no holder, the end\n * of a failed attempt's retry hold.\n */\n claimExpiresAt: Date | null\n /**\n * Failed attempts on this head: caught failures, and lapsed claims a later\n * claim took over. This alone drives dead-lettering.\n */\n failureCount: number\n /** Adapter clock time recorded by the most recent caught failure. */\n lastFailedAt: Date | null\n /** Attempt that produced the most recent caught failure. */\n lastFailedAttempt: number | null\n /** The last failure, stringified. */\n lastError: string | null\n /** Adapter clock time recorded when dead-lettered; null otherwise. */\n failedAt: Date | null\n}\n\n/** Where one cursor stands: its position, its head, and the head's dispatch state. */\nexport type StoredCursor = HeadDispatch & {\n /** The last index this cursor finished; a log cursor counts from the latest clear marker. */\n position: number\n /** The event it runs next; null when it has nothing to run. */\n head: number | null\n}\n\n/** A cursor's head event together with its dispatch state. */\nexport type HeadEvent = StoredEvent &\n HeadDispatch & {\n /** Latest clear marker, on claimed heads of a cleared session. */\n clearIndex?: number\n }\n\n/** Names one cursor head: the consumer, its lane, and the head's index. */\nexport type HeadRef = {\n consumer: string\n lane: string | null\n index: number\n}\n\n/**\n * A consumer the caller serves. Work for consumers it does not name is\n * neither pending nor claimed, so a removed consumer's cursors wait for its\n * name to return.\n */\nexport type StoreConsumer = {\n name: string\n /**\n * Set for a consumer with one string lane. Its cursor keeps one position\n * over the log and runs the next event whose type is in `types` (null:\n * every type). A missing cursor is created by the first append that\n * carries one of those types: at the start of the log with `backfill`,\n * otherwise just before that append.\n */\n log?: {\n lane: string\n types: readonly string[] | null\n backfill: boolean\n }\n}\n\n/**\n * One live presence value, as `A2Store.presence.read` returns it. The\n * row is the LWW unit — one participant's one field. `at` is the\n * sender's stamp, the LWW comparator. `expiresAt` is the storage's\n * own clock at the applied set plus its `ttlMs` — never derived from\n * the sender stamp; a row is live strictly before it.\n */\nexport type PresenceRow = {\n participant: string\n field: string\n value: unknown\n seen: number\n at: Date\n expiresAt: Date\n}\n\n/** One consistent cache-plus-tail read for a reducer fold. */\nexport type StoreStateRead = {\n /** The current head checkpoint, even when an older historical snapshot is selected. */\n headIndex: number | null\n /** The greatest cached fold at or before the requested snapshot frontier. */\n snapshot: { index: number; state: unknown } | null\n /** Immutable events strictly after `snapshot.index`, or the full log on a miss. */\n events: Event[]\n /** Latest clear marker; omitted when the session was never cleared. */\n clearIndex?: number\n}\n\nexport type StoreSnapshotWrite = {\n index: number\n state: unknown\n /** Unfinished cursor heads that durably retain this exact checkpoint. */\n pins?: readonly HeadRef[]\n}\n\nexport type StoreStateReadRequest = {\n sessionId: string\n throughIndex?: number\n snapshotThroughIndex?: number\n}\n\n/** The result of atomically claiming every currently eligible head. */\nexport type StoreClaimAvailableResult =\n | {\n outcome: 'claimed'\n events: HeadEvent[]\n /** The session's head when the claim was made: how far behind each event is. */\n head?: number\n }\n | { outcome: 'busy'; retryAt: Date }\n | { outcome: 'settled' }\n\n/** A completion may lose to a newer claim or an earlier completion. */\nexport type CompleteAttemptResult =\n { outcome: 'completed'; events: StoredEvent[] } | { outcome: 'superseded' }\n\n/** The result of one claim-renewal heartbeat, both lists in head order. */\nexport type RenewClaimsResult = {\n /** Listed claims that remain owned by the holder. */\n renewed: HeadRef[]\n /** Listed claims a newer attempt has durably taken, or whose cursor moved on. */\n superseded: HeadRef[]\n}\n\n/** The result of atomically recording a caught failure. */\nexport type FailAttemptResult = {\n outcome: 'failed' | 'dead_lettered' | 'superseded'\n failureCount: number\n}\n\n/** A consumer an appended event starts work for, with its resolved lane. */\nexport type EventTarget = {\n consumer: string\n /** The lane a lane function resolved; null runs the event concurrently. */\n lane: string | null\n}\n\n/** Input to `A2Store.append` — already validated by the machine. */\nexport type AppendEvent = {\n type: string\n payload: unknown\n /** Caller-supplied idempotency key; generated when absent. */\n id?: string\n /** Internal causal edge supplied atomically by consumer `session.append`. */\n cause?: EventCause\n /**\n * Lane-function and concurrent consumers this event starts work for,\n * resolved before persistence. Log-cursor consumers are matched by type\n * from `StoreConsumer.log` instead.\n */\n targets?: readonly EventTarget[]\n}\n\n/** A consumer-returned event with the deterministic id retries require. */\nexport type ReturnedEvent = AppendEvent & { id: string }\n\n/** The rows written by an append and the session's pending state. */\nexport type StoreAppendResult = {\n events: StoredEvent[]\n /**\n * Whether a served consumer has a live head in this session: one that is\n * not dead-lettered. An append whose own batch starts work for a served\n * consumer may report true without checking that work is runnable.\n */\n hasPending: boolean\n}\n\nexport type StoreClearOptions = {\n sessionId: string\n ifLastIndex?: number\n /** The clearing consumer's attempt, fenced like a consumer append. */\n cause?: EventCause\n}\n\nexport type StoreClearResult = {\n cleared: boolean\n /** The head after the operation. */\n index: number\n /** The latest clear marker after the operation, or 0. */\n clearIndex: number\n}\n\nexport type StoreReclaimResult = { deleted: number; done: boolean }\n\nexport type StoreRedriveOptions = {\n sessionId: string\n consumer: string\n index: number\n /** `retry` clears the dead letter; `skip` moves the cursor past it. */\n action: 'retry' | 'skip'\n consumers?: readonly StoreConsumer[]\n}\n\nexport type StoreRedriveResult = {\n /** Whether the head was dead-lettered and this operation resolved it. */\n redriven: boolean\n /** Whether a served consumer has a live head in this session: one that is not dead-lettered. */\n hasPending: boolean\n}\n\n/**\n * An injectable clock. Adapters take one so tests can drive claim\n * expiry, failure timestamps, and (later) stuck-session detection\n * deterministically — against real storage, no mocking.\n */\nexport type Clock = {\n now(): Date\n}\n\n/** An injectable id source for generated event ids. */\nexport type IdSource = () => string\n\nexport const SYSTEM_CLOCK: Clock = {\n now: () => new Date(),\n}\n\nexport const RANDOM_IDS: IdSource = () => crypto.randomUUID()\n\n/**\n * Cursor rules every operation shares:\n *\n * - `consumers` names the consumers the caller serves. Omitted, every cursor\n * counts and no log cursor is created or advanced by type.\n * - A cursor's head is the next event it runs: the lowest unfinished event of\n * its lane, the event itself for a concurrent cursor, or for a log cursor\n * the next event after its position whose type it takes. The clear marker\n * is never a head.\n * - A head is eligible when no live claim or retry hold owns it, it is not\n * dead-lettered, and it lies above the latest clear marker.\n * - Moving a cursor past its head resets the head's attempt and failure\n * fields and releases snapshot pins on it.\n */\nexport interface A2Store {\n /**\n * Accepts a batch; the batch is atomic — one transaction, consecutive\n * `index`es, all-or-nothing. The idempotency key covers the whole\n * operation, not each item: if *every* event's `id` already exists in\n * this session, this is a retry of a committed batch whose ack was\n * lost — return the existing rows as success. If only *some* ids\n * exist, the caller mixed an already-sent batch with fresh events —\n * always a caller bug — so throw `A2Error('PARTIAL_DUPLICATE_BATCH')`.\n * Ids are unique per session: the same id in another session names a\n * different event and plays no part in these checks.\n *\n * In the same atomic operation, each event's `targets` start cursor work:\n * a lane target queues the event in that consumer's lane, a null lane\n * creates a cursor for that event alone. Each log consumer in `consumers`\n * whose types the batch carries gets its cursor created or, when idle, a\n * head: the next event after its position that it takes, which may\n * precede the batch when an appender that doesn't serve it wrote in\n * between. `hasPending` reflects the whole session for the served consumers,\n * including older work and idempotent retries.\n *\n * An event carrying `cause` is a consumer append, fenced by attempt\n * currency: accept it only while the cause's cursor still has\n * `cause.index` as its head, `cause.attempt` is that head's latest\n * attempt, and the head is not dead-lettered; otherwise throw\n * `A2Error('SUPERSEDED_ATTEMPT')` and write nothing. The check is part of\n * this atomic operation and must serialize against a concurrent\n * `claimAvailable` — an unlocked read of the cursor admits write skew. The\n * idempotent-replay path runs first, so a batch whose ids all exist\n * replays regardless of the current attempt.\n *\n * Clearing stores (a2-implementation.md §17.2) fence one level earlier:\n * a `cause` at or below the latest clear marker throws\n * `SUPERSEDED_ATTEMPT`, an `originIndex` there throws `SESSION_CLEARED`,\n * and ids whose rows lie below the marker are free to reuse.\n */\n append(\n sessionId: string,\n events: AppendEvent[],\n options?: {\n originIndex?: number\n consumers?: readonly StoreConsumer[]\n },\n ): Promise<StoreAppendResult>\n\n /**\n * Optional with `reclaim`. Serialized with `append`: checks\n * `ifLastIndex` against the head and the latest marker, then appends a\n * clear marker at the next index without touching existing rows.\n * Afterwards every event at or below the marker is superseded: no head\n * lies there, and every log cursor's position counts from the marker.\n */\n clear?(options: StoreClearOptions): Promise<StoreClearResult>\n\n /**\n * Deletes one bounded batch of rows below the latest clear marker, with\n * their cursor records, id records, and cached folds. `done` once nothing\n * remains below it. Never waits on a lock that other operations hold.\n */\n reclaim?(sessionId: string): Promise<StoreReclaimResult>\n\n /**\n * Optional with `redrive`. The session's dead-lettered heads above the\n * latest clear marker, in event order, then by consumer name.\n */\n deadLetters?(sessionId: string): Promise<HeadEvent[]>\n\n /**\n * Optional with `deadLetters`. Atomically resolves the consumer's\n * dead-lettered head at `index` above the latest clear marker; anything\n * else is untouched and reports `redriven: false`. `retry` clears\n * `failedAt` and `failureCount`, so the head is claimable again with a\n * fresh failure budget, keeping its claim history and last failure. `skip`\n * moves the cursor past the head with no completion. Both serialize with\n * `claimAvailable` and the consumer-append fence. `hasPending` is read in\n * the same step.\n */\n redrive?(options: StoreRedriveOptions): Promise<StoreRedriveResult>\n\n /**\n * Brings one log consumer's cursor up to date without an append, for\n * `session.consume()`. A missing cursor is created: with `backfill`, at\n * the latest clear marker, taking the first event of its types after it;\n * otherwise at the head, with nothing to run. When the session has nothing\n * after its latest clear (or was never written), a missing cursor stays\n * missing: nothing is written, and the cursor comes back idle at the\n * marker, so a consume of an unknown session leaves no trace. That is\n * exact with `backfill`; without it, the consumer starts at the first\n * consume or serving append that finds events. An\n * idle cursor takes the next event of its types after its position, so it\n * finds events appended by deployments that don't serve it. A cursor with\n * a head, claimed or not, is left as it is. Records the consumer's types,\n * as an append would, and returns the cursor and the session's head.\n */\n wakeLog(options: {\n sessionId: string\n consumer: StoreConsumer & { log: NonNullable<StoreConsumer['log']> }\n }): Promise<{ cursor: StoredCursor; head: number }>\n\n /**\n * The session's cursors: every log and lane cursor, and every concurrent\n * cursor that still has a head, by consumer, then lane (concurrent cursors\n * last, by head). Lane and concurrent cursors whose work lies at or below\n * the latest clear marker are not listed.\n */\n cursors(sessionId: string): Promise<StoredCursor[]>\n\n /** Events for one session, oldest first. Bounds form `(afterIndex, throughIndex]`. */\n read(\n sessionId: string,\n opts?: { afterIndex?: number; throughIndex?: number },\n ): Promise<StoredEvent[]>\n\n /** Public history without causal edges; core falls back to read when absent. */\n readHistory?(\n sessionId: string,\n opts?: { afterIndex?: number; throughIndex?: number },\n ): Promise<Event[]>\n\n /**\n * Atomically claims every eligible head of the served consumers. A live\n * claim or retry hold produces `busy` only when it is the sole remaining\n * obstacle to actionable work. Claimed heads are returned in event order,\n * then by consumer name. Excluded heads stay unclaimed and keep blocking\n * their lane.\n */\n claimAvailable(options: {\n sessionId: string\n holder: string\n ttlMs: number\n expiresAtMs?: number\n exclude?: readonly HeadRef[]\n consumers?: readonly StoreConsumer[]\n /**\n * Taking over a lapsed claim (one whose holder is still recorded, never\n * completed or failed) adds one to `failureCount`. When that reaches\n * `maxFailures`, the head dead-letters instead of being claimed: it\n * comes back in `events` with `failedAt` set and no claim. Its\n * `attemptCount` still advances, fencing the lapsed attempt, and its\n * `lastFailedAttempt` is unchanged.\n */\n maxFailures?: number\n /**\n * Claims only heads at or below this index: a head past it is neither\n * claimed nor reported `busy`, and stays claimable without it.\n */\n through?: number\n }): Promise<StoreClaimAvailableResult>\n\n /**\n * Renews the listed live claims still owned by `holder`. Each listed claim\n * carries the attempt the holder owns. `renewed` lists the claims that\n * remain owned after the operation; `superseded` lists the claims whose\n * head a newer attempt has durably taken, or whose cursor has moved past\n * it. An expired claim no successor has taken appears in neither list — its\n * attempt may still complete (`completeAttempt` is the fence), so it is\n * not reported as lost. Renewal never revives an expired claim.\n */\n renewClaims(options: {\n sessionId: string\n holder: string\n claims: readonly (HeadRef & { attempt: number })[]\n ttlMs: number\n expiresAtMs?: number\n }): Promise<RenewClaimsResult>\n\n /**\n * Atomically completes one current attempt: appends its returned events\n * (with their own targets, waking the served log consumers) and moves the\n * cursor past its head. Retrying a committed completion with the same\n * attempt and deterministic child ids returns the existing children. A\n * stale attempt never appends.\n */\n completeAttempt(options: {\n sessionId: string\n consumer: string\n lane: string | null\n index: number\n attempt: number\n events: ReturnedEvent[]\n consumers?: readonly StoreConsumer[]\n }): Promise<CompleteAttemptResult>\n\n /**\n * Atomically records a caught failure for one claimed attempt. A stale\n * attempt cannot poison a finished head or a newer attempt. Accepted\n * failures record the operation's clock time. A failure that does not\n * dead-letter releases the claim and, with `retryAfterMs`, keeps the head\n * unclaimable for that long: its claim expiry is set with no holder, so\n * `claimAvailable` reports it `busy` until then.\n */\n failAttempt(options: {\n sessionId: string\n consumer: string\n lane: string | null\n index: number\n attempt: number\n error: string\n maxFailures: number\n retryAfterMs?: number\n }): Promise<FailAttemptResult>\n\n /**\n * Reads a reducer snapshot and its event tail as one consistent adapter\n * operation. On a cache miss, `snapshot` is null and `events` is the full\n * log. The snapshot is untrusted; core may reject it and issue a full\n * `read()` when its state schema no longer accepts the cached value.\n * Operational failures propagate without falling back to a full-log read.\n */\n readState(\n sessionId: string,\n reducerName: string,\n options?: { throughIndex?: number; snapshotThroughIndex?: number },\n ): Promise<StoreStateRead>\n\n /**\n * Optional batched `readState` — one consistent snapshot-plus-tail read\n * per session id, aligned positionally with the input (duplicates\n * allowed). Each element has its own frontier; the batch makes no\n * cross-session consistency claim. Core falls back to parallel\n * `readState` calls when absent.\n */\n readStates?(\n requests: readonly StoreStateReadRequest[],\n reducerName: string,\n ): Promise<StoreStateRead[]>\n\n /**\n * Atomically writes disposable reducer checkpoints. The greatest index\n * advances the head cache. Older checkpoints survive only while at least\n * one listed cursor head is still unfinished; moving that cursor past it\n * or dead-lettering it releases the pin and collects unreferenced\n * historical checkpoints.\n */\n putSnapshots(\n sessionId: string,\n reducerName: string,\n snapshots: readonly StoreSnapshotWrite[],\n ): Promise<void>\n\n /**\n * Optional ephemeral-plane capability (specs/a2-implementation.md\n * §15.1) — optional like snapshots are. Values arrive already\n * validated by core; adapters store them opaquely. Presence never\n * touches the event log: no index, no history row, no recovery arm.\n */\n presence?: {\n /**\n * Field-wise last-writer-wins merge of one participant's values:\n * a field whose unexpired entry has a strictly newer `at` (the\n * sender's stamp) is left untouched. `null` deletes the value but\n * keeps a tombstone with its `at`, which takes part in the merge\n * like a value until it expires, so a set older than the delete\n * still loses when it arrives later. Every applied write, value or\n * tombstone, refreshes that field's expiry to the storage's own\n * clock plus `ttlMs` — the sender stamp orders writes but never\n * anchors their lifetime. `subscribe` delivers applied writes only,\n * a delete as `null`.\n */\n set(\n ns: string,\n participant: string,\n values: Record<string, unknown | null>,\n meta: { seen: number; at: Date; ttlMs: number },\n ): Promise<void>\n\n /**\n * The current map, pruned of rows at or past their `expiresAt`.\n * Tombstones never appear.\n */\n read(ns: string): Promise<PresenceRow[]>\n\n /**\n * Adapter-managed patch delivery. Without it, live feeds re-read\n * presence on their poll cadence. HTTP Redis uses adaptive polling\n * here when its endpoint does not support subscriptions.\n */\n subscribe?(ns: string, onPatch: (patch: PresencePatch) => void): () => void\n }\n\n /**\n * A live feed of one session's events, starting after `startAfter`\n * (exclusive). Transport is the backend's choice — in-process pub/sub,\n * polling, LISTEN/NOTIFY — callers never branch on which. The iterable\n * ends when the consumer calls `return()` (e.g. a disconnecting SSE\n * client) and must deliver events appended after subscription.\n */\n stream(\n sessionId: string,\n opts?: { startAfter?: number },\n ): AsyncIterable<Event>\n}\n"],"mappings":";AAiRA,MAAa,eAAsB,EACjC,2BAAW,IAAI,KAAK,EACtB;AAEA,MAAa,mBAA6B,OAAO,WAAW"}
|
package/dist/store-memory.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { r as Clock, s as IdSource, t as A2Store } from "./store-
|
|
1
|
+
import { r as Clock, s as IdSource, t as A2Store } from "./store-D0MhBvg6.js";
|
|
2
2
|
//#region src/store-memory.d.ts
|
|
3
3
|
type MemoryStoreOptions = {
|
|
4
4
|
/** Injectable clock — every stored timestamp comes from here. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store-memory.d.ts","names":[],"sources":["../src/store-memory.ts"],"mappings":";;KAiCY;;EAEV,QAAQ;;EAER,MAAM;;
|
|
1
|
+
{"version":3,"file":"store-memory.d.ts","names":[],"sources":["../src/store-memory.ts"],"mappings":";;KAiCY;;EAEV,QAAQ;;EAER,MAAM;;iBAoLQ,OAAO,UAAS,qBAA0B"}
|
package/dist/store-memory.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { i as A2Error, r as sessionClearedError, s as supersededAttemptError, t as CLEAR_EVENT_TYPE } from "./session-clear-wHd5GCpZ.js";
|
|
2
|
-
import {
|
|
2
|
+
import { y as nullProtoRecord } from "./internal-CvsrprnU.js";
|
|
3
3
|
import { a as idempotentReplay, i as idleLogCursor } from "./store-codec-DwrWlgQx.js";
|
|
4
4
|
import { n as SYSTEM_CLOCK, t as RANDOM_IDS } from "./store-N8PXxDAS.js";
|
|
5
5
|
//#region src/store-memory.ts
|
|
@@ -92,8 +92,6 @@ function memory(options = {}) {
|
|
|
92
92
|
const sessions = /* @__PURE__ */ new Map();
|
|
93
93
|
/** Session id → cursor key → cursor. */
|
|
94
94
|
const cursors = /* @__PURE__ */ new Map();
|
|
95
|
-
/** Global unique index on event ids, like the SQL schema's. */
|
|
96
|
-
const byEventId = /* @__PURE__ */ new Map();
|
|
97
95
|
/** Keyed by `${sessionId}\u0000${reducerName}` — a pure cache. */
|
|
98
96
|
const snapshots = /* @__PURE__ */ new Map();
|
|
99
97
|
const historicalSnapshots = /* @__PURE__ */ new Map();
|
|
@@ -114,7 +112,8 @@ function memory(options = {}) {
|
|
|
114
112
|
log = {
|
|
115
113
|
rows: [],
|
|
116
114
|
offset: 0,
|
|
117
|
-
clearIndex: 0
|
|
115
|
+
clearIndex: 0,
|
|
116
|
+
byEventId: /* @__PURE__ */ new Map()
|
|
118
117
|
};
|
|
119
118
|
sessions.set(sessionId, log);
|
|
120
119
|
}
|
|
@@ -125,10 +124,11 @@ function memory(options = {}) {
|
|
|
125
124
|
return log && index > log.offset ? log.rows[index - log.offset - 1] : void 0;
|
|
126
125
|
};
|
|
127
126
|
const clearIndexOf = (sessionId) => sessions.get(sessionId)?.clearIndex ?? 0;
|
|
128
|
-
/** The row owning `id`, ignoring
|
|
127
|
+
/** The session's row owning `id`, ignoring rows below its clear. */
|
|
129
128
|
const ownerOf = (sessionId, id) => {
|
|
130
|
-
const
|
|
131
|
-
|
|
129
|
+
const log = sessions.get(sessionId);
|
|
130
|
+
const row = log?.byEventId.get(id);
|
|
131
|
+
return log && row && row.index >= log.clearIndex ? row : void 0;
|
|
132
132
|
};
|
|
133
133
|
const cursorsOf = (sessionId) => {
|
|
134
134
|
let map = cursors.get(sessionId);
|
|
@@ -213,10 +213,7 @@ function memory(options = {}) {
|
|
|
213
213
|
const checkBatchIds = (sessionId, events) => {
|
|
214
214
|
const supplied = events.filter((candidate) => candidate.id !== void 0);
|
|
215
215
|
if (new Set(supplied.map((candidate) => candidate.id)).size !== supplied.length) throw new A2Error("PARTIAL_DUPLICATE_BATCH", "batch contains the same event id more than once");
|
|
216
|
-
|
|
217
|
-
const foreign = existing.find((row) => row.sessionId !== sessionId);
|
|
218
|
-
if (foreign) throw new A2Error("PARTIAL_DUPLICATE_BATCH", `event id '${foreign.id}' already exists in another session`);
|
|
219
|
-
return existing;
|
|
216
|
+
return supplied.map((candidate) => ownerOf(sessionId, candidate.id)).filter((row) => row !== void 0);
|
|
220
217
|
};
|
|
221
218
|
/** Records the types a declared log consumer takes on its cursor. */
|
|
222
219
|
const refreshLogTypes = (sessionId, consumers) => {
|
|
@@ -312,7 +309,7 @@ function memory(options = {}) {
|
|
|
312
309
|
for (const row of inserted) if (ownerOf(sessionId, row.id)) throw new A2Error("PARTIAL_DUPLICATE_BATCH", `event id '${row.id}' already exists`);
|
|
313
310
|
for (const row of inserted) {
|
|
314
311
|
log.rows.push(row);
|
|
315
|
-
byEventId.set(row.id, row);
|
|
312
|
+
log.byEventId.set(row.id, row);
|
|
316
313
|
}
|
|
317
314
|
enqueue(sessionId, inserted, events, base, consumers);
|
|
318
315
|
return inserted;
|
|
@@ -436,7 +433,7 @@ function memory(options = {}) {
|
|
|
436
433
|
};
|
|
437
434
|
const removed = log.rows.splice(0, Math.min(RECLAIM_BATCH, log.clearIndex - 1 - log.offset));
|
|
438
435
|
log.offset += removed.length;
|
|
439
|
-
for (const row of removed) if (byEventId.get(row.id) === row) byEventId.delete(row.id);
|
|
436
|
+
for (const row of removed) if (log.byEventId.get(row.id) === row) log.byEventId.delete(row.id);
|
|
440
437
|
const done = log.offset === log.clearIndex - 1;
|
|
441
438
|
if (done) dropCheckpointsBelow(sessionId, log.clearIndex);
|
|
442
439
|
return {
|
|
@@ -741,14 +738,14 @@ function memory(options = {}) {
|
|
|
741
738
|
fields = /* @__PURE__ */ new Map();
|
|
742
739
|
participants.set(participant, fields);
|
|
743
740
|
}
|
|
744
|
-
const
|
|
741
|
+
const now = clock.now();
|
|
742
|
+
const expiresAtMs = now.getTime() + meta.ttlMs;
|
|
745
743
|
const applied = nullProtoRecord();
|
|
746
744
|
let appliedCount = 0;
|
|
747
745
|
for (const [field, value] of Object.entries(values)) {
|
|
748
746
|
const existing = fields.get(field);
|
|
749
|
-
if (existing && existing.at > meta.at) continue;
|
|
750
|
-
|
|
751
|
-
else fields.set(field, {
|
|
747
|
+
if (existing && existing.expiresAt > now && existing.at > meta.at) continue;
|
|
748
|
+
fields.set(field, {
|
|
752
749
|
value: structuredClone(value),
|
|
753
750
|
seen: meta.seen,
|
|
754
751
|
at: new Date(meta.at),
|
|
@@ -781,6 +778,7 @@ function memory(options = {}) {
|
|
|
781
778
|
fields.delete(field);
|
|
782
779
|
continue;
|
|
783
780
|
}
|
|
781
|
+
if (entry.value === null) continue;
|
|
784
782
|
rows.push({
|
|
785
783
|
participant,
|
|
786
784
|
field,
|