@systemfsoftware/agent-storage-cloudflare 0.0.0-stage → 0.1.0-beta.192

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 (101) hide show
  1. package/LICENSE +21 -0
  2. package/dist/DoMemoryStore-AaGtt8CZ.d.mts +29 -0
  3. package/dist/DoMemoryStore-DVun329p.mjs +67 -0
  4. package/dist/DoMemoryStore-DVun329p.mjs.map +1 -0
  5. package/dist/DoMemoryStore.d.mts +2 -0
  6. package/dist/DoMemoryStore.mjs +1 -0
  7. package/dist/DoMessageDeliveryStore-BvB6OPI1.mjs +34 -0
  8. package/dist/DoMessageDeliveryStore-BvB6OPI1.mjs.map +1 -0
  9. package/dist/DoMessageDeliveryStore-Cb-DNN5s.d.mts +16 -0
  10. package/dist/DoMessageDeliveryStore.d.mts +2 -0
  11. package/dist/DoMessageDeliveryStore.mjs +1 -0
  12. package/dist/DoScheduleStore-BiTgDvX1.d.mts +36 -0
  13. package/dist/DoScheduleStore-C7GkSReF.mjs +167 -0
  14. package/dist/DoScheduleStore-C7GkSReF.mjs.map +1 -0
  15. package/dist/DoScheduleStore.d.mts +2 -0
  16. package/dist/DoScheduleStore.mjs +1 -0
  17. package/dist/DoStorageConfig-BqezsbD6.mjs +43 -0
  18. package/dist/DoStorageConfig-BqezsbD6.mjs.map +1 -0
  19. package/dist/DoStorageConfig-CuB6ZOtX.d.mts +36 -0
  20. package/dist/DoStorageConfig.d.mts +2 -0
  21. package/dist/DoStorageConfig.mjs +1 -0
  22. package/dist/DoStorageError-C-F5Z_FZ.d.mts +82 -0
  23. package/dist/DoStorageError-DSQzuCb0.mjs +138 -0
  24. package/dist/DoStorageError-DSQzuCb0.mjs.map +1 -0
  25. package/dist/DoStorageError.d.mts +2 -0
  26. package/dist/DoStorageError.mjs +1 -0
  27. package/dist/DoStorageFailpoint-C7zLUULu.d.mts +19 -0
  28. package/dist/DoStorageFailpoint-WO3B_DQl.mjs +20 -0
  29. package/dist/DoStorageFailpoint-WO3B_DQl.mjs.map +1 -0
  30. package/dist/DoStorageFailpoint.d.mts +2 -0
  31. package/dist/DoStorageFailpoint.mjs +1 -0
  32. package/dist/DoStorageFailpointTesting.d.mts +21 -0
  33. package/dist/DoStorageFailpointTesting.mjs +18 -0
  34. package/dist/DoStorageFailpointTesting.mjs.map +1 -0
  35. package/dist/DoStorageVersion-BrolfBDS.mjs +7 -0
  36. package/dist/DoStorageVersion-BrolfBDS.mjs.map +1 -0
  37. package/dist/DoStorageVersion-D7CIxFc_.d.mts +8 -0
  38. package/dist/DoStorageVersion.d.mts +3 -0
  39. package/dist/DoStorageVersion.mjs +2 -0
  40. package/dist/DoSubmissionLedger-Oq5OstxL.mjs +1878 -0
  41. package/dist/DoSubmissionLedger-Oq5OstxL.mjs.map +1 -0
  42. package/dist/DoSubmissionLedger-tLjwidUn.d.mts +25 -0
  43. package/dist/DoSubmissionLedger.d.mts +2 -0
  44. package/dist/DoSubmissionLedger.mjs +1 -0
  45. package/dist/DoSubscriptionStore-BMJiFxt3.mjs +185 -0
  46. package/dist/DoSubscriptionStore-BMJiFxt3.mjs.map +1 -0
  47. package/dist/DoSubscriptionStore-zx6nfbbh.d.mts +25 -0
  48. package/dist/DoSubscriptionStore.d.mts +2 -0
  49. package/dist/DoSubscriptionStore.mjs +1 -0
  50. package/dist/DoThreadStore-2zTSfui-.d.mts +81 -0
  51. package/dist/DoThreadStore-CeYHcRR9.mjs +411 -0
  52. package/dist/DoThreadStore-CeYHcRR9.mjs.map +1 -0
  53. package/dist/DoThreadStore.d.mts +2 -0
  54. package/dist/DoThreadStore.mjs +5 -0
  55. package/dist/MemoryProtocol-CtCFYe4s.mjs +221 -0
  56. package/dist/MemoryProtocol-CtCFYe4s.mjs.map +1 -0
  57. package/dist/MemoryProtocol-DXV77CcJ.d.mts +38160 -0
  58. package/dist/MemoryProtocol.d.mts +2 -0
  59. package/dist/MemoryProtocol.mjs +1 -0
  60. package/dist/PortProtocol-4xvMyCgP.mjs +322 -0
  61. package/dist/PortProtocol-4xvMyCgP.mjs.map +1 -0
  62. package/dist/PortProtocol-DXuguAgD.d.mts +966 -0
  63. package/dist/PortProtocol.d.mts +2 -0
  64. package/dist/PortProtocol.mjs +1 -0
  65. package/dist/PortRouting-B9302ouX.mjs +683 -0
  66. package/dist/PortRouting-B9302ouX.mjs.map +1 -0
  67. package/dist/PortRouting-DsoI6soW.d.mts +105 -0
  68. package/dist/PortRouting.d.mts +2 -0
  69. package/dist/PortRouting.mjs +1 -0
  70. package/dist/do-journal-nPNEAjV5.mjs +769 -0
  71. package/dist/do-journal-nPNEAjV5.mjs.map +1 -0
  72. package/dist/index.d.mts +14 -0
  73. package/dist/index.mjs +14 -0
  74. package/dist/migrations-BRTvj8Ue.mjs +233 -0
  75. package/dist/migrations-BRTvj8Ue.mjs.map +1 -0
  76. package/dist/owned-state-DrOD9s0c.mjs +157 -0
  77. package/dist/owned-state-DrOD9s0c.mjs.map +1 -0
  78. package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
  79. package/package.json +106 -3
  80. package/src/DoMemoryStore.ts +71 -0
  81. package/src/DoMessageDeliveryStore.ts +46 -0
  82. package/src/DoScheduleStore.ts +276 -0
  83. package/src/DoStorageConfig.ts +45 -0
  84. package/src/DoStorageError.ts +146 -0
  85. package/src/DoStorageFailpoint.ts +25 -0
  86. package/src/DoStorageFailpointTesting.ts +42 -0
  87. package/src/DoStorageVersion.ts +2 -0
  88. package/src/DoSubmissionLedger.ts +3980 -0
  89. package/src/DoSubscriptionStore.ts +331 -0
  90. package/src/DoThreadStore.ts +602 -0
  91. package/src/MemoryProtocol.ts +357 -0
  92. package/src/PortProtocol.ts +626 -0
  93. package/src/PortRouting.ts +1888 -0
  94. package/src/index.ts +13 -0
  95. package/src/internal/canonical-append.ts +15 -0
  96. package/src/internal/do-journal.ts +1449 -0
  97. package/src/internal/migrations.ts +395 -0
  98. package/src/internal/owned-state.ts +300 -0
  99. package/src/internal/prompt-checkpoint.ts +170 -0
  100. package/src/internal/storage-span.ts +54 -0
  101. package/README.md +0 -3
