@effect-agent/storage-cloudflare 0.1.0-beta.83 → 0.1.0-beta.85
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/dist/DoMemoryStore.mjs +1 -1
- package/dist/DoMemoryStore.mjs.map +1 -1
- package/dist/DoMessageDeliveryStore.mjs +1 -1
- package/dist/DoScheduleStore.mjs +2 -2
- package/dist/DoScheduleStore.mjs.map +1 -1
- package/dist/DoSubmissionLedger.mjs +32 -32
- package/dist/DoSubmissionLedger.mjs.map +1 -1
- package/dist/DoSubscriptionStore.mjs +1 -1
- package/dist/DoSubscriptionStore.mjs.map +1 -1
- package/dist/DoThreadStore.mjs +22 -22
- package/dist/DoThreadStore.mjs.map +1 -1
- package/dist/MemoryProtocol.mjs +1 -1
- package/dist/MemoryProtocol.mjs.map +1 -1
- package/dist/PortProtocol.d.mts +938 -341
- package/dist/{do-journal-DHqCQeBU.mjs → do-journal-C18d6Yu0.mjs} +3 -3
- package/dist/do-journal-C18d6Yu0.mjs.map +1 -0
- package/package.json +1 -1
- package/src/DoMemoryStore.ts +1 -1
- package/src/DoScheduleStore.ts +2 -2
- package/src/DoSubmissionLedger.ts +61 -61
- package/src/DoSubscriptionStore.ts +1 -1
- package/src/DoThreadStore.ts +32 -34
- package/src/MemoryProtocol.ts +1 -1
- package/src/internal/do-journal.ts +2 -2
- package/dist/do-journal-DHqCQeBU.mjs.map +0 -1
package/dist/DoMemoryStore.mjs
CHANGED
|
@@ -44,7 +44,7 @@ const defaultDoMemoryStorageLimits = DoMemoryStorageLimits.make({
|
|
|
44
44
|
* Ordinary Put cannot consume them. Deploy exclusively upgraded writers before relying
|
|
45
45
|
* on reserves; the SQL accounting migration preserves older writers and their receipts.
|
|
46
46
|
*/
|
|
47
|
-
const doMemoryStoreLayerWithFailpoints = (storage, limits = defaultDoMemoryStorageLimits) => Layer.unwrap(Schema.
|
|
47
|
+
const doMemoryStoreLayerWithFailpoints = (storage, limits = defaultDoMemoryStorageLimits) => Layer.unwrap(Schema.decodeEffect(DoMemoryStorageLimits)(limits).pipe(Effect.mapError(() => MemoryStorageError.make({
|
|
48
48
|
operation: "memory storage limits",
|
|
49
49
|
reason: "invalid-input"
|
|
50
50
|
})), Effect.map((validated) => memoryStoreLayerWithFailpoints.pipe(Layer.provide(Layer.succeed(SqlMemoryLimits, validated)), Layer.provide(SqliteClient.layer({ storage }))))));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DoMemoryStore.mjs","names":[],"sources":["../src/DoMemoryStore.ts"],"sourcesContent":["import { MemoryStorageError, MemoryMutationFailpoint } from \"@effect-agent/core/MemoryStore\";\nimport {\n memoryStoreLayerWithFailpoints,\n SqlMemoryLimits,\n} from \"@effect-agent/thread/SqlMemoryStore\";\nimport { SqliteClient } from \"@effect/sql-sqlite-do\";\nimport { Effect, Layer, Schema } from \"effect\";\n\nexport class DoMemoryStorageLimits extends Schema.Class<DoMemoryStorageLimits>(\n \"@effect-agent/storage-cloudflare/DoMemoryStorageLimits\",\n)({\n maxRowBytes: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 1_900_000 })),\n maxStorageBytes: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 536_870_912 })),\n maxDocuments: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100_000 })),\n maxReceipts: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 1_000_000 })),\n reservedWithdrawalBytes: Schema.optional(Schema.Natural),\n reservedWithdrawalReceipts: Schema.optional(Schema.Natural),\n}) {}\n\nexport const defaultDoMemoryStorageLimits = DoMemoryStorageLimits.make({\n maxRowBytes: 1_900_000,\n maxStorageBytes: 536_870_912,\n maxDocuments: 10_000,\n maxReceipts: 100_000,\n});\n\n/**\n * Local memory only, without Thread tables. Keep one SQL client per owner and pass the\n * full storage handle: sql-only handles cannot provide atomic receipts and revisions.\n * Byte limits conservatively count encoded rows, not SQLite page/index overhead.\n * Optional withdrawal reserves default to zero and stay within hard byte/receipt limits.\n * Ordinary Put cannot consume them. Deploy exclusively upgraded writers before relying\n * on reserves; the SQL accounting migration preserves older writers and their receipts.\n */\nexport const doMemoryStoreLayerWithFailpoints = (\n storage: NonNullable<SqliteClient.SqliteClientConfig[\"storage\"]>,\n limits: DoMemoryStorageLimits = defaultDoMemoryStorageLimits,\n) =>\n Layer.unwrap(\n Schema.
|
|
1
|
+
{"version":3,"file":"DoMemoryStore.mjs","names":[],"sources":["../src/DoMemoryStore.ts"],"sourcesContent":["import { MemoryStorageError, MemoryMutationFailpoint } from \"@effect-agent/core/MemoryStore\";\nimport {\n memoryStoreLayerWithFailpoints,\n SqlMemoryLimits,\n} from \"@effect-agent/thread/SqlMemoryStore\";\nimport { SqliteClient } from \"@effect/sql-sqlite-do\";\nimport { Effect, Layer, Schema } from \"effect\";\n\nexport class DoMemoryStorageLimits extends Schema.Class<DoMemoryStorageLimits>(\n \"@effect-agent/storage-cloudflare/DoMemoryStorageLimits\",\n)({\n maxRowBytes: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 1_900_000 })),\n maxStorageBytes: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 536_870_912 })),\n maxDocuments: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100_000 })),\n maxReceipts: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 1_000_000 })),\n reservedWithdrawalBytes: Schema.optional(Schema.Natural),\n reservedWithdrawalReceipts: Schema.optional(Schema.Natural),\n}) {}\n\nexport const defaultDoMemoryStorageLimits = DoMemoryStorageLimits.make({\n maxRowBytes: 1_900_000,\n maxStorageBytes: 536_870_912,\n maxDocuments: 10_000,\n maxReceipts: 100_000,\n});\n\n/**\n * Local memory only, without Thread tables. Keep one SQL client per owner and pass the\n * full storage handle: sql-only handles cannot provide atomic receipts and revisions.\n * Byte limits conservatively count encoded rows, not SQLite page/index overhead.\n * Optional withdrawal reserves default to zero and stay within hard byte/receipt limits.\n * Ordinary Put cannot consume them. Deploy exclusively upgraded writers before relying\n * on reserves; the SQL accounting migration preserves older writers and their receipts.\n */\nexport const doMemoryStoreLayerWithFailpoints = (\n storage: NonNullable<SqliteClient.SqliteClientConfig[\"storage\"]>,\n limits: DoMemoryStorageLimits = defaultDoMemoryStorageLimits,\n) =>\n Layer.unwrap(\n Schema.decodeEffect(DoMemoryStorageLimits)(limits).pipe(\n Effect.mapError(() =>\n MemoryStorageError.make({ operation: \"memory storage limits\", reason: \"invalid-input\" }),\n ),\n Effect.map((validated) =>\n memoryStoreLayerWithFailpoints.pipe(\n Layer.provide(Layer.succeed(SqlMemoryLimits, validated)),\n Layer.provide(SqliteClient.layer({ storage })),\n ),\n ),\n ),\n );\n\nexport const doMemoryStoreLayer = (\n storage: NonNullable<SqliteClient.SqliteClientConfig[\"storage\"]>,\n limits: DoMemoryStorageLimits = defaultDoMemoryStorageLimits,\n) =>\n doMemoryStoreLayerWithFailpoints(storage, limits).pipe(\n Layer.provide(MemoryMutationFailpoint.layer),\n );\n"],"mappings":";;;;;;;;;;;;AAQA,IAAa,wBAAb,cAA2C,OAAO,MAChD,wDACF,CAAC,CAAC;CACA,aAAa,OAAO,IAAI,MAAM,OAAO,UAAU;EAAE,SAAS;EAAG,SAAS;CAAU,CAAC,CAAC;CAClF,iBAAiB,OAAO,IAAI,MAAM,OAAO,UAAU;EAAE,SAAS;EAAG,SAAS;CAAY,CAAC,CAAC;CACxF,cAAc,OAAO,IAAI,MAAM,OAAO,UAAU;EAAE,SAAS;EAAG,SAAS;CAAQ,CAAC,CAAC;CACjF,aAAa,OAAO,IAAI,MAAM,OAAO,UAAU;EAAE,SAAS;EAAG,SAAS;CAAU,CAAC,CAAC;CAClF,yBAAyB,OAAO,SAAS,OAAO,OAAO;CACvD,4BAA4B,OAAO,SAAS,OAAO,OAAO;AAC5D,CAAC,CAAC,CAAC,CAAC;AAEJ,MAAa,+BAA+B,sBAAsB,KAAK;CACrE,aAAa;CACb,iBAAiB;CACjB,cAAc;CACd,aAAa;AACf,CAAC;;;;;;;;;AAUD,MAAa,oCACX,SACA,SAAgC,iCAEhC,MAAM,OACJ,OAAO,aAAa,qBAAqB,CAAC,CAAC,MAAM,CAAC,CAAC,KACjD,OAAO,eACL,mBAAmB,KAAK;CAAE,WAAW;CAAyB,QAAQ;AAAgB,CAAC,CACzF,GACA,OAAO,KAAK,cACV,+BAA+B,KAC7B,MAAM,QAAQ,MAAM,QAAQ,iBAAiB,SAAS,CAAC,GACvD,MAAM,QAAQ,aAAa,MAAM,EAAE,QAAQ,CAAC,CAAC,CAC/C,CACF,CACF,CACF;AAEF,MAAa,sBACX,SACA,SAAgC,iCAEhC,iCAAiC,SAAS,MAAM,CAAC,CAAC,KAChD,MAAM,QAAQ,wBAAwB,KAAK,CAC7C"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
|
|
2
2
|
import { DoStorageConfig } from "./DoStorageConfig.mjs";
|
|
3
3
|
import { DoStorageFailpoint } from "./DoStorageFailpoint.mjs";
|
|
4
|
-
import { a as initializeDoJournal } from "./do-journal-
|
|
4
|
+
import { a as initializeDoJournal } from "./do-journal-C18d6Yu0.mjs";
|
|
5
5
|
import { MessageDeliveryError, MessageDeliveryStore } from "@effect-agent/thread/MessageDelivery";
|
|
6
6
|
import { SqlMessageDeliveryTransaction, makeSqlMessageDeliveryStore } from "@effect-agent/thread/SqlMessageDeliveryStore";
|
|
7
7
|
import { Effect, Layer } from "effect";
|
package/dist/DoScheduleStore.mjs
CHANGED
|
@@ -60,7 +60,7 @@ const decodeRecord = Effect.fn("DoScheduleStore.decodeRecord")(function* (row) {
|
|
|
60
60
|
});
|
|
61
61
|
const encodeRecord = Effect.fn("DoScheduleStore.encodeRecord")(function* (record) {
|
|
62
62
|
const encoded = yield* Schema.encodeEffect(Schema.fromJsonString(ScheduleRecord))(record).pipe(Effect.mapError(() => corrupt("encode schedule")));
|
|
63
|
-
return yield* Schema.
|
|
63
|
+
return yield* Schema.decodeEffect(StoredScheduleJson)(encoded).pipe(Effect.mapError(() => corrupt("encode schedule bounds")));
|
|
64
64
|
});
|
|
65
65
|
const initializeScheduleStore = Effect.fn("DoScheduleStore.initialize")(function* () {
|
|
66
66
|
const sql = yield* SqlClientService.SqlClient;
|
|
@@ -322,7 +322,7 @@ const makeServices = Effect.gen(function* () {
|
|
|
322
322
|
});
|
|
323
323
|
const due = Effect.fn("DoScheduleStore.due")(function* (nowMillis, limit, owner, after) {
|
|
324
324
|
const operation = "query due schedules";
|
|
325
|
-
const cursor = after === void 0 ? void 0 : yield* Schema.
|
|
325
|
+
const cursor = after === void 0 ? void 0 : yield* Schema.decodeEffect(ScheduleDueCursor)(after).pipe(Effect.mapError(() => corrupt(operation)));
|
|
326
326
|
const continuation = cursor === void 0 ? sql`1 = 1` : sql`
|
|
327
327
|
(deadline_at_millis, tenant_id, owner_id, schedule_id) >
|
|
328
328
|
(${cursor.deadlineAtMillis}, ${cursor.owner.tenantId}, ${cursor.owner.ownerId}, ${cursor.scheduleId})`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DoScheduleStore.mjs","names":[],"sources":["../src/DoScheduleStore.ts"],"sourcesContent":["import {\n ScheduleCapacityError,\n ScheduleDueCursor,\n defaultSchedulingLimits,\n ScheduleChange,\n ScheduleConflict,\n ScheduleFailpoint,\n type ScheduleFailpointError,\n ScheduleKey,\n ScheduleId,\n ScheduleInstant,\n ScheduleNotFound,\n ScheduleOwner,\n type SchedulePage,\n SchedulePageRequest,\n ScheduleRecord,\n ScheduleStorageError,\n ScheduleStore,\n} from \"@effect-agent/thread/Schedule\";\nimport {\n applyScheduleChange,\n scheduleUsesCapacity,\n scheduleDeadline,\n} from \"@effect-agent/thread/ScheduleTransition\";\nimport { upgradeV2Schedules } from \"@effect-agent/thread/SqlStorageV2Upgrade\";\nimport { Context, Effect, Layer, Result, Schema } from \"effect\";\nimport * as SqlClientService from \"effect/unstable/sql/SqlClient\";\n\nconst CURRENT_SCHEDULE_STORE_VERSION = 3;\nconst MAX_STORED_SCHEDULE_BYTES = 1_900_000;\n\nconst StoredScheduleJson = Schema.String.check(Schema.isMaxLength(MAX_STORED_SCHEDULE_BYTES));\nconst StoredDeadline = Schema.NullOr(ScheduleInstant);\n\nclass ScheduleRow extends Schema.Class<ScheduleRow>(\"@effect-agent/storage-cloudflare/ScheduleRow\")(\n {\n tenant_id: ScheduleOwner.fields.tenantId,\n owner_id: ScheduleOwner.fields.ownerId,\n schedule_id: ScheduleId,\n deadline_at_millis: StoredDeadline,\n record_json: StoredScheduleJson,\n },\n) {}\n\nconst ScheduleDueRow = Schema.Struct({\n tenant_id: ScheduleOwner.fields.tenantId,\n owner_id: ScheduleOwner.fields.ownerId,\n schedule_id: ScheduleId,\n deadline_at_millis: ScheduleInstant,\n});\n\nclass ScheduleCountRow extends Schema.Class<ScheduleCountRow>(\n \"@effect-agent/storage-cloudflare/ScheduleCountRow\",\n)({\n schedule_count: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\nclass ScheduleDeadlineRow extends Schema.Class<ScheduleDeadlineRow>(\n \"@effect-agent/storage-cloudflare/ScheduleDeadlineRow\",\n)({\n deadline_at_millis: StoredDeadline,\n}) {}\n\nclass ScheduleStoreStateRow extends Schema.Class<ScheduleStoreStateRow>(\n \"@effect-agent/storage-cloudflare/ScheduleStoreStateRow\",\n)({\n storage_version: Schema.Int.check(Schema.isGreaterThan(0)),\n alarm_generation: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\nclass ScheduleTableNameRow extends Schema.Class<ScheduleTableNameRow>(\n \"@effect-agent/storage-cloudflare/ScheduleTableNameRow\",\n)({\n name: Schema.String,\n}) {}\n\nexport interface DoScheduleAlarmReplacement {\n readonly deadlineAtMillis: number | null;\n /** Included in every logical alarm payload so equal-time replacement stays distinguishable. */\n readonly generation: number;\n}\n\nexport type DoScheduleReplaceAlarm = (\n replacement: DoScheduleAlarmReplacement,\n) => Effect.Effect<void, ScheduleStorageError>;\n\n/**\n * Platform-owned transaction boundary for schedule SQL and logical alarm mutation. The callback\n * and its `replaceAlarm` capability belong to one fiber and must not escape or fork.\n */\nexport class DoScheduleTransaction extends Context.Service<\n DoScheduleTransaction,\n {\n readonly run: <A, E, R>(\n body: (replaceAlarm: DoScheduleReplaceAlarm) => Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | ScheduleStorageError, R>;\n }\n>()(\"@effect-agent/storage-cloudflare/DoScheduleTransaction\") {}\n\n/** Platform driver operations that use the same schedule-state and alarm transaction. */\nexport class DoScheduleAlarmControl extends Context.Service<\n DoScheduleAlarmControl,\n {\n /** Establish a future recovery wake before cross-Object admission starts. */\n readonly prearm: (\n deadlineAtMillis: number,\n ) => Effect.Effect<void, ScheduleStorageError | ScheduleFailpointError>;\n /** Replace or cancel the wake from the object's authoritative indexed deadline. */\n readonly reconcile: Effect.Effect<void, ScheduleStorageError | ScheduleFailpointError>;\n }\n>()(\"@effect-agent/storage-cloudflare/DoScheduleAlarmControl\") {}\n\nconst unavailable = (operation: string): ScheduleStorageError =>\n ScheduleStorageError.make({ operation, reason: \"unavailable\" });\n\nconst corrupt = (operation: string): ScheduleStorageError =>\n ScheduleStorageError.make({ operation, reason: \"corrupt\" });\n\nconst decodeRows = Effect.fn(\"DoScheduleStore.decodeRows\")(function* <A, I, R>(\n schema: Schema.Codec<A, I, R>,\n rows: ReadonlyArray<unknown>,\n operation: string,\n): Effect.fn.Return<A, ScheduleStorageError, R> {\n return yield* Schema.decodeUnknownEffect(schema)(rows).pipe(\n Effect.mapError(() => corrupt(operation)),\n );\n});\n\nconst decodeBoundary = <A, I, R>(\n schema: Schema.Codec<A, I, R>,\n value: unknown,\n operation: string,\n): Effect.Effect<A, ScheduleStorageError, R> =>\n Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError(() => corrupt(operation)));\n\nconst decodeRecord = Effect.fn(\"DoScheduleStore.decodeRecord\")(function* (\n row: ScheduleRow,\n): Effect.fn.Return<ScheduleRecord, ScheduleStorageError> {\n const record = yield* Schema.decodeEffect(Schema.fromJsonString(ScheduleRecord))(\n row.record_json,\n ).pipe(Effect.mapError(() => corrupt(\"decode schedule\")));\n\n if (\n record.owner.tenantId !== row.tenant_id ||\n record.owner.ownerId !== row.owner_id ||\n record.scheduleId !== row.schedule_id ||\n scheduleDeadline(record) !== row.deadline_at_millis\n ) {\n return yield* corrupt(\"decode schedule index\");\n }\n\n return record;\n});\n\nconst encodeRecord = Effect.fn(\"DoScheduleStore.encodeRecord\")(function* (\n record: ScheduleRecord,\n): Effect.fn.Return<string, ScheduleStorageError> {\n const encoded = yield* Schema.encodeEffect(Schema.fromJsonString(ScheduleRecord))(record).pipe(\n Effect.mapError(() => corrupt(\"encode schedule\")),\n );\n\n return yield* Schema.decodeUnknownEffect(StoredScheduleJson)(encoded).pipe(\n Effect.mapError(() => corrupt(\"encode schedule bounds\")),\n );\n});\n\nconst initializeScheduleStore = Effect.fn(\"DoScheduleStore.initialize\")(function* () {\n const sql = yield* SqlClientService.SqlClient;\n const operation = \"initialize schedule store\";\n\n const rawTables = yield* sql<Record<string, unknown>>`\n SELECT name\n FROM sqlite_master\n WHERE type = 'table'\n AND name IN (\n 'effect_agent_schedule_store_state',\n 'effect_agent_schedules'\n )\n ORDER BY name\n `.pipe(Effect.mapError(() => unavailable(operation)));\n\n const tables = yield* decodeRows(Schema.Array(ScheduleTableNameRow), rawTables, operation);\n const hasState = tables.some((row) => row.name === \"effect_agent_schedule_store_state\");\n const hasSchedules = tables.some((row) => row.name === \"effect_agent_schedules\");\n\n if (!hasState) {\n if (hasSchedules) return yield* corrupt(operation);\n yield* sql\n .withTransaction(\n Effect.gen(function* () {\n yield* sql`\n CREATE TABLE effect_agent_schedule_store_state (\n singleton INTEGER PRIMARY KEY NOT NULL CHECK (singleton = 1),\n storage_version INTEGER NOT NULL,\n alarm_generation INTEGER NOT NULL\n )\n `.withoutTransform;\n yield* sql`\n CREATE TABLE effect_agent_schedules (\n tenant_id TEXT NOT NULL,\n owner_id TEXT NOT NULL,\n schedule_id TEXT NOT NULL,\n deadline_at_millis INTEGER,\n record_json TEXT NOT NULL,\n PRIMARY KEY (tenant_id, owner_id, schedule_id)\n )\n `.withoutTransform;\n yield* sql`\n CREATE INDEX effect_agent_schedules_deadline\n ON effect_agent_schedules (deadline_at_millis, tenant_id, owner_id, schedule_id)\n WHERE deadline_at_millis IS NOT NULL\n `.withoutTransform;\n yield* sql`\n CREATE INDEX effect_agent_schedules_owner_deadline\n ON effect_agent_schedules (tenant_id, owner_id, deadline_at_millis, schedule_id)\n WHERE deadline_at_millis IS NOT NULL\n `.withoutTransform;\n yield* sql`\n INSERT INTO effect_agent_schedule_store_state (\n singleton, storage_version, alarm_generation\n ) VALUES (1, ${CURRENT_SCHEDULE_STORE_VERSION}, 0)\n `.withoutTransform;\n }),\n )\n .pipe(Effect.mapError(() => unavailable(operation)));\n\n return;\n }\n\n if (!hasSchedules) return yield* corrupt(operation);\n\n const rawState = yield* sql<Record<string, unknown>>`\n SELECT storage_version, alarm_generation\n FROM effect_agent_schedule_store_state\n WHERE singleton = 1\n `.pipe(Effect.mapError(() => unavailable(operation)));\n\n const state = yield* decodeRows(Schema.Array(ScheduleStoreStateRow), rawState, operation);\n\n if (state.length === 1 && state[0].storage_version === 2) {\n const failpoint = yield* ScheduleFailpoint;\n\n yield* sql\n .withTransaction(\n Effect.gen(function* () {\n const current = yield* sql<{\n storage_version: number;\n }>`SELECT storage_version FROM effect_agent_schedule_store_state WHERE singleton=1`;\n\n if (current.length === 1 && current[0].storage_version === 3) return;\n if (current.length !== 1 || current[0].storage_version !== 2)\n return yield* corrupt(\"schedule version changed during upgrade\");\n yield* upgradeV2Schedules(MAX_STORED_SCHEDULE_BYTES);\n yield* failpoint.hit(\"upgrade:before-version\");\n yield* sql`UPDATE effect_agent_schedule_store_state SET storage_version=3 WHERE singleton=1`;\n yield* failpoint.hit(\"upgrade:after-version\");\n }),\n )\n .pipe(\n Effect.catchTag(\"StorageUpgradeError\", (error) =>\n ScheduleStorageError.make({\n reason: \"corrupt\",\n operation: \"upgrade v2 schedules\",\n cause: error,\n }),\n ),\n Effect.catchTag(\"SqlError\", () => unavailable(\"upgrade v2 schedules\")),\n Effect.catchTag(\"ScheduleFailpointError\", () =>\n unavailable(\"upgrade v2 schedules failpoint\"),\n ),\n );\n\n return;\n }\n\n if (state.length !== 1 || state[0].storage_version !== CURRENT_SCHEDULE_STORE_VERSION) {\n return yield* corrupt(\n state.length === 1\n ? `${operation}: incompatible storage version ${state[0].storage_version}; expected ${CURRENT_SCHEDULE_STORE_VERSION}`\n : `${operation}: invalid storage version row`,\n );\n }\n});\n\nconst makeServices = Effect.gen(function* () {\n const sql = yield* SqlClientService.SqlClient;\n const transactions = yield* DoScheduleTransaction;\n const scheduleFailpoint = yield* ScheduleFailpoint;\n\n yield* initializeScheduleStore();\n\n const readRows = Effect.fn(\"DoScheduleStore.readRows\")(function* (\n key: ScheduleKey,\n operation: string,\n ): Effect.fn.Return<ReadonlyArray<ScheduleRow>, ScheduleStorageError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT tenant_id, owner_id, schedule_id, deadline_at_millis, record_json\n FROM effect_agent_schedules\n WHERE tenant_id = ${key.owner.tenantId}\n AND owner_id = ${key.owner.ownerId}\n AND schedule_id = ${key.scheduleId}\n `.pipe(Effect.mapError(() => unavailable(operation)));\n\n return yield* decodeRows(Schema.Array(ScheduleRow), rows, operation);\n });\n\n const readOne = Effect.fn(\"DoScheduleStore.readOne\")(function* (\n key: ScheduleKey,\n operation: string,\n ): Effect.fn.Return<ScheduleRecord | null, ScheduleStorageError> {\n const rows = yield* readRows(key, operation);\n\n if (rows.length === 0) return null;\n if (rows.length !== 1) return yield* corrupt(operation);\n\n return yield* decodeRecord(rows[0]);\n });\n\n const readNextDeadline = Effect.fn(\"DoScheduleStore.readNextDeadline\")(function* (\n owner: ScheduleOwner | undefined,\n operation: string,\n ): Effect.fn.Return<number | null, ScheduleStorageError> {\n const rows =\n owner === undefined\n ? yield* sql<Record<string, unknown>>`\n SELECT MIN(deadline_at_millis) AS deadline_at_millis\n FROM effect_agent_schedules\n WHERE deadline_at_millis IS NOT NULL\n `.pipe(Effect.mapError(() => unavailable(operation)))\n : yield* sql<Record<string, unknown>>`\n SELECT MIN(deadline_at_millis) AS deadline_at_millis\n FROM effect_agent_schedules\n WHERE tenant_id = ${owner.tenantId}\n AND owner_id = ${owner.ownerId}\n AND deadline_at_millis IS NOT NULL\n `.pipe(Effect.mapError(() => unavailable(operation)));\n\n const decoded = yield* decodeRows(Schema.Array(ScheduleDeadlineRow), rows, operation);\n\n if (decoded.length !== 1) return yield* corrupt(operation);\n\n return decoded[0].deadline_at_millis;\n });\n\n const replaceAlarm = Effect.fn(\"DoScheduleStore.replaceAlarm\")(function* (\n replace: DoScheduleReplaceAlarm,\n deadlineAtMillis: number | null,\n operation: string,\n ) {\n const rawState = yield* sql<Record<string, unknown>>`\n UPDATE effect_agent_schedule_store_state\n SET alarm_generation = alarm_generation + 1\n WHERE singleton = 1\n RETURNING storage_version, alarm_generation\n `.pipe(Effect.mapError(() => unavailable(operation)));\n\n const state = yield* decodeRows(Schema.Array(ScheduleStoreStateRow), rawState, operation);\n\n if (state.length !== 1 || state[0].storage_version !== CURRENT_SCHEDULE_STORE_VERSION) {\n return yield* corrupt(operation);\n }\n yield* scheduleFailpoint.hit(\"schedule:alarm:before\");\n yield* replace({ deadlineAtMillis, generation: state[0].alarm_generation });\n yield* scheduleFailpoint.hit(\"schedule:alarm:after\");\n });\n\n const insert: ScheduleStore[\"Service\"][\"insert\"] = Effect.fn(\"DoScheduleStore.insert\")(\n function* (record, ownerLimit) {\n const operation = \"insert schedule\";\n const canonical = yield* decodeBoundary(ScheduleRecord, record, operation);\n const recordJson = yield* encodeRecord(canonical);\n\n const result = yield* transactions.run((replace) =>\n Effect.gen(function* () {\n const existing = yield* readOne(canonical, operation);\n\n if (existing !== null) {\n if (existing.creationFingerprint === canonical.creationFingerprint) {\n return { record: existing, inserted: false } as const;\n }\n\n return yield* ScheduleConflict.make({ reason: \"creation\", key: canonical });\n }\n\n const rawCounts = yield* sql<Record<string, unknown>>`\n SELECT COUNT(*) AS schedule_count\n FROM effect_agent_schedules\n WHERE tenant_id = ${canonical.owner.tenantId}\n AND owner_id = ${canonical.owner.ownerId}\n AND (json_extract(record_json, '$.pending') IS NOT NULL OR\n (json_extract(record_json, '$.state') != 'cancelled' AND json_extract(record_json, '$.nextAtMillis') IS NOT NULL))\n `.pipe(Effect.mapError(() => unavailable(operation)));\n\n const counts = yield* decodeRows(Schema.Array(ScheduleCountRow), rawCounts, operation);\n\n if (counts.length !== 1) return yield* corrupt(operation);\n if (counts[0].schedule_count >= ownerLimit) {\n return yield* ScheduleCapacityError.make({ limit: ownerLimit });\n }\n yield* scheduleFailpoint.hit(\"schedule:insert:before\");\n yield* sql`\n INSERT INTO effect_agent_schedules (\n tenant_id, owner_id, schedule_id, deadline_at_millis, record_json\n ) VALUES (\n ${canonical.owner.tenantId},\n ${canonical.owner.ownerId},\n ${canonical.scheduleId},\n ${scheduleDeadline(canonical)},\n ${recordJson}\n )\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const deadline = yield* readNextDeadline(undefined, operation);\n\n yield* replaceAlarm(replace, deadline, operation);\n\n return { record: canonical, inserted: true } as const;\n }),\n );\n\n if (result.inserted) yield* scheduleFailpoint.hit(\"schedule:insert:after\");\n\n return result.record;\n },\n );\n\n const get: ScheduleStore[\"Service\"][\"get\"] = Effect.fn(\"DoScheduleStore.get\")(function* (key) {\n const canonical = yield* decodeBoundary(ScheduleKey, key, \"get schedule\");\n\n return yield* readOne(canonical, \"get schedule\");\n });\n\n const list: ScheduleStore[\"Service\"][\"list\"] = Effect.fn(\"DoScheduleStore.list\")(function* (\n requestValue: SchedulePageRequest,\n ): Effect.fn.Return<SchedulePage, ScheduleStorageError> {\n const operation = \"list schedules\";\n const request = yield* decodeBoundary(SchedulePageRequest, requestValue, operation);\n\n const rows =\n request.after === undefined\n ? yield* sql<Record<string, unknown>>`\n SELECT tenant_id, owner_id, schedule_id, deadline_at_millis, record_json\n FROM effect_agent_schedules\n WHERE tenant_id = ${request.owner.tenantId}\n AND owner_id = ${request.owner.ownerId}\n ORDER BY schedule_id\n LIMIT ${request.limit + 1}\n `.pipe(Effect.mapError(() => unavailable(operation)))\n : yield* sql<Record<string, unknown>>`\n SELECT tenant_id, owner_id, schedule_id, deadline_at_millis, record_json\n FROM effect_agent_schedules\n WHERE tenant_id = ${request.owner.tenantId}\n AND owner_id = ${request.owner.ownerId}\n AND schedule_id > ${request.after}\n ORDER BY schedule_id\n LIMIT ${request.limit + 1}\n `.pipe(Effect.mapError(() => unavailable(operation)));\n\n const decoded = yield* decodeRows(Schema.Array(ScheduleRow), rows, operation);\n const records = yield* Effect.forEach(decoded, decodeRecord);\n const hasNext = records.length > request.limit;\n const items = hasNext ? records.slice(0, request.limit) : records;\n\n return { items, next: hasNext ? (items.at(-1)?.scheduleId ?? null) : null };\n });\n\n const change: ScheduleStore[\"Service\"][\"change\"] = Effect.fn(\"DoScheduleStore.change\")(function* (\n key,\n change,\n ownerLimit = defaultSchedulingLimits.maxSchedulesPerOwner,\n ) {\n const operation = \"change schedule\";\n const canonicalKey = yield* decodeBoundary(ScheduleKey, key, operation);\n const canonicalChange = yield* decodeBoundary(ScheduleChange, change, operation);\n\n const result = yield* transactions.run((replace) =>\n Effect.gen(function* () {\n const current = yield* readOne(canonicalKey, operation);\n\n if (current === null) return yield* ScheduleNotFound.make({ key: canonicalKey });\n const transition = applyScheduleChange(current, canonicalChange);\n\n if (Result.isFailure(transition)) return yield* transition.failure;\n const next = transition.success;\n\n if (!scheduleUsesCapacity(current) && scheduleUsesCapacity(next)) {\n const rawCounts = yield* sql<Record<string, unknown>>`\n SELECT COUNT(*) AS schedule_count FROM effect_agent_schedules\n WHERE tenant_id = ${key.owner.tenantId} AND owner_id = ${key.owner.ownerId}\n AND (json_extract(record_json, '$.pending') IS NOT NULL OR\n (json_extract(record_json, '$.state') != 'cancelled' AND json_extract(record_json, '$.nextAtMillis') IS NOT NULL))\n `.pipe(Effect.mapError(() => unavailable(operation)));\n\n const counts = yield* decodeRows(Schema.Array(ScheduleCountRow), rawCounts, operation);\n\n if (counts.length !== 1) return yield* corrupt(operation);\n if (counts[0].schedule_count >= ownerLimit)\n return yield* ScheduleCapacityError.make({ limit: ownerLimit });\n }\n if (next === current) return { record: current, changed: false } as const;\n const recordJson = yield* encodeRecord(next);\n\n yield* scheduleFailpoint.hit(`schedule:${canonicalChange._tag.toLowerCase()}:before`);\n yield* sql`\n UPDATE effect_agent_schedules\n SET deadline_at_millis = ${scheduleDeadline(next)}, record_json = ${recordJson}\n WHERE tenant_id = ${canonicalKey.owner.tenantId}\n AND owner_id = ${canonicalKey.owner.ownerId}\n AND schedule_id = ${canonicalKey.scheduleId}\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const deadline = yield* readNextDeadline(undefined, operation);\n\n yield* replaceAlarm(replace, deadline, operation);\n\n return { record: next, changed: true } as const;\n }),\n );\n\n if (result.changed) {\n yield* scheduleFailpoint.hit(`schedule:${canonicalChange._tag.toLowerCase()}:after`);\n }\n\n return result.record;\n });\n\n const due: ScheduleStore[\"Service\"][\"due\"] = Effect.fn(\"DoScheduleStore.due\")(function* (\n nowMillis,\n limit,\n owner?: ScheduleOwner,\n after?: ScheduleDueCursor,\n ) {\n const operation = \"query due schedules\";\n\n const cursor =\n after === undefined\n ? undefined\n : yield* Schema.decodeUnknownEffect(ScheduleDueCursor)(after).pipe(\n Effect.mapError(() => corrupt(operation)),\n );\n\n const continuation =\n cursor === undefined\n ? sql`1 = 1`\n : sql`\n (deadline_at_millis, tenant_id, owner_id, schedule_id) >\n (${cursor.deadlineAtMillis}, ${cursor.owner.tenantId}, ${cursor.owner.ownerId}, ${cursor.scheduleId})`;\n\n const rows =\n owner === undefined\n ? yield* sql<Record<string, unknown>>`\n SELECT tenant_id, owner_id, schedule_id, deadline_at_millis\n FROM effect_agent_schedules\n WHERE deadline_at_millis <= ${nowMillis} AND ${continuation}\n ORDER BY deadline_at_millis, tenant_id, owner_id, schedule_id\n LIMIT ${limit}\n `.pipe(Effect.mapError(() => unavailable(operation)))\n : yield* sql<Record<string, unknown>>`\n SELECT tenant_id, owner_id, schedule_id, deadline_at_millis\n FROM effect_agent_schedules\n WHERE tenant_id = ${owner.tenantId}\n AND owner_id = ${owner.ownerId}\n AND deadline_at_millis <= ${nowMillis} AND ${continuation}\n ORDER BY deadline_at_millis, schedule_id\n LIMIT ${limit}\n `.pipe(Effect.mapError(() => unavailable(operation)));\n\n const decoded = yield* decodeRows(Schema.Array(ScheduleDueRow), rows, operation);\n\n return decoded.map((row) => ({\n owner: { tenantId: row.tenant_id, ownerId: row.owner_id },\n scheduleId: row.schedule_id,\n deadlineAtMillis: row.deadline_at_millis,\n }));\n });\n\n const nextDeadline: ScheduleStore[\"Service\"][\"nextDeadline\"] = Effect.fn(\n \"DoScheduleStore.nextDeadline\",\n )(function* (owner?: ScheduleOwner) {\n const operation = \"query next schedule deadline\";\n\n return yield* readNextDeadline(owner, operation);\n });\n\n const prearm = Effect.fn(\"DoScheduleStore.prearm\")(function* (\n deadlineAtMillis: number,\n ): Effect.fn.Return<void, ScheduleStorageError | ScheduleFailpointError> {\n yield* decodeBoundary(ScheduleInstant, deadlineAtMillis, \"pre-arm schedule recovery\");\n yield* transactions.run((replace) =>\n replaceAlarm(replace, deadlineAtMillis, \"pre-arm schedule recovery\"),\n );\n yield* scheduleFailpoint.hit(\"schedule:prearm:after\");\n });\n\n const reconcile = Effect.gen(function* () {\n yield* transactions.run((replace) =>\n Effect.gen(function* () {\n const deadline = yield* readNextDeadline(undefined, \"reconcile schedule alarm\");\n\n yield* replaceAlarm(replace, deadline, \"reconcile schedule alarm\");\n }),\n );\n yield* scheduleFailpoint.hit(\"schedule:reconcile:after\");\n });\n\n return Context.make(ScheduleStore, {\n insert,\n get,\n list,\n change,\n due,\n nextDeadline,\n }).pipe(Context.add(DoScheduleAlarmControl, { prearm, reconcile }));\n});\n\n/**\n * Durable Object SQLite ScheduleStore. Platform code supplies the one transaction owner that\n * combines these SQL mutations with its logical and native alarm lifecycle.\n */\nexport const scheduleStoreLayer: Layer.Layer<\n ScheduleStore | DoScheduleAlarmControl,\n ScheduleStorageError,\n SqlClientService.SqlClient | DoScheduleTransaction\n> = Layer.effectContext(makeServices);\n"],"mappings":";;;;;;;;;;;;AA4BA,MAAM,iCAAiC;AACvC,MAAM,4BAA4B;AAElC,MAAM,qBAAqB,OAAO,OAAO,MAAM,OAAO,YAAY,yBAAyB,CAAC;AAC5F,MAAM,iBAAiB,OAAO,OAAO,eAAe;AAEpD,IAAM,cAAN,cAA0B,OAAO,MAAmB,8CAA8C,CAAC,CACjG;CACE,WAAW,cAAc,OAAO;CAChC,UAAU,cAAc,OAAO;CAC/B,aAAa;CACb,oBAAoB;CACpB,aAAa;AACf,CACF,CAAC,CAAC,CAAC;AAEH,MAAM,iBAAiB,OAAO,OAAO;CACnC,WAAW,cAAc,OAAO;CAChC,UAAU,cAAc,OAAO;CAC/B,aAAa;CACb,oBAAoB;AACtB,CAAC;AAED,IAAM,mBAAN,cAA+B,OAAO,MACpC,mDACF,CAAC,CAAC,EACA,gBAAgB,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC,EACnE,CAAC,CAAC,CAAC,CAAC;AAEJ,IAAM,sBAAN,cAAkC,OAAO,MACvC,sDACF,CAAC,CAAC,EACA,oBAAoB,eACtB,CAAC,CAAC,CAAC,CAAC;AAEJ,IAAM,wBAAN,cAAoC,OAAO,MACzC,wDACF,CAAC,CAAC;CACA,iBAAiB,OAAO,IAAI,MAAM,OAAO,cAAc,CAAC,CAAC;CACzD,kBAAkB,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC;AACrE,CAAC,CAAC,CAAC,CAAC;AAEJ,IAAM,uBAAN,cAAmC,OAAO,MACxC,uDACF,CAAC,CAAC,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ACxC,OAAO,aAAa,KAAK,YACvB,OAAO,IAAI,aAAa;GACtB,MAAM,WAAW,OAAO,iBAAiB,KAAA,GAAW,0BAA0B;GAE9E,OAAO,aAAa,SAAS,UAAU,0BAA0B;EACnE,CAAC,CACH;EACA,OAAO,kBAAkB,IAAI,0BAA0B;CACzD,CAAC;CAED,OAAO,QAAQ,KAAK,eAAe;EACjC;EACA;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,CAAC,KAAK,QAAQ,IAAI,wBAAwB;EAAE;EAAQ;CAAU,CAAC,CAAC;AACpE,CAAC;;;;;AAMD,MAAa,qBAIT,MAAM,cAAc,YAAY"}
|
|
1
|
+
{"version":3,"file":"DoScheduleStore.mjs","names":[],"sources":["../src/DoScheduleStore.ts"],"sourcesContent":["import {\n ScheduleCapacityError,\n ScheduleDueCursor,\n defaultSchedulingLimits,\n ScheduleChange,\n ScheduleConflict,\n ScheduleFailpoint,\n type ScheduleFailpointError,\n ScheduleKey,\n ScheduleId,\n ScheduleInstant,\n ScheduleNotFound,\n ScheduleOwner,\n type SchedulePage,\n SchedulePageRequest,\n ScheduleRecord,\n ScheduleStorageError,\n ScheduleStore,\n} from \"@effect-agent/thread/Schedule\";\nimport {\n applyScheduleChange,\n scheduleUsesCapacity,\n scheduleDeadline,\n} from \"@effect-agent/thread/ScheduleTransition\";\nimport { upgradeV2Schedules } from \"@effect-agent/thread/SqlStorageV2Upgrade\";\nimport { Context, Effect, Layer, Result, Schema } from \"effect\";\nimport * as SqlClientService from \"effect/unstable/sql/SqlClient\";\n\nconst CURRENT_SCHEDULE_STORE_VERSION = 3;\nconst MAX_STORED_SCHEDULE_BYTES = 1_900_000;\n\nconst StoredScheduleJson = Schema.String.check(Schema.isMaxLength(MAX_STORED_SCHEDULE_BYTES));\nconst StoredDeadline = Schema.NullOr(ScheduleInstant);\n\nclass ScheduleRow extends Schema.Class<ScheduleRow>(\"@effect-agent/storage-cloudflare/ScheduleRow\")(\n {\n tenant_id: ScheduleOwner.fields.tenantId,\n owner_id: ScheduleOwner.fields.ownerId,\n schedule_id: ScheduleId,\n deadline_at_millis: StoredDeadline,\n record_json: StoredScheduleJson,\n },\n) {}\n\nconst ScheduleDueRow = Schema.Struct({\n tenant_id: ScheduleOwner.fields.tenantId,\n owner_id: ScheduleOwner.fields.ownerId,\n schedule_id: ScheduleId,\n deadline_at_millis: ScheduleInstant,\n});\n\nclass ScheduleCountRow extends Schema.Class<ScheduleCountRow>(\n \"@effect-agent/storage-cloudflare/ScheduleCountRow\",\n)({\n schedule_count: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\nclass ScheduleDeadlineRow extends Schema.Class<ScheduleDeadlineRow>(\n \"@effect-agent/storage-cloudflare/ScheduleDeadlineRow\",\n)({\n deadline_at_millis: StoredDeadline,\n}) {}\n\nclass ScheduleStoreStateRow extends Schema.Class<ScheduleStoreStateRow>(\n \"@effect-agent/storage-cloudflare/ScheduleStoreStateRow\",\n)({\n storage_version: Schema.Int.check(Schema.isGreaterThan(0)),\n alarm_generation: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\nclass ScheduleTableNameRow extends Schema.Class<ScheduleTableNameRow>(\n \"@effect-agent/storage-cloudflare/ScheduleTableNameRow\",\n)({\n name: Schema.String,\n}) {}\n\nexport interface DoScheduleAlarmReplacement {\n readonly deadlineAtMillis: number | null;\n /** Included in every logical alarm payload so equal-time replacement stays distinguishable. */\n readonly generation: number;\n}\n\nexport type DoScheduleReplaceAlarm = (\n replacement: DoScheduleAlarmReplacement,\n) => Effect.Effect<void, ScheduleStorageError>;\n\n/**\n * Platform-owned transaction boundary for schedule SQL and logical alarm mutation. The callback\n * and its `replaceAlarm` capability belong to one fiber and must not escape or fork.\n */\nexport class DoScheduleTransaction extends Context.Service<\n DoScheduleTransaction,\n {\n readonly run: <A, E, R>(\n body: (replaceAlarm: DoScheduleReplaceAlarm) => Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | ScheduleStorageError, R>;\n }\n>()(\"@effect-agent/storage-cloudflare/DoScheduleTransaction\") {}\n\n/** Platform driver operations that use the same schedule-state and alarm transaction. */\nexport class DoScheduleAlarmControl extends Context.Service<\n DoScheduleAlarmControl,\n {\n /** Establish a future recovery wake before cross-Object admission starts. */\n readonly prearm: (\n deadlineAtMillis: number,\n ) => Effect.Effect<void, ScheduleStorageError | ScheduleFailpointError>;\n /** Replace or cancel the wake from the object's authoritative indexed deadline. */\n readonly reconcile: Effect.Effect<void, ScheduleStorageError | ScheduleFailpointError>;\n }\n>()(\"@effect-agent/storage-cloudflare/DoScheduleAlarmControl\") {}\n\nconst unavailable = (operation: string): ScheduleStorageError =>\n ScheduleStorageError.make({ operation, reason: \"unavailable\" });\n\nconst corrupt = (operation: string): ScheduleStorageError =>\n ScheduleStorageError.make({ operation, reason: \"corrupt\" });\n\nconst decodeRows = Effect.fn(\"DoScheduleStore.decodeRows\")(function* <A, I, R>(\n schema: Schema.Codec<A, I, R>,\n rows: ReadonlyArray<unknown>,\n operation: string,\n): Effect.fn.Return<A, ScheduleStorageError, R> {\n return yield* Schema.decodeUnknownEffect(schema)(rows).pipe(\n Effect.mapError(() => corrupt(operation)),\n );\n});\n\nconst decodeBoundary = <A, I, R>(\n schema: Schema.Codec<A, I, R>,\n value: unknown,\n operation: string,\n): Effect.Effect<A, ScheduleStorageError, R> =>\n Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError(() => corrupt(operation)));\n\nconst decodeRecord = Effect.fn(\"DoScheduleStore.decodeRecord\")(function* (\n row: ScheduleRow,\n): Effect.fn.Return<ScheduleRecord, ScheduleStorageError> {\n const record = yield* Schema.decodeEffect(Schema.fromJsonString(ScheduleRecord))(\n row.record_json,\n ).pipe(Effect.mapError(() => corrupt(\"decode schedule\")));\n\n if (\n record.owner.tenantId !== row.tenant_id ||\n record.owner.ownerId !== row.owner_id ||\n record.scheduleId !== row.schedule_id ||\n scheduleDeadline(record) !== row.deadline_at_millis\n ) {\n return yield* corrupt(\"decode schedule index\");\n }\n\n return record;\n});\n\nconst encodeRecord = Effect.fn(\"DoScheduleStore.encodeRecord\")(function* (\n record: ScheduleRecord,\n): Effect.fn.Return<string, ScheduleStorageError> {\n const encoded = yield* Schema.encodeEffect(Schema.fromJsonString(ScheduleRecord))(record).pipe(\n Effect.mapError(() => corrupt(\"encode schedule\")),\n );\n\n return yield* Schema.decodeEffect(StoredScheduleJson)(encoded).pipe(\n Effect.mapError(() => corrupt(\"encode schedule bounds\")),\n );\n});\n\nconst initializeScheduleStore = Effect.fn(\"DoScheduleStore.initialize\")(function* () {\n const sql = yield* SqlClientService.SqlClient;\n const operation = \"initialize schedule store\";\n\n const rawTables = yield* sql<Record<string, unknown>>`\n SELECT name\n FROM sqlite_master\n WHERE type = 'table'\n AND name IN (\n 'effect_agent_schedule_store_state',\n 'effect_agent_schedules'\n )\n ORDER BY name\n `.pipe(Effect.mapError(() => unavailable(operation)));\n\n const tables = yield* decodeRows(Schema.Array(ScheduleTableNameRow), rawTables, operation);\n const hasState = tables.some((row) => row.name === \"effect_agent_schedule_store_state\");\n const hasSchedules = tables.some((row) => row.name === \"effect_agent_schedules\");\n\n if (!hasState) {\n if (hasSchedules) return yield* corrupt(operation);\n yield* sql\n .withTransaction(\n Effect.gen(function* () {\n yield* sql`\n CREATE TABLE effect_agent_schedule_store_state (\n singleton INTEGER PRIMARY KEY NOT NULL CHECK (singleton = 1),\n storage_version INTEGER NOT NULL,\n alarm_generation INTEGER NOT NULL\n )\n `.withoutTransform;\n yield* sql`\n CREATE TABLE effect_agent_schedules (\n tenant_id TEXT NOT NULL,\n owner_id TEXT NOT NULL,\n schedule_id TEXT NOT NULL,\n deadline_at_millis INTEGER,\n record_json TEXT NOT NULL,\n PRIMARY KEY (tenant_id, owner_id, schedule_id)\n )\n `.withoutTransform;\n yield* sql`\n CREATE INDEX effect_agent_schedules_deadline\n ON effect_agent_schedules (deadline_at_millis, tenant_id, owner_id, schedule_id)\n WHERE deadline_at_millis IS NOT NULL\n `.withoutTransform;\n yield* sql`\n CREATE INDEX effect_agent_schedules_owner_deadline\n ON effect_agent_schedules (tenant_id, owner_id, deadline_at_millis, schedule_id)\n WHERE deadline_at_millis IS NOT NULL\n `.withoutTransform;\n yield* sql`\n INSERT INTO effect_agent_schedule_store_state (\n singleton, storage_version, alarm_generation\n ) VALUES (1, ${CURRENT_SCHEDULE_STORE_VERSION}, 0)\n `.withoutTransform;\n }),\n )\n .pipe(Effect.mapError(() => unavailable(operation)));\n\n return;\n }\n\n if (!hasSchedules) return yield* corrupt(operation);\n\n const rawState = yield* sql<Record<string, unknown>>`\n SELECT storage_version, alarm_generation\n FROM effect_agent_schedule_store_state\n WHERE singleton = 1\n `.pipe(Effect.mapError(() => unavailable(operation)));\n\n const state = yield* decodeRows(Schema.Array(ScheduleStoreStateRow), rawState, operation);\n\n if (state.length === 1 && state[0].storage_version === 2) {\n const failpoint = yield* ScheduleFailpoint;\n\n yield* sql\n .withTransaction(\n Effect.gen(function* () {\n const current = yield* sql<{\n storage_version: number;\n }>`SELECT storage_version FROM effect_agent_schedule_store_state WHERE singleton=1`;\n\n if (current.length === 1 && current[0].storage_version === 3) return;\n if (current.length !== 1 || current[0].storage_version !== 2)\n return yield* corrupt(\"schedule version changed during upgrade\");\n yield* upgradeV2Schedules(MAX_STORED_SCHEDULE_BYTES);\n yield* failpoint.hit(\"upgrade:before-version\");\n yield* sql`UPDATE effect_agent_schedule_store_state SET storage_version=3 WHERE singleton=1`;\n yield* failpoint.hit(\"upgrade:after-version\");\n }),\n )\n .pipe(\n Effect.catchTag(\"StorageUpgradeError\", (error) =>\n ScheduleStorageError.make({\n reason: \"corrupt\",\n operation: \"upgrade v2 schedules\",\n cause: error,\n }),\n ),\n Effect.catchTag(\"SqlError\", () => unavailable(\"upgrade v2 schedules\")),\n Effect.catchTag(\"ScheduleFailpointError\", () =>\n unavailable(\"upgrade v2 schedules failpoint\"),\n ),\n );\n\n return;\n }\n\n if (state.length !== 1 || state[0].storage_version !== CURRENT_SCHEDULE_STORE_VERSION) {\n return yield* corrupt(\n state.length === 1\n ? `${operation}: incompatible storage version ${state[0].storage_version}; expected ${CURRENT_SCHEDULE_STORE_VERSION}`\n : `${operation}: invalid storage version row`,\n );\n }\n});\n\nconst makeServices = Effect.gen(function* () {\n const sql = yield* SqlClientService.SqlClient;\n const transactions = yield* DoScheduleTransaction;\n const scheduleFailpoint = yield* ScheduleFailpoint;\n\n yield* initializeScheduleStore();\n\n const readRows = Effect.fn(\"DoScheduleStore.readRows\")(function* (\n key: ScheduleKey,\n operation: string,\n ): Effect.fn.Return<ReadonlyArray<ScheduleRow>, ScheduleStorageError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT tenant_id, owner_id, schedule_id, deadline_at_millis, record_json\n FROM effect_agent_schedules\n WHERE tenant_id = ${key.owner.tenantId}\n AND owner_id = ${key.owner.ownerId}\n AND schedule_id = ${key.scheduleId}\n `.pipe(Effect.mapError(() => unavailable(operation)));\n\n return yield* decodeRows(Schema.Array(ScheduleRow), rows, operation);\n });\n\n const readOne = Effect.fn(\"DoScheduleStore.readOne\")(function* (\n key: ScheduleKey,\n operation: string,\n ): Effect.fn.Return<ScheduleRecord | null, ScheduleStorageError> {\n const rows = yield* readRows(key, operation);\n\n if (rows.length === 0) return null;\n if (rows.length !== 1) return yield* corrupt(operation);\n\n return yield* decodeRecord(rows[0]);\n });\n\n const readNextDeadline = Effect.fn(\"DoScheduleStore.readNextDeadline\")(function* (\n owner: ScheduleOwner | undefined,\n operation: string,\n ): Effect.fn.Return<number | null, ScheduleStorageError> {\n const rows =\n owner === undefined\n ? yield* sql<Record<string, unknown>>`\n SELECT MIN(deadline_at_millis) AS deadline_at_millis\n FROM effect_agent_schedules\n WHERE deadline_at_millis IS NOT NULL\n `.pipe(Effect.mapError(() => unavailable(operation)))\n : yield* sql<Record<string, unknown>>`\n SELECT MIN(deadline_at_millis) AS deadline_at_millis\n FROM effect_agent_schedules\n WHERE tenant_id = ${owner.tenantId}\n AND owner_id = ${owner.ownerId}\n AND deadline_at_millis IS NOT NULL\n `.pipe(Effect.mapError(() => unavailable(operation)));\n\n const decoded = yield* decodeRows(Schema.Array(ScheduleDeadlineRow), rows, operation);\n\n if (decoded.length !== 1) return yield* corrupt(operation);\n\n return decoded[0].deadline_at_millis;\n });\n\n const replaceAlarm = Effect.fn(\"DoScheduleStore.replaceAlarm\")(function* (\n replace: DoScheduleReplaceAlarm,\n deadlineAtMillis: number | null,\n operation: string,\n ) {\n const rawState = yield* sql<Record<string, unknown>>`\n UPDATE effect_agent_schedule_store_state\n SET alarm_generation = alarm_generation + 1\n WHERE singleton = 1\n RETURNING storage_version, alarm_generation\n `.pipe(Effect.mapError(() => unavailable(operation)));\n\n const state = yield* decodeRows(Schema.Array(ScheduleStoreStateRow), rawState, operation);\n\n if (state.length !== 1 || state[0].storage_version !== CURRENT_SCHEDULE_STORE_VERSION) {\n return yield* corrupt(operation);\n }\n yield* scheduleFailpoint.hit(\"schedule:alarm:before\");\n yield* replace({ deadlineAtMillis, generation: state[0].alarm_generation });\n yield* scheduleFailpoint.hit(\"schedule:alarm:after\");\n });\n\n const insert: ScheduleStore[\"Service\"][\"insert\"] = Effect.fn(\"DoScheduleStore.insert\")(\n function* (record, ownerLimit) {\n const operation = \"insert schedule\";\n const canonical = yield* decodeBoundary(ScheduleRecord, record, operation);\n const recordJson = yield* encodeRecord(canonical);\n\n const result = yield* transactions.run((replace) =>\n Effect.gen(function* () {\n const existing = yield* readOne(canonical, operation);\n\n if (existing !== null) {\n if (existing.creationFingerprint === canonical.creationFingerprint) {\n return { record: existing, inserted: false } as const;\n }\n\n return yield* ScheduleConflict.make({ reason: \"creation\", key: canonical });\n }\n\n const rawCounts = yield* sql<Record<string, unknown>>`\n SELECT COUNT(*) AS schedule_count\n FROM effect_agent_schedules\n WHERE tenant_id = ${canonical.owner.tenantId}\n AND owner_id = ${canonical.owner.ownerId}\n AND (json_extract(record_json, '$.pending') IS NOT NULL OR\n (json_extract(record_json, '$.state') != 'cancelled' AND json_extract(record_json, '$.nextAtMillis') IS NOT NULL))\n `.pipe(Effect.mapError(() => unavailable(operation)));\n\n const counts = yield* decodeRows(Schema.Array(ScheduleCountRow), rawCounts, operation);\n\n if (counts.length !== 1) return yield* corrupt(operation);\n if (counts[0].schedule_count >= ownerLimit) {\n return yield* ScheduleCapacityError.make({ limit: ownerLimit });\n }\n yield* scheduleFailpoint.hit(\"schedule:insert:before\");\n yield* sql`\n INSERT INTO effect_agent_schedules (\n tenant_id, owner_id, schedule_id, deadline_at_millis, record_json\n ) VALUES (\n ${canonical.owner.tenantId},\n ${canonical.owner.ownerId},\n ${canonical.scheduleId},\n ${scheduleDeadline(canonical)},\n ${recordJson}\n )\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const deadline = yield* readNextDeadline(undefined, operation);\n\n yield* replaceAlarm(replace, deadline, operation);\n\n return { record: canonical, inserted: true } as const;\n }),\n );\n\n if (result.inserted) yield* scheduleFailpoint.hit(\"schedule:insert:after\");\n\n return result.record;\n },\n );\n\n const get: ScheduleStore[\"Service\"][\"get\"] = Effect.fn(\"DoScheduleStore.get\")(function* (key) {\n const canonical = yield* decodeBoundary(ScheduleKey, key, \"get schedule\");\n\n return yield* readOne(canonical, \"get schedule\");\n });\n\n const list: ScheduleStore[\"Service\"][\"list\"] = Effect.fn(\"DoScheduleStore.list\")(function* (\n requestValue: SchedulePageRequest,\n ): Effect.fn.Return<SchedulePage, ScheduleStorageError> {\n const operation = \"list schedules\";\n const request = yield* decodeBoundary(SchedulePageRequest, requestValue, operation);\n\n const rows =\n request.after === undefined\n ? yield* sql<Record<string, unknown>>`\n SELECT tenant_id, owner_id, schedule_id, deadline_at_millis, record_json\n FROM effect_agent_schedules\n WHERE tenant_id = ${request.owner.tenantId}\n AND owner_id = ${request.owner.ownerId}\n ORDER BY schedule_id\n LIMIT ${request.limit + 1}\n `.pipe(Effect.mapError(() => unavailable(operation)))\n : yield* sql<Record<string, unknown>>`\n SELECT tenant_id, owner_id, schedule_id, deadline_at_millis, record_json\n FROM effect_agent_schedules\n WHERE tenant_id = ${request.owner.tenantId}\n AND owner_id = ${request.owner.ownerId}\n AND schedule_id > ${request.after}\n ORDER BY schedule_id\n LIMIT ${request.limit + 1}\n `.pipe(Effect.mapError(() => unavailable(operation)));\n\n const decoded = yield* decodeRows(Schema.Array(ScheduleRow), rows, operation);\n const records = yield* Effect.forEach(decoded, decodeRecord);\n const hasNext = records.length > request.limit;\n const items = hasNext ? records.slice(0, request.limit) : records;\n\n return { items, next: hasNext ? (items.at(-1)?.scheduleId ?? null) : null };\n });\n\n const change: ScheduleStore[\"Service\"][\"change\"] = Effect.fn(\"DoScheduleStore.change\")(function* (\n key,\n change,\n ownerLimit = defaultSchedulingLimits.maxSchedulesPerOwner,\n ) {\n const operation = \"change schedule\";\n const canonicalKey = yield* decodeBoundary(ScheduleKey, key, operation);\n const canonicalChange = yield* decodeBoundary(ScheduleChange, change, operation);\n\n const result = yield* transactions.run((replace) =>\n Effect.gen(function* () {\n const current = yield* readOne(canonicalKey, operation);\n\n if (current === null) return yield* ScheduleNotFound.make({ key: canonicalKey });\n const transition = applyScheduleChange(current, canonicalChange);\n\n if (Result.isFailure(transition)) return yield* transition.failure;\n const next = transition.success;\n\n if (!scheduleUsesCapacity(current) && scheduleUsesCapacity(next)) {\n const rawCounts = yield* sql<Record<string, unknown>>`\n SELECT COUNT(*) AS schedule_count FROM effect_agent_schedules\n WHERE tenant_id = ${key.owner.tenantId} AND owner_id = ${key.owner.ownerId}\n AND (json_extract(record_json, '$.pending') IS NOT NULL OR\n (json_extract(record_json, '$.state') != 'cancelled' AND json_extract(record_json, '$.nextAtMillis') IS NOT NULL))\n `.pipe(Effect.mapError(() => unavailable(operation)));\n\n const counts = yield* decodeRows(Schema.Array(ScheduleCountRow), rawCounts, operation);\n\n if (counts.length !== 1) return yield* corrupt(operation);\n if (counts[0].schedule_count >= ownerLimit)\n return yield* ScheduleCapacityError.make({ limit: ownerLimit });\n }\n if (next === current) return { record: current, changed: false } as const;\n const recordJson = yield* encodeRecord(next);\n\n yield* scheduleFailpoint.hit(`schedule:${canonicalChange._tag.toLowerCase()}:before`);\n yield* sql`\n UPDATE effect_agent_schedules\n SET deadline_at_millis = ${scheduleDeadline(next)}, record_json = ${recordJson}\n WHERE tenant_id = ${canonicalKey.owner.tenantId}\n AND owner_id = ${canonicalKey.owner.ownerId}\n AND schedule_id = ${canonicalKey.scheduleId}\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const deadline = yield* readNextDeadline(undefined, operation);\n\n yield* replaceAlarm(replace, deadline, operation);\n\n return { record: next, changed: true } as const;\n }),\n );\n\n if (result.changed) {\n yield* scheduleFailpoint.hit(`schedule:${canonicalChange._tag.toLowerCase()}:after`);\n }\n\n return result.record;\n });\n\n const due: ScheduleStore[\"Service\"][\"due\"] = Effect.fn(\"DoScheduleStore.due\")(function* (\n nowMillis,\n limit,\n owner?: ScheduleOwner,\n after?: ScheduleDueCursor,\n ) {\n const operation = \"query due schedules\";\n\n const cursor =\n after === undefined\n ? undefined\n : yield* Schema.decodeEffect(ScheduleDueCursor)(after).pipe(\n Effect.mapError(() => corrupt(operation)),\n );\n\n const continuation =\n cursor === undefined\n ? sql`1 = 1`\n : sql`\n (deadline_at_millis, tenant_id, owner_id, schedule_id) >\n (${cursor.deadlineAtMillis}, ${cursor.owner.tenantId}, ${cursor.owner.ownerId}, ${cursor.scheduleId})`;\n\n const rows =\n owner === undefined\n ? yield* sql<Record<string, unknown>>`\n SELECT tenant_id, owner_id, schedule_id, deadline_at_millis\n FROM effect_agent_schedules\n WHERE deadline_at_millis <= ${nowMillis} AND ${continuation}\n ORDER BY deadline_at_millis, tenant_id, owner_id, schedule_id\n LIMIT ${limit}\n `.pipe(Effect.mapError(() => unavailable(operation)))\n : yield* sql<Record<string, unknown>>`\n SELECT tenant_id, owner_id, schedule_id, deadline_at_millis\n FROM effect_agent_schedules\n WHERE tenant_id = ${owner.tenantId}\n AND owner_id = ${owner.ownerId}\n AND deadline_at_millis <= ${nowMillis} AND ${continuation}\n ORDER BY deadline_at_millis, schedule_id\n LIMIT ${limit}\n `.pipe(Effect.mapError(() => unavailable(operation)));\n\n const decoded = yield* decodeRows(Schema.Array(ScheduleDueRow), rows, operation);\n\n return decoded.map((row) => ({\n owner: { tenantId: row.tenant_id, ownerId: row.owner_id },\n scheduleId: row.schedule_id,\n deadlineAtMillis: row.deadline_at_millis,\n }));\n });\n\n const nextDeadline: ScheduleStore[\"Service\"][\"nextDeadline\"] = Effect.fn(\n \"DoScheduleStore.nextDeadline\",\n )(function* (owner?: ScheduleOwner) {\n const operation = \"query next schedule deadline\";\n\n return yield* readNextDeadline(owner, operation);\n });\n\n const prearm = Effect.fn(\"DoScheduleStore.prearm\")(function* (\n deadlineAtMillis: number,\n ): Effect.fn.Return<void, ScheduleStorageError | ScheduleFailpointError> {\n yield* decodeBoundary(ScheduleInstant, deadlineAtMillis, \"pre-arm schedule recovery\");\n yield* transactions.run((replace) =>\n replaceAlarm(replace, deadlineAtMillis, \"pre-arm schedule recovery\"),\n );\n yield* scheduleFailpoint.hit(\"schedule:prearm:after\");\n });\n\n const reconcile = Effect.gen(function* () {\n yield* transactions.run((replace) =>\n Effect.gen(function* () {\n const deadline = yield* readNextDeadline(undefined, \"reconcile schedule alarm\");\n\n yield* replaceAlarm(replace, deadline, \"reconcile schedule alarm\");\n }),\n );\n yield* scheduleFailpoint.hit(\"schedule:reconcile:after\");\n });\n\n return Context.make(ScheduleStore, {\n insert,\n get,\n list,\n change,\n due,\n nextDeadline,\n }).pipe(Context.add(DoScheduleAlarmControl, { prearm, reconcile }));\n});\n\n/**\n * Durable Object SQLite ScheduleStore. Platform code supplies the one transaction owner that\n * combines these SQL mutations with its logical and native alarm lifecycle.\n */\nexport const scheduleStoreLayer: Layer.Layer<\n ScheduleStore | DoScheduleAlarmControl,\n ScheduleStorageError,\n SqlClientService.SqlClient | DoScheduleTransaction\n> = Layer.effectContext(makeServices);\n"],"mappings":";;;;;;;;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K,QAAQ,IAAI,wBAAwB;EAAE;EAAQ;CAAU,CAAC,CAAC;AACpE,CAAC;;;;;AAMD,MAAa,qBAIT,MAAM,cAAc,YAAY"}
|
|
@@ -2,14 +2,14 @@ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
|
|
|
2
2
|
import { DoStorageConfig } from "./DoStorageConfig.mjs";
|
|
3
3
|
import { DoStorageFailpoint } from "./DoStorageFailpoint.mjs";
|
|
4
4
|
import { DoLedgerError, DoStorageCorruptionError, DoStorageError } from "./DoStorageError.mjs";
|
|
5
|
-
import { a as initializeDoJournal, i as decodeRows } from "./do-journal-
|
|
5
|
+
import { a as initializeDoJournal, i as decodeRows } from "./do-journal-C18d6Yu0.mjs";
|
|
6
6
|
import { storageConfigLayer, storageFailpointLayer } from "./DoThreadStore.mjs";
|
|
7
7
|
import { Clock, Context, Crypto, DateTime, Effect, Layer, Option, Schema, Stream } from "effect";
|
|
8
8
|
import * as SqlClientService from "effect/unstable/sql/SqlClient";
|
|
9
9
|
import { EMPTY_TAIL_DIGEST } from "@effect-agent/thread/Digest";
|
|
10
10
|
import { ApprovalDecision, CanonicalSequence, DefinitionDigests, Digest, PersistedJson, ProducerEpoch, RecordEnvelope, SettlementOutcome, WorkerAdmission } from "@effect-agent/thread/Records";
|
|
11
11
|
import { SqliteClient } from "@effect/sql-sqlite-do";
|
|
12
|
-
import {
|
|
12
|
+
import { InputMessage } from "@effect-agent/core/Messaging";
|
|
13
13
|
import { AbortCommand, AbortIntent, AbortIntentRequest, AdmissionAdmitted, AdmissionConflict, AdmissionFence, AdmissionGroup, AdmissionNotAdmitted, AdmissionPolicyError, AdmissionRequest, AdmissionResult, ApprovalConflict, ApprovalDecisionCommand, ApprovalDecisionIntent, AttachChildToReservationRequest, BeginChildBudgetReleaseRequest, ChildAttachmentSnapshot, ChildBudgetReservationRequest, ChildBudgetReservationSnapshot, ChildReservationConflict, ChildReservationStatus, ChildSettledNotification, Claim, ClaimJoiningRequest, ClaimRequest, InputAppliedMarker, JoinSnapshot, JoinedToHost, JoiningClaim, LedgerCapabilities, LedgerError, MarkInputAppliedRequest, MarkJoinedRequest, MarkReadyRequest, MarkUnknownRequest, OwnershipLost, OwnershipRenewal, OwnershipSnapshot, ParentLinkage, QueueSequence, RecoverySnapshot, RecoverySnapshotRequest, ReleaseChildBudgetRequest, ReleaseOwnershipRequest, RenewOwnershipRequest, ReservedChildBudget, ReservedSettlement, RevertJoiningRequest, Settlement, SettlementConflict, SettlementFinalization, SettlementReservation, SettlementReservationSnapshot, SubmissionAdmissionFence, SubmissionLedger, SubmissionLookup, SubmissionLookupByKey, SubmissionSnapshot, SubmissionState, SuspendRequest, SuspensionReason, SuspensionSnapshot, UnknownResolution, UnknownResolutionCommand, UnknownResolutionConflict, UnknownResolutionIntent, settlementFailureFromRecord, submissionAbortRecordId } from "@effect-agent/thread/SubmissionLedger";
|
|
14
14
|
import { BrowserCrypto } from "@effect/platform-browser";
|
|
15
15
|
//#region src/DoSubmissionLedger.ts
|
|
@@ -298,7 +298,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
298
298
|
const ownership = yield* readOwnership(operation, submission.submission_id);
|
|
299
299
|
if (Option.isNone(ownership) || ownership.value.ownership_token !== ownershipToken) {
|
|
300
300
|
const actualEpoch = yield* threadEpoch(operation, submission.thread_id);
|
|
301
|
-
const submissionId = yield* Schema.
|
|
301
|
+
const submissionId = yield* Schema.decodeEffect(SubmissionSnapshot.fields.submissionId)(submission.submission_id).pipe(Effect.mapError(internalFailure(operation)));
|
|
302
302
|
return yield* OwnershipLost.make({
|
|
303
303
|
submissionId,
|
|
304
304
|
actualEpoch
|
|
@@ -522,7 +522,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
522
522
|
const capabilities = Effect.succeed(LedgerCapabilities.make({ durability: "durable-cloudflare" }));
|
|
523
523
|
const admit = Effect.fn("DoSubmissionLedger.admit")(function* (request) {
|
|
524
524
|
const operation = "ledger admit";
|
|
525
|
-
const validated = yield* Schema.
|
|
525
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(AdmissionRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
526
526
|
const inputJson = yield* encodePersistedJsonText(validated.inputPayload).pipe(Effect.mapError(internalFailure(operation)));
|
|
527
527
|
yield* journal.checkValueBound(operation, inputJson).pipe(Effect.mapError(internalFailure(operation)));
|
|
528
528
|
const workerAdmissionJson = validated.workerAdmission === void 0 ? null : yield* Schema.encodeEffect(Schema.fromJsonString(WorkerAdmission))(validated.workerAdmission).pipe(Effect.mapError(internalFailure(operation)));
|
|
@@ -530,7 +530,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
530
530
|
operation,
|
|
531
531
|
message: "Worker admission metadata exceeds the stored value bound"
|
|
532
532
|
});
|
|
533
|
-
const messageAdmissionJson = validated.messageAdmission === void 0 ? null : yield* Schema.encodeEffect(Schema.fromJsonString(
|
|
533
|
+
const messageAdmissionJson = validated.messageAdmission === void 0 ? null : yield* Schema.encodeEffect(Schema.fromJsonString(InputMessage))(validated.messageAdmission).pipe(Effect.mapError(internalFailure(operation)));
|
|
534
534
|
if (messageAdmissionJson !== null && new TextEncoder().encode(messageAdmissionJson).byteLength > config.maxStoredValueBytes) return yield* LedgerError.make({
|
|
535
535
|
operation,
|
|
536
536
|
message: "Message admission metadata exceeds the stored value bound"
|
|
@@ -564,9 +564,9 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
564
564
|
attemptedInputDigest: validated.inputDigest
|
|
565
565
|
});
|
|
566
566
|
const retainedWorkerAdmission = existing[0].worker_admission_json === null ? void 0 : yield* Schema.decodeEffect(Schema.fromJsonString(WorkerAdmission))(existing[0].worker_admission_json).pipe(Effect.mapError(internalFailure(operation)));
|
|
567
|
-
const
|
|
567
|
+
const retainedInputMessage = existing[0].message_admission_json === null ? void 0 : yield* Schema.decodeEffect(Schema.fromJsonString(InputMessage))(existing[0].message_admission_json).pipe(Effect.mapError(internalFailure(operation)));
|
|
568
568
|
const retainedFence = existing[0].admission_fence_json === null ? void 0 : yield* Schema.decodeEffect(Schema.fromJsonString(AdmissionFence))(existing[0].admission_fence_json).pipe(Effect.mapError(internalFailure(operation)));
|
|
569
|
-
if ((existing[0].admission_group ?? void 0) !== validated.admissionGroup || !Schema.toEquivalence(Schema.optional(WorkerAdmission))(retainedWorkerAdmission, validated.workerAdmission) || !Schema.toEquivalence(Schema.optional(
|
|
569
|
+
if ((existing[0].admission_group ?? void 0) !== validated.admissionGroup || !Schema.toEquivalence(Schema.optional(WorkerAdmission))(retainedWorkerAdmission, validated.workerAdmission) || !Schema.toEquivalence(Schema.optional(InputMessage))(retainedInputMessage, validated.messageAdmission) || !Schema.toEquivalence(Schema.optional(AdmissionFence))(retainedFence, validated.admissionFence)) return yield* AdmissionConflict.make({
|
|
570
570
|
threadId: validated.threadId,
|
|
571
571
|
principal: validated.principal,
|
|
572
572
|
idempotencyKey: validated.idempotencyKey,
|
|
@@ -667,7 +667,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
667
667
|
});
|
|
668
668
|
const markReady = Effect.fn("DoSubmissionLedger.markReady")(function* (request) {
|
|
669
669
|
const operation = "ledger mark ready";
|
|
670
|
-
const validated = yield* Schema.
|
|
670
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(MarkReadyRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
671
671
|
yield* hitFailpoint("ledger:mark-ready:before", operation);
|
|
672
672
|
yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
673
673
|
if ((yield* requireSubmission(operation, validated.submissionId)).state !== "admitted") return;
|
|
@@ -682,7 +682,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
682
682
|
});
|
|
683
683
|
const lookup = Effect.fn("DoSubmissionLedger.lookup")(function* (request) {
|
|
684
684
|
const operation = "ledger lookup";
|
|
685
|
-
const validated = yield* Schema.
|
|
685
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(SubmissionLookup))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
686
686
|
if (validated._tag === "SubmissionLookupById") {
|
|
687
687
|
const row = yield* readSubmission(operation, validated.submissionId);
|
|
688
688
|
if (Option.isNone(row)) return Option.none();
|
|
@@ -702,7 +702,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
702
702
|
});
|
|
703
703
|
const resolveAdmission = Effect.fn("DoSubmissionLedger.resolveAdmission")(function* (request) {
|
|
704
704
|
const operation = "ledger resolve admission";
|
|
705
|
-
const validated = yield* Schema.
|
|
705
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(SubmissionLookupByKey))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
706
706
|
const rows = yield* sql`
|
|
707
707
|
SELECT ${sql.literal(SUBMISSION_COLUMNS)}
|
|
708
708
|
FROM effect_agent_submissions
|
|
@@ -717,7 +717,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
717
717
|
});
|
|
718
718
|
const claim = Effect.fn("DoSubmissionLedger.claim")(function* (request) {
|
|
719
719
|
const operation = "ledger claim";
|
|
720
|
-
const validated = yield* Schema.
|
|
720
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(ClaimRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
721
721
|
const attemptId = `attempt-${yield* mintUuid(operation)}`;
|
|
722
722
|
const ownershipToken = `owner-${yield* mintUuid(operation)}`;
|
|
723
723
|
yield* hitFailpoint("ledger:claim:before", operation);
|
|
@@ -827,7 +827,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
827
827
|
});
|
|
828
828
|
const renewOwnership = Effect.fn("DoSubmissionLedger.renewOwnership")(function* (request) {
|
|
829
829
|
const operation = "ledger renew ownership";
|
|
830
|
-
const validated = yield* Schema.
|
|
830
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(RenewOwnershipRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
831
831
|
yield* hitFailpoint("ledger:renew:before", operation);
|
|
832
832
|
const renewal = yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
833
833
|
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
@@ -849,7 +849,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
849
849
|
});
|
|
850
850
|
const releaseOwnership = Effect.fn("DoSubmissionLedger.releaseOwnership")(function* (request) {
|
|
851
851
|
const operation = "ledger release ownership";
|
|
852
|
-
const validated = yield* Schema.
|
|
852
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(ReleaseOwnershipRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
853
853
|
yield* hitFailpoint("ledger:release:before", operation);
|
|
854
854
|
yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
855
855
|
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
@@ -868,7 +868,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
868
868
|
});
|
|
869
869
|
const markInputApplied = Effect.fn("DoSubmissionLedger.markInputApplied")(function* (request) {
|
|
870
870
|
const operation = "ledger mark input applied";
|
|
871
|
-
const validated = yield* Schema.
|
|
871
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(MarkInputAppliedRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
872
872
|
yield* hitFailpoint("ledger:mark-input-applied:before", operation);
|
|
873
873
|
yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
874
874
|
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
@@ -893,7 +893,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
893
893
|
});
|
|
894
894
|
const reserveSettlement = Effect.fn("DoSubmissionLedger.reserveSettlement")(function* (request) {
|
|
895
895
|
const operation = "ledger reserve settlement";
|
|
896
|
-
const validated = yield* Schema.
|
|
896
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(SettlementReservation))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
897
897
|
const recordJson = yield* encodeRecordEnvelopeText(validated.record).pipe(Effect.mapError(internalFailure(operation)));
|
|
898
898
|
yield* journal.checkValueBound(operation, recordJson).pipe(Effect.mapError(internalFailure(operation)));
|
|
899
899
|
yield* hitFailpoint("ledger:reserve-settlement:before", operation);
|
|
@@ -1002,7 +1002,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
1002
1002
|
});
|
|
1003
1003
|
const finalizeSettlement = Effect.fn("DoSubmissionLedger.finalizeSettlement")(function* (request) {
|
|
1004
1004
|
const operation = "ledger finalize settlement";
|
|
1005
|
-
const validated = yield* Schema.
|
|
1005
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(SettlementFinalization))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1006
1006
|
yield* hitFailpoint("ledger:finalize-settlement:before", operation);
|
|
1007
1007
|
const replayRows = yield* sql`
|
|
1008
1008
|
SELECT submission.*, reservation.settlement_id, reservation.outcome,
|
|
@@ -1057,7 +1057,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
1057
1057
|
});
|
|
1058
1058
|
const requestAbort = Effect.fn("DoSubmissionLedger.requestAbort")(function* (request) {
|
|
1059
1059
|
const operation = "ledger request abort";
|
|
1060
|
-
const validated = yield* Schema.
|
|
1060
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(AbortCommand))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1061
1061
|
yield* hitFailpoint("ledger:request-abort:before", operation);
|
|
1062
1062
|
const intent = yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
1063
1063
|
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
@@ -1106,7 +1106,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
1106
1106
|
});
|
|
1107
1107
|
const claimJoining = Effect.fn("DoSubmissionLedger.claimJoining")(function* (request) {
|
|
1108
1108
|
const operation = "ledger claim joining";
|
|
1109
|
-
const validated = yield* Schema.
|
|
1109
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(ClaimJoiningRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1110
1110
|
yield* hitFailpoint("ledger:claim-joining:before", operation);
|
|
1111
1111
|
const claims = yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
1112
1112
|
const host = yield* requireSubmission(operation, validated.hostSubmissionId);
|
|
@@ -1148,7 +1148,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
1148
1148
|
});
|
|
1149
1149
|
const markJoined = Effect.fn("DoSubmissionLedger.markJoined")(function* (request) {
|
|
1150
1150
|
const operation = "ledger mark joined";
|
|
1151
|
-
const validated = yield* Schema.
|
|
1151
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(MarkJoinedRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1152
1152
|
yield* hitFailpoint("ledger:mark-joined:before", operation);
|
|
1153
1153
|
yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
1154
1154
|
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
@@ -1179,7 +1179,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
1179
1179
|
});
|
|
1180
1180
|
const revertJoining = Effect.fn("DoSubmissionLedger.revertJoining")(function* (request) {
|
|
1181
1181
|
const operation = "ledger revert joining";
|
|
1182
|
-
const validated = yield* Schema.
|
|
1182
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(RevertJoiningRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1183
1183
|
yield* hitFailpoint("ledger:revert-joining:before", operation);
|
|
1184
1184
|
yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
1185
1185
|
if ((yield* requireSubmission(operation, validated.submissionId)).state !== "joining") return;
|
|
@@ -1193,7 +1193,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
1193
1193
|
});
|
|
1194
1194
|
const suspend = Effect.fn("DoSubmissionLedger.suspend")(function* (request) {
|
|
1195
1195
|
const operation = "ledger suspend";
|
|
1196
|
-
const validated = yield* Schema.
|
|
1196
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(SuspendRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1197
1197
|
const reasonJson = yield* encodeSuspensionReasonText(validated.reason).pipe(Effect.mapError(internalFailure(operation)));
|
|
1198
1198
|
yield* hitFailpoint("ledger:suspend:before", operation);
|
|
1199
1199
|
const outcome = yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
@@ -1267,7 +1267,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
1267
1267
|
});
|
|
1268
1268
|
const recordApprovalDecision = Effect.fn("DoSubmissionLedger.recordApprovalDecision")(function* (command) {
|
|
1269
1269
|
const operation = "ledger record approval decision";
|
|
1270
|
-
const validated = yield* Schema.
|
|
1270
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(ApprovalDecisionCommand))(command).pipe(Effect.mapError(internalFailure(operation)));
|
|
1271
1271
|
yield* hitFailpoint("ledger:approval-decision:before", operation);
|
|
1272
1272
|
const intent = yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
1273
1273
|
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
@@ -1320,7 +1320,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
1320
1320
|
});
|
|
1321
1321
|
const markUnknown = Effect.fn("DoSubmissionLedger.markUnknown")(function* (request) {
|
|
1322
1322
|
const operation = "ledger mark unknown";
|
|
1323
|
-
const validated = yield* Schema.
|
|
1323
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(MarkUnknownRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1324
1324
|
yield* hitFailpoint("ledger:mark-unknown:before", operation);
|
|
1325
1325
|
yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
1326
1326
|
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
@@ -1353,7 +1353,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
1353
1353
|
});
|
|
1354
1354
|
const recordUnknownResolution = Effect.fn("DoSubmissionLedger.recordUnknownResolution")(function* (command) {
|
|
1355
1355
|
const operation = "ledger record unknown resolution";
|
|
1356
|
-
const validated = yield* Schema.
|
|
1356
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(UnknownResolutionCommand))(command).pipe(Effect.mapError(internalFailure(operation)));
|
|
1357
1357
|
const resolutionJson = yield* encodeUnknownResolutionText(validated.resolution).pipe(Effect.mapError(internalFailure(operation)));
|
|
1358
1358
|
yield* hitFailpoint("ledger:unknown-resolution:before", operation);
|
|
1359
1359
|
const intent = yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
@@ -1422,7 +1422,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
1422
1422
|
});
|
|
1423
1423
|
const recordChildSettled = Effect.fn("DoSubmissionLedger.recordChildSettled")(function* (request) {
|
|
1424
1424
|
const operation = "ledger record child settled";
|
|
1425
|
-
const validated = yield* Schema.
|
|
1425
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(ChildSettledNotification))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1426
1426
|
yield* hitFailpoint("ledger:child-settled:before", operation);
|
|
1427
1427
|
const outcome = yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
1428
1428
|
const parent = yield* requireSubmission(operation, validated.parentSubmissionId);
|
|
@@ -1469,7 +1469,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
1469
1469
|
});
|
|
1470
1470
|
const reserveChildBudget = Effect.fn("DoSubmissionLedger.reserveChildBudget")(function* (request) {
|
|
1471
1471
|
const operation = "ledger reserve child budget";
|
|
1472
|
-
const validated = yield* Schema.
|
|
1472
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(ChildBudgetReservationRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1473
1473
|
const allocationJson = yield* encodePersistedJsonText(validated.allocation).pipe(Effect.mapError(internalFailure(operation)));
|
|
1474
1474
|
yield* hitFailpoint("ledger:child-reservation:before", operation);
|
|
1475
1475
|
const reserved = yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
@@ -1526,7 +1526,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
1526
1526
|
});
|
|
1527
1527
|
const attachChildToReservation = Effect.fn("DoSubmissionLedger.attachChildToReservation")(function* (request) {
|
|
1528
1528
|
const operation = "ledger attach child to reservation";
|
|
1529
|
-
const validated = yield* Schema.
|
|
1529
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(AttachChildToReservationRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1530
1530
|
yield* hitFailpoint("ledger:child-attach:before", operation);
|
|
1531
1531
|
const attached = yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
1532
1532
|
const existing = yield* readChildReservation(operation, validated.reservationId);
|
|
@@ -1563,7 +1563,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
1563
1563
|
});
|
|
1564
1564
|
const beginChildBudgetRelease = Effect.fn("DoSubmissionLedger.beginChildBudgetRelease")(function* (request) {
|
|
1565
1565
|
const operation = "ledger begin child budget release";
|
|
1566
|
-
const validated = yield* Schema.
|
|
1566
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(BeginChildBudgetReleaseRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1567
1567
|
const accountingJson = yield* encodePersistedJsonText(validated.accounting).pipe(Effect.mapError(internalFailure(operation)));
|
|
1568
1568
|
yield* hitFailpoint("ledger:child-release-pending:before", operation);
|
|
1569
1569
|
const frozen = yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
@@ -1599,7 +1599,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
1599
1599
|
});
|
|
1600
1600
|
const releaseChildBudget = Effect.fn("DoSubmissionLedger.releaseChildBudget")(function* (request) {
|
|
1601
1601
|
const operation = "ledger release child budget";
|
|
1602
|
-
const validated = yield* Schema.
|
|
1602
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(ReleaseChildBudgetRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1603
1603
|
yield* hitFailpoint("ledger:child-release:before", operation);
|
|
1604
1604
|
const released = yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
1605
1605
|
const existing = yield* readChildReservation(operation, validated.reservationId);
|
|
@@ -1653,7 +1653,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
1653
1653
|
const scanNonterminal = Stream.paginate(void 0, scanPage);
|
|
1654
1654
|
const readAbortIntentForSubmission = Effect.fn("DoSubmissionLedger.readAbortIntentForSubmission")(function* (request) {
|
|
1655
1655
|
const operation = "ledger read abort intent";
|
|
1656
|
-
const validated = yield* Schema.
|
|
1656
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(AbortIntentRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1657
1657
|
const recordId = submissionAbortRecordId(validated.submissionId);
|
|
1658
1658
|
const rows = yield* sql`
|
|
1659
1659
|
SELECT
|
|
@@ -1689,7 +1689,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
1689
1689
|
});
|
|
1690
1690
|
const loadRecoverySnapshot = Effect.fn("DoSubmissionLedger.loadRecoverySnapshot")(function* (request) {
|
|
1691
1691
|
const operation = "ledger load recovery snapshot";
|
|
1692
|
-
const validated = yield* Schema.
|
|
1692
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(RecoverySnapshotRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1693
1693
|
return yield* sql.withTransaction(Effect.gen(function* () {
|
|
1694
1694
|
const submissionRow = yield* requireSubmission(operation, validated.submissionId);
|
|
1695
1695
|
const submission = yield* decodeSubmissionSnapshot(operation, submissionRow);
|
|
@@ -1710,7 +1710,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
1710
1710
|
const reservationRow = yield* readReservation(operation, validated.submissionId);
|
|
1711
1711
|
if (Option.isSome(reservationRow)) {
|
|
1712
1712
|
const record = yield* decodeRecordEnvelopeText(reservationRow.value.record_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_settlement_reservations", validated.submissionId, error.message)));
|
|
1713
|
-
const settlementId = yield* Schema.
|
|
1713
|
+
const settlementId = yield* Schema.decodeEffect(SettlementReservationSnapshot.fields.settlementId)(reservationRow.value.settlement_id).pipe(Effect.mapError(internalFailure(operation)));
|
|
1714
1714
|
reservation = SettlementReservationSnapshot.make({
|
|
1715
1715
|
settlementId,
|
|
1716
1716
|
outcome: reservationRow.value.outcome,
|