@effect-agent/storage-cloudflare 0.1.0-beta.9 → 0.1.0-beta.91

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.
Files changed (73) hide show
  1. package/dist/DoMemoryStore.d.mts +29 -0
  2. package/dist/DoMemoryStore.mjs +55 -0
  3. package/dist/DoMemoryStore.mjs.map +1 -0
  4. package/dist/DoMessageDeliveryStore.d.mts +17 -0
  5. package/dist/DoMessageDeliveryStore.mjs +32 -0
  6. package/dist/DoMessageDeliveryStore.mjs.map +1 -0
  7. package/dist/DoScheduleStore.d.mts +36 -0
  8. package/dist/DoScheduleStore.mjs +388 -0
  9. package/dist/DoScheduleStore.mjs.map +1 -0
  10. package/dist/DoStorageConfig.d.mts +45 -0
  11. package/dist/DoStorageConfig.mjs +52 -0
  12. package/dist/DoStorageConfig.mjs.map +1 -0
  13. package/dist/DoStorageError-Cmhvl4TQ.d.mts +98 -0
  14. package/dist/DoStorageError.d.mts +2 -0
  15. package/dist/DoStorageError.mjs +164 -0
  16. package/dist/DoStorageError.mjs.map +1 -0
  17. package/dist/DoStorageFailpoint.d.mts +17 -0
  18. package/dist/DoStorageFailpoint.mjs +14 -0
  19. package/dist/DoStorageFailpoint.mjs.map +1 -0
  20. package/dist/DoStorageFailpointTesting.d.mts +34 -0
  21. package/dist/DoStorageFailpointTesting.mjs +35 -0
  22. package/dist/DoStorageFailpointTesting.mjs.map +1 -0
  23. package/dist/DoStorageVersion-x5OOurvZ.d.mts +12 -0
  24. package/dist/DoStorageVersion.d.mts +2 -0
  25. package/dist/DoStorageVersion.mjs +8 -0
  26. package/dist/DoStorageVersion.mjs.map +1 -0
  27. package/dist/DoSubmissionLedger.d.mts +23 -0
  28. package/dist/DoSubmissionLedger.mjs +1849 -0
  29. package/dist/DoSubmissionLedger.mjs.map +1 -0
  30. package/dist/DoSubscriptionStore.d.mts +25 -0
  31. package/dist/DoSubscriptionStore.mjs +183 -0
  32. package/dist/DoSubscriptionStore.mjs.map +1 -0
  33. package/dist/DoThreadStore.d.mts +59 -0
  34. package/dist/DoThreadStore.mjs +465 -0
  35. package/dist/DoThreadStore.mjs.map +1 -0
  36. package/dist/MemoryProtocol.d.mts +38160 -0
  37. package/dist/MemoryProtocol.mjs +219 -0
  38. package/dist/MemoryProtocol.mjs.map +1 -0
  39. package/dist/PortProtocol.d.mts +3804 -0
  40. package/dist/PortProtocol.mjs +176 -0
  41. package/dist/PortProtocol.mjs.map +1 -0
  42. package/dist/PortRouting.d.mts +83 -0
  43. package/dist/PortRouting.mjs +410 -0
  44. package/dist/PortRouting.mjs.map +1 -0
  45. package/dist/do-journal-dJ01KSKf.mjs +991 -0
  46. package/dist/do-journal-dJ01KSKf.mjs.map +1 -0
  47. package/dist/index.d.mts +14 -1525
  48. package/dist/index.mjs +14 -3695
  49. package/dist/migrations-Ba_kOrSx.mjs +287 -0
  50. package/dist/migrations-Ba_kOrSx.mjs.map +1 -0
  51. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  52. package/package.json +1 -45
  53. package/src/DoMemoryStore.ts +56 -0
  54. package/src/DoMessageDeliveryStore.ts +53 -0
  55. package/src/DoScheduleStore.ts +622 -0
  56. package/src/{errors.ts → DoStorageError.ts} +10 -3
  57. package/src/DoStorageFailpoint.ts +20 -0
  58. package/src/{do-storage-failpoint.ts → DoStorageFailpointTesting.ts} +5 -18
  59. package/src/DoStorageVersion.ts +2 -0
  60. package/src/{do-ledger.ts → DoSubmissionLedger.ts} +924 -225
  61. package/src/DoSubscriptionStore.ts +329 -0
  62. package/src/DoThreadStore.ts +1012 -0
  63. package/src/MemoryProtocol.ts +351 -0
  64. package/src/{port-protocol.ts → PortProtocol.ts} +45 -38
  65. package/src/{routing.ts → PortRouting.ts} +292 -264
  66. package/src/index.ts +13 -32
  67. package/src/{do-journal.ts → internal/do-journal.ts} +718 -234
  68. package/src/internal/message-delivery-schema.ts +24 -0
  69. package/src/{migrations.ts → internal/migrations.ts} +51 -35
  70. package/src/internal/recovery-checkpoint-schema.ts +17 -0
  71. package/dist/index.mjs.map +0 -1
  72. package/src/do-conversation-store.ts +0 -850
  73. /package/src/{do-storage-config.ts → DoStorageConfig.ts} +0 -0
@@ -0,0 +1,329 @@
1
+ import { BrowserCrypto } from "@effect/platform-browser";
2
+ import { Context, Effect, Layer, Schema } from "effect";
3
+ import { upgradeV2Subscriptions } from "effect-agent/sql-storage-v2-upgrade";
4
+ import {
5
+ makeSqlSubscriptionStore,
6
+ SqlSubscriptionTransaction,
7
+ } from "effect-agent/sql-subscription-store";
8
+ import {
9
+ SourcePartition,
10
+ SubscriptionError,
11
+ SubscriptionFailpoint,
12
+ type SubscriptionFailpointError,
13
+ SubscriptionStore,
14
+ } from "effect-agent/subscription";
15
+ import * as SqlClientService from "effect/unstable/sql/SqlClient";
16
+ import type { SqlError } from "effect/unstable/sql/SqlError";
17
+
18
+ const CURRENT_SUBSCRIPTION_STORE_VERSION = 3;
19
+
20
+ const ScanRow = Schema.Struct({
21
+ event_scan_cursor: Schema.String,
22
+ delivery_scan_cursor: Schema.String,
23
+ recovery_scan_cursor: Schema.Natural,
24
+ });
25
+
26
+ const StoreStateRow = Schema.Struct({
27
+ storage_version: Schema.Int,
28
+ alarm_generation: Schema.Natural,
29
+ });
30
+
31
+ export interface DoSubscriptionAlarmReplacement {
32
+ readonly deadlineAtMillis: number | null;
33
+ readonly generation: number;
34
+ }
35
+
36
+ export type DoSubscriptionReplaceAlarm = (
37
+ replacement: DoSubscriptionAlarmReplacement,
38
+ ) => Effect.Effect<void, SubscriptionError>;
39
+
40
+ /** One Durable Object transaction combining subscription SQL and its single native alarm. */
41
+ export class DoSubscriptionTransaction extends Context.Service<
42
+ DoSubscriptionTransaction,
43
+ {
44
+ readonly run: <A, E, R>(
45
+ body: (replaceAlarm: DoSubscriptionReplaceAlarm) => Effect.Effect<A, E, R>,
46
+ ) => Effect.Effect<A, E | SubscriptionError, R>;
47
+ }
48
+ >()("@effect-agent/storage-cloudflare/DoSubscriptionTransaction") {}
49
+
50
+ export class DoSubscriptionAlarmControl extends Context.Service<
51
+ DoSubscriptionAlarmControl,
52
+ {
53
+ readonly prearm: (
54
+ deadlineAtMillis: number,
55
+ ) => Effect.Effect<void, SubscriptionError | SubscriptionFailpointError>;
56
+ readonly reconcile: Effect.Effect<void, SubscriptionError | SubscriptionFailpointError>;
57
+ }
58
+ >()("@effect-agent/storage-cloudflare/DoSubscriptionAlarmControl") {}
59
+
60
+ const error = (reason: SubscriptionError["reason"], code: string) =>
61
+ SubscriptionError.make({ reason, code });
62
+
63
+ const unavailable = (operation: string) => error("storage", operation);
64
+ const corrupt = (operation: string) => error("corrupt", operation);
65
+
66
+ const validate = <A, I>(schema: Schema.Codec<A, I>, value: unknown, code: string) =>
67
+ Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError(() => error("validation", code)));
68
+
69
+ const decodeRows = <A, I>(schema: Schema.Codec<A, I>, rows: unknown, code: string) =>
70
+ Schema.decodeUnknownEffect(Schema.Array(schema))(rows).pipe(Effect.mapError(() => corrupt(code)));
71
+
72
+ const initializeDoSubscriptionStore = Effect.fn("DoSubscriptionStore.initialize")(function* () {
73
+ const sql = yield* SqlClientService.SqlClient;
74
+
75
+ const names = yield* sql<Record<string, unknown>>`
76
+ SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'effect_agent_subscription_%'
77
+ `.pipe(Effect.mapError(() => unavailable("inspect subscription storage")));
78
+
79
+ const decodedNames = yield* decodeRows(
80
+ Schema.Struct({ name: Schema.String }),
81
+ names,
82
+ "inspect subscription storage",
83
+ );
84
+
85
+ const expected = new Set([
86
+ "effect_agent_subscription_store_state",
87
+ "effect_agent_subscription_sequences",
88
+ "effect_agent_subscriptions",
89
+ "effect_agent_subscription_events",
90
+ "effect_agent_subscription_deliveries",
91
+ ]);
92
+
93
+ const hasState = decodedNames.some(
94
+ ({ name }) => name === "effect_agent_subscription_store_state",
95
+ );
96
+
97
+ if (!hasState && decodedNames.length > 0) return yield* corrupt("partial subscription storage");
98
+ if (!hasState) {
99
+ yield* sql
100
+ .withTransaction(
101
+ Effect.gen(function* () {
102
+ yield* sql`CREATE TABLE effect_agent_subscription_store_state (
103
+ singleton INTEGER PRIMARY KEY NOT NULL CHECK(singleton=1), storage_version INTEGER NOT NULL, alarm_generation INTEGER NOT NULL
104
+ )`.withoutTransform;
105
+ yield* sql`CREATE TABLE effect_agent_subscription_sequences (
106
+ tenant_id TEXT NOT NULL, source_address TEXT NOT NULL, sequence INTEGER NOT NULL,
107
+ event_scan_cursor TEXT NOT NULL, delivery_scan_cursor TEXT NOT NULL, recovery_scan_cursor INTEGER NOT NULL,
108
+ PRIMARY KEY (tenant_id, source_address)
109
+ )`.withoutTransform;
110
+ yield* sql`CREATE TABLE effect_agent_subscriptions (
111
+ tenant_id TEXT NOT NULL, source_address TEXT NOT NULL, owner_id TEXT NOT NULL, subscription_id TEXT NOT NULL,
112
+ ordinal INTEGER NOT NULL, source_name TEXT NOT NULL, source_version TEXT NOT NULL, matching_key TEXT NOT NULL,
113
+ state TEXT NOT NULL, expires_at_millis INTEGER, recovery_at_millis INTEGER, recovery_present INTEGER NOT NULL DEFAULT 0, record_json TEXT NOT NULL,
114
+ PRIMARY KEY (tenant_id, source_address, owner_id, subscription_id), UNIQUE (tenant_id, source_address, ordinal)
115
+ )`.withoutTransform;
116
+ yield* sql`CREATE INDEX effect_agent_subscriptions_owner ON effect_agent_subscriptions (tenant_id, source_address, owner_id, ordinal)`
117
+ .withoutTransform;
118
+ yield* sql`CREATE INDEX effect_agent_subscriptions_candidates ON effect_agent_subscriptions (tenant_id, source_address, source_name, source_version, matching_key, ordinal)`
119
+ .withoutTransform;
120
+ yield* sql`CREATE INDEX effect_agent_subscriptions_recovery ON effect_agent_subscriptions (tenant_id, source_address, recovery_at_millis, ordinal) WHERE recovery_at_millis IS NOT NULL`
121
+ .withoutTransform;
122
+ yield* sql`CREATE TABLE effect_agent_subscription_events (
123
+ tenant_id TEXT NOT NULL, source_address TEXT NOT NULL, event_id TEXT NOT NULL, source_name TEXT NOT NULL,
124
+ source_version TEXT NOT NULL, matching_key TEXT NOT NULL, payload_digest TEXT NOT NULL, cutoff INTEGER NOT NULL,
125
+ cursor INTEGER NOT NULL, routing_complete INTEGER NOT NULL, tombstone INTEGER NOT NULL DEFAULT 0, next_attempt_at_millis INTEGER NOT NULL, record_json TEXT NOT NULL,
126
+ PRIMARY KEY (tenant_id, source_address, event_id)
127
+ )`.withoutTransform;
128
+ yield* sql`CREATE INDEX effect_agent_subscription_events_pending ON effect_agent_subscription_events (tenant_id, source_address, routing_complete, next_attempt_at_millis, event_id)`
129
+ .withoutTransform;
130
+ yield* sql`CREATE TABLE effect_agent_subscription_deliveries (
131
+ tenant_id TEXT NOT NULL, source_address TEXT NOT NULL, owner_id TEXT NOT NULL, subscription_id TEXT NOT NULL,
132
+ event_id TEXT NOT NULL, delivery_key TEXT NOT NULL, state TEXT NOT NULL, next_attempt_at_millis INTEGER NOT NULL,
133
+ record_json TEXT NOT NULL, PRIMARY KEY (tenant_id, source_address, owner_id, subscription_id, event_id),
134
+ UNIQUE (tenant_id, source_address, delivery_key)
135
+ )`.withoutTransform;
136
+ yield* sql`CREATE INDEX effect_agent_subscription_deliveries_pending ON effect_agent_subscription_deliveries (tenant_id, source_address, state, next_attempt_at_millis, delivery_key)`
137
+ .withoutTransform;
138
+ yield* sql`CREATE INDEX effect_agent_subscription_deliveries_registration ON effect_agent_subscription_deliveries (tenant_id, source_address, owner_id, subscription_id, delivery_key)`
139
+ .withoutTransform;
140
+ yield* sql`INSERT INTO effect_agent_subscription_store_state (singleton, storage_version, alarm_generation)
141
+ VALUES (1, ${CURRENT_SUBSCRIPTION_STORE_VERSION}, 0)`.withoutTransform;
142
+ }),
143
+ )
144
+ .pipe(Effect.mapError(() => unavailable("initialize subscription storage")));
145
+
146
+ return;
147
+ }
148
+ if (decodedNames.length !== expected.size || decodedNames.some(({ name }) => !expected.has(name)))
149
+ return yield* corrupt("subscription storage tables");
150
+
151
+ const rows = yield* sql<
152
+ Record<string, unknown>
153
+ >`SELECT storage_version, alarm_generation FROM effect_agent_subscription_store_state WHERE singleton=1`.pipe(
154
+ Effect.mapError(() => unavailable("read subscription storage version")),
155
+ );
156
+
157
+ const state = yield* decodeRows(StoreStateRow, rows, "read subscription storage version");
158
+
159
+ if (state.length === 1 && state[0].storage_version === 2) {
160
+ const failpoint = yield* SubscriptionFailpoint;
161
+
162
+ yield* sql
163
+ .withTransaction(
164
+ Effect.gen(function* () {
165
+ const current = yield* sql<{
166
+ storage_version: number;
167
+ }>`SELECT storage_version FROM effect_agent_subscription_store_state WHERE singleton=1`;
168
+
169
+ if (current.length === 1 && current[0].storage_version === 3) return;
170
+ if (current.length !== 1 || current[0].storage_version !== 2)
171
+ return yield* corrupt("subscription version changed during upgrade");
172
+ yield* upgradeV2Subscriptions(1_900_000);
173
+ yield* failpoint.hit("upgrade:before-version");
174
+ yield* sql`UPDATE effect_agent_subscription_store_state SET storage_version=3 WHERE singleton=1`;
175
+ yield* failpoint.hit("upgrade:after-version");
176
+ }),
177
+ )
178
+ .pipe(
179
+ Effect.provide(BrowserCrypto.layer),
180
+ Effect.catchTag("StorageUpgradeError", (error) =>
181
+ SubscriptionError.make({
182
+ reason: "corrupt",
183
+ code: "upgrade-v2-subscriptions",
184
+ cause: error,
185
+ }),
186
+ ),
187
+ Effect.catchTag("SqlError", () => unavailable("upgrade v2 subscriptions")),
188
+ Effect.catchTag("SchemaError", () => corrupt("upgrade v2 subscription encoding")),
189
+ Effect.catchTag("SubscriptionFailpointError", () =>
190
+ unavailable("upgrade v2 subscriptions failpoint"),
191
+ ),
192
+ );
193
+
194
+ return;
195
+ }
196
+
197
+ if (state.length !== 1 || state[0].storage_version !== CURRENT_SUBSCRIPTION_STORE_VERSION)
198
+ return yield* corrupt(
199
+ state.length === 1
200
+ ? `incompatible subscription storage version ${state[0].storage_version}; expected ${CURRENT_SUBSCRIPTION_STORE_VERSION}`
201
+ : "invalid subscription storage version row",
202
+ );
203
+ });
204
+
205
+ const makeSubscriptionStore = Effect.fn("DoSubscriptionStore.make")(function* (
206
+ owned: SourcePartition,
207
+ ) {
208
+ const partition = yield* validate(SourcePartition, owned, "partition");
209
+ const sql = yield* SqlClientService.SqlClient;
210
+ const failpoint = yield* SubscriptionFailpoint;
211
+ const transactions = yield* DoSubscriptionTransaction;
212
+
213
+ yield* initializeDoSubscriptionStore();
214
+
215
+ const query = <A extends object>(
216
+ effect: Effect.Effect<ReadonlyArray<A>, SqlError>,
217
+ code: string,
218
+ ) => effect.pipe(Effect.mapError(() => unavailable(code)));
219
+
220
+ const readIndexedDeadline = Effect.fn("DoSubscriptionStore.readIndexedDeadline")(function* () {
221
+ const scanRows = yield* query(
222
+ sql<Record<string, unknown>>`
223
+ SELECT event_scan_cursor, delivery_scan_cursor, recovery_scan_cursor FROM effect_agent_subscription_sequences
224
+ WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}
225
+ `,
226
+ "read scan cursor deadline",
227
+ );
228
+
229
+ const scans = yield* decodeRows(ScanRow, scanRows, "read scan cursor deadline");
230
+
231
+ if (scans.length !== 1) return yield* corrupt("scan cursor deadline");
232
+ if (
233
+ scans[0].event_scan_cursor !== "" ||
234
+ scans[0].delivery_scan_cursor !== "" ||
235
+ scans[0].recovery_scan_cursor !== 0
236
+ )
237
+ return 0;
238
+
239
+ const rows = yield* query(
240
+ sql<Record<string, unknown>>`
241
+ SELECT MIN(deadline) AS deadline FROM (
242
+ SELECT next_attempt_at_millis AS deadline FROM effect_agent_subscription_events
243
+ WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND routing_complete=0
244
+ UNION ALL SELECT next_attempt_at_millis FROM effect_agent_subscription_deliveries
245
+ WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND CASE WHEN json_valid(record_json) THEN
246
+ ((state NOT IN ('delivered','refused') AND COALESCE(json_extract(record_json, '$.retry.parked'), 0)=0) OR (state='delivered' AND json_extract(record_json, '$.observeSettlement')=1))
247
+ ELSE state<>'refused' END
248
+ UNION ALL SELECT next_maintenance_at_millis FROM effect_agent_event_retention
249
+ WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}
250
+ UNION ALL SELECT recovery_at_millis FROM effect_agent_subscriptions
251
+ WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND state='active' AND recovery_at_millis IS NOT NULL
252
+ )
253
+ `,
254
+ "read subscription deadline",
255
+ );
256
+
257
+ const decoded = yield* decodeRows(
258
+ Schema.Struct({ deadline: Schema.NullOr(Schema.Number) }),
259
+ rows,
260
+ "read subscription deadline",
261
+ );
262
+
263
+ if (decoded.length !== 1) return yield* corrupt("subscription deadline");
264
+
265
+ return decoded[0].deadline;
266
+ });
267
+
268
+ const replaceAlarm = Effect.fn("DoSubscriptionStore.replaceAlarm")(function* (
269
+ replace: DoSubscriptionReplaceAlarm,
270
+ deadlineAtMillis: number | null,
271
+ ) {
272
+ const rows = yield* query(
273
+ sql<Record<string, unknown>>`
274
+ UPDATE effect_agent_subscription_store_state SET alarm_generation=alarm_generation+1
275
+ WHERE singleton=1 RETURNING storage_version, alarm_generation
276
+ `,
277
+ "advance subscription alarm generation",
278
+ );
279
+
280
+ const state = yield* decodeRows(StoreStateRow, rows, "advance subscription alarm generation");
281
+
282
+ if (state.length !== 1 || state[0].storage_version !== CURRENT_SUBSCRIPTION_STORE_VERSION)
283
+ return yield* corrupt("subscription alarm state");
284
+ yield* failpoint.hit("subscription:alarm:before");
285
+ yield* replace({ deadlineAtMillis, generation: state[0].alarm_generation });
286
+ yield* failpoint.hit("subscription:alarm:after");
287
+ });
288
+
289
+ const transact = <A>(effect: Effect.Effect<A, SubscriptionError | SubscriptionFailpointError>) =>
290
+ transactions.run((replace) =>
291
+ Effect.gen(function* () {
292
+ const value = yield* effect;
293
+
294
+ yield* replaceAlarm(replace, yield* readIndexedDeadline());
295
+
296
+ return value;
297
+ }),
298
+ );
299
+
300
+ const store = yield* makeSqlSubscriptionStore(partition, {
301
+ maxStoredJsonLength: 1_900_000,
302
+ }).pipe(Effect.provideService(SqlSubscriptionTransaction, { run: transact }));
303
+
304
+ const prearm = Effect.fn("DoSubscriptionStore.prearm")(function* (deadlineAtMillis: number) {
305
+ yield* transactions.run((replace) => replaceAlarm(replace, deadlineAtMillis));
306
+ yield* failpoint.hit("subscription:prearm:after");
307
+ });
308
+
309
+ const reconcile = Effect.gen(function* () {
310
+ yield* transactions.run((replace) =>
311
+ Effect.gen(function* () {
312
+ yield* replaceAlarm(replace, yield* readIndexedDeadline());
313
+ }),
314
+ );
315
+ yield* failpoint.hit("subscription:reconcile:after");
316
+ });
317
+
318
+ return Context.make(SubscriptionStore, store).pipe(
319
+ Context.add(DoSubscriptionAlarmControl, { prearm, reconcile }),
320
+ );
321
+ });
322
+
323
+ export const doSubscriptionStoreLayer = (
324
+ partition: SourcePartition,
325
+ ): Layer.Layer<
326
+ SubscriptionStore | DoSubscriptionAlarmControl,
327
+ SubscriptionError,
328
+ DoSubscriptionTransaction | SqlClientService.SqlClient
329
+ > => Layer.effectContext(makeSubscriptionStore(partition));