@systemfsoftware/agent-platform-node 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/dist/NodeDurableAgentRuntime-C5SFn9kf.mjs +218 -0
- package/dist/NodeDurableAgentRuntime-C5SFn9kf.mjs.map +1 -0
- package/dist/NodeDurableAgentRuntime-CUrOl39W.d.mts +163 -0
- package/dist/NodeDurableAgentRuntime.d.mts +2 -0
- package/dist/NodeDurableAgentRuntime.mjs +1 -0
- package/dist/NodeDurableHost-BztkzCGh.mjs +271 -0
- package/dist/NodeDurableHost-BztkzCGh.mjs.map +1 -0
- package/dist/NodeDurableHost-CFvVn1w1.d.mts +153 -0
- package/dist/NodeDurableHost.d.mts +2 -0
- package/dist/NodeDurableHost.mjs +1 -0
- package/dist/NodeScheduling-CD_CZvQ6.d.mts +20 -0
- package/dist/NodeScheduling-gNj8jB4g.mjs +64 -0
- package/dist/NodeScheduling-gNj8jB4g.mjs.map +1 -0
- package/dist/NodeScheduling.d.mts +2 -0
- package/dist/NodeScheduling.mjs +1 -0
- package/dist/NodeSubscriptions-Bd_3VxqD.d.mts +23 -0
- package/dist/NodeSubscriptions-KgvkfIMl.mjs +62 -0
- package/dist/NodeSubscriptions-KgvkfIMl.mjs.map +1 -0
- package/dist/NodeSubscriptions.d.mts +2 -0
- package/dist/NodeSubscriptions.mjs +1 -0
- package/dist/NodeWakeScheduler-Dyha4GZJ.d.mts +28 -0
- package/dist/NodeWakeScheduler-dVNAHWsN.mjs +58 -0
- package/dist/NodeWakeScheduler-dVNAHWsN.mjs.map +1 -0
- package/dist/NodeWakeScheduler.d.mts +2 -0
- package/dist/NodeWakeScheduler.mjs +1 -0
- package/dist/index.d.mts +6 -0
- package/dist/index.mjs +6 -0
- package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
- package/package.json +68 -3
- package/src/NodeDurableAgentRuntime.ts +603 -0
- package/src/NodeDurableHost.ts +403 -0
- package/src/NodeScheduling.ts +122 -0
- package/src/NodeSubscriptions.ts +124 -0
- package/src/NodeWakeScheduler.ts +94 -0
- package/src/index.ts +5 -0
- package/src/internal/application-context.ts +25 -0
- package/src/internal/exclusive-host.ts +7 -0
- package/src/internal/message-delivery.ts +54 -0
- package/src/internal/prepared-admission.ts +79 -0
- package/src/internal/worker-dispatch.ts +116 -0
- package/README.md +0 -3
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
import * as NodeCrypto from '@effect/platform-node/NodeCrypto'
|
|
2
|
+
import {
|
|
3
|
+
type AgentRegistration,
|
|
4
|
+
type DurableBindingFailure,
|
|
5
|
+
type ResolvedBinding,
|
|
6
|
+
} from '@systemfsoftware/agent/agent-registration'
|
|
7
|
+
import {
|
|
8
|
+
type DurableAbortFailure,
|
|
9
|
+
DurableAgentRuntime,
|
|
10
|
+
type DurableAwaitFailure,
|
|
11
|
+
type DurableObserveOptions,
|
|
12
|
+
type DurableSubmitAgent,
|
|
13
|
+
type DurableSubmitFailure,
|
|
14
|
+
type DurableSubmitOptions,
|
|
15
|
+
type DurableWorkerFailure,
|
|
16
|
+
type Receipt,
|
|
17
|
+
type RecoveryBlocked,
|
|
18
|
+
type RecoveryReport,
|
|
19
|
+
} from '@systemfsoftware/agent/durable-agent-runtime'
|
|
20
|
+
import {
|
|
21
|
+
MessageDeliveryDriver,
|
|
22
|
+
type MessageDeliveryError,
|
|
23
|
+
MessageDeliveryStore,
|
|
24
|
+
} from '@systemfsoftware/agent/message-delivery'
|
|
25
|
+
import { type OperationDenied } from '@systemfsoftware/agent/operation-authorizer'
|
|
26
|
+
import { PreparedInputAdmission } from '@systemfsoftware/agent/prepared-input-admission'
|
|
27
|
+
import { type CanonicalRecordEnvelope } from '@systemfsoftware/agent/records'
|
|
28
|
+
import {
|
|
29
|
+
type AbortCommand,
|
|
30
|
+
type AbortIntent,
|
|
31
|
+
type Settlement,
|
|
32
|
+
SubmissionLedger,
|
|
33
|
+
} from '@systemfsoftware/agent/submission-ledger'
|
|
34
|
+
import { type ThreadNotMaterialized, ThreadReader, type ThreadStoreError } from '@systemfsoftware/agent/thread-store'
|
|
35
|
+
import { MAX_RECOVERY_WORK_ITEMS } from '@systemfsoftware/agent/thread-work'
|
|
36
|
+
import { WakeScheduler } from '@systemfsoftware/agent/wake-scheduler'
|
|
37
|
+
import * as Context from 'effect/Context'
|
|
38
|
+
import * as Effect from 'effect/Effect'
|
|
39
|
+
import * as Fiber from 'effect/Fiber'
|
|
40
|
+
import * as Layer from 'effect/Layer'
|
|
41
|
+
import * as Ref from 'effect/Ref'
|
|
42
|
+
import * as Schema from 'effect/Schema'
|
|
43
|
+
import type * as Stream from 'effect/Stream'
|
|
44
|
+
|
|
45
|
+
import { applicationInvocationContext } from './internal/application-context'
|
|
46
|
+
import { ExclusiveSqliteHost } from './internal/exclusive-host'
|
|
47
|
+
import { runNodeMessageDeliveries } from './internal/message-delivery'
|
|
48
|
+
import { makeNodePreparedInputAdmission, NodeAdmission } from './internal/prepared-admission'
|
|
49
|
+
import { runNodeWorkerDispatch } from './internal/worker-dispatch'
|
|
50
|
+
import {
|
|
51
|
+
NodeDurableAgentRuntime,
|
|
52
|
+
NodeDurableAgentRuntimeConfig,
|
|
53
|
+
type NodeDurableAgentRuntimeOptions,
|
|
54
|
+
} from './NodeDurableAgentRuntime'
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Admission is not open on this host: it is shutting down (deployment §6 step 1, DEPLOY-005).
|
|
58
|
+
* Accepted work is unaffected — only NEW admissions are refused.
|
|
59
|
+
*/
|
|
60
|
+
export class AdmissionClosed extends Schema.TaggedError<AdmissionClosed>()('AdmissionClosed', {
|
|
61
|
+
message: Schema.String,
|
|
62
|
+
}) {}
|
|
63
|
+
|
|
64
|
+
const makeHost = Effect.fnUntraced(function*(
|
|
65
|
+
managedWorkers?: Effect.Effect<void, DurableWorkerFailure | DurableBindingFailure>,
|
|
66
|
+
) {
|
|
67
|
+
const runtime = yield* DurableAgentRuntime
|
|
68
|
+
const config = yield* NodeDurableAgentRuntimeConfig
|
|
69
|
+
|
|
70
|
+
// Startup gate (deployment §5, plan §host): configuration decoding and storage compatibility
|
|
71
|
+
// already gated this Layer's dependencies; the last gate before admission opens is recovering
|
|
72
|
+
// EVERY nonterminal Submission. Work needing a live Agent Binding is reported `deferred` and
|
|
73
|
+
// stays a visible obligation for `runWorkers`; submissions parked on an Unknown Outcome are
|
|
74
|
+
// reported `unknown` and wait for the authorized `resolveUnknown` path (DUR-017) — they consume
|
|
75
|
+
// no worker permit while the settlement obligation stays owed and later input can run.
|
|
76
|
+
let recoveryCursor: string | undefined
|
|
77
|
+
let startupReports: ReadonlyArray<RecoveryReport> = []
|
|
78
|
+
|
|
79
|
+
do {
|
|
80
|
+
const recovered = yield* runtime.runRecovery(
|
|
81
|
+
recoveryCursor === undefined ? undefined : { cursor: recoveryCursor },
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
// This host opens one shared pool; every selected owner must pass the readiness gate.
|
|
85
|
+
const blocked = recovered.blocked[0]
|
|
86
|
+
|
|
87
|
+
if (blocked !== undefined) return yield* blocked
|
|
88
|
+
startupReports = [...startupReports, ...recovered.reports].slice(-MAX_RECOVERY_WORK_ITEMS)
|
|
89
|
+
recoveryCursor = recovered.cursor
|
|
90
|
+
} while (recoveryCursor !== undefined)
|
|
91
|
+
|
|
92
|
+
const admission = yield* Ref.make(true)
|
|
93
|
+
|
|
94
|
+
const requireAdmission: Effect.Effect<void, AdmissionClosed> = Ref.get(admission).pipe(
|
|
95
|
+
Effect.flatMap((open) =>
|
|
96
|
+
open
|
|
97
|
+
? Effect.void
|
|
98
|
+
: Effect.fail(
|
|
99
|
+
AdmissionClosed.make({ message: 'The host is shutting down; admission is closed.' }),
|
|
100
|
+
)
|
|
101
|
+
),
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
const submit = <InputSchema extends Schema.Top>(
|
|
105
|
+
agent: DurableSubmitAgent<InputSchema>,
|
|
106
|
+
input: InputSchema['Type'],
|
|
107
|
+
options: DurableSubmitOptions,
|
|
108
|
+
): Effect.Effect<
|
|
109
|
+
Receipt,
|
|
110
|
+
AdmissionClosed | DurableSubmitFailure,
|
|
111
|
+
InputSchema['EncodingServices']
|
|
112
|
+
> => requireAdmission.pipe(Effect.andThen(runtime.submit(agent, input, options)))
|
|
113
|
+
|
|
114
|
+
const deliveryServices = (yield* Effect.context<MessageDeliveryStore>()).pipe(
|
|
115
|
+
Context.pick(MessageDeliveryStore),
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
const deliveryContext = yield* Layer.build(
|
|
119
|
+
MessageDeliveryDriver.layer({
|
|
120
|
+
batchSize: 100,
|
|
121
|
+
concurrency: Math.min(config.workerConcurrency, 32),
|
|
122
|
+
}).pipe(
|
|
123
|
+
Layer.provide(NodeCrypto.layer),
|
|
124
|
+
Layer.provide(
|
|
125
|
+
Layer.effect(PreparedInputAdmission, makeNodePreparedInputAdmission).pipe(
|
|
126
|
+
Layer.provide(
|
|
127
|
+
Layer.succeed(NodeAdmission, { submit, submissionStatus: runtime.submissionStatus }),
|
|
128
|
+
),
|
|
129
|
+
),
|
|
130
|
+
),
|
|
131
|
+
),
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
const runDeliveries = Effect.contextWith((live: Context.Context<never>) =>
|
|
135
|
+
runNodeMessageDeliveries(config.wakeScanInterval).pipe(
|
|
136
|
+
Effect.setContext(
|
|
137
|
+
Context.mergeAll(applicationInvocationContext(live), deliveryServices, deliveryContext),
|
|
138
|
+
),
|
|
139
|
+
)
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
const withDeliveries = <A, E, R>(worker: Effect.Effect<A, E, R>): Effect.Effect<void, E, R> =>
|
|
143
|
+
Effect.scoped(
|
|
144
|
+
// Either side exiting stops and joins the other; delivery interruption cannot leave
|
|
145
|
+
// an apparently healthy worker pool running without message recovery.
|
|
146
|
+
Effect.raceFirst(worker, runDeliveries).pipe(Effect.asVoid),
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
const runWorkers = <A, E, R>(worker: Effect.Effect<A, E, R>): Effect.Effect<void, E, R> =>
|
|
150
|
+
withDeliveries(
|
|
151
|
+
Effect.forEach(
|
|
152
|
+
Array.from({ length: config.workerConcurrency }, (_, index) => index),
|
|
153
|
+
() => worker,
|
|
154
|
+
{ concurrency: 'unbounded', discard: true },
|
|
155
|
+
),
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
// Managed hosts dispatch each lane once. Bare host layers retain their existing service
|
|
159
|
+
// requirements and generic worker-loop composition.
|
|
160
|
+
const runResolvedWorkers = managedWorkers === undefined
|
|
161
|
+
? runWorkers(runtime.runResolvedWorker)
|
|
162
|
+
: withDeliveries(managedWorkers)
|
|
163
|
+
|
|
164
|
+
const run = managedWorkers !== undefined
|
|
165
|
+
? Fiber.join(
|
|
166
|
+
yield* runResolvedWorkers.pipe(
|
|
167
|
+
Effect.onExit(() => Ref.set(admission, false)),
|
|
168
|
+
Effect.forkScoped,
|
|
169
|
+
),
|
|
170
|
+
)
|
|
171
|
+
: runResolvedWorkers
|
|
172
|
+
|
|
173
|
+
// Register after the worker fiber: close admission, interrupt/join workers, close
|
|
174
|
+
// local owner generations, then close storage and captured application services.
|
|
175
|
+
yield* Effect.addFinalizer(() => Ref.set(admission, false))
|
|
176
|
+
|
|
177
|
+
return NodeDurableHost.of({
|
|
178
|
+
startupRecovery: startupReports,
|
|
179
|
+
admissionOpen: Ref.get(admission),
|
|
180
|
+
submit,
|
|
181
|
+
awaitSettlement: runtime.awaitSettlement,
|
|
182
|
+
submissionStatus: runtime.submissionStatus,
|
|
183
|
+
observe: runtime.observe,
|
|
184
|
+
abort: runtime.abort,
|
|
185
|
+
runWorkers,
|
|
186
|
+
run,
|
|
187
|
+
runResolvedWorkers: run,
|
|
188
|
+
})
|
|
189
|
+
})
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Operational host service. Prefer the module's `layer` and `run` for managed workers.
|
|
193
|
+
* The static constructors on this class retain explicit, manual worker ownership.
|
|
194
|
+
* Use the accompanying `DurableAgentRuntime` service for inspection and recovery operations.
|
|
195
|
+
*
|
|
196
|
+
* Startup gates run during Layer construction, so the service existing implies readiness:
|
|
197
|
+
* configuration was schema-decoded, the SQLite file passed the exact-version compatibility check,
|
|
198
|
+
* and the complete native work inventory passed recovery BEFORE admission opened.
|
|
199
|
+
* `startupRecovery` retains the last bounded page of Submission decisions.
|
|
200
|
+
*
|
|
201
|
+
* Shutdown runs in reverse Layer order when the owning Scope closes: `submit` starts refusing
|
|
202
|
+
* with `AdmissionClosed` first, then workers stop and local owner generations close before
|
|
203
|
+
* SQLite resources. Accepted work remains recoverable after forced termination (DEPLOY-006).
|
|
204
|
+
*/
|
|
205
|
+
export class NodeDurableHost extends Context.Service<
|
|
206
|
+
NodeDurableHost,
|
|
207
|
+
{
|
|
208
|
+
/**
|
|
209
|
+
* The last 32 Submission decisions executed (or deferred) at startup. Earlier pages are
|
|
210
|
+
* released as reconciliation advances, so startup memory does not grow with Thread count.
|
|
211
|
+
* Reports with the `unknown` disposition identify parked Submissions with Unknown Outcomes.
|
|
212
|
+
* They retain their settlement obligation while later input can run; authorized resolution
|
|
213
|
+
* or abort advances the parked Submission.
|
|
214
|
+
*/
|
|
215
|
+
readonly startupRecovery: ReadonlyArray<RecoveryReport>
|
|
216
|
+
/** Admission-role readiness (deployment §7): true until shutdown begins. */
|
|
217
|
+
readonly admissionOpen: Effect.Effect<boolean>
|
|
218
|
+
/** Observe the managed worker pool, preserving its failure. Manual hosts start their pool here. */
|
|
219
|
+
readonly run: Effect.Effect<void, DurableWorkerFailure | DurableBindingFailure>
|
|
220
|
+
/** `DurableAgentRuntime.submit` behind the host admission gate. */
|
|
221
|
+
readonly submit: <InputSchema extends Schema.Top>(
|
|
222
|
+
agent: DurableSubmitAgent<InputSchema>,
|
|
223
|
+
input: InputSchema['Type'],
|
|
224
|
+
options: DurableSubmitOptions,
|
|
225
|
+
) => Effect.Effect<
|
|
226
|
+
Receipt,
|
|
227
|
+
AdmissionClosed | DurableSubmitFailure,
|
|
228
|
+
InputSchema['EncodingServices']
|
|
229
|
+
>
|
|
230
|
+
readonly submissionStatus: DurableAgentRuntime['Service']['submissionStatus']
|
|
231
|
+
readonly awaitSettlement: (receipt: Receipt) => Effect.Effect<Settlement, DurableAwaitFailure>
|
|
232
|
+
readonly observe: (
|
|
233
|
+
receipt: Receipt,
|
|
234
|
+
options?: DurableObserveOptions,
|
|
235
|
+
) => Stream.Stream<
|
|
236
|
+
CanonicalRecordEnvelope,
|
|
237
|
+
ThreadStoreError | ThreadNotMaterialized | OperationDenied
|
|
238
|
+
>
|
|
239
|
+
readonly abort: (command: AbortCommand) => Effect.Effect<AbortIntent, DurableAbortFailure>
|
|
240
|
+
/**
|
|
241
|
+
* Run `workerConcurrency` copies of the given worker effect (typically
|
|
242
|
+
* `DurableAgentRuntime.runResolvedWorker`) until the caller's Scope interrupts them. The
|
|
243
|
+
* same Scope drives pending message admission and settlement observation independently
|
|
244
|
+
* of Submission liveness. The host never forks daemon fibers.
|
|
245
|
+
*/
|
|
246
|
+
readonly runWorkers: <A, E, R>(worker: Effect.Effect<A, E, R>) => Effect.Effect<void, E, R>
|
|
247
|
+
/**
|
|
248
|
+
* Run `workerConcurrency` copies of `DurableAgentRuntime.runResolvedWorker` over the host's
|
|
249
|
+
* registered Bindings: every claimed head resolves the current Binding for its stable
|
|
250
|
+
* agentId, so one bounded pool serves parent and attached-child lanes.
|
|
251
|
+
* Hosts built with the module-level `layer` instead join their existing pool, which
|
|
252
|
+
* dispatches distinct Thread lanes through one bounded queue.
|
|
253
|
+
*/
|
|
254
|
+
readonly runResolvedWorkers: Effect.Effect<void, DurableWorkerFailure | DurableBindingFailure>
|
|
255
|
+
}
|
|
256
|
+
>()('@effect-agent/platform-node/NodeDurableHost') {
|
|
257
|
+
/**
|
|
258
|
+
* Compile typed registrations and acquire the complete host in one Layer Scope.
|
|
259
|
+
* Node supplies Digest and SecureRandom; model, tool, instruction, and schema services remain required.
|
|
260
|
+
* Startup recovery and shutdown gates are unchanged. Workers start only when the caller
|
|
261
|
+
* runs runResolvedWorkers; this constructor never starts a background worker.
|
|
262
|
+
*/
|
|
263
|
+
static layerRegistered<
|
|
264
|
+
const Entries extends ReadonlyArray<AgentRegistration>,
|
|
265
|
+
ContextError = never,
|
|
266
|
+
ContextRequirements = never,
|
|
267
|
+
AuthorizationError = never,
|
|
268
|
+
AuthorizationRequirements = never,
|
|
269
|
+
ReconcilerError = never,
|
|
270
|
+
ReconcilerRequirements = never,
|
|
271
|
+
>(
|
|
272
|
+
registrations: Entries,
|
|
273
|
+
options: NodeDurableAgentRuntimeOptions<
|
|
274
|
+
ContextError,
|
|
275
|
+
ContextRequirements,
|
|
276
|
+
AuthorizationError,
|
|
277
|
+
AuthorizationRequirements,
|
|
278
|
+
ReconcilerError,
|
|
279
|
+
ReconcilerRequirements
|
|
280
|
+
>,
|
|
281
|
+
) {
|
|
282
|
+
return NodeDurableHost.layer.pipe(
|
|
283
|
+
Layer.provideMerge(NodeDurableAgentRuntime.layerRegistered(registrations, options)),
|
|
284
|
+
)
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Host gates over an assembled `NodeDurableAgentRuntime` stack. The runtime Layer owns
|
|
289
|
+
* executable registrations; omission registers no Agents, so resolved work fails closed.
|
|
290
|
+
*/
|
|
291
|
+
static readonly layer: Layer.Layer<
|
|
292
|
+
NodeDurableHost,
|
|
293
|
+
DurableWorkerFailure | RecoveryBlocked | MessageDeliveryError,
|
|
294
|
+
DurableAgentRuntime | NodeDurableAgentRuntimeConfig | MessageDeliveryStore
|
|
295
|
+
> = Layer.effect(NodeDurableHost)(makeHost())
|
|
296
|
+
|
|
297
|
+
/** The complete DN host: `NodeDurableAgentRuntime.layer(options)` plus the host lifecycle gates. */
|
|
298
|
+
static layerStack<
|
|
299
|
+
ContextError = never,
|
|
300
|
+
ContextRequirements = never,
|
|
301
|
+
AuthorizationError = never,
|
|
302
|
+
AuthorizationRequirements = never,
|
|
303
|
+
ReconcilerError = never,
|
|
304
|
+
ReconcilerRequirements = never,
|
|
305
|
+
>(
|
|
306
|
+
options:
|
|
307
|
+
& NodeDurableAgentRuntimeOptions<
|
|
308
|
+
ContextError,
|
|
309
|
+
ContextRequirements,
|
|
310
|
+
AuthorizationError,
|
|
311
|
+
AuthorizationRequirements,
|
|
312
|
+
ReconcilerError,
|
|
313
|
+
ReconcilerRequirements
|
|
314
|
+
>
|
|
315
|
+
& { readonly bindings?: ReadonlyArray<ResolvedBinding> },
|
|
316
|
+
) {
|
|
317
|
+
const { bindings = [], ...runtimeOptions } = options
|
|
318
|
+
|
|
319
|
+
return NodeDurableHost.layer.pipe(
|
|
320
|
+
Layer.provideMerge(NodeDurableAgentRuntime.layerWithBindings(bindings, runtimeOptions)),
|
|
321
|
+
)
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* Acquire a complete Node host and start one bounded, scoped worker pool after recovery.
|
|
327
|
+
* Own the SQLite file exclusively until the host and its storage close. A second connection
|
|
328
|
+
* fails construction. Process death releases the file lock; a replacement acquires it before
|
|
329
|
+
* recovering retained work with fresh local generations. Use this host's services for live inspection.
|
|
330
|
+
* Provide model, tool, instruction, and schema dependencies to this Layer. Reusing the Layer
|
|
331
|
+
* shares the same pool. A worker failure closes admission; observe it with `run` at the process
|
|
332
|
+
* boundary so the application exits and releases the host instead of remaining idle.
|
|
333
|
+
*/
|
|
334
|
+
export const layer = <
|
|
335
|
+
const Entries extends ReadonlyArray<AgentRegistration>,
|
|
336
|
+
ContextError = never,
|
|
337
|
+
ContextRequirements = never,
|
|
338
|
+
AuthorizationError = never,
|
|
339
|
+
AuthorizationRequirements = never,
|
|
340
|
+
ReconcilerError = never,
|
|
341
|
+
ReconcilerRequirements = never,
|
|
342
|
+
>(
|
|
343
|
+
registrations: Entries,
|
|
344
|
+
options: NodeDurableAgentRuntimeOptions<
|
|
345
|
+
ContextError,
|
|
346
|
+
ContextRequirements,
|
|
347
|
+
AuthorizationError,
|
|
348
|
+
AuthorizationRequirements,
|
|
349
|
+
ReconcilerError,
|
|
350
|
+
ReconcilerRequirements
|
|
351
|
+
>,
|
|
352
|
+
) =>
|
|
353
|
+
Layer.effectContext(
|
|
354
|
+
Effect.gen(function*() {
|
|
355
|
+
// The runtime compiles registrations in application Context before acquiring storage.
|
|
356
|
+
const services = yield* Layer.build(
|
|
357
|
+
NodeDurableAgentRuntime.layerRegistered(registrations, options).pipe(
|
|
358
|
+
Layer.provide(Layer.succeed(ExclusiveSqliteHost, true)),
|
|
359
|
+
),
|
|
360
|
+
)
|
|
361
|
+
|
|
362
|
+
const config = Context.get(services, NodeDurableAgentRuntimeConfig)
|
|
363
|
+
|
|
364
|
+
const workerServices = services.pipe(
|
|
365
|
+
Context.pick(DurableAgentRuntime, SubmissionLedger, WakeScheduler),
|
|
366
|
+
)
|
|
367
|
+
|
|
368
|
+
const hostServices = services.pipe(
|
|
369
|
+
Context.pick(DurableAgentRuntime, NodeDurableAgentRuntimeConfig, MessageDeliveryStore),
|
|
370
|
+
)
|
|
371
|
+
|
|
372
|
+
const host = yield* makeHost(
|
|
373
|
+
Effect.contextWith((live: Context.Context<never>) =>
|
|
374
|
+
runNodeWorkerDispatch(config.workerConcurrency).pipe(
|
|
375
|
+
Effect.setContext(Context.merge(applicationInvocationContext(live), workerServices)),
|
|
376
|
+
)
|
|
377
|
+
),
|
|
378
|
+
).pipe(Effect.provide(hostServices))
|
|
379
|
+
|
|
380
|
+
// Export actual capabilities: canonical reads and the separately owned delivery queue.
|
|
381
|
+
// Raw SQL, canonical writes and submission ownership remain private.
|
|
382
|
+
return services.pipe(
|
|
383
|
+
Context.pick(
|
|
384
|
+
DurableAgentRuntime,
|
|
385
|
+
ThreadReader,
|
|
386
|
+
NodeDurableAgentRuntimeConfig,
|
|
387
|
+
MessageDeliveryStore,
|
|
388
|
+
),
|
|
389
|
+
Context.add(NodeDurableHost, host),
|
|
390
|
+
)
|
|
391
|
+
}),
|
|
392
|
+
)
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* Supervise the host's existing workers without starting another pool. Use with
|
|
396
|
+
* `Effect.provide(HostLive)` and `NodeRuntime.runMain`; race it with a server Effect when
|
|
397
|
+
* the same process also serves requests. Unlike `Layer.launch`, this observes worker failures.
|
|
398
|
+
*/
|
|
399
|
+
export const run = Effect.gen(function*() {
|
|
400
|
+
const host = yield* NodeDurableHost
|
|
401
|
+
|
|
402
|
+
return yield* host.run
|
|
403
|
+
})
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import * as NodeCrypto from '@effect/platform-node/NodeCrypto'
|
|
2
|
+
import {
|
|
3
|
+
defaultSchedulingLimits,
|
|
4
|
+
type ScheduleAuthorizer,
|
|
5
|
+
ScheduleStorageError,
|
|
6
|
+
ScheduleStore,
|
|
7
|
+
type ScheduleValidationError,
|
|
8
|
+
ScheduleWake,
|
|
9
|
+
type SchedulingLimits,
|
|
10
|
+
} from '@systemfsoftware/agent/schedule'
|
|
11
|
+
import { ScheduleDriver, type ScheduleProcessFailure, Scheduling } from '@systemfsoftware/agent/scheduling'
|
|
12
|
+
import * as Cause from 'effect/Cause'
|
|
13
|
+
import * as Duration from 'effect/Duration'
|
|
14
|
+
import * as Effect from 'effect/Effect'
|
|
15
|
+
import * as Layer from 'effect/Layer'
|
|
16
|
+
import * as Option from 'effect/Option'
|
|
17
|
+
import * as PubSub from 'effect/PubSub'
|
|
18
|
+
import * as Result from 'effect/Result'
|
|
19
|
+
|
|
20
|
+
import type { NodeDurableHost } from './NodeDurableHost'
|
|
21
|
+
import { nodePreparedInputAdmissionLayer } from './NodeSubscriptions'
|
|
22
|
+
|
|
23
|
+
/** One bounded hint slot for the single supported Node scheduler. Indexed polling repairs loss. */
|
|
24
|
+
export const nodeScheduleWakeLayer: Layer.Layer<ScheduleWake> = Layer.effect(
|
|
25
|
+
ScheduleWake,
|
|
26
|
+
Effect.gen(function*() {
|
|
27
|
+
const hints = yield* PubSub.sliding<void>(1)
|
|
28
|
+
const subscription = yield* PubSub.subscribe(hints)
|
|
29
|
+
|
|
30
|
+
yield* Effect.addFinalizer(() => PubSub.shutdown(hints))
|
|
31
|
+
|
|
32
|
+
return ScheduleWake.of({
|
|
33
|
+
notify: PubSub.publish(hints, undefined).pipe(Effect.asVoid),
|
|
34
|
+
await: PubSub.take(subscription),
|
|
35
|
+
})
|
|
36
|
+
}),
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
const reportPassFailure = (cause: Cause.Cause<ScheduleProcessFailure>): Effect.Effect<boolean> =>
|
|
40
|
+
Cause.hasInterruptsOnly(cause)
|
|
41
|
+
? Effect.interrupt
|
|
42
|
+
: Effect.logWarning('Node scheduling pass failed').pipe(
|
|
43
|
+
Effect.annotateLogs({
|
|
44
|
+
failureTag: Option.match(Cause.findErrorOption(cause), {
|
|
45
|
+
onNone: () => 'Defect',
|
|
46
|
+
onSome: (error) => error._tag,
|
|
47
|
+
}),
|
|
48
|
+
}),
|
|
49
|
+
Effect.as(false),
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
const nodeSchedulingDriverLayer = (
|
|
53
|
+
limits: SchedulingLimits,
|
|
54
|
+
): Layer.Layer<never, never, ScheduleDriver | ScheduleStore | ScheduleWake> =>
|
|
55
|
+
Layer.effectDiscard(
|
|
56
|
+
Effect.gen(function*() {
|
|
57
|
+
const scheduling = yield* ScheduleDriver
|
|
58
|
+
const store = yield* ScheduleStore
|
|
59
|
+
const wake = yield* ScheduleWake
|
|
60
|
+
|
|
61
|
+
const run = Effect.gen(function*() {
|
|
62
|
+
while (true) {
|
|
63
|
+
const passSucceeded = yield* scheduling.runDue().pipe(
|
|
64
|
+
Effect.map((pass) => pass.failed === 0),
|
|
65
|
+
Effect.catchCause(reportPassFailure),
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
const deadlineResult = passSucceeded
|
|
69
|
+
? yield* store.nextDeadline().pipe(Effect.result)
|
|
70
|
+
: Result.fail(
|
|
71
|
+
ScheduleStorageError.make({ operation: 'driver pass', reason: 'unavailable' }),
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
if (Result.isFailure(deadlineResult) && passSucceeded) {
|
|
75
|
+
yield* Effect.logWarning('Node scheduling deadline query failed')
|
|
76
|
+
}
|
|
77
|
+
const nowMillis = yield* Effect.clockWith((clock) => clock.currentTimeMillis)
|
|
78
|
+
|
|
79
|
+
const deadlineDelay = Result.isSuccess(deadlineResult) && deadlineResult.success !== null
|
|
80
|
+
? Math.max(0, deadlineResult.success - nowMillis)
|
|
81
|
+
: limits.recoveryPollMillis
|
|
82
|
+
|
|
83
|
+
const delay = Math.min(deadlineDelay, limits.recoveryPollMillis)
|
|
84
|
+
|
|
85
|
+
yield* Effect.raceFirst(wake.await, Effect.sleep(Duration.millis(delay)))
|
|
86
|
+
}
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
yield* Effect.forkScoped(run)
|
|
90
|
+
}),
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
export interface NodeSchedulingOptions {
|
|
94
|
+
readonly limits?: SchedulingLimits | undefined
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Optional Scope-owned Node scheduling service and driver. The caller must provide the existing
|
|
99
|
+
* host, its SQLite ScheduleStore, and an explicit ScheduleAuthorizer.
|
|
100
|
+
*/
|
|
101
|
+
export class NodeScheduling {
|
|
102
|
+
static layer(
|
|
103
|
+
options: NodeSchedulingOptions = {},
|
|
104
|
+
): Layer.Layer<
|
|
105
|
+
Scheduling,
|
|
106
|
+
ScheduleValidationError,
|
|
107
|
+
NodeDurableHost | ScheduleStore | ScheduleAuthorizer
|
|
108
|
+
> {
|
|
109
|
+
const limits = options.limits ?? defaultSchedulingLimits
|
|
110
|
+
|
|
111
|
+
const schedulingWithDriver = nodeSchedulingDriverLayer(limits).pipe(
|
|
112
|
+
Layer.provide(ScheduleDriver.layer(limits)),
|
|
113
|
+
Layer.merge(Scheduling.layer(limits)),
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
return schedulingWithDriver.pipe(
|
|
117
|
+
Layer.provide(
|
|
118
|
+
Layer.mergeAll(nodePreparedInputAdmissionLayer, nodeScheduleWakeLayer, NodeCrypto.layer),
|
|
119
|
+
),
|
|
120
|
+
)
|
|
121
|
+
}
|
|
122
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import * as NodeCrypto from '@effect/platform-node/NodeCrypto'
|
|
2
|
+
import { type EventSources } from '@systemfsoftware/agent/event-source'
|
|
3
|
+
import { PreparedInputAdmission } from '@systemfsoftware/agent/prepared-input-admission'
|
|
4
|
+
import {
|
|
5
|
+
defaultSubscriptionLimits,
|
|
6
|
+
type SubscriptionAuthorizer,
|
|
7
|
+
type SubscriptionError,
|
|
8
|
+
type SubscriptionLimits,
|
|
9
|
+
SubscriptionStore,
|
|
10
|
+
type SubscriptionStoreFailure,
|
|
11
|
+
} from '@systemfsoftware/agent/subscription'
|
|
12
|
+
import { type SubscriptionInputBindings } from '@systemfsoftware/agent/subscription-input'
|
|
13
|
+
import { SubscriptionDriver, SubscriptionIntake, Subscriptions } from '@systemfsoftware/agent/subscriptions'
|
|
14
|
+
import * as Cause from 'effect/Cause'
|
|
15
|
+
import * as Duration from 'effect/Duration'
|
|
16
|
+
import * as Effect from 'effect/Effect'
|
|
17
|
+
import * as Exit from 'effect/Exit'
|
|
18
|
+
import * as Layer from 'effect/Layer'
|
|
19
|
+
import * as Option from 'effect/Option'
|
|
20
|
+
|
|
21
|
+
import { makeNodePreparedInputAdmission, NodeAdmission } from './internal/prepared-admission'
|
|
22
|
+
import { NodeDurableHost } from './NodeDurableHost'
|
|
23
|
+
|
|
24
|
+
/** Ordinary prepared admission through the Scope-owned Node host gate. */
|
|
25
|
+
export const nodePreparedInputAdmissionLayer: Layer.Layer<
|
|
26
|
+
PreparedInputAdmission,
|
|
27
|
+
never,
|
|
28
|
+
NodeDurableHost
|
|
29
|
+
> = Layer.effect(PreparedInputAdmission, makeNodePreparedInputAdmission).pipe(
|
|
30
|
+
Layer.provide(Layer.effect(NodeAdmission, NodeDurableHost)),
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
const reportPassFailure = (cause: Cause.Cause<SubscriptionStoreFailure>): Effect.Effect<boolean> =>
|
|
34
|
+
Cause.hasInterruptsOnly(cause)
|
|
35
|
+
? Effect.interrupt
|
|
36
|
+
: Effect.logWarning('Node subscription pass failed').pipe(
|
|
37
|
+
Effect.annotateLogs({
|
|
38
|
+
failureTag: Option.match(Cause.findErrorOption(cause), {
|
|
39
|
+
onNone: () => 'Defect',
|
|
40
|
+
onSome: (error) => error._tag,
|
|
41
|
+
}),
|
|
42
|
+
}),
|
|
43
|
+
Effect.as(false),
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
const nodeSubscriptionDriverLayer = (
|
|
47
|
+
limits: SubscriptionLimits,
|
|
48
|
+
): Layer.Layer<never, never, SubscriptionDriver | SubscriptionStore> =>
|
|
49
|
+
Layer.effectDiscard(
|
|
50
|
+
Effect.gen(function*() {
|
|
51
|
+
const driver = yield* SubscriptionDriver
|
|
52
|
+
const store = yield* SubscriptionStore
|
|
53
|
+
|
|
54
|
+
const run = Effect.gen(function*() {
|
|
55
|
+
while (true) {
|
|
56
|
+
const passSucceeded = yield* driver.runDue.pipe(
|
|
57
|
+
Effect.map((pass) => pass.failed === 0),
|
|
58
|
+
Effect.catchCause(reportPassFailure),
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
if (!passSucceeded) {
|
|
62
|
+
yield* Effect.sleep(Duration.millis(limits.retryMillis))
|
|
63
|
+
continue
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const deadline = yield* store.nextDeadline.pipe(Effect.exit)
|
|
67
|
+
|
|
68
|
+
if (Exit.isFailure(deadline)) {
|
|
69
|
+
yield* reportPassFailure(deadline.cause)
|
|
70
|
+
yield* Effect.sleep(Duration.millis(limits.retryMillis))
|
|
71
|
+
continue
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const nowMillis = yield* Effect.clockWith((clock) => clock.currentTimeMillis)
|
|
75
|
+
|
|
76
|
+
const delay = deadline.value === null
|
|
77
|
+
? limits.retryMillis
|
|
78
|
+
: Math.max(1, Math.min(deadline.value - nowMillis, limits.retryMillis))
|
|
79
|
+
|
|
80
|
+
yield* Effect.sleep(Duration.millis(delay))
|
|
81
|
+
}
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
yield* Effect.forkScoped(run)
|
|
85
|
+
}),
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
export interface NodeSubscriptionsOptions {
|
|
89
|
+
readonly limits?: SubscriptionLimits | undefined
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* One Scope-owned subscription partition in the sole process owning its SQLite database.
|
|
94
|
+
* Indexed polling repairs restart and lost wake state; closing the Scope interrupts the driver.
|
|
95
|
+
*/
|
|
96
|
+
export class NodeSubscriptions {
|
|
97
|
+
static layer(
|
|
98
|
+
options: NodeSubscriptionsOptions = {},
|
|
99
|
+
): Layer.Layer<
|
|
100
|
+
Subscriptions | SubscriptionIntake,
|
|
101
|
+
SubscriptionError,
|
|
102
|
+
| NodeDurableHost
|
|
103
|
+
| SubscriptionStore
|
|
104
|
+
| SubscriptionAuthorizer
|
|
105
|
+
| EventSources
|
|
106
|
+
| SubscriptionInputBindings
|
|
107
|
+
> {
|
|
108
|
+
const limits = options.limits ?? defaultSubscriptionLimits
|
|
109
|
+
|
|
110
|
+
const publicServices = Layer.merge(
|
|
111
|
+
Subscriptions.layer(limits),
|
|
112
|
+
SubscriptionIntake.layer(limits),
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
const driver = nodeSubscriptionDriverLayer(limits).pipe(
|
|
116
|
+
Layer.provide(SubscriptionDriver.layer(limits)),
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
return Layer.merge(publicServices, driver).pipe(
|
|
120
|
+
Layer.provide(nodePreparedInputAdmissionLayer),
|
|
121
|
+
Layer.provide(NodeCrypto.layer),
|
|
122
|
+
)
|
|
123
|
+
}
|
|
124
|
+
}
|