@@ -0,0 +1,331 @@
1
+ import {
2
+ backfillSubscriptionSettlementObservation,
3
+ makeSqlSubscriptionStore,
4
+ } from '@systemfsoftware/agent-storage-sql/sql-subscription-store'
5
+ import { sameSqliteLayoutStatement } from '@systemfsoftware/agent-storage-sql/sqlite-layout-inspection'
6
+ import {
7
+ SourcePartition,
8
+ SubscriptionError,
9
+ SubscriptionFailpoint,
10
+ type SubscriptionFailpointError,
11
+ SubscriptionStore,
12
+ } from '@systemfsoftware/agent/subscription'
13
+ import * as Context from 'effect/Context'
14
+ import * as Effect from 'effect/Effect'
15
+ import * as Layer from 'effect/Layer'
16
+ import * as Schema from 'effect/Schema'
17
+ import * as SqlClientService from 'effect/sql/SqlClient'
18
+ import type * as SqlError from 'effect/sql/SqlError'
19
+
20
+ const CURRENT_SUBSCRIPTION_STORE_VERSION = 4
21
+
22
+ const ScanRow = Schema.Struct({
23
+ event_scan_cursor: Schema.String,
24
+ delivery_scan_cursor: Schema.String,
25
+ recovery_scan_cursor: Schema.Natural,
26
+ })
27
+
28
+ const StoreStateRow = Schema.Struct({
29
+ storage_version: Schema.Int,
30
+ alarm_generation: Schema.Natural,
31
+ })
32
+
33
+ export interface DoSubscriptionAlarmReplacement {
34
+ readonly deadlineAtMillis: number | null
35
+ readonly generation: number
36
+ }
37
+
38
+ export type DoSubscriptionReplaceAlarm = (
39
+ replacement: DoSubscriptionAlarmReplacement,
40
+ ) => Effect.Effect<void, SubscriptionError>
41
+
42
+ /** One Durable Object transaction combining subscription SQL and its single native alarm. */
43
+ export class DoSubscriptionTransaction extends Context.Service<
44
+ DoSubscriptionTransaction,
45
+ {
46
+ readonly run: <A, E, R>(
47
+ body: (replaceAlarm: DoSubscriptionReplaceAlarm) => Effect.Effect<A, E, R>,
48
+ ) => Effect.Effect<A, E | SubscriptionError, R>
49
+ }
50
+ >()('@effect-agent/storage-cloudflare/DoSubscriptionTransaction') {}
51
+
52
+ export class DoSubscriptionAlarmControl extends Context.Service<
53
+ DoSubscriptionAlarmControl,
54
+ {
55
+ readonly prearm: (
56
+ deadlineAtMillis: number,
57
+ ) => Effect.Effect<void, SubscriptionError | SubscriptionFailpointError>
58
+ readonly reconcile: Effect.Effect<void, SubscriptionError | SubscriptionFailpointError>
59
+ }
60
+ >()('@effect-agent/storage-cloudflare/DoSubscriptionAlarmControl') {}
61
+
62
+ const error = (reason: SubscriptionError['reason'], code: string) => SubscriptionError.make({ reason, code })
63
+
64
+ const unavailable = (operation: string) => error('storage', operation)
65
+ const corrupt = (operation: string) => error('corrupt', operation)
66
+
67
+ const validate = <A, I>(schema: Schema.Codec<A, I>, value: unknown, code: string) =>
68
+ Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError(() => error('validation', code)))
69
+
70
+ const decodeRows = <A, I>(schema: Schema.Codec<A, I>, rows: unknown, code: string) =>
71
+ Schema.decodeUnknownEffect(Schema.Array(schema))(rows).pipe(Effect.mapError(() => corrupt(code)))
72
+
73
+ const layoutStatements = [
74
+ 'CREATE TABLE effect_agent_subscription_store_state ( singleton INTEGER PRIMARY KEY NOT NULL CHECK(singleton=1), storage_version INTEGER NOT NULL, alarm_generation INTEGER NOT NULL )',
75
+ 'CREATE TABLE effect_agent_subscription_sequences ( tenant_id TEXT NOT NULL, source_address TEXT NOT NULL, sequence INTEGER NOT NULL, event_scan_cursor TEXT NOT NULL, delivery_scan_cursor TEXT NOT NULL, recovery_scan_cursor INTEGER NOT NULL, PRIMARY KEY (tenant_id, source_address) )',
76
+ 'CREATE TABLE effect_agent_subscriptions ( tenant_id TEXT NOT NULL, source_address TEXT NOT NULL, owner_id TEXT NOT NULL, subscription_id TEXT NOT NULL, ordinal INTEGER NOT NULL, source_name TEXT NOT NULL, source_version TEXT NOT NULL, matching_key TEXT NOT NULL, state TEXT NOT NULL, expires_at_millis INTEGER, recovery_at_millis INTEGER, recovery_present INTEGER NOT NULL DEFAULT 0, record_json TEXT NOT NULL, PRIMARY KEY (tenant_id, source_address, owner_id, subscription_id), UNIQUE (tenant_id, source_address, ordinal) )',
77
+ 'CREATE INDEX effect_agent_subscriptions_owner ON effect_agent_subscriptions (tenant_id, source_address, owner_id, ordinal)',
78
+ "CREATE INDEX effect_agent_subscriptions_capacity ON effect_agent_subscriptions (tenant_id, source_address, expires_at_millis) WHERE state IN ('active', 'paused')",
79
+ "CREATE INDEX effect_agent_subscriptions_owner_capacity ON effect_agent_subscriptions (tenant_id, source_address, owner_id, expires_at_millis) WHERE state IN ('active', 'paused')",
80
+ 'CREATE INDEX effect_agent_subscriptions_candidates ON effect_agent_subscriptions (tenant_id, source_address, source_name, source_version, matching_key, ordinal)',
81
+ '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',
82
+ 'CREATE TABLE effect_agent_subscription_events ( tenant_id TEXT NOT NULL, source_address TEXT NOT NULL, event_id TEXT NOT NULL, source_name TEXT NOT NULL, source_version TEXT NOT NULL, matching_key TEXT NOT NULL, payload_digest TEXT NOT NULL, cutoff INTEGER NOT NULL, 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, PRIMARY KEY (tenant_id, source_address, event_id) )',
83
+ 'CREATE INDEX effect_agent_subscription_events_pending ON effect_agent_subscription_events (tenant_id, source_address, routing_complete, next_attempt_at_millis, event_id)',
84
+ 'CREATE TABLE effect_agent_subscription_deliveries ( tenant_id TEXT NOT NULL, source_address TEXT NOT NULL, owner_id TEXT NOT NULL, subscription_id TEXT NOT NULL, event_id TEXT NOT NULL, delivery_key TEXT NOT NULL, state TEXT NOT NULL, next_attempt_at_millis INTEGER NOT NULL, record_json TEXT NOT NULL, observe_settlement INTEGER NOT NULL DEFAULT 0 CHECK (observe_settlement IN (0, 1)), PRIMARY KEY (tenant_id, source_address, owner_id, subscription_id, event_id), UNIQUE (tenant_id, source_address, delivery_key) )',
85
+ 'CREATE INDEX effect_agent_subscription_deliveries_pending ON effect_agent_subscription_deliveries (tenant_id, source_address, state, next_attempt_at_millis, delivery_key)',
86
+ 'CREATE INDEX effect_agent_subscription_deliveries_registration ON effect_agent_subscription_deliveries (tenant_id, source_address, owner_id, subscription_id, delivery_key)',
87
+ "CREATE INDEX effect_agent_subscription_deliveries_capacity ON effect_agent_subscription_deliveries (tenant_id, source_address, owner_id) WHERE state IN ('selected', 'prepared')",
88
+ "CREATE INDEX effect_agent_subscription_deliveries_observing ON effect_agent_subscription_deliveries (tenant_id, source_address, owner_id) WHERE state='delivered' AND observe_settlement=1",
89
+ ] as const
90
+
91
+ const layoutObjects = layoutStatements.map((statement, index) => {
92
+ const name = /^CREATE (TABLE|INDEX) ([a-z_][a-z_0-9]*)/.exec(statement)
93
+
94
+ // oxlint-disable-next-line effect/no-untyped-throw, effect/no-native-error -- Module initialization validates developer-authored SQL constants before any storage workflow starts.
95
+ if (name === null) throw new Error('Invalid subscription layout statement')
96
+
97
+ return [name[1].toLowerCase(), name[2], index] as const
98
+ })
99
+
100
+ const addedIndexes = new Set([
101
+ 'effect_agent_subscriptions_capacity',
102
+ 'effect_agent_subscriptions_owner_capacity',
103
+ 'effect_agent_subscription_deliveries_capacity',
104
+ 'effect_agent_subscription_deliveries_observing',
105
+ ])
106
+
107
+ const LayoutObject = Schema.Struct({
108
+ name: Schema.String,
109
+ type: Schema.String,
110
+ sql: Schema.NullOr(Schema.String),
111
+ })
112
+
113
+ /** Only the released v3 layout may upgrade; schema, backfill and version publish commit together. */
114
+ const initializeDoSubscriptionStore = Effect.fnUntraced(function*() {
115
+ const sql = (yield* SqlClientService.SqlClient).withoutTransforms()
116
+ const tables = layoutObjects.filter(([type]) => type === 'table').map(([, name]) => name)
117
+
118
+ const readObjects = sql`SELECT name, type, sql FROM sqlite_master
119
+ WHERE name GLOB 'effect_agent_subscription*' OR (type='trigger' AND tbl_name IN ${sql.in(tables)})`.pipe(
120
+ Effect.flatMap((rows) => decodeRows(LayoutObject, rows, 'subscription storage layout')),
121
+ )
122
+
123
+ const checkLayout = Effect.fnUntraced(function*(
124
+ objects: ReadonlyArray<typeof LayoutObject.Type>,
125
+ version: number,
126
+ ) {
127
+ if (
128
+ objects.some(
129
+ ({ name, type }) =>
130
+ (type === 'table' && !tables.includes(name)) ||
131
+ type === 'trigger' ||
132
+ (version === 3 && addedIndexes.has(name)),
133
+ )
134
+ ) {
135
+ return yield* corrupt('ambiguous subscription storage layout')
136
+ }
137
+ for (const [type, name, index] of layoutObjects) {
138
+ if (version === 3 && addedIndexes.has(name)) continue
139
+
140
+ const expected = version === 3
141
+ ? layoutStatements[index].replace(
142
+ ', observe_settlement INTEGER NOT NULL DEFAULT 0 CHECK (observe_settlement IN (0, 1))',
143
+ '',
144
+ )
145
+ : layoutStatements[index]
146
+
147
+ const actual = objects.find((row) => row.name === name)
148
+
149
+ if (
150
+ actual?.type !== type ||
151
+ actual.sql === null ||
152
+ !sameSqliteLayoutStatement(actual.sql, expected)
153
+ ) {
154
+ return yield* corrupt('incompatible subscription storage layout ' + name)
155
+ }
156
+ }
157
+ })
158
+
159
+ yield* sql
160
+ .withTransaction(
161
+ Effect.gen(function*() {
162
+ const objects = yield* readObjects
163
+
164
+ const hasState = objects.some(
165
+ ({ name }) => name === 'effect_agent_subscription_store_state',
166
+ )
167
+
168
+ if (!hasState) {
169
+ if (objects.length > 0) return yield* corrupt('partial subscription storage')
170
+ for (const statement of layoutStatements) yield* sql.unsafe(statement).withoutTransform
171
+ yield* sql`INSERT INTO effect_agent_subscription_store_state (singleton, storage_version, alarm_generation)
172
+ VALUES (1, ${CURRENT_SUBSCRIPTION_STORE_VERSION}, 0)`
173
+
174
+ return
175
+ }
176
+
177
+ const state = yield* decodeRows(
178
+ StoreStateRow,
179
+ yield* sql`SELECT storage_version, alarm_generation FROM effect_agent_subscription_store_state`,
180
+ 'read subscription storage version',
181
+ )
182
+
183
+ if (state.length !== 1) return yield* corrupt('invalid subscription storage version row')
184
+ const version = state[0].storage_version
185
+
186
+ if (version !== 3 && version !== CURRENT_SUBSCRIPTION_STORE_VERSION) {
187
+ return yield* corrupt(
188
+ `incompatible subscription storage version ${version}; expected ${CURRENT_SUBSCRIPTION_STORE_VERSION}`,
189
+ )
190
+ }
191
+ yield* checkLayout(objects, version)
192
+ if (version === CURRENT_SUBSCRIPTION_STORE_VERSION) return
193
+
194
+ yield* sql`ALTER TABLE effect_agent_subscription_deliveries ADD COLUMN observe_settlement INTEGER NOT NULL DEFAULT 0 CHECK (observe_settlement IN (0, 1))`
195
+ yield* backfillSubscriptionSettlementObservation()
196
+ for (const [, name, index] of layoutObjects) {
197
+ if (addedIndexes.has(name)) yield* sql.unsafe(layoutStatements[index]).withoutTransform
198
+ }
199
+ yield* sql`UPDATE effect_agent_subscription_store_state SET storage_version=${CURRENT_SUBSCRIPTION_STORE_VERSION} WHERE singleton=1`
200
+ yield* checkLayout(yield* readObjects, CURRENT_SUBSCRIPTION_STORE_VERSION)
201
+ }),
202
+ )
203
+ .pipe(Effect.catchTag('SqlError', () => unavailable('initialize subscription storage')))
204
+ })
205
+
206
+ const makeSubscriptionStore = Effect.fnUntraced(function*(owned: SourcePartition) {
207
+ const partition = yield* validate(SourcePartition, owned, 'partition')
208
+ const sql = yield* SqlClientService.SqlClient
209
+ const failpoint = yield* SubscriptionFailpoint
210
+ const transactions = yield* DoSubscriptionTransaction
211
+
212
+ yield* initializeDoSubscriptionStore()
213
+
214
+ const query = <A extends object>(
215
+ effect: Effect.Effect<ReadonlyArray<A>, SqlError.SqlError>,
216
+ code: string,
217
+ ) => effect.pipe(Effect.mapError(() => unavailable(code)))
218
+
219
+ const readIndexedDeadline = Effect.fnUntraced(function*() {
220
+ const scanRows = yield* query(
221
+ sql<Record<string, unknown>>`
222
+ SELECT event_scan_cursor, delivery_scan_cursor, recovery_scan_cursor FROM effect_agent_subscription_sequences
223
+ WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}
224
+ `,
225
+ 'read scan cursor deadline',
226
+ )
227
+
228
+ const scans = yield* decodeRows(ScanRow, scanRows, 'read scan cursor deadline')
229
+
230
+ if (scans.length !== 1) return yield* corrupt('scan cursor deadline')
231
+ if (
232
+ scans[0].event_scan_cursor !== '' ||
233
+ scans[0].delivery_scan_cursor !== '' ||
234
+ scans[0].recovery_scan_cursor !== 0
235
+ ) {
236
+ return 0
237
+ }
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.Finite) }),
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.fnUntraced(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
+ }
285
+ yield* failpoint.hit('subscription:alarm:before')
286
+ yield* replace({ deadlineAtMillis, generation: state[0].alarm_generation })
287
+ yield* failpoint.hit('subscription:alarm:after')
288
+ })
289
+
290
+ const transact = <A>(effect: Effect.Effect<A, SubscriptionError | SubscriptionFailpointError>) =>
291
+ transactions.run((replace) =>
292
+ Effect.gen(function*() {
293
+ const value = yield* effect
294
+
295
+ yield* replaceAlarm(replace, yield* readIndexedDeadline())
296
+
297
+ return value
298
+ })
299
+ )
300
+
301
+ const store = yield* makeSqlSubscriptionStore(partition, {
302
+ maxStoredJsonLength: 1_900_000,
303
+ transaction: transact,
304
+ })
305
+
306
+ const prearm = Effect.fnUntraced(function*(deadlineAtMillis: number) {
307
+ yield* transactions.run((replace) => replaceAlarm(replace, deadlineAtMillis))
308
+ yield* failpoint.hit('subscription:prearm:after')
309
+ })
310
+
311
+ const reconcile = Effect.gen(function*() {
312
+ yield* transactions.run((replace) =>
313
+ Effect.gen(function*() {
314
+ yield* replaceAlarm(replace, yield* readIndexedDeadline())
315
+ })
316
+ )
317
+ yield* failpoint.hit('subscription:reconcile:after')
318
+ })
319
+
320
+ return Context.make(SubscriptionStore, store).pipe(
321
+ Context.add(DoSubscriptionAlarmControl, { prearm, reconcile }),
322
+ )
323
+ })
324
+
325
+ export const doSubscriptionStoreLayer = (
326
+ partition: SourcePartition,
327
+ ): Layer.Layer<
328
+ SubscriptionStore | DoSubscriptionAlarmControl,
329
+ SubscriptionError,
330
+ DoSubscriptionTransaction | SqlClientService.SqlClient
331
+ > => Layer.effectContext(makeSubscriptionStore(partition))