@effect-agent/platform-cloudflare 0.1.0-beta.11 → 0.1.0-beta.111
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 +208 -0
- package/dist/Alarm.mjs +601 -0
- package/dist/Alarm.mjs.map +1 -0
- package/dist/BrowserRestCapture.d.mts +34 -0
- package/dist/BrowserRestCapture.mjs +238 -0
- package/dist/BrowserRestCapture.mjs.map +1 -0
- package/dist/BrowserRestCrawl.d.mts +16 -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-DKXGo8L3.d.mts +106 -0
- package/dist/CloudflareConfig.d.mts +2 -0
- package/dist/CloudflareConfig.mjs +128 -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 +1675 -0
- package/dist/CloudflareThreadClient.mjs +382 -0
- package/dist/CloudflareThreadClient.mjs.map +1 -0
- package/dist/InteractiveBrowser-BQo7QKaP.d.mts +228 -0
- package/dist/InteractiveBrowser-CBUFAECo.mjs +1749 -0
- package/dist/InteractiveBrowser-CBUFAECo.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 +1161 -0
- package/dist/ProtectedBrowser.mjs.map +1 -0
- package/dist/ThreadObject-BGla_Obk.mjs +858 -0
- package/dist/ThreadObject-BGla_Obk.mjs.map +1 -0
- package/dist/ThreadObject-Cmn8pAQ3.d.mts +829 -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 +1323 -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} +19 -12
- 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 +3241 -0
- package/src/ProtectedBrowser.ts +9 -0
- package/src/ThreadObject.ts +1184 -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-binding.ts +82 -0
- package/src/internal/browser-failure.ts +92 -0
- package/src/internal/browser-file-selection.ts +126 -0
- package/src/internal/browser-quick-action.ts +857 -0
- package/src/internal/browser-session-lifecycle.ts +193 -0
- package/src/internal/layers.ts +765 -0
- package/src/internal/message-delivery.ts +181 -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 +354 -0
- package/src/protected-browser/host.ts +379 -0
- package/src/protected-browser/inspect-frame.ts +125 -0
- package/src/protected-browser/native.ts +473 -0
- package/src/protected-browser/policy.ts +857 -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/dist/Alarm.mjs
ADDED
|
@@ -0,0 +1,601 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
|
|
2
|
+
import { DurableObjectContext } from "./CloudflareBindings.mjs";
|
|
3
|
+
import { AuxiliaryDispatchMillis, CloudflareDurableRuntimeConfig } from "./CloudflareConfig.mjs";
|
|
4
|
+
import { r as safeCauseMessage } from "./boundary-BguazVkh.mjs";
|
|
5
|
+
import { Cause, Clock, Context, DateTime, Deferred, Effect, Exit, Fiber, Layer, Option, Random, Ref, Schema, Scope, Semaphore, Stream, Struct } from "effect";
|
|
6
|
+
import "effect-agent/agent-registration";
|
|
7
|
+
import { DurableAgentRuntime } from "effect-agent/durable-agent-runtime";
|
|
8
|
+
import { SubmissionId, ThreadId } from "effect-agent/identifiers";
|
|
9
|
+
import { SubmissionLedger } from "effect-agent/submission-ledger";
|
|
10
|
+
import { ThreadProjectionMaintenance, drainDue } from "effect-agent/thread-projection-maintenance";
|
|
11
|
+
import { WakeScheduler } from "effect-agent/wake-scheduler";
|
|
12
|
+
import { SqlClient } from "effect/unstable/sql/SqlClient";
|
|
13
|
+
//#region src/Alarm.ts
|
|
14
|
+
var Alarm_exports = /* @__PURE__ */ __exportAll({
|
|
15
|
+
DurableAlarmError: () => DurableAlarmError,
|
|
16
|
+
DurableAlarmService: () => DurableAlarmService,
|
|
17
|
+
MaintenancePassReport: () => MaintenancePassReport,
|
|
18
|
+
ThreadHostMaintenance: () => ThreadHostMaintenance,
|
|
19
|
+
ThreadMaintenance: () => ThreadMaintenance,
|
|
20
|
+
ThreadMaintenanceFailpoint: () => ThreadMaintenanceFailpoint,
|
|
21
|
+
ThreadMessageDelivery: () => ThreadMessageDelivery,
|
|
22
|
+
ThreadMutationGate: () => ThreadMutationGate,
|
|
23
|
+
ThreadPublication: () => ThreadPublication,
|
|
24
|
+
publishCommitted: () => publishCommitted
|
|
25
|
+
});
|
|
26
|
+
/**
|
|
27
|
+
* The single multiplexed Durable Object alarm (decision D-P6-2). A Durable Object has ONE
|
|
28
|
+
* alarm slot; every cadence the Node host ran on fibers (wake scan, lease expiry, settlement
|
|
29
|
+
* and abort re-checks, retry backoff) multiplexes into one idempotent maintenance pass, and
|
|
30
|
+
* the slot always holds the EARLIEST deadline any caller asked for.
|
|
31
|
+
*
|
|
32
|
+
* The alarm invariant (plan §1.4): every committed actionable mutation carries a newer durable
|
|
33
|
+
* maintenance generation and a committed alarm. Stable externally-driven waits may be
|
|
34
|
+
* nonterminal without retaining an alarm; their resolving mutation advances the generation and
|
|
35
|
+
* restores the alarm atomically.
|
|
36
|
+
*/
|
|
37
|
+
/** The Durable Object alarm API failed; surfaces on host entry points as a typed refusal. */
|
|
38
|
+
var DurableAlarmError = class extends Schema.TaggedError()("DurableAlarmError", {
|
|
39
|
+
operation: Schema.String,
|
|
40
|
+
message: Schema.String,
|
|
41
|
+
cause: Schema.optionalKey(Schema.Defect())
|
|
42
|
+
}) {};
|
|
43
|
+
const alarmFailure = (operation) => (cause) => DurableAlarmError.make({
|
|
44
|
+
operation,
|
|
45
|
+
message: safeCauseMessage(cause, "The Cloudflare alarm API failed without a diagnostic"),
|
|
46
|
+
cause
|
|
47
|
+
});
|
|
48
|
+
const makeStorageOperation = Effect.map(SqlClient, (sql) => (operation, execute) => Effect.flatMap(Effect.serviceOption(sql.transactionService), (current) => {
|
|
49
|
+
const body = Effect.uninterruptible(Effect.tryPromise({
|
|
50
|
+
try: execute,
|
|
51
|
+
catch: alarmFailure(operation)
|
|
52
|
+
}));
|
|
53
|
+
return current._tag === "Some" ? body : Effect.scoped(Effect.andThen(sql.reserve.pipe(Effect.mapError(alarmFailure(operation))), body));
|
|
54
|
+
}));
|
|
55
|
+
/** `ctx.storage` alarm slot as an Effect service; storage is truth, never a memory field. */
|
|
56
|
+
var DurableAlarmService = class DurableAlarmService extends Context.Service()("@effect-agent/platform-cloudflare/DurableAlarmService") {
|
|
57
|
+
static layer = Layer.effect(DurableAlarmService)(Effect.gen(function* () {
|
|
58
|
+
const { ctx } = yield* DurableObjectContext;
|
|
59
|
+
/**
|
|
60
|
+
* In-memory pass bookkeeping — a pure CACHE, never state: a fresh incarnation has no
|
|
61
|
+
* running pass, and a deferred wake lost to eviction was only ever a promptness hint
|
|
62
|
+
* on top of the already-committed pre-armed alarm.
|
|
63
|
+
*/
|
|
64
|
+
const runningPasses = yield* Ref.make(0);
|
|
65
|
+
const storageOperation = yield* makeStorageOperation;
|
|
66
|
+
const scheduled = storageOperation("get alarm", () => ctx.storage.getAlarm()).pipe(Effect.map((deadline) => deadline === null ? Option.none() : Option.some(deadline)));
|
|
67
|
+
const scheduleAt = (epochMillis) => storageOperation("set alarm", () => ctx.storage.setAlarm(epochMillis));
|
|
68
|
+
const ensureScheduledBy = (epochMillis) => storageOperation("ensure alarm", () => ctx.storage.transaction(async (transaction) => {
|
|
69
|
+
const existing = await transaction.getAlarm();
|
|
70
|
+
if (existing === null || existing > epochMillis) await transaction.setAlarm(epochMillis);
|
|
71
|
+
}));
|
|
72
|
+
const armNow = Clock.currentTimeMillis.pipe(Effect.flatMap((now) => ensureScheduledBy(now)));
|
|
73
|
+
const scheduleNow = Ref.get(runningPasses).pipe(Effect.flatMap((passes) => passes > 0 ? Effect.void : armNow));
|
|
74
|
+
const withWakesDeferred = (body) => Ref.update(runningPasses, (passes) => passes + 1).pipe(Effect.andThen(body), Effect.ensuring(Ref.update(runningPasses, (passes) => passes - 1)));
|
|
75
|
+
const cancel = storageOperation("delete alarm", () => ctx.storage.deleteAlarm());
|
|
76
|
+
return DurableAlarmService.of({
|
|
77
|
+
scheduled,
|
|
78
|
+
scheduleAt,
|
|
79
|
+
ensureScheduledBy,
|
|
80
|
+
scheduleNow,
|
|
81
|
+
withWakesDeferred,
|
|
82
|
+
cancel
|
|
83
|
+
});
|
|
84
|
+
}));
|
|
85
|
+
};
|
|
86
|
+
/** What one maintenance pass did — auditable evidence mirroring `NodeDurableHost`'s report. */
|
|
87
|
+
var MaintenancePassReport = class extends Schema.Class("@effect-agent/platform-cloudflare/MaintenancePassReport")({
|
|
88
|
+
/** `caught-up` ran no runtime work (publication may be pending); `actionable` ran recovery. */
|
|
89
|
+
phase: Schema.Literals(["caught-up", "actionable"]),
|
|
90
|
+
/** Recovery decisions executed (or deferred) BEFORE any new claim in this pass. */
|
|
91
|
+
recovered: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
|
|
92
|
+
/** Head Attempts settled during the event. Joined input may settle with each head. */
|
|
93
|
+
settled: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
|
|
94
|
+
/** Submissions still nonterminal after the pass (suspended/unknown lanes stay honest). */
|
|
95
|
+
nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
|
|
96
|
+
/** `rearmed` for dirty/autonomous work, `cleared` for stable waits or settlement. */
|
|
97
|
+
alarm: Schema.Literals(["rearmed", "cleared"])
|
|
98
|
+
}) {};
|
|
99
|
+
/** Test-only fault authority; production uses the inert layer. */
|
|
100
|
+
var ThreadMaintenanceFailpoint = class extends Context.Service()("@effect-agent/platform-cloudflare/ThreadMaintenanceFailpoint") {
|
|
101
|
+
static layer = Layer.succeed(this)({ hit: () => Effect.void });
|
|
102
|
+
};
|
|
103
|
+
/** Opt in with `ThreadObject.layer(registrations, { publication: Layer.effect(ThreadPublication)(...) })`. */
|
|
104
|
+
var ThreadPublication = class extends Context.Service()("@effect-agent/platform-cloudflare/ThreadPublication") {
|
|
105
|
+
static layer = Layer.succeed(this)({
|
|
106
|
+
invalidate: Effect.void,
|
|
107
|
+
prepareGeneration: () => Effect.void,
|
|
108
|
+
drain: Effect.void,
|
|
109
|
+
pendingDeadline: Effect.succeed(Option.none())
|
|
110
|
+
});
|
|
111
|
+
};
|
|
112
|
+
/**
|
|
113
|
+
* Host-assembled native message recovery. The driver bounds each actual Claim and persists its
|
|
114
|
+
* timeout/retry before this pump returns. Do not add a second timer starting at batch selection:
|
|
115
|
+
* local Claim setup may take time, and expiration still owes the driver's local retry commit.
|
|
116
|
+
*/
|
|
117
|
+
const ThreadMessageDelivery = Context.Reference("@effect-agent/platform-cloudflare/ThreadMessageDelivery", { defaultValue: () => ({
|
|
118
|
+
drainUntil: () => Effect.void,
|
|
119
|
+
pendingDeadline: Effect.succeed(Option.none())
|
|
120
|
+
}) });
|
|
121
|
+
/**
|
|
122
|
+
* Application obligations sharing this Object's alarm. Admit one initial external wave even on
|
|
123
|
+
* a caught-up pass, then respond to wakes until dispatchClosed. This closes only admission
|
|
124
|
+
* of NEW external waves; native work can continue while admitted waves finish. Keep local
|
|
125
|
+
* admission/hub subscriptions in the event Scope until maintenance tears it down.
|
|
126
|
+
* No deadline sleeps or automatic retry loops. Return after already-admitted waves finish.
|
|
127
|
+
*
|
|
128
|
+
* Declare a finite whole-wave allowance (1..300000ms): maximum for parallel lanes, sum for
|
|
129
|
+
* sequential operations. Admit a wave only if its allowance fits before dispatchUntil. Later
|
|
130
|
+
* arrivals cannot renew the retirement window. Maintenance bounds the join after dispatchClosed,
|
|
131
|
+
* interrupts and joins event Scope, then reads local deadlines under the mutation gate.
|
|
132
|
+
*
|
|
133
|
+
* Setup and pendingDeadline are bounded local operations. Persist claims/envelopes before
|
|
134
|
+
* dispatch; interrupted waits leave exact retries/receipts recoverable. Cancellation is local,
|
|
135
|
+
* not remote rollback. Retry accounting is unchanged. Network waits/finalizers must be
|
|
136
|
+
* interruptible; short local atomic commits may be uninterruptible. Hooks never write the raw
|
|
137
|
+
* alarm slot. Required native publication gates belong to ThreadPublication.
|
|
138
|
+
*/
|
|
139
|
+
const ThreadHostMaintenance = Context.Reference("@effect-agent/platform-cloudflare/ThreadHostMaintenance", { defaultValue: () => ({
|
|
140
|
+
dispatchTimeoutMillis: 1,
|
|
141
|
+
drainUntil: () => Effect.void,
|
|
142
|
+
pendingDeadline: Effect.succeed(Option.none())
|
|
143
|
+
}) });
|
|
144
|
+
const earliestDeadline = (left, right) => Option.isSome(left) ? Option.isSome(right) ? Option.some(Math.min(left.value, right.value)) : left : right;
|
|
145
|
+
/** @internal A committed source operation must not become a failed operation because delivery failed. */
|
|
146
|
+
const publishCommitted = Effect.gen(function* () {
|
|
147
|
+
const publication = yield* ThreadPublication;
|
|
148
|
+
yield* publication.invalidate.pipe(Effect.andThen(publication.drain));
|
|
149
|
+
}).pipe(Effect.catchCause((cause) => Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.logError("Thread publication deferred after source commit", cause)));
|
|
150
|
+
const MaintenanceGeneration = Schema.BigIntFromString.check(Schema.isGreaterThanOrEqualToBigInt(0n));
|
|
151
|
+
var BindingRetry = class extends Schema.Class("BindingRetry")({
|
|
152
|
+
threadId: ThreadId,
|
|
153
|
+
submissionId: SubmissionId,
|
|
154
|
+
attempts: Schema.Natural,
|
|
155
|
+
notBefore: Schema.Finite,
|
|
156
|
+
reportedAt: Schema.Finite
|
|
157
|
+
}) {};
|
|
158
|
+
var MaintenanceRetry = class extends Schema.Class("MaintenanceRetry")({
|
|
159
|
+
generation: MaintenanceGeneration,
|
|
160
|
+
notBefore: Schema.Finite,
|
|
161
|
+
nativeOnly: Schema.Boolean,
|
|
162
|
+
stalls: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(30))
|
|
163
|
+
}) {};
|
|
164
|
+
/** Versioned, platform-private maintenance state stored through Durable Object KV. */
|
|
165
|
+
var ThreadMaintenanceState = class extends Schema.Class("@effect-agent/platform-cloudflare/ThreadMaintenanceState")({
|
|
166
|
+
schemaVersion: Schema.Literal(1),
|
|
167
|
+
dirty: MaintenanceGeneration,
|
|
168
|
+
processed: MaintenanceGeneration,
|
|
169
|
+
nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
|
|
170
|
+
/** One physical-owner cursor; old single-lane records need no conversion. */
|
|
171
|
+
lastServedThreadId: Schema.optionalKey(ThreadId),
|
|
172
|
+
bindingRetries: Schema.optionalKey(Schema.Array(BindingRetry)),
|
|
173
|
+
/** Absent on older records. A newer mutation makes this retry obsolete. */
|
|
174
|
+
retry: Schema.optionalKey(MaintenanceRetry)
|
|
175
|
+
}) {};
|
|
176
|
+
const MAINTENANCE_STATE_KEY = "effect-agent:thread-maintenance:v1";
|
|
177
|
+
const decodeMaintenanceState = Schema.decodeUnknownSync(ThreadMaintenanceState);
|
|
178
|
+
const encodeMaintenanceState = Schema.encodeSync(ThreadMaintenanceState);
|
|
179
|
+
const initialMaintenanceState = () => ThreadMaintenanceState.make({
|
|
180
|
+
schemaVersion: 1,
|
|
181
|
+
dirty: 1n,
|
|
182
|
+
processed: 0n,
|
|
183
|
+
nonterminal: 0
|
|
184
|
+
});
|
|
185
|
+
const readMaintenanceState = async (transaction) => {
|
|
186
|
+
const encoded = await transaction.get(MAINTENANCE_STATE_KEY);
|
|
187
|
+
return encoded === void 0 ? {
|
|
188
|
+
state: initialMaintenanceState(),
|
|
189
|
+
initialized: false
|
|
190
|
+
} : {
|
|
191
|
+
state: decodeMaintenanceState(encoded),
|
|
192
|
+
initialized: true
|
|
193
|
+
};
|
|
194
|
+
};
|
|
195
|
+
const ensureTransactionAlarmBy = async (transaction, deadline) => {
|
|
196
|
+
const scheduled = await transaction.getAlarm();
|
|
197
|
+
if (scheduled === null || scheduled > deadline) await transaction.setAlarm(deadline);
|
|
198
|
+
};
|
|
199
|
+
const stableExternalWait = (snapshot, reports) => {
|
|
200
|
+
const report = reports.get(snapshot.submissionId);
|
|
201
|
+
if (report?.decision._tag === "SettleAborted") return false;
|
|
202
|
+
switch (snapshot.state) {
|
|
203
|
+
case "suspended":
|
|
204
|
+
case "joined": return true;
|
|
205
|
+
case "unknown": return report?.disposition === "unknown";
|
|
206
|
+
case "admitted": return reports.get(snapshot.submissionId)?.decision._tag === "AwaitParentEstablishment";
|
|
207
|
+
case "input-applied":
|
|
208
|
+
case "joining":
|
|
209
|
+
case "ready":
|
|
210
|
+
case "running":
|
|
211
|
+
case "settled":
|
|
212
|
+
case "terminalizing": return false;
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
/**
|
|
216
|
+
* Shared prearm/acknowledgement boundary for ingress and runtime-owned producers.
|
|
217
|
+
* `ThreadObject.layer` provides this same instance in its Services. Rebuilt runtime/maintenance
|
|
218
|
+
* Layers must reuse that instance; a second gate cannot observe the native producers' activity.
|
|
219
|
+
*/
|
|
220
|
+
var ThreadMutationGate = class ThreadMutationGate extends Context.Service()("@effect-agent/platform-cloudflare/internal/ThreadMutationGate") {
|
|
221
|
+
static layer = Layer.effect(this)(Effect.gen(function* () {
|
|
222
|
+
const { ctx } = yield* DurableObjectContext;
|
|
223
|
+
const config = yield* CloudflareDurableRuntimeConfig;
|
|
224
|
+
const failpoint = yield* ThreadMaintenanceFailpoint;
|
|
225
|
+
const activeMutations = yield* Ref.make(0);
|
|
226
|
+
const generationGate = yield* Semaphore.make(1);
|
|
227
|
+
const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));
|
|
228
|
+
const runTransaction = yield* makeStorageOperation;
|
|
229
|
+
const beginMutation = Effect.fn("ThreadMaintenance.beginMutation")(function* (invalidatesRecovery) {
|
|
230
|
+
yield* failpoint.hit("maintenance:dirty:before");
|
|
231
|
+
const now = yield* Clock.currentTimeMillis;
|
|
232
|
+
yield* runTransaction("advance maintenance generation", () => ctx.storage.transaction(async (transaction) => {
|
|
233
|
+
const { state, initialized } = await readMaintenanceState(transaction);
|
|
234
|
+
const next = ThreadMaintenanceState.make({
|
|
235
|
+
...state,
|
|
236
|
+
dirty: state.dirty + (invalidatesRecovery ? 1n : 0n)
|
|
237
|
+
});
|
|
238
|
+
if (invalidatesRecovery || !initialized) await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));
|
|
239
|
+
await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);
|
|
240
|
+
}));
|
|
241
|
+
yield* failpoint.hit("maintenance:dirty:after");
|
|
242
|
+
yield* Ref.update(activeMutations, (active) => active + 1);
|
|
243
|
+
});
|
|
244
|
+
const endMutation = generationGate.withPermit(Ref.update(activeMutations, (active) => Math.max(0, active - 1)));
|
|
245
|
+
const withMutation = (body, options) => Effect.acquireUseRelease(generationGate.withPermit(beginMutation(options?.invalidatesRecovery ?? true)), () => failpoint.hit("maintenance:mutation:armed").pipe(Effect.andThen(body), Effect.tap(() => failpoint.hit("maintenance:mutation:finished"))), () => endMutation);
|
|
246
|
+
return ThreadMutationGate.of({
|
|
247
|
+
withMutation,
|
|
248
|
+
withSnapshot: (body) => generationGate.withPermit(Effect.flatMap(Ref.get(activeMutations), body))
|
|
249
|
+
});
|
|
250
|
+
}));
|
|
251
|
+
};
|
|
252
|
+
/**
|
|
253
|
+
* Incremental, quiescent maintenance over a durable dirty/processed generation (issue #93).
|
|
254
|
+
*
|
|
255
|
+
* One physical event owns native scheduling, auxiliary delivery and final alarm rearming.
|
|
256
|
+
*
|
|
257
|
+
* 1. Prearm before any work. A caught-up native step uses the O(1) generation record without
|
|
258
|
+
* recovery, ledger scans or canonical-history reads.
|
|
259
|
+
* 2. Reconcile before each head Attempt, then checkpoint only the observed generation. A racing
|
|
260
|
+
* producer keeps its newer generation dirty. Native retries retain their durable backoff.
|
|
261
|
+
* 3. After the initial native opportunity, stop admitting new external waves and let the
|
|
262
|
+
* active waves finish. While they remain in flight, native wakes and bounded scans can
|
|
263
|
+
* advance more heads. All Attempts share the event's original ten-minute yield deadline.
|
|
264
|
+
* 4. Native message delivery retains its driver-owned Claim deadline. Host/backfill joins are
|
|
265
|
+
* bounded independently; incoming native work never restarts or cancels their attempts.
|
|
266
|
+
* Auxiliary failures are reported after the current native opportunity.
|
|
267
|
+
* 5. Close every event resource before the final gated deadline snapshot and alarm decision.
|
|
268
|
+
* The whole event retains one fourteen-minute cooperative timeout.
|
|
269
|
+
*/
|
|
270
|
+
var ThreadMaintenance = class ThreadMaintenance extends Context.Service()("@effect-agent/platform-cloudflare/ThreadMaintenance") {
|
|
271
|
+
static layer = Layer.effect(ThreadMaintenance)(Effect.gen(function* () {
|
|
272
|
+
const runtime = yield* DurableAgentRuntime;
|
|
273
|
+
const ledger = yield* SubmissionLedger;
|
|
274
|
+
const wakes = yield* WakeScheduler;
|
|
275
|
+
const alarm = yield* DurableAlarmService;
|
|
276
|
+
const config = yield* CloudflareDurableRuntimeConfig;
|
|
277
|
+
const { ctx } = yield* DurableObjectContext;
|
|
278
|
+
const failpoint = yield* ThreadMaintenanceFailpoint;
|
|
279
|
+
const mutations = yield* ThreadMutationGate;
|
|
280
|
+
const publication = yield* ThreadPublication;
|
|
281
|
+
const projection = yield* ThreadProjectionMaintenance;
|
|
282
|
+
const messages = yield* ThreadMessageDelivery;
|
|
283
|
+
const host = yield* ThreadHostMaintenance;
|
|
284
|
+
const projectionDeadline = projection.pendingDeadline.pipe(Effect.catchCauseIf((cause) => !Cause.hasInterrupts(cause), (cause) => Effect.logError("Thread projection deadline unavailable", cause).pipe(Effect.as(Option.some(0)))));
|
|
285
|
+
const pendingDeadline = Effect.gen(function* () {
|
|
286
|
+
return earliestDeadline(earliestDeadline(yield* publication.pendingDeadline, yield* messages.pendingDeadline), earliestDeadline(yield* projectionDeadline, yield* host.pendingDeadline));
|
|
287
|
+
});
|
|
288
|
+
const maintenancePassGate = yield* Semaphore.make(1);
|
|
289
|
+
const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));
|
|
290
|
+
const runTransaction = yield* makeStorageOperation;
|
|
291
|
+
const ensureAlarm = Effect.fn("ThreadMaintenance.ensureAlarm")(function* () {
|
|
292
|
+
yield* failpoint.hit("maintenance:ensure:before");
|
|
293
|
+
const now = yield* Clock.currentTimeMillis;
|
|
294
|
+
const retry = yield* runTransaction("ensure maintenance alarm", () => ctx.storage.transaction(async (transaction) => {
|
|
295
|
+
const { state, initialized } = await readMaintenanceState(transaction);
|
|
296
|
+
if (!initialized) await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));
|
|
297
|
+
if (state.dirty > state.processed) await ensureTransactionAlarmBy(transaction, state.retry?.generation === state.dirty ? Math.max(now + minimumAlarmDelay, state.retry.notBefore) : now + config.wakeScanInterval);
|
|
298
|
+
return state.retry?.generation === state.dirty ? state.retry : void 0;
|
|
299
|
+
}));
|
|
300
|
+
const deadline = yield* pendingDeadline;
|
|
301
|
+
if (Option.isSome(deadline)) yield* runTransaction("ensure publication alarm", () => ctx.storage.transaction((transaction) => ensureTransactionAlarmBy(transaction, Math.max(now + minimumAlarmDelay, deadline.value <= now && retry !== void 0 && !retry.nativeOnly ? Math.max(deadline.value, retry.notBefore) : deadline.value))));
|
|
302
|
+
yield* failpoint.hit("maintenance:ensure:after");
|
|
303
|
+
});
|
|
304
|
+
const beginPass = Effect.fn("ThreadMaintenance.beginPass")(function* (observed) {
|
|
305
|
+
yield* failpoint.hit("maintenance:begin:before");
|
|
306
|
+
const now = yield* Clock.currentTimeMillis;
|
|
307
|
+
const result = yield* runTransaction("begin maintenance pass", () => ctx.storage.transaction(async (transaction) => {
|
|
308
|
+
const { state, initialized } = await readMaintenanceState(transaction);
|
|
309
|
+
observed.generation = state.dirty;
|
|
310
|
+
if (!initialized) await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));
|
|
311
|
+
const retryAt = state.retry?.generation === state.dirty ? state.retry.notBefore : 0;
|
|
312
|
+
await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);
|
|
313
|
+
if (state.processed >= state.dirty || retryAt > now) return {
|
|
314
|
+
_tag: "CaughtUp",
|
|
315
|
+
nonterminal: state.nonterminal
|
|
316
|
+
};
|
|
317
|
+
return {
|
|
318
|
+
_tag: "Actionable",
|
|
319
|
+
generation: state.dirty,
|
|
320
|
+
nonterminal: state.nonterminal,
|
|
321
|
+
stalls: state.retry?.generation === state.dirty ? state.retry.stalls : 0
|
|
322
|
+
};
|
|
323
|
+
}));
|
|
324
|
+
yield* failpoint.hit("maintenance:begin:after");
|
|
325
|
+
return result;
|
|
326
|
+
});
|
|
327
|
+
const backoffDelay = (priorStalls, jitter) => {
|
|
328
|
+
const backoff = Math.min(config.alarmBackoffCap, config.alarmBackoffBase * 2 ** Math.min(priorStalls, 30));
|
|
329
|
+
return Math.ceil(backoff / 2 + backoff / 2 * jitter);
|
|
330
|
+
};
|
|
331
|
+
const rearmDelay = Effect.fn("ThreadMaintenance.rearmDelay")(function* (progressed, priorStalls) {
|
|
332
|
+
return progressed ? config.alarmBackoffBase : backoffDelay(priorStalls, yield* Random.next);
|
|
333
|
+
});
|
|
334
|
+
const rearmFailure = Effect.fn("ThreadMaintenance.rearmFailure")(function* (observed) {
|
|
335
|
+
const { generation, nativeOnly } = observed;
|
|
336
|
+
if (generation === void 0) return;
|
|
337
|
+
yield* failpoint.hit("maintenance:retry:before");
|
|
338
|
+
yield* mutations.withSnapshot((active) => Effect.gen(function* () {
|
|
339
|
+
const deadline = yield* pendingDeadline.pipe(Effect.catchCause(() => Effect.succeed(Option.none())));
|
|
340
|
+
const now = yield* Clock.currentTimeMillis;
|
|
341
|
+
const jitter = yield* Random.next;
|
|
342
|
+
yield* runTransaction("back off failed maintenance", () => ctx.storage.transaction(async (transaction) => {
|
|
343
|
+
const { state } = await readMaintenanceState(transaction);
|
|
344
|
+
const previous = state.retry?.generation === generation && state.retry.nativeOnly === nativeOnly ? state.retry : void 0;
|
|
345
|
+
const retry = MaintenanceRetry.make({
|
|
346
|
+
generation,
|
|
347
|
+
notBefore: Math.max(previous?.notBefore ?? 0, now + backoffDelay(previous?.stalls ?? 0, jitter)),
|
|
348
|
+
nativeOnly,
|
|
349
|
+
stalls: Math.min(30, (previous?.stalls ?? 0) + 1)
|
|
350
|
+
});
|
|
351
|
+
await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(ThreadMaintenanceState.make({
|
|
352
|
+
...state,
|
|
353
|
+
retry
|
|
354
|
+
})));
|
|
355
|
+
const nativeDeadline = active > 0 || state.dirty !== generation ? now + minimumAlarmDelay : retry.notBefore;
|
|
356
|
+
await transaction.setAlarm(Math.max(now + minimumAlarmDelay, Option.isSome(deadline) && (nativeOnly || deadline.value > now) ? Math.min(nativeDeadline, deadline.value) : nativeDeadline));
|
|
357
|
+
}));
|
|
358
|
+
}));
|
|
359
|
+
yield* failpoint.hit("maintenance:retry:after");
|
|
360
|
+
});
|
|
361
|
+
const beginNative = Effect.fn("ThreadMaintenance.beginNative")(function* (observed) {
|
|
362
|
+
return yield* mutations.withSnapshot((activeAtStart) => Effect.gen(function* () {
|
|
363
|
+
const generation = yield* beginPass(observed);
|
|
364
|
+
if (generation._tag === "Actionable" && activeAtStart === 0) yield* publication.prepareGeneration(generation.generation);
|
|
365
|
+
return {
|
|
366
|
+
...generation,
|
|
367
|
+
activeAtStart
|
|
368
|
+
};
|
|
369
|
+
}));
|
|
370
|
+
});
|
|
371
|
+
const advance = Effect.fn("ThreadMaintenance.advance")(function* (started, yieldAfter, observed) {
|
|
372
|
+
const deadline = yield* publication.pendingDeadline;
|
|
373
|
+
if (started._tag === "Actionable" || Option.isSome(deadline) && deadline.value <= (yield* Clock.currentTimeMillis)) yield* publication.drain;
|
|
374
|
+
const pending = yield* publication.pendingDeadline;
|
|
375
|
+
if (started._tag === "CaughtUp" || Option.isSome(pending)) {
|
|
376
|
+
const nextAttemptAt = yield* mutations.withSnapshot((active) => Effect.gen(function* () {
|
|
377
|
+
const now = yield* Clock.currentTimeMillis;
|
|
378
|
+
const { state } = yield* runTransaction("read native maintenance deadline", () => ctx.storage.transaction((transaction) => readMaintenanceState(transaction)));
|
|
379
|
+
const native = active > 0 || state.dirty > state.processed ? state.retry?.generation === state.dirty && active === 0 ? state.retry.notBefore : now + minimumAlarmDelay : Infinity;
|
|
380
|
+
const next = Option.isSome(pending) ? pending.value : native;
|
|
381
|
+
return Number.isFinite(next) ? Math.max(now + minimumAlarmDelay, next) : void 0;
|
|
382
|
+
}));
|
|
383
|
+
return {
|
|
384
|
+
phase: "caught-up",
|
|
385
|
+
recovered: 0,
|
|
386
|
+
settled: 0,
|
|
387
|
+
nonterminal: started.nonterminal,
|
|
388
|
+
nextAttemptAt
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
observed.nativeOnly = true;
|
|
392
|
+
const recovered = yield* runtime.runRecovery;
|
|
393
|
+
const reports = new Map(recovered.map((report) => [report.submissionId, report]));
|
|
394
|
+
const current = yield* Stream.runCollect(ledger.scanNonterminal);
|
|
395
|
+
const heads = /* @__PURE__ */ new Map();
|
|
396
|
+
for (const row of current) {
|
|
397
|
+
if (row.state === "unknown" && stableExternalWait(row, reports)) continue;
|
|
398
|
+
if (!heads.has(row.threadId)) heads.set(row.threadId, row);
|
|
399
|
+
}
|
|
400
|
+
const eligible = [...heads.values()].filter((head) => !stableExternalWait(head, reports)).map((head) => head.threadId).sort();
|
|
401
|
+
const selectionTime = yield* Clock.currentTimeMillis;
|
|
402
|
+
yield* failpoint.hit("maintenance:select:before");
|
|
403
|
+
const selection = yield* runTransaction("select maintenance lane", () => ctx.storage.transaction(async (transaction) => {
|
|
404
|
+
const { state } = await readMaintenanceState(transaction);
|
|
405
|
+
const retries = (state.bindingRetries ?? []).filter((retry) => heads.get(retry.threadId)?.submissionId === retry.submissionId);
|
|
406
|
+
const runnable = eligible.filter((threadId) => !retries.some((retry) => retry.threadId === threadId && retry.notBefore > selectionTime));
|
|
407
|
+
const next = runnable.find((threadId) => state.lastServedThreadId === void 0 || threadId > state.lastServedThreadId) ?? runnable[0];
|
|
408
|
+
if (next !== void 0) await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(ThreadMaintenanceState.make({
|
|
409
|
+
...state,
|
|
410
|
+
lastServedThreadId: next
|
|
411
|
+
})));
|
|
412
|
+
return {
|
|
413
|
+
selected: next,
|
|
414
|
+
retries
|
|
415
|
+
};
|
|
416
|
+
}));
|
|
417
|
+
yield* failpoint.hit("maintenance:select:after");
|
|
418
|
+
const selected = selection.selected === void 0 ? void 0 : heads.get(selection.selected);
|
|
419
|
+
let retries = selection.retries;
|
|
420
|
+
let bindingFailure;
|
|
421
|
+
const settlement = selected === void 0 ? Option.none() : yield* runtime.processThreadHead(selected.threadId, { yieldAfter }).pipe(Effect.catchTag("BindingUnavailable", (failure) => {
|
|
422
|
+
bindingFailure = failure;
|
|
423
|
+
return Effect.succeed(Option.none());
|
|
424
|
+
}));
|
|
425
|
+
if (selected !== void 0) {
|
|
426
|
+
const previous = retries.find((retry) => retry.submissionId === selected.submissionId);
|
|
427
|
+
let retry;
|
|
428
|
+
let reportBindingFailure = false;
|
|
429
|
+
if (bindingFailure !== void 0) {
|
|
430
|
+
const now = yield* Clock.currentTimeMillis;
|
|
431
|
+
const attempts = Math.min(30, (previous?.attempts ?? 0) + 1);
|
|
432
|
+
reportBindingFailure = previous === void 0 || now - previous.reportedAt >= 9e5;
|
|
433
|
+
retry = BindingRetry.make({
|
|
434
|
+
threadId: selected.threadId,
|
|
435
|
+
submissionId: selected.submissionId,
|
|
436
|
+
attempts,
|
|
437
|
+
notBefore: now + Math.min(6e4, 5e3 * 2 ** (attempts - 1)),
|
|
438
|
+
reportedAt: reportBindingFailure ? now : previous?.reportedAt ?? now
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
if (retry !== void 0 || previous !== void 0) {
|
|
442
|
+
yield* failpoint.hit("maintenance:binding-retry:before");
|
|
443
|
+
retries = yield* runTransaction("record submission binding retry", () => ctx.storage.transaction(async (transaction) => {
|
|
444
|
+
const { state } = await readMaintenanceState(transaction);
|
|
445
|
+
const bindingRetries = [...(state.bindingRetries ?? []).filter((entry) => entry.submissionId !== selected.submissionId), ...retry === void 0 ? [] : [retry]];
|
|
446
|
+
await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(ThreadMaintenanceState.make({
|
|
447
|
+
...state,
|
|
448
|
+
bindingRetries
|
|
449
|
+
})));
|
|
450
|
+
return bindingRetries;
|
|
451
|
+
}));
|
|
452
|
+
yield* failpoint.hit("maintenance:binding-retry:after");
|
|
453
|
+
}
|
|
454
|
+
if (bindingFailure !== void 0) yield* reportBindingFailure ? Effect.logError("Thread awaits a current agent binding; original work remains pending", Cause.fail(bindingFailure)) : Effect.logDebug("Thread binding retry remains pending", Cause.fail(bindingFailure));
|
|
455
|
+
}
|
|
456
|
+
const remaining = yield* Stream.runCollect(ledger.scanNonterminal);
|
|
457
|
+
const waitingHeads = /* @__PURE__ */ new Map();
|
|
458
|
+
const autonomous = remaining.some((snapshot) => {
|
|
459
|
+
if (snapshot.state === "unknown" && stableExternalWait(snapshot, reports)) return false;
|
|
460
|
+
const headWaiting = waitingHeads.get(snapshot.threadId);
|
|
461
|
+
if (headWaiting === void 0) waitingHeads.set(snapshot.threadId, stableExternalWait(snapshot, reports));
|
|
462
|
+
if (headWaiting === true && snapshot.state === "ready" && reports.get(snapshot.submissionId)?.decision._tag === "ApplyInput") return false;
|
|
463
|
+
return !stableExternalWait(snapshot, reports);
|
|
464
|
+
});
|
|
465
|
+
const progressed = Option.isSome(settlement) || recovered.some((report) => report.disposition === "repaired");
|
|
466
|
+
const now = yield* Clock.currentTimeMillis;
|
|
467
|
+
const ordinaryDelay = autonomous ? yield* rearmDelay(progressed, started.stalls) : 0;
|
|
468
|
+
const nextEligible = eligible.map((threadId) => retries.find((retry) => retry.submissionId === heads.get(threadId)?.submissionId)?.notBefore ?? now);
|
|
469
|
+
const bindingDelay = nextEligible.length === 0 ? 0 : Math.max(0, Math.min(...nextEligible) - now);
|
|
470
|
+
const delay = Math.max(ordinaryDelay, bindingDelay);
|
|
471
|
+
yield* failpoint.hit("maintenance:checkpoint:before");
|
|
472
|
+
const nextAttemptAt = yield* mutations.withSnapshot((active) => runTransaction("checkpoint native maintenance", () => ctx.storage.transaction(async (transaction) => {
|
|
473
|
+
const { state } = await readMaintenanceState(transaction);
|
|
474
|
+
const processed = autonomous || started.activeAtStart > 0 || active > 0 ? state.processed : state.processed > started.generation ? state.processed : started.generation;
|
|
475
|
+
const next = ThreadMaintenanceState.make({
|
|
476
|
+
...Struct.omit(state, ["retry"]),
|
|
477
|
+
processed,
|
|
478
|
+
nonterminal: remaining.length,
|
|
479
|
+
bindingRetries: (state.bindingRetries ?? []).filter((retry) => remaining.some((row) => row.submissionId === retry.submissionId)),
|
|
480
|
+
...autonomous && !progressed ? { retry: MaintenanceRetry.make({
|
|
481
|
+
generation: started.generation,
|
|
482
|
+
notBefore: now + delay,
|
|
483
|
+
nativeOnly: true,
|
|
484
|
+
stalls: Math.min(30, started.stalls + 1)
|
|
485
|
+
}) } : {}
|
|
486
|
+
});
|
|
487
|
+
await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));
|
|
488
|
+
if (autonomous) return started.activeAtStart > 0 || active > 0 || state.dirty !== started.generation ? now + minimumAlarmDelay : now + delay;
|
|
489
|
+
return started.activeAtStart > 0 || active > 0 || next.dirty > next.processed ? now + minimumAlarmDelay : void 0;
|
|
490
|
+
})));
|
|
491
|
+
yield* failpoint.hit("maintenance:checkpoint:after");
|
|
492
|
+
return {
|
|
493
|
+
phase: "actionable",
|
|
494
|
+
recovered: recovered.length,
|
|
495
|
+
settled: Option.isSome(settlement) ? 1 : 0,
|
|
496
|
+
nonterminal: remaining.length,
|
|
497
|
+
nextAttemptAt
|
|
498
|
+
};
|
|
499
|
+
});
|
|
500
|
+
const pass = Effect.fn("ThreadMaintenance.pass")(function* (yieldAfter, dispatchUntil, observed) {
|
|
501
|
+
const notified = (yield* Stream.toPull(wakes.wakes)).pipe(Effect.asVoid, Effect.catch(() => Effect.never));
|
|
502
|
+
let started = yield* beginNative(observed);
|
|
503
|
+
const auxiliaryScope = yield* Effect.acquireRelease(Scope.make("parallel"), (scope, exit) => Scope.close(scope, exit));
|
|
504
|
+
const dispatchClosed = yield* Deferred.make();
|
|
505
|
+
const stopDispatch = Deferred.await(dispatchClosed);
|
|
506
|
+
const deliveryFiber = yield* Effect.forkIn(Scope.provide(auxiliaryScope)(messages.drainUntil(stopDispatch, dispatchUntil)), auxiliaryScope);
|
|
507
|
+
const hostFiber = yield* Effect.forkIn(Scope.provide(auxiliaryScope)(Effect.gen(function* () {
|
|
508
|
+
yield* Schema.decodeEffect(AuxiliaryDispatchMillis)(host.dispatchTimeoutMillis).pipe(Effect.mapError((cause) => DurableAlarmError.make({
|
|
509
|
+
operation: "host dispatch allowance",
|
|
510
|
+
message: "Declare an integer whole-wave allowance between 1 and 300000 milliseconds",
|
|
511
|
+
cause
|
|
512
|
+
})));
|
|
513
|
+
yield* host.drainUntil(stopDispatch, dispatchUntil);
|
|
514
|
+
})), auxiliaryScope);
|
|
515
|
+
const backfill = yield* Effect.forkIn(drainDue.pipe(Effect.provideService(ThreadProjectionMaintenance, projection), Effect.timeoutOption(config.projectionDispatchTimeoutMillis)), auxiliaryScope);
|
|
516
|
+
let result = yield* advance(started, yieldAfter, observed);
|
|
517
|
+
let phase = result.phase;
|
|
518
|
+
let recovered = result.recovered;
|
|
519
|
+
let settled = result.settled;
|
|
520
|
+
observed.nativeOnly = false;
|
|
521
|
+
yield* Deferred.succeed(dispatchClosed, void 0);
|
|
522
|
+
const remaining = Math.max(1, DateTime.toEpochMillis(dispatchUntil) - (yield* Clock.currentTimeMillis));
|
|
523
|
+
const hostJoin = yield* Effect.forkIn(Fiber.join(hostFiber).pipe(Effect.timeoutOption(Math.min(host.dispatchTimeoutMillis, remaining)), Effect.tap((outcome) => Effect.annotateCurrentSpan({ "host.timedOut": Option.isNone(outcome) }))), auxiliaryScope);
|
|
524
|
+
const retired = yield* Effect.forkChild(Fiber.joinAll([
|
|
525
|
+
deliveryFiber,
|
|
526
|
+
hostJoin,
|
|
527
|
+
backfill
|
|
528
|
+
]));
|
|
529
|
+
const auxiliaryPending = () => deliveryFiber.pollUnsafe() === void 0 || hostFiber.pollUnsafe() === void 0 || backfill.pollUnsafe() === void 0;
|
|
530
|
+
while (retired.pollUnsafe() === void 0 && auxiliaryPending()) {
|
|
531
|
+
const now = yield* Clock.currentTimeMillis;
|
|
532
|
+
const until = DateTime.toEpochMillis(yieldAfter);
|
|
533
|
+
if (now >= until) break;
|
|
534
|
+
const next = Math.min(result.nextAttemptAt ?? Infinity, now + config.wakeScanInterval, until);
|
|
535
|
+
if (!(yield* Effect.raceFirst(Effect.raceFirst(notified, Effect.sleep(Math.max(0, next - now))).pipe(Effect.as(true)), Fiber.await(retired).pipe(Effect.as(false)))) || retired.pollUnsafe() !== void 0 || !auxiliaryPending()) break;
|
|
536
|
+
if ((yield* Clock.currentTimeMillis) >= until) break;
|
|
537
|
+
started = yield* beginNative(observed);
|
|
538
|
+
result = yield* advance(started, yieldAfter, observed);
|
|
539
|
+
if (result.phase === "actionable") phase = "actionable";
|
|
540
|
+
recovered += result.recovered;
|
|
541
|
+
settled += result.settled;
|
|
542
|
+
observed.nativeOnly = false;
|
|
543
|
+
}
|
|
544
|
+
yield* Fiber.join(retired);
|
|
545
|
+
yield* Scope.close(auxiliaryScope, Exit.void);
|
|
546
|
+
yield* failpoint.hit("maintenance:finish:before");
|
|
547
|
+
const disposition = yield* mutations.withSnapshot((active) => Effect.gen(function* () {
|
|
548
|
+
const latest = yield* pendingDeadline;
|
|
549
|
+
const now = yield* Clock.currentTimeMillis;
|
|
550
|
+
return yield* runTransaction("finish maintenance event", () => ctx.storage.transaction(async (transaction) => {
|
|
551
|
+
const { state } = await readMaintenanceState(transaction);
|
|
552
|
+
const native = active > 0 || state.dirty > state.processed ? state.retry?.generation === state.dirty && active === 0 ? Math.max(now + minimumAlarmDelay, state.retry.notBefore) : state.dirty === observed.generation && active === 0 ? result.nextAttemptAt ?? now + config.wakeScanInterval : now + minimumAlarmDelay : Infinity;
|
|
553
|
+
const next = Option.isSome(latest) ? Math.min(native, latest.value) : native;
|
|
554
|
+
if (Number.isFinite(next)) {
|
|
555
|
+
await transaction.setAlarm(Math.max(now + minimumAlarmDelay, next));
|
|
556
|
+
return "rearmed";
|
|
557
|
+
}
|
|
558
|
+
await transaction.deleteAlarm();
|
|
559
|
+
return "cleared";
|
|
560
|
+
}));
|
|
561
|
+
}));
|
|
562
|
+
yield* failpoint.hit("maintenance:finish:after");
|
|
563
|
+
const report = MaintenancePassReport.make({
|
|
564
|
+
phase,
|
|
565
|
+
recovered,
|
|
566
|
+
settled,
|
|
567
|
+
nonterminal: result.nonterminal,
|
|
568
|
+
alarm: disposition
|
|
569
|
+
});
|
|
570
|
+
yield* Effect.annotateCurrentSpan({
|
|
571
|
+
phase: report.phase,
|
|
572
|
+
recovered: report.recovered,
|
|
573
|
+
settled: report.settled,
|
|
574
|
+
nonterminal: report.nonterminal,
|
|
575
|
+
alarm: report.alarm
|
|
576
|
+
});
|
|
577
|
+
return report;
|
|
578
|
+
});
|
|
579
|
+
return ThreadMaintenance.of({
|
|
580
|
+
pass: Effect.gen(function* () {
|
|
581
|
+
const now = yield* Clock.currentTimeMillis;
|
|
582
|
+
const yieldAfter = DateTime.makeUnsafe(now + 6e5);
|
|
583
|
+
const dispatchUntil = DateTime.makeUnsafe(now + 84e4);
|
|
584
|
+
const observed = { nativeOnly: false };
|
|
585
|
+
return yield* alarm.withWakesDeferred(maintenancePassGate.withPermit(Effect.scoped(pass(yieldAfter, dispatchUntil, observed)).pipe(Effect.onErrorIf(() => true, () => rearmFailure(observed)))));
|
|
586
|
+
}).pipe(Effect.timeoutOrElse({
|
|
587
|
+
duration: "14 minutes",
|
|
588
|
+
orElse: () => DurableAlarmError.make({
|
|
589
|
+
operation: "maintenance pass deadline",
|
|
590
|
+
message: "The maintenance event exceeded its 14 minute deadline; durable recovery remains pending"
|
|
591
|
+
})
|
|
592
|
+
})),
|
|
593
|
+
ensureAlarm: mutations.withSnapshot(() => ensureAlarm()),
|
|
594
|
+
withMutation: (body) => mutations.withMutation(body.pipe(Effect.tap(() => publishCommitted.pipe(Effect.provideService(ThreadPublication, publication)))))
|
|
595
|
+
});
|
|
596
|
+
}));
|
|
597
|
+
};
|
|
598
|
+
//#endregion
|
|
599
|
+
export { DurableAlarmError, DurableAlarmService, MaintenancePassReport, ThreadHostMaintenance, ThreadMaintenance, ThreadMaintenanceFailpoint, ThreadMessageDelivery, ThreadMutationGate, ThreadPublication, publishCommitted, Alarm_exports as t };
|
|
600
|
+
|
|
601
|
+
//# sourceMappingURL=Alarm.mjs.map
|