@effect-agent/platform-cloudflare 0.1.0-beta.9 → 0.1.0-beta.90
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/Alarm.d.mts +188 -0
- package/dist/Alarm.mjs +451 -0
- package/dist/Alarm.mjs.map +1 -0
- package/dist/BrowserRestCapture.d.mts +35 -0
- package/dist/BrowserRestCapture.mjs +238 -0
- package/dist/BrowserRestCapture.mjs.map +1 -0
- package/dist/BrowserRestCrawl.d.mts +17 -0
- package/dist/BrowserRestCrawl.mjs +244 -0
- package/dist/BrowserRestCrawl.mjs.map +1 -0
- package/dist/CloudflareAiGateway.d.mts +64 -0
- package/dist/CloudflareAiGateway.mjs +70 -0
- package/dist/CloudflareAiGateway.mjs.map +1 -0
- package/dist/CloudflareBindings.d.mts +115 -0
- package/dist/CloudflareBindings.mjs +113 -0
- package/dist/CloudflareBindings.mjs.map +1 -0
- package/dist/CloudflareBrowser-DV6kya1H.mjs +495 -0
- package/dist/CloudflareBrowser-DV6kya1H.mjs.map +1 -0
- package/dist/CloudflareBrowser-Doe1M7R5.d.mts +80 -0
- package/dist/CloudflareBrowser.d.mts +2 -0
- package/dist/CloudflareBrowser.mjs +2 -0
- package/dist/CloudflareCodeMode.d.mts +44 -0
- package/dist/CloudflareCodeMode.mjs +616 -0
- package/dist/CloudflareCodeMode.mjs.map +1 -0
- package/dist/CloudflareConfig-f3CqTel1.d.mts +101 -0
- package/dist/CloudflareConfig.d.mts +2 -0
- package/dist/CloudflareConfig.mjs +122 -0
- package/dist/CloudflareConfig.mjs.map +1 -0
- package/dist/CloudflareMemory.d.mts +142 -0
- package/dist/CloudflareMemory.mjs +202 -0
- package/dist/CloudflareMemory.mjs.map +1 -0
- package/dist/CloudflareScheduling.d.mts +52 -0
- package/dist/CloudflareScheduling.mjs +396 -0
- package/dist/CloudflareScheduling.mjs.map +1 -0
- package/dist/CloudflareSubscriptions.d.mts +87 -0
- package/dist/CloudflareSubscriptions.mjs +530 -0
- package/dist/CloudflareSubscriptions.mjs.map +1 -0
- package/dist/CloudflareThreadClient.d.mts +1496 -0
- package/dist/CloudflareThreadClient.mjs +382 -0
- package/dist/CloudflareThreadClient.mjs.map +1 -0
- package/dist/InteractiveBrowser-DUE_m12-.d.mts +161 -0
- package/dist/InteractiveBrowser-DupDtfw2.mjs +1169 -0
- package/dist/InteractiveBrowser-DupDtfw2.mjs.map +1 -0
- package/dist/InteractiveBrowser.d.mts +2 -0
- package/dist/InteractiveBrowser.mjs +2 -0
- package/dist/ProtectedBrowser.d.mts +123 -0
- package/dist/ProtectedBrowser.mjs +1135 -0
- package/dist/ProtectedBrowser.mjs.map +1 -0
- package/dist/ThreadObject-CIbmXZCY.d.mts +812 -0
- package/dist/ThreadObject-DvRG0dDz.mjs +835 -0
- package/dist/ThreadObject-DvRG0dDz.mjs.map +1 -0
- package/dist/ThreadObject.d.mts +2 -0
- package/dist/ThreadObject.mjs +3 -0
- package/dist/WakeScheduler.d.mts +23 -0
- package/dist/WakeScheduler.mjs +57 -0
- package/dist/WakeScheduler.mjs.map +1 -0
- package/dist/boundary-BguazVkh.mjs +42 -0
- package/dist/boundary-BguazVkh.mjs.map +1 -0
- package/dist/index.d.mts +13 -1548
- package/dist/index.mjs +13 -1636
- package/dist/prepared-admission-DU0_T-ev.mjs +73 -0
- package/dist/prepared-admission-DU0_T-ev.mjs.map +1 -0
- package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
- package/package.json +1 -53
- package/src/Alarm.ts +973 -0
- package/src/BrowserRestCapture.ts +477 -0
- package/src/BrowserRestCrawl.ts +540 -0
- package/src/CloudflareAiGateway.ts +170 -0
- package/src/CloudflareBindings.ts +199 -0
- package/src/CloudflareBrowser.ts +15 -0
- package/src/{code-mode-executor.ts → CloudflareCodeMode.ts} +372 -204
- package/src/{config.ts → CloudflareConfig.ts} +9 -8
- package/src/CloudflareMemory.ts +420 -0
- package/src/CloudflareScheduling.ts +747 -0
- package/src/CloudflareSubscriptions.ts +1041 -0
- package/src/CloudflareThreadClient.ts +809 -0
- package/src/InteractiveBrowser.ts +2354 -0
- package/src/ProtectedBrowser.ts +9 -0
- package/src/ThreadObject.ts +1179 -0
- package/src/{wake-scheduler.ts → WakeScheduler.ts} +32 -26
- package/src/index.ts +12 -23
- package/src/internal/boundary.ts +55 -0
- package/src/internal/browser-quick-action.ts +857 -0
- package/src/internal/browser-session-lifecycle.ts +160 -0
- package/src/internal/layers.ts +751 -0
- package/src/internal/message-delivery.ts +152 -0
- package/src/internal/prepared-admission.ts +116 -0
- package/src/internal/progress-wait.ts +121 -0
- package/src/internal/transport.ts +44 -0
- package/src/protected-browser/binding.ts +313 -0
- package/src/protected-browser/host.ts +344 -0
- package/src/protected-browser/inspect-frame.ts +125 -0
- package/src/protected-browser/native.ts +445 -0
- package/src/protected-browser/policy.ts +821 -0
- package/dist/index.mjs.map +0 -1
- package/src/alarm.ts +0 -334
- package/src/bindings.ts +0 -145
- package/src/client.ts +0 -646
- package/src/conversation-object.ts +0 -768
- package/src/layers.ts +0 -376
- package/src/transport.ts +0 -38
package/src/Alarm.ts
ADDED
|
@@ -0,0 +1,973 @@
|
|
|
1
|
+
import {
|
|
2
|
+
Cause,
|
|
3
|
+
Clock,
|
|
4
|
+
Context,
|
|
5
|
+
DateTime,
|
|
6
|
+
Deferred,
|
|
7
|
+
Effect,
|
|
8
|
+
Exit,
|
|
9
|
+
Fiber,
|
|
10
|
+
Layer,
|
|
11
|
+
Option,
|
|
12
|
+
Random,
|
|
13
|
+
Ref,
|
|
14
|
+
Schema,
|
|
15
|
+
Semaphore,
|
|
16
|
+
Stream,
|
|
17
|
+
} from "effect";
|
|
18
|
+
import { type DurableBindingFailure } from "effect-agent/agent-registration";
|
|
19
|
+
import {
|
|
20
|
+
DurableAgentRuntime,
|
|
21
|
+
type DurableWorkerFailure,
|
|
22
|
+
type RecoveryReport,
|
|
23
|
+
} from "effect-agent/durable-agent-runtime";
|
|
24
|
+
import { ThreadId } from "effect-agent/identifiers";
|
|
25
|
+
import { SubmissionLedger, type SubmissionSnapshot } from "effect-agent/submission-ledger";
|
|
26
|
+
import {
|
|
27
|
+
ThreadProjectionMaintenance,
|
|
28
|
+
drainDue,
|
|
29
|
+
type ThreadProjectionError,
|
|
30
|
+
} from "effect-agent/thread-projection-maintenance";
|
|
31
|
+
import { SqlClient } from "effect/unstable/sql/SqlClient";
|
|
32
|
+
|
|
33
|
+
import { DurableObjectContext } from "./CloudflareBindings.ts";
|
|
34
|
+
import { CloudflareDurableRuntimeConfig } from "./CloudflareConfig.ts";
|
|
35
|
+
import { safeCauseMessage } from "./internal/boundary.ts";
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The single multiplexed Durable Object alarm (decision D-P6-2). A Durable Object has ONE
|
|
39
|
+
* alarm slot; every cadence the Node host ran on fibers (wake scan, lease expiry, settlement
|
|
40
|
+
* and abort re-checks, retry backoff) multiplexes into one idempotent maintenance pass, and
|
|
41
|
+
* the slot always holds the EARLIEST deadline any caller asked for.
|
|
42
|
+
*
|
|
43
|
+
* The alarm invariant (plan §1.4): every committed actionable mutation carries a newer durable
|
|
44
|
+
* maintenance generation and a committed alarm. Stable externally-driven waits may be
|
|
45
|
+
* nonterminal without retaining an alarm; their resolving mutation advances the generation and
|
|
46
|
+
* restores the alarm atomically.
|
|
47
|
+
*/
|
|
48
|
+
|
|
49
|
+
/** The Durable Object alarm API failed; surfaces on host entry points as a typed refusal. */
|
|
50
|
+
export class DurableAlarmError extends Schema.TaggedError<DurableAlarmError>()(
|
|
51
|
+
"DurableAlarmError",
|
|
52
|
+
{
|
|
53
|
+
operation: Schema.String,
|
|
54
|
+
message: Schema.String,
|
|
55
|
+
cause: Schema.optionalKey(Schema.Defect()),
|
|
56
|
+
},
|
|
57
|
+
) {}
|
|
58
|
+
|
|
59
|
+
const alarmFailure =
|
|
60
|
+
(operation: string) =>
|
|
61
|
+
(cause: unknown): DurableAlarmError =>
|
|
62
|
+
DurableAlarmError.make({
|
|
63
|
+
operation,
|
|
64
|
+
message: safeCauseMessage(cause, "The Cloudflare alarm API failed without a diagnostic"),
|
|
65
|
+
cause,
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
// SQL and raw KV/alarm operations share one physical SQLite transaction. Reserve its
|
|
69
|
+
// connection for each short storage operation, never around a mutation or snapshot body.
|
|
70
|
+
const makeStorageOperation = Effect.map(
|
|
71
|
+
SqlClient,
|
|
72
|
+
(sql) =>
|
|
73
|
+
<A>(operation: string, execute: () => Promise<A>) =>
|
|
74
|
+
Effect.flatMap(Effect.serviceOption(sql.transactionService), (current) => {
|
|
75
|
+
const body = Effect.uninterruptible(
|
|
76
|
+
Effect.tryPromise({ try: execute, catch: alarmFailure(operation) }),
|
|
77
|
+
);
|
|
78
|
+
|
|
79
|
+
return current._tag === "Some"
|
|
80
|
+
? body
|
|
81
|
+
: Effect.scoped(
|
|
82
|
+
Effect.andThen(sql.reserve.pipe(Effect.mapError(alarmFailure(operation))), body),
|
|
83
|
+
);
|
|
84
|
+
}),
|
|
85
|
+
);
|
|
86
|
+
|
|
87
|
+
/** `ctx.storage` alarm slot as an Effect service; storage is truth, never a memory field. */
|
|
88
|
+
export class DurableAlarmService extends Context.Service<
|
|
89
|
+
DurableAlarmService,
|
|
90
|
+
{
|
|
91
|
+
/** The scheduled deadline in epoch milliseconds, if any. */
|
|
92
|
+
readonly scheduled: Effect.Effect<Option.Option<number>, DurableAlarmError>;
|
|
93
|
+
/** Replace the slot with this deadline. */
|
|
94
|
+
readonly scheduleAt: (epochMillis: number) => Effect.Effect<void, DurableAlarmError>;
|
|
95
|
+
/** Keep the EARLIER of the existing deadline and this one (the multiplexing rule). */
|
|
96
|
+
readonly ensureScheduledBy: (epochMillis: number) => Effect.Effect<void, DurableAlarmError>;
|
|
97
|
+
/**
|
|
98
|
+
* Arm an immediate alarm (the durable, coalescing local wake) — DEFERRED while a
|
|
99
|
+
* maintenance pass is executing. Workerd cancels an in-flight alarm handler when a new
|
|
100
|
+
* EARLIER deadline is written during its execution (`requestScheduledAlarm`), and the
|
|
101
|
+
* maintenance pass runs INSIDE the alarm handler: an immediate wake landing mid-pass
|
|
102
|
+
* (a routed port mutation, a sibling's `wake()`, the coordinator's own local notify)
|
|
103
|
+
* would kill the running Attempt — manufacturing an ownership loss no real eviction
|
|
104
|
+
* caused, and routing open uncertain-class Tool Calls into spurious Unknown Outcomes.
|
|
105
|
+
* Deferral is contract-safe: wakes are droppable hints, every mutating entry point
|
|
106
|
+
* pre-arms BEFORE its first durable mutation (the alarm invariant never rests on this
|
|
107
|
+
* call). The pass's durable generation check observes any racing mutation, so the
|
|
108
|
+
* in-memory hint does not need to be flushed after a stable wait is acknowledged.
|
|
109
|
+
*/
|
|
110
|
+
readonly scheduleNow: Effect.Effect<void, DurableAlarmError>;
|
|
111
|
+
/**
|
|
112
|
+
* Run one maintenance pass with wake deferral (see `scheduleNow`). Calls made while `body`
|
|
113
|
+
* executes are droppable promptness hints; correctness rests on the durable generation.
|
|
114
|
+
*/
|
|
115
|
+
readonly withWakesDeferred: <A, E, R>(body: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
|
|
116
|
+
/** Clear the slot; correctness-sensitive clears live in maintenance generation transactions. */
|
|
117
|
+
readonly cancel: Effect.Effect<void, DurableAlarmError>;
|
|
118
|
+
}
|
|
119
|
+
>()("@effect-agent/platform-cloudflare/DurableAlarmService") {
|
|
120
|
+
static readonly layer: Layer.Layer<DurableAlarmService, never, DurableObjectContext | SqlClient> =
|
|
121
|
+
Layer.effect(DurableAlarmService)(
|
|
122
|
+
Effect.gen(function* () {
|
|
123
|
+
const { ctx } = yield* DurableObjectContext;
|
|
124
|
+
/**
|
|
125
|
+
* In-memory pass bookkeeping — a pure CACHE, never state: a fresh incarnation has no
|
|
126
|
+
* running pass, and a deferred wake lost to eviction was only ever a promptness hint
|
|
127
|
+
* on top of the already-committed pre-armed alarm.
|
|
128
|
+
*/
|
|
129
|
+
const runningPasses = yield* Ref.make(0);
|
|
130
|
+
|
|
131
|
+
const storageOperation = yield* makeStorageOperation;
|
|
132
|
+
|
|
133
|
+
const scheduled = storageOperation("get alarm", () => ctx.storage.getAlarm()).pipe(
|
|
134
|
+
Effect.map((deadline) =>
|
|
135
|
+
deadline === null ? Option.none<number>() : Option.some(deadline),
|
|
136
|
+
),
|
|
137
|
+
);
|
|
138
|
+
|
|
139
|
+
const scheduleAt = (epochMillis: number) =>
|
|
140
|
+
storageOperation("set alarm", () => ctx.storage.setAlarm(epochMillis));
|
|
141
|
+
|
|
142
|
+
const ensureScheduledBy = (epochMillis: number) =>
|
|
143
|
+
storageOperation("ensure alarm", () =>
|
|
144
|
+
ctx.storage.transaction(async (transaction) => {
|
|
145
|
+
const existing = await transaction.getAlarm();
|
|
146
|
+
|
|
147
|
+
if (existing === null || existing > epochMillis) {
|
|
148
|
+
await transaction.setAlarm(epochMillis);
|
|
149
|
+
}
|
|
150
|
+
}),
|
|
151
|
+
);
|
|
152
|
+
|
|
153
|
+
const armNow = Clock.currentTimeMillis.pipe(
|
|
154
|
+
Effect.flatMap((now) => ensureScheduledBy(now)),
|
|
155
|
+
);
|
|
156
|
+
|
|
157
|
+
const scheduleNow = Ref.get(runningPasses).pipe(
|
|
158
|
+
Effect.flatMap((passes) => (passes > 0 ? Effect.void : armNow)),
|
|
159
|
+
);
|
|
160
|
+
|
|
161
|
+
const withWakesDeferred = <A, E, R>(body: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
|
|
162
|
+
Ref.update(runningPasses, (passes) => passes + 1).pipe(
|
|
163
|
+
Effect.andThen(body),
|
|
164
|
+
Effect.ensuring(Ref.update(runningPasses, (passes) => passes - 1)),
|
|
165
|
+
);
|
|
166
|
+
|
|
167
|
+
const cancel = storageOperation("delete alarm", () => ctx.storage.deleteAlarm());
|
|
168
|
+
|
|
169
|
+
return DurableAlarmService.of({
|
|
170
|
+
scheduled,
|
|
171
|
+
scheduleAt,
|
|
172
|
+
ensureScheduledBy,
|
|
173
|
+
scheduleNow,
|
|
174
|
+
withWakesDeferred,
|
|
175
|
+
cancel,
|
|
176
|
+
});
|
|
177
|
+
}),
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** What one maintenance pass did — auditable evidence mirroring `NodeDurableHost`'s report. */
|
|
182
|
+
export class MaintenancePassReport extends Schema.Class<MaintenancePassReport>(
|
|
183
|
+
"@effect-agent/platform-cloudflare/MaintenancePassReport",
|
|
184
|
+
)({
|
|
185
|
+
/** `caught-up` ran no runtime work (publication may be pending); `actionable` ran recovery. */
|
|
186
|
+
phase: Schema.Literals(["caught-up", "actionable"]),
|
|
187
|
+
/** Recovery decisions executed (or deferred) BEFORE any new claim in this pass. */
|
|
188
|
+
recovered: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
|
|
189
|
+
/** Whether the head Attempt settled. Joined input may settle with that head. */
|
|
190
|
+
settled: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
|
|
191
|
+
/** Submissions still nonterminal after the pass (suspended/unknown lanes stay honest). */
|
|
192
|
+
nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
|
|
193
|
+
/** `rearmed` for dirty/autonomous work, `cleared` for stable waits or settlement. */
|
|
194
|
+
alarm: Schema.Literals(["rearmed", "cleared"]),
|
|
195
|
+
}) {}
|
|
196
|
+
|
|
197
|
+
/** Fault boundaries around every maintenance-owned durable mutation. */
|
|
198
|
+
export type ThreadMaintenanceFailpointLocation =
|
|
199
|
+
| "maintenance:dirty:before"
|
|
200
|
+
| "maintenance:dirty:after"
|
|
201
|
+
| "maintenance:mutation:armed"
|
|
202
|
+
| "maintenance:mutation:finished"
|
|
203
|
+
| "maintenance:ensure:before"
|
|
204
|
+
| "maintenance:ensure:after"
|
|
205
|
+
| "maintenance:begin:before"
|
|
206
|
+
| "maintenance:begin:after"
|
|
207
|
+
| "maintenance:select:before"
|
|
208
|
+
| "maintenance:select:after"
|
|
209
|
+
| "maintenance:finish:before"
|
|
210
|
+
| "maintenance:finish:after";
|
|
211
|
+
|
|
212
|
+
export type ThreadMaintenanceFailpointHandler = (
|
|
213
|
+
location: ThreadMaintenanceFailpointLocation,
|
|
214
|
+
) => Effect.Effect<void>;
|
|
215
|
+
|
|
216
|
+
/** Test-only fault authority; production uses the inert layer. */
|
|
217
|
+
export class ThreadMaintenanceFailpoint extends Context.Service<
|
|
218
|
+
ThreadMaintenanceFailpoint,
|
|
219
|
+
{
|
|
220
|
+
readonly hit: ThreadMaintenanceFailpointHandler;
|
|
221
|
+
}
|
|
222
|
+
>()("@effect-agent/platform-cloudflare/ThreadMaintenanceFailpoint") {
|
|
223
|
+
static readonly layer = Layer.succeed(this)({ hit: () => Effect.void });
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Durable host publication of canonical records and ledger approval/abort/resolution intents.
|
|
228
|
+
* The host owns schema-versioned cursors, destination idempotency and acknowledgement. Delivery
|
|
229
|
+
* is at least once. Hooks must not write the alarm slot or mutate the supplied raw source ports.
|
|
230
|
+
*
|
|
231
|
+
* `invalidate`, `prepareGeneration` and `pendingDeadline` must be bounded local operations.
|
|
232
|
+
* `prepareGeneration` durably invalidates a scan only when its generation changes; repeated
|
|
233
|
+
* calls must preserve partial scan progress. It runs with no source mutation in flight.
|
|
234
|
+
* `drain` performs bounded delivery and persists retries before returning. A pending deadline
|
|
235
|
+
* defers runtime recovery/Attempts, allowing committed host publications to drain first.
|
|
236
|
+
* Unexpected hook failures leave the prearmed generation for retry. Hooks acquire per-call
|
|
237
|
+
* resources with Effect.scoped; Layer construction owns incarnation resources (eviction need
|
|
238
|
+
* not run finalizers). Do not hold a local hook behind network I/O or call back into producers.
|
|
239
|
+
*/
|
|
240
|
+
export interface ThreadPublicationService {
|
|
241
|
+
readonly invalidate: Effect.Effect<void, DurableAlarmError>;
|
|
242
|
+
readonly prepareGeneration: (generation: bigint) => Effect.Effect<void, DurableAlarmError>;
|
|
243
|
+
readonly drain: Effect.Effect<void, DurableAlarmError>;
|
|
244
|
+
readonly pendingDeadline: Effect.Effect<Option.Option<number>, DurableAlarmError>;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Opt in with `ThreadObject.layer(registrations, { publication: Layer.effect(ThreadPublication)(...) })`. */
|
|
248
|
+
export class ThreadPublication extends Context.Service<
|
|
249
|
+
ThreadPublication,
|
|
250
|
+
ThreadPublicationService
|
|
251
|
+
>()("@effect-agent/platform-cloudflare/ThreadPublication") {
|
|
252
|
+
static readonly layer = Layer.succeed(this)({
|
|
253
|
+
invalidate: Effect.void,
|
|
254
|
+
prepareGeneration: () => Effect.void,
|
|
255
|
+
drain: Effect.void,
|
|
256
|
+
pendingDeadline: Effect.succeed(Option.none()),
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Host-assembled message recovery, supplied by ThreadObject.layer even when the application
|
|
262
|
+
* rebuilds ThreadMaintenance. These obligations outlive source Runs and never defer a ready
|
|
263
|
+
* source Attempt while a destination is processing an accepted message.
|
|
264
|
+
*/
|
|
265
|
+
export const ThreadMessageDelivery = Context.Reference<{
|
|
266
|
+
readonly drain: Effect.Effect<void, DurableAlarmError>;
|
|
267
|
+
/** Drain inserts and due retries during source work, finishing the bounded wave on completion. */
|
|
268
|
+
readonly drainUntil?: (
|
|
269
|
+
finished: Deferred.Deferred<void>,
|
|
270
|
+
) => Effect.Effect<void, DurableAlarmError>;
|
|
271
|
+
readonly pendingDeadline: Effect.Effect<Option.Option<number>, DurableAlarmError>;
|
|
272
|
+
}>("@effect-agent/platform-cloudflare/ThreadMessageDelivery", {
|
|
273
|
+
defaultValue: () => ({ drain: Effect.void, pendingDeadline: Effect.succeed(Option.none()) }),
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Application obligations sharing this Object's alarm. The deadline read is local and
|
|
278
|
+
* read-only. Drain beside the native Attempt and always finish one initial bounded wave,
|
|
279
|
+
* even when `finished` was already signalled. Then stop starting new waves on that signal
|
|
280
|
+
* and finish the bounded current wave before returning. Native maintenance joins that work
|
|
281
|
+
* before acknowledging a generation. Mutations use the same ThreadMutationGate; hooks never
|
|
282
|
+
* write the raw alarm slot. Pending host work does not defer a ready model Attempt.
|
|
283
|
+
*/
|
|
284
|
+
export const ThreadHostMaintenance = Context.Reference<{
|
|
285
|
+
readonly pendingDeadline: Effect.Effect<Option.Option<number>, DurableAlarmError>;
|
|
286
|
+
readonly drainUntil: (
|
|
287
|
+
finished: Deferred.Deferred<void>,
|
|
288
|
+
) => Effect.Effect<void, DurableAlarmError>;
|
|
289
|
+
}>("@effect-agent/platform-cloudflare/ThreadHostMaintenance", {
|
|
290
|
+
defaultValue: () => ({
|
|
291
|
+
pendingDeadline: Effect.succeed(Option.none()),
|
|
292
|
+
drainUntil: () => Effect.void,
|
|
293
|
+
}),
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
const earliestDeadline = (
|
|
297
|
+
left: Option.Option<number>,
|
|
298
|
+
right: Option.Option<number>,
|
|
299
|
+
): Option.Option<number> =>
|
|
300
|
+
Option.isSome(left)
|
|
301
|
+
? Option.isSome(right)
|
|
302
|
+
? Option.some(Math.min(left.value, right.value))
|
|
303
|
+
: left
|
|
304
|
+
: right;
|
|
305
|
+
|
|
306
|
+
/** @internal A committed source operation must not become a failed operation because delivery failed. */
|
|
307
|
+
export const publishCommitted = Effect.gen(function* () {
|
|
308
|
+
const publication = yield* ThreadPublication;
|
|
309
|
+
|
|
310
|
+
yield* publication.invalidate.pipe(Effect.andThen(publication.drain));
|
|
311
|
+
}).pipe(
|
|
312
|
+
Effect.catchCause((cause) =>
|
|
313
|
+
Cause.hasInterrupts(cause)
|
|
314
|
+
? Effect.interrupt
|
|
315
|
+
: Effect.logError("Thread publication deferred after source commit", cause),
|
|
316
|
+
),
|
|
317
|
+
);
|
|
318
|
+
|
|
319
|
+
const MaintenanceGeneration = Schema.BigIntFromString.check(
|
|
320
|
+
Schema.isGreaterThanOrEqualToBigInt(0n),
|
|
321
|
+
);
|
|
322
|
+
|
|
323
|
+
/** Versioned, platform-private maintenance state stored through Durable Object KV. */
|
|
324
|
+
class ThreadMaintenanceState extends Schema.Class<ThreadMaintenanceState>(
|
|
325
|
+
"@effect-agent/platform-cloudflare/ThreadMaintenanceState",
|
|
326
|
+
)({
|
|
327
|
+
schemaVersion: Schema.Literal(1),
|
|
328
|
+
dirty: MaintenanceGeneration,
|
|
329
|
+
processed: MaintenanceGeneration,
|
|
330
|
+
nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
|
|
331
|
+
/** One physical-owner cursor; old single-lane records need no conversion. */
|
|
332
|
+
lastServedThreadId: Schema.optionalKey(ThreadId),
|
|
333
|
+
}) {}
|
|
334
|
+
|
|
335
|
+
const MAINTENANCE_STATE_KEY = "effect-agent:thread-maintenance:v1";
|
|
336
|
+
const decodeMaintenanceState = Schema.decodeUnknownSync(ThreadMaintenanceState);
|
|
337
|
+
const encodeMaintenanceState = Schema.encodeSync(ThreadMaintenanceState);
|
|
338
|
+
|
|
339
|
+
const initialMaintenanceState = (): ThreadMaintenanceState =>
|
|
340
|
+
ThreadMaintenanceState.make({
|
|
341
|
+
schemaVersion: 1,
|
|
342
|
+
// Bootstrap Objects created by the pre-generation release without scanning the ledger in
|
|
343
|
+
// the constructor. One useful pass classifies and acknowledges any existing obligation.
|
|
344
|
+
dirty: 1n,
|
|
345
|
+
processed: 0n,
|
|
346
|
+
nonterminal: 0,
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
const readMaintenanceState = async (
|
|
350
|
+
transaction: DurableObjectTransaction,
|
|
351
|
+
): Promise<{ readonly state: ThreadMaintenanceState; readonly initialized: boolean }> => {
|
|
352
|
+
const encoded = await transaction.get(MAINTENANCE_STATE_KEY);
|
|
353
|
+
|
|
354
|
+
return encoded === undefined
|
|
355
|
+
? { state: initialMaintenanceState(), initialized: false }
|
|
356
|
+
: { state: decodeMaintenanceState(encoded), initialized: true };
|
|
357
|
+
};
|
|
358
|
+
|
|
359
|
+
const ensureTransactionAlarmBy = async (
|
|
360
|
+
transaction: DurableObjectTransaction,
|
|
361
|
+
deadline: number,
|
|
362
|
+
): Promise<void> => {
|
|
363
|
+
const scheduled = await transaction.getAlarm();
|
|
364
|
+
|
|
365
|
+
if (scheduled === null || scheduled > deadline) {
|
|
366
|
+
await transaction.setAlarm(deadline);
|
|
367
|
+
}
|
|
368
|
+
};
|
|
369
|
+
|
|
370
|
+
const stableExternalWait = (
|
|
371
|
+
snapshot: SubmissionSnapshot,
|
|
372
|
+
reports: ReadonlyMap<string, RecoveryReport>,
|
|
373
|
+
): boolean => {
|
|
374
|
+
const decision = reports.get(snapshot.submissionId)?.decision._tag;
|
|
375
|
+
|
|
376
|
+
// An accepted abort still owes cleanup/settlement even if its claim was deferred this pass.
|
|
377
|
+
if (decision === "SettleAborted") return false;
|
|
378
|
+
switch (snapshot.state) {
|
|
379
|
+
case "suspended":
|
|
380
|
+
case "joined":
|
|
381
|
+
return true;
|
|
382
|
+
case "unknown":
|
|
383
|
+
return decision === "AwaitUnknownResolution" || decision === "MarkUnknown";
|
|
384
|
+
case "admitted":
|
|
385
|
+
return reports.get(snapshot.submissionId)?.decision._tag === "AwaitParentEstablishment";
|
|
386
|
+
case "input-applied":
|
|
387
|
+
case "joining":
|
|
388
|
+
case "ready":
|
|
389
|
+
case "running":
|
|
390
|
+
case "settled":
|
|
391
|
+
case "terminalizing":
|
|
392
|
+
return false;
|
|
393
|
+
}
|
|
394
|
+
};
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Shared prearm/acknowledgement boundary for ingress and runtime-owned producers.
|
|
398
|
+
* `ThreadObject.layer` provides this same instance in its Services. Rebuilt runtime/maintenance
|
|
399
|
+
* Layers must reuse that instance; a second gate cannot observe the native producers' activity.
|
|
400
|
+
*/
|
|
401
|
+
export class ThreadMutationGate extends Context.Service<
|
|
402
|
+
ThreadMutationGate,
|
|
403
|
+
{
|
|
404
|
+
readonly withMutation: <A, E, R>(
|
|
405
|
+
body: Effect.Effect<A, E, R>,
|
|
406
|
+
/** Indexed host work has its own durable deadline and does not invalidate ledger recovery. */
|
|
407
|
+
options?: { readonly invalidatesRecovery: boolean },
|
|
408
|
+
) => Effect.Effect<A, E | DurableAlarmError, R>;
|
|
409
|
+
readonly withSnapshot: <A, E, R>(
|
|
410
|
+
body: (active: number) => Effect.Effect<A, E, R>,
|
|
411
|
+
) => Effect.Effect<A, E, R>;
|
|
412
|
+
}
|
|
413
|
+
>()("@effect-agent/platform-cloudflare/internal/ThreadMutationGate") {
|
|
414
|
+
static readonly layer = Layer.effect(this)(
|
|
415
|
+
Effect.gen(function* () {
|
|
416
|
+
const { ctx } = yield* DurableObjectContext;
|
|
417
|
+
const config = yield* CloudflareDurableRuntimeConfig;
|
|
418
|
+
const failpoint = yield* ThreadMaintenanceFailpoint;
|
|
419
|
+
// A fresh incarnation has no live mutations; durable generations survive eviction.
|
|
420
|
+
const activeMutations = yield* Ref.make(0);
|
|
421
|
+
const generationGate = yield* Semaphore.make(1);
|
|
422
|
+
const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));
|
|
423
|
+
|
|
424
|
+
const runTransaction = yield* makeStorageOperation;
|
|
425
|
+
|
|
426
|
+
const beginMutation = Effect.fn("ThreadMaintenance.beginMutation")(function* (
|
|
427
|
+
invalidatesRecovery: boolean,
|
|
428
|
+
) {
|
|
429
|
+
yield* failpoint.hit("maintenance:dirty:before");
|
|
430
|
+
const now = yield* Clock.currentTimeMillis;
|
|
431
|
+
|
|
432
|
+
yield* runTransaction("advance maintenance generation", () =>
|
|
433
|
+
ctx.storage.transaction(async (transaction) => {
|
|
434
|
+
const { state, initialized } = await readMaintenanceState(transaction);
|
|
435
|
+
|
|
436
|
+
const next = ThreadMaintenanceState.make({
|
|
437
|
+
...state,
|
|
438
|
+
dirty: state.dirty + (invalidatesRecovery ? 1n : 0n),
|
|
439
|
+
});
|
|
440
|
+
|
|
441
|
+
if (invalidatesRecovery || !initialized)
|
|
442
|
+
await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));
|
|
443
|
+
// The earliest configured retry bounds a newly actionable mutation without relying
|
|
444
|
+
// on its best-effort immediate wake hint.
|
|
445
|
+
await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);
|
|
446
|
+
}),
|
|
447
|
+
);
|
|
448
|
+
yield* failpoint.hit("maintenance:dirty:after");
|
|
449
|
+
yield* Ref.update(activeMutations, (active) => active + 1);
|
|
450
|
+
});
|
|
451
|
+
|
|
452
|
+
const endMutation = generationGate.withPermit(
|
|
453
|
+
Ref.update(activeMutations, (active) => Math.max(0, active - 1)),
|
|
454
|
+
);
|
|
455
|
+
|
|
456
|
+
const withMutation = <A, E, R>(
|
|
457
|
+
body: Effect.Effect<A, E, R>,
|
|
458
|
+
options?: { readonly invalidatesRecovery: boolean },
|
|
459
|
+
): Effect.Effect<A, E | DurableAlarmError, R> =>
|
|
460
|
+
Effect.acquireUseRelease(
|
|
461
|
+
generationGate.withPermit(beginMutation(options?.invalidatesRecovery ?? true)),
|
|
462
|
+
() =>
|
|
463
|
+
failpoint.hit("maintenance:mutation:armed").pipe(
|
|
464
|
+
Effect.andThen(body),
|
|
465
|
+
Effect.tap(() => failpoint.hit("maintenance:mutation:finished")),
|
|
466
|
+
),
|
|
467
|
+
() => endMutation,
|
|
468
|
+
);
|
|
469
|
+
|
|
470
|
+
return ThreadMutationGate.of({
|
|
471
|
+
withMutation,
|
|
472
|
+
withSnapshot: (body) =>
|
|
473
|
+
generationGate.withPermit(Effect.flatMap(Ref.get(activeMutations), body)),
|
|
474
|
+
});
|
|
475
|
+
}),
|
|
476
|
+
);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
export type MaintenancePassFailure =
|
|
480
|
+
| DurableWorkerFailure
|
|
481
|
+
| DurableBindingFailure
|
|
482
|
+
| DurableAlarmError
|
|
483
|
+
| ThreadProjectionError;
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Incremental, quiescent maintenance over a durable dirty/processed generation (issue #93).
|
|
487
|
+
*
|
|
488
|
+
* `pass` = generation snapshot/pre-arm → recovery → one head Attempt → generation acknowledgement:
|
|
489
|
+
*
|
|
490
|
+
* 1. One storage transaction reads dirty/processed and re-arms before work. A caught-up forced
|
|
491
|
+
* alarm takes an O(1) path without recovery, ledger scans, or canonical-history reads.
|
|
492
|
+
* 2. Recovery strictly precedes a new claim. One head Attempt advances the lane and requests
|
|
493
|
+
* a safe yield after ten minutes. The whole event has a fourteen-minute cooperative timeout.
|
|
494
|
+
* 3. The final transaction acknowledges only the generation observed at pass start. A racing
|
|
495
|
+
* mutation therefore remains `dirty > processed` and retains its atomically-established alarm.
|
|
496
|
+
* 4. Stable external waits acknowledge and clear. Autonomous retry, indeterminate, and lease
|
|
497
|
+
* recovery states leave their generation dirty and retain bounded backoff rearming.
|
|
498
|
+
*/
|
|
499
|
+
export class ThreadMaintenance extends Context.Service<
|
|
500
|
+
ThreadMaintenance,
|
|
501
|
+
{
|
|
502
|
+
/** One idempotent maintenance pass; failures propagate so workerd retries the alarm. */
|
|
503
|
+
readonly pass: Effect.Effect<MaintenancePassReport, MaintenancePassFailure>;
|
|
504
|
+
/**
|
|
505
|
+
* Constructor gate: initialize/inspect only the O(1) maintenance record and ensure a dirty
|
|
506
|
+
* generation has an alarm. It never scans the ledger or canonical history.
|
|
507
|
+
*/
|
|
508
|
+
readonly ensureAlarm: Effect.Effect<void, MaintenancePassFailure>;
|
|
509
|
+
/**
|
|
510
|
+
* Serialize the pre-arm boundary with pass acknowledgement, advance the durable dirty
|
|
511
|
+
* generation and arm the alarm in one transaction BEFORE running the caller's mutation.
|
|
512
|
+
* A pass cannot acknowledge while that mutation remains in flight.
|
|
513
|
+
*/
|
|
514
|
+
readonly withMutation: <A, E, R>(
|
|
515
|
+
body: Effect.Effect<A, E, R>,
|
|
516
|
+
) => Effect.Effect<A, E | DurableAlarmError, R>;
|
|
517
|
+
}
|
|
518
|
+
>()("@effect-agent/platform-cloudflare/ThreadMaintenance") {
|
|
519
|
+
static readonly layer: Layer.Layer<
|
|
520
|
+
ThreadMaintenance,
|
|
521
|
+
never,
|
|
522
|
+
| ThreadMutationGate
|
|
523
|
+
| ThreadPublication
|
|
524
|
+
| ThreadProjectionMaintenance
|
|
525
|
+
| DurableAgentRuntime
|
|
526
|
+
| SubmissionLedger
|
|
527
|
+
| DurableAlarmService
|
|
528
|
+
| ThreadMaintenanceFailpoint
|
|
529
|
+
| CloudflareDurableRuntimeConfig
|
|
530
|
+
| DurableObjectContext
|
|
531
|
+
| SqlClient
|
|
532
|
+
> = Layer.effect(ThreadMaintenance)(
|
|
533
|
+
Effect.gen(function* () {
|
|
534
|
+
const runtime = yield* DurableAgentRuntime;
|
|
535
|
+
const ledger = yield* SubmissionLedger;
|
|
536
|
+
const alarm = yield* DurableAlarmService;
|
|
537
|
+
const config = yield* CloudflareDurableRuntimeConfig;
|
|
538
|
+
const { ctx } = yield* DurableObjectContext;
|
|
539
|
+
const failpoint = yield* ThreadMaintenanceFailpoint;
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* Consecutive no-progress passes — an in-memory CACHE, not state: a fresh incarnation
|
|
543
|
+
* restarts at zero and merely re-arms sooner than a long-lived one would have.
|
|
544
|
+
*/
|
|
545
|
+
const stalls = yield* Ref.make(0);
|
|
546
|
+
const mutations = yield* ThreadMutationGate;
|
|
547
|
+
const publication = yield* ThreadPublication;
|
|
548
|
+
const projection = yield* ThreadProjectionMaintenance;
|
|
549
|
+
const messages = yield* ThreadMessageDelivery;
|
|
550
|
+
const host = yield* ThreadHostMaintenance;
|
|
551
|
+
|
|
552
|
+
// A broken disposable index still needs a retry alarm and must not prevent startup.
|
|
553
|
+
const projectionDeadline = projection.pendingDeadline.pipe(
|
|
554
|
+
Effect.catchCauseIf(
|
|
555
|
+
(cause) => !Cause.hasInterrupts(cause),
|
|
556
|
+
(cause) =>
|
|
557
|
+
Effect.logError("Thread projection deadline unavailable", cause).pipe(
|
|
558
|
+
Effect.as(Option.some(0)),
|
|
559
|
+
),
|
|
560
|
+
),
|
|
561
|
+
);
|
|
562
|
+
|
|
563
|
+
const pendingDeadline = Effect.gen(function* () {
|
|
564
|
+
return earliestDeadline(
|
|
565
|
+
earliestDeadline(yield* publication.pendingDeadline, yield* messages.pendingDeadline),
|
|
566
|
+
earliestDeadline(yield* projectionDeadline, yield* host.pendingDeadline),
|
|
567
|
+
);
|
|
568
|
+
});
|
|
569
|
+
|
|
570
|
+
const maintenancePassGate = yield* Semaphore.make(1);
|
|
571
|
+
const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));
|
|
572
|
+
|
|
573
|
+
const runTransaction = yield* makeStorageOperation;
|
|
574
|
+
|
|
575
|
+
const ensureAlarm = Effect.fn("ThreadMaintenance.ensureAlarm")(function* () {
|
|
576
|
+
yield* failpoint.hit("maintenance:ensure:before");
|
|
577
|
+
const now = yield* Clock.currentTimeMillis;
|
|
578
|
+
|
|
579
|
+
yield* runTransaction("ensure maintenance alarm", () =>
|
|
580
|
+
ctx.storage.transaction(async (transaction) => {
|
|
581
|
+
const { state, initialized } = await readMaintenanceState(transaction);
|
|
582
|
+
|
|
583
|
+
if (!initialized) {
|
|
584
|
+
await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));
|
|
585
|
+
}
|
|
586
|
+
if (state.dirty > state.processed) {
|
|
587
|
+
await ensureTransactionAlarmBy(transaction, now + config.wakeScanInterval);
|
|
588
|
+
}
|
|
589
|
+
}),
|
|
590
|
+
);
|
|
591
|
+
const deadline = yield* pendingDeadline;
|
|
592
|
+
|
|
593
|
+
if (Option.isSome(deadline)) {
|
|
594
|
+
yield* runTransaction("ensure publication alarm", () =>
|
|
595
|
+
ctx.storage.transaction((transaction) =>
|
|
596
|
+
ensureTransactionAlarmBy(
|
|
597
|
+
transaction,
|
|
598
|
+
Math.max(now + minimumAlarmDelay, deadline.value),
|
|
599
|
+
),
|
|
600
|
+
),
|
|
601
|
+
);
|
|
602
|
+
}
|
|
603
|
+
yield* failpoint.hit("maintenance:ensure:after");
|
|
604
|
+
});
|
|
605
|
+
|
|
606
|
+
const beginPass = Effect.fn("ThreadMaintenance.beginPass")(function* () {
|
|
607
|
+
yield* failpoint.hit("maintenance:begin:before");
|
|
608
|
+
const now = yield* Clock.currentTimeMillis;
|
|
609
|
+
|
|
610
|
+
const result = yield* runTransaction("begin maintenance pass", () =>
|
|
611
|
+
ctx.storage.transaction(async (transaction) => {
|
|
612
|
+
const { state, initialized } = await readMaintenanceState(transaction);
|
|
613
|
+
|
|
614
|
+
if (!initialized) {
|
|
615
|
+
await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));
|
|
616
|
+
}
|
|
617
|
+
if (state.processed >= state.dirty) {
|
|
618
|
+
// Prearm even a publication-only pass before invoking any host hook.
|
|
619
|
+
await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);
|
|
620
|
+
|
|
621
|
+
return { _tag: "CaughtUp" as const, nonterminal: state.nonterminal };
|
|
622
|
+
}
|
|
623
|
+
// Pre-arm the earliest retry before recovery. A successful finish may move this slot
|
|
624
|
+
// LATER to its bounded backoff, which does not cancel the running handler.
|
|
625
|
+
await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);
|
|
626
|
+
|
|
627
|
+
return {
|
|
628
|
+
_tag: "Actionable" as const,
|
|
629
|
+
generation: state.dirty,
|
|
630
|
+
nonterminal: state.nonterminal,
|
|
631
|
+
};
|
|
632
|
+
}),
|
|
633
|
+
);
|
|
634
|
+
|
|
635
|
+
yield* failpoint.hit("maintenance:begin:after");
|
|
636
|
+
|
|
637
|
+
return result;
|
|
638
|
+
});
|
|
639
|
+
|
|
640
|
+
const rearmDelay = Effect.fn("ThreadMaintenance.rearmDelay")(function* (progressed: boolean) {
|
|
641
|
+
const priorStalls = yield* Ref.getAndUpdate(stalls, (count) =>
|
|
642
|
+
progressed ? 0 : count + 1,
|
|
643
|
+
);
|
|
644
|
+
|
|
645
|
+
if (progressed) return config.alarmBackoffBase;
|
|
646
|
+
const exponent = Math.min(priorStalls, 30);
|
|
647
|
+
const backoff = Math.min(config.alarmBackoffCap, config.alarmBackoffBase * 2 ** exponent);
|
|
648
|
+
const jitter = yield* Random.next;
|
|
649
|
+
// Full jitter over [backoff/2, backoff]: desynchronizes retry storms without ever
|
|
650
|
+
// waiting longer than the deterministic bound.
|
|
651
|
+
const jittered = Math.ceil(backoff / 2 + (backoff / 2) * jitter);
|
|
652
|
+
|
|
653
|
+
return Math.min(jittered, config.wakeScanInterval);
|
|
654
|
+
});
|
|
655
|
+
|
|
656
|
+
const pass = Effect.fn("ThreadMaintenance.pass")(function* (
|
|
657
|
+
yieldAfter: DateTime.Utc,
|
|
658
|
+
): Effect.fn.Return<MaintenancePassReport, MaintenancePassFailure> {
|
|
659
|
+
const annotate = (report: MaintenancePassReport) =>
|
|
660
|
+
Effect.annotateCurrentSpan({
|
|
661
|
+
phase: report.phase,
|
|
662
|
+
recovered: report.recovered,
|
|
663
|
+
settled: report.settled,
|
|
664
|
+
nonterminal: report.nonterminal,
|
|
665
|
+
alarm: report.alarm,
|
|
666
|
+
}).pipe(Effect.as(report));
|
|
667
|
+
|
|
668
|
+
const started = yield* mutations.withSnapshot((activeAtStart) =>
|
|
669
|
+
Effect.gen(function* () {
|
|
670
|
+
const generation = yield* beginPass();
|
|
671
|
+
|
|
672
|
+
if (generation._tag === "Actionable" && activeAtStart === 0) {
|
|
673
|
+
// The gate excludes a producer starting between the snapshot and certification.
|
|
674
|
+
yield* publication.prepareGeneration(generation.generation);
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
return { ...generation, activeAtStart };
|
|
678
|
+
}),
|
|
679
|
+
);
|
|
680
|
+
|
|
681
|
+
// Deliver beside source work, including messages inserted by the running Attempt.
|
|
682
|
+
// Slow destination RPCs never consume the source execution window. Stop starting
|
|
683
|
+
// waves when source work ends, then join the bounded current wave before acknowledgement.
|
|
684
|
+
const deliveryFinished = yield* Deferred.make<void>();
|
|
685
|
+
|
|
686
|
+
const delivery = yield* Effect.forkChild(
|
|
687
|
+
messages.drainUntil?.(deliveryFinished) ?? messages.drain,
|
|
688
|
+
);
|
|
689
|
+
|
|
690
|
+
const hostWork = yield* Effect.forkChild(host.drainUntil(deliveryFinished));
|
|
691
|
+
|
|
692
|
+
const finishDelivery = Deferred.succeed(deliveryFinished, undefined).pipe(
|
|
693
|
+
Effect.andThen(Fiber.awaitAll([delivery, hostWork])),
|
|
694
|
+
Effect.flatMap((outcomes) =>
|
|
695
|
+
Effect.forEach(outcomes, (outcome) => outcome, { discard: true }),
|
|
696
|
+
),
|
|
697
|
+
);
|
|
698
|
+
|
|
699
|
+
// Capture derived-index failures until canonical work has had its turn. Interruption
|
|
700
|
+
// still stops the event; ordinary failures and defects retain the prearmed generation.
|
|
701
|
+
const projected = yield* Effect.exit(
|
|
702
|
+
drainDue.pipe(Effect.provideService(ThreadProjectionMaintenance, projection)),
|
|
703
|
+
);
|
|
704
|
+
|
|
705
|
+
if (Exit.isFailure(projected) && Cause.hasInterrupts(projected.cause))
|
|
706
|
+
return yield* Effect.failCause(projected.cause);
|
|
707
|
+
const deadline = yield* publication.pendingDeadline;
|
|
708
|
+
|
|
709
|
+
if (
|
|
710
|
+
started._tag === "Actionable" ||
|
|
711
|
+
(Option.isSome(deadline) && deadline.value <= (yield* Clock.currentTimeMillis))
|
|
712
|
+
) {
|
|
713
|
+
yield* publication.drain;
|
|
714
|
+
}
|
|
715
|
+
const pending = yield* publication.pendingDeadline;
|
|
716
|
+
|
|
717
|
+
if (started._tag === "CaughtUp" || Option.isSome(pending)) {
|
|
718
|
+
yield* finishDelivery;
|
|
719
|
+
if (Exit.isFailure(projected)) return yield* Effect.failCause(projected.cause);
|
|
720
|
+
yield* failpoint.hit("maintenance:finish:before");
|
|
721
|
+
|
|
722
|
+
const disposition = yield* mutations.withSnapshot((active) =>
|
|
723
|
+
Effect.gen(function* () {
|
|
724
|
+
// Re-read under the producer gate: a concurrent append/host mutation cannot be
|
|
725
|
+
// cleared using a stale empty deadline. Dirty generations bound all producer races.
|
|
726
|
+
const latest = yield* pendingDeadline;
|
|
727
|
+
const now = yield* Clock.currentTimeMillis;
|
|
728
|
+
|
|
729
|
+
return yield* runTransaction("finish publication pass", () =>
|
|
730
|
+
ctx.storage.transaction(async (transaction) => {
|
|
731
|
+
const { state } = await readMaintenanceState(transaction);
|
|
732
|
+
|
|
733
|
+
const nativeDeadline =
|
|
734
|
+
active > 0 || state.dirty > state.processed
|
|
735
|
+
? now + config.wakeScanInterval
|
|
736
|
+
: Infinity;
|
|
737
|
+
|
|
738
|
+
const next = Option.isSome(latest)
|
|
739
|
+
? Math.min(nativeDeadline, latest.value)
|
|
740
|
+
: nativeDeadline;
|
|
741
|
+
|
|
742
|
+
if (Number.isFinite(next)) {
|
|
743
|
+
await transaction.setAlarm(Math.max(now + minimumAlarmDelay, next));
|
|
744
|
+
|
|
745
|
+
return "rearmed" as const;
|
|
746
|
+
}
|
|
747
|
+
await transaction.deleteAlarm();
|
|
748
|
+
|
|
749
|
+
return "cleared" as const;
|
|
750
|
+
}),
|
|
751
|
+
);
|
|
752
|
+
}),
|
|
753
|
+
);
|
|
754
|
+
|
|
755
|
+
yield* failpoint.hit("maintenance:finish:after");
|
|
756
|
+
|
|
757
|
+
return yield* annotate(
|
|
758
|
+
MaintenancePassReport.make({
|
|
759
|
+
phase: "caught-up",
|
|
760
|
+
recovered: 0,
|
|
761
|
+
settled: 0,
|
|
762
|
+
nonterminal: started.nonterminal,
|
|
763
|
+
alarm: disposition,
|
|
764
|
+
}),
|
|
765
|
+
);
|
|
766
|
+
}
|
|
767
|
+
// Step 2 — reconciliation strictly precedes new work in this pass (exit gate).
|
|
768
|
+
const recovered: ReadonlyArray<RecoveryReport> = yield* runtime.runRecovery;
|
|
769
|
+
const reports = new Map(recovered.map((report) => [report.submissionId, report]));
|
|
770
|
+
const current = yield* Stream.runCollect(ledger.scanNonterminal);
|
|
771
|
+
const heads = new Map<ThreadId, SubmissionSnapshot>();
|
|
772
|
+
|
|
773
|
+
for (const row of current) {
|
|
774
|
+
if (!heads.has(row.threadId)) heads.set(row.threadId, row);
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
const eligible = [...heads.values()]
|
|
778
|
+
.filter((head) => !stableExternalWait(head, reports))
|
|
779
|
+
.map((head) => head.threadId)
|
|
780
|
+
.sort();
|
|
781
|
+
|
|
782
|
+
let selected = eligible[0];
|
|
783
|
+
|
|
784
|
+
if (heads.size > 1 && selected !== undefined) {
|
|
785
|
+
yield* failpoint.hit("maintenance:select:before");
|
|
786
|
+
selected = yield* runTransaction("select maintenance lane", () =>
|
|
787
|
+
ctx.storage.transaction(async (transaction) => {
|
|
788
|
+
const { state } = await readMaintenanceState(transaction);
|
|
789
|
+
|
|
790
|
+
const next =
|
|
791
|
+
eligible.find(
|
|
792
|
+
(threadId) =>
|
|
793
|
+
state.lastServedThreadId === undefined || threadId > state.lastServedThreadId,
|
|
794
|
+
) ?? eligible[0];
|
|
795
|
+
|
|
796
|
+
if (next !== undefined) {
|
|
797
|
+
// Persist before the Attempt so an eviction or repeated yield cannot
|
|
798
|
+
// monopolize the first lane. The generation and prearmed alarm survive.
|
|
799
|
+
await transaction.put(
|
|
800
|
+
MAINTENANCE_STATE_KEY,
|
|
801
|
+
encodeMaintenanceState(
|
|
802
|
+
ThreadMaintenanceState.make({ ...state, lastServedThreadId: next }),
|
|
803
|
+
),
|
|
804
|
+
);
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
return next;
|
|
808
|
+
}),
|
|
809
|
+
);
|
|
810
|
+
yield* failpoint.hit("maintenance:select:after");
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
// One FIFO head per event, across all local lanes. The runtime keeps its normal
|
|
814
|
+
// bounded Attempt and recovery contracts; followers belong to another alarm.
|
|
815
|
+
const settlement =
|
|
816
|
+
selected === undefined
|
|
817
|
+
? Option.none()
|
|
818
|
+
: yield* runtime.processThreadHead(selected, { yieldAfter });
|
|
819
|
+
|
|
820
|
+
yield* finishDelivery;
|
|
821
|
+
if (Exit.isFailure(projected)) return yield* Effect.failCause(projected.cause);
|
|
822
|
+
// Observe residual state before acknowledging this exact pass-start generation.
|
|
823
|
+
const remaining = yield* Stream.runCollect(ledger.scanNonterminal);
|
|
824
|
+
const waitingHeads = new Map<ThreadId, boolean>();
|
|
825
|
+
|
|
826
|
+
const autonomous = remaining.some((snapshot) => {
|
|
827
|
+
const headWaiting = waitingHeads.get(snapshot.threadId);
|
|
828
|
+
|
|
829
|
+
if (headWaiting === undefined)
|
|
830
|
+
waitingHeads.set(snapshot.threadId, stableExternalWait(snapshot, reports));
|
|
831
|
+
// FIFO followers cannot execute through a stable external wait. Only plain queued
|
|
832
|
+
// input is dormant here; admission repairs and accepted aborts still need a pass.
|
|
833
|
+
if (
|
|
834
|
+
headWaiting === true &&
|
|
835
|
+
snapshot.state === "ready" &&
|
|
836
|
+
reports.get(snapshot.submissionId)?.decision._tag === "ApplyInput"
|
|
837
|
+
)
|
|
838
|
+
return false;
|
|
839
|
+
|
|
840
|
+
return !stableExternalWait(snapshot, reports);
|
|
841
|
+
});
|
|
842
|
+
|
|
843
|
+
const progressed =
|
|
844
|
+
Option.isSome(settlement) ||
|
|
845
|
+
recovered.some((report) => report.disposition === "repaired");
|
|
846
|
+
|
|
847
|
+
const delay = autonomous ? yield* rearmDelay(progressed) : 0;
|
|
848
|
+
const now = yield* Clock.currentTimeMillis;
|
|
849
|
+
|
|
850
|
+
yield* failpoint.hit("maintenance:finish:before");
|
|
851
|
+
|
|
852
|
+
const alarmDisposition = yield* mutations.withSnapshot((active) =>
|
|
853
|
+
Effect.gen(function* () {
|
|
854
|
+
const publicationDeadline = yield* pendingDeadline;
|
|
855
|
+
|
|
856
|
+
return yield* runTransaction("finish maintenance pass", () =>
|
|
857
|
+
ctx.storage.transaction(async (transaction) => {
|
|
858
|
+
const { state } = await readMaintenanceState(transaction);
|
|
859
|
+
|
|
860
|
+
// Autonomous work and in-flight mutations intentionally leave the observed
|
|
861
|
+
// generation dirty. Otherwise acknowledge only the pass-start generation.
|
|
862
|
+
const processed =
|
|
863
|
+
autonomous || started.activeAtStart > 0 || active > 0
|
|
864
|
+
? state.processed
|
|
865
|
+
: state.processed > started.generation
|
|
866
|
+
? state.processed
|
|
867
|
+
: started.generation;
|
|
868
|
+
|
|
869
|
+
const next = ThreadMaintenanceState.make({
|
|
870
|
+
...state,
|
|
871
|
+
processed,
|
|
872
|
+
nonterminal: remaining.length,
|
|
873
|
+
});
|
|
874
|
+
|
|
875
|
+
await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));
|
|
876
|
+
if (autonomous) {
|
|
877
|
+
// Replace the crash-fallback slot with this pass's bounded backoff. The target
|
|
878
|
+
// is never earlier than the begin-pass fallback, so workerd does not cancel
|
|
879
|
+
// this running alarm handler before its report/span can complete.
|
|
880
|
+
await transaction.setAlarm(
|
|
881
|
+
Option.isSome(publicationDeadline)
|
|
882
|
+
? Math.max(
|
|
883
|
+
now + minimumAlarmDelay,
|
|
884
|
+
Math.min(now + delay, publicationDeadline.value),
|
|
885
|
+
)
|
|
886
|
+
: now + delay,
|
|
887
|
+
);
|
|
888
|
+
|
|
889
|
+
return "rearmed" as const;
|
|
890
|
+
}
|
|
891
|
+
if (started.activeAtStart > 0 || active > 0 || next.dirty > next.processed) {
|
|
892
|
+
// A mutation overlapped this pass's observation window or raced
|
|
893
|
+
// acknowledgement. It stays dirty and its pre-armed bounded alarm survives;
|
|
894
|
+
// unseen effects are never acknowledged. Do not accelerate that future alarm
|
|
895
|
+
// from inside the current handler: workerd cancels a running handler when it
|
|
896
|
+
// writes an earlier slot.
|
|
897
|
+
await ensureTransactionAlarmBy(
|
|
898
|
+
transaction,
|
|
899
|
+
Option.isSome(publicationDeadline)
|
|
900
|
+
? Math.max(
|
|
901
|
+
now + minimumAlarmDelay,
|
|
902
|
+
Math.min(now + config.wakeScanInterval, publicationDeadline.value),
|
|
903
|
+
)
|
|
904
|
+
: now + config.wakeScanInterval,
|
|
905
|
+
);
|
|
906
|
+
|
|
907
|
+
return "rearmed" as const;
|
|
908
|
+
}
|
|
909
|
+
if (Option.isSome(publicationDeadline)) {
|
|
910
|
+
await transaction.setAlarm(
|
|
911
|
+
Math.max(now + minimumAlarmDelay, publicationDeadline.value),
|
|
912
|
+
);
|
|
913
|
+
|
|
914
|
+
return "rearmed" as const;
|
|
915
|
+
}
|
|
916
|
+
await transaction.deleteAlarm();
|
|
917
|
+
|
|
918
|
+
return "cleared" as const;
|
|
919
|
+
}),
|
|
920
|
+
);
|
|
921
|
+
}),
|
|
922
|
+
);
|
|
923
|
+
|
|
924
|
+
yield* failpoint.hit("maintenance:finish:after");
|
|
925
|
+
if (alarmDisposition === "cleared") {
|
|
926
|
+
yield* Ref.set(stalls, 0);
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
return yield* annotate(
|
|
930
|
+
MaintenancePassReport.make({
|
|
931
|
+
phase: "actionable",
|
|
932
|
+
recovered: recovered.length,
|
|
933
|
+
settled: Option.isSome(settlement) ? 1 : 0,
|
|
934
|
+
nonterminal: remaining.length,
|
|
935
|
+
alarm: alarmDisposition,
|
|
936
|
+
}),
|
|
937
|
+
);
|
|
938
|
+
});
|
|
939
|
+
|
|
940
|
+
return ThreadMaintenance.of({
|
|
941
|
+
// A mid-pass immediate hint is droppable; durable dirty state decides the final alarm.
|
|
942
|
+
pass: Effect.gen(function* () {
|
|
943
|
+
const yieldAfter = DateTime.makeUnsafe((yield* Clock.currentTimeMillis) + 10 * 60_000);
|
|
944
|
+
|
|
945
|
+
return yield* alarm.withWakesDeferred(maintenancePassGate.withPermit(pass(yieldAfter)));
|
|
946
|
+
}).pipe(
|
|
947
|
+
// Include permit waiting, recovery and acknowledgement in the event deadline.
|
|
948
|
+
// Interruption releases Attempt ownership, leaving the prearmed dirty generation
|
|
949
|
+
// for recovery. It never changes the logical Run duration or settles a policy failure.
|
|
950
|
+
// This cooperative timer cannot preempt synchronous CPU work or stuck finalizers.
|
|
951
|
+
Effect.timeoutOrElse({
|
|
952
|
+
duration: "14 minutes",
|
|
953
|
+
orElse: () =>
|
|
954
|
+
DurableAlarmError.make({
|
|
955
|
+
operation: "maintenance pass deadline",
|
|
956
|
+
message:
|
|
957
|
+
"The maintenance event exceeded its 14 minute deadline; durable recovery remains pending",
|
|
958
|
+
}),
|
|
959
|
+
}),
|
|
960
|
+
),
|
|
961
|
+
ensureAlarm: mutations.withSnapshot(() => ensureAlarm()),
|
|
962
|
+
withMutation: (body) =>
|
|
963
|
+
mutations.withMutation(
|
|
964
|
+
body.pipe(
|
|
965
|
+
Effect.tap(() =>
|
|
966
|
+
publishCommitted.pipe(Effect.provideService(ThreadPublication, publication)),
|
|
967
|
+
),
|
|
968
|
+
),
|
|
969
|
+
),
|
|
970
|
+
});
|
|
971
|
+
}),
|
|
972
|
+
);
|
|
973
|
+
}
|