brass-runtime 1.15.0 → 1.16.1
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/CHANGELOG.md +17 -0
- package/README.md +673 -136
- package/dist/agent/cli/main.cjs +40 -35
- package/dist/agent/cli/main.js +9 -4
- package/dist/agent/cli/main.mjs +9 -4
- package/dist/agent/index.cjs +8 -4
- package/dist/agent/index.d.ts +1 -1
- package/dist/agent/index.js +7 -3
- package/dist/agent/index.mjs +7 -3
- package/dist/chunk-2HQTDLHF.mjs +683 -0
- package/dist/chunk-36I3M4UC.mjs +370 -0
- package/dist/chunk-3AYM6WPJ.js +1629 -0
- package/dist/chunk-3LOYJFRR.cjs +300 -0
- package/dist/chunk-3RG5ZIWI.js +10 -0
- package/dist/chunk-3Y2RIUMM.js +300 -0
- package/dist/{chunk-VEZNF5GZ.cjs → chunk-4ROBZFL6.cjs} +130 -126
- package/dist/{chunk-3QMOKAS5.js → chunk-52OB2ROS.js} +9 -5
- package/dist/chunk-52PPNNI4.cjs +416 -0
- package/dist/chunk-5EC274J5.cjs +2874 -0
- package/dist/chunk-5QC7LRZ3.js +229 -0
- package/dist/chunk-5VRJNBLZ.mjs +2874 -0
- package/dist/chunk-62AZW6UT.cjs +313 -0
- package/dist/chunk-6IXXWIUM.js +683 -0
- package/dist/chunk-74ZTY6CP.js +2871 -0
- package/dist/chunk-76YMRMH2.cjs +777 -0
- package/dist/chunk-7CMJS3QE.mjs +2871 -0
- package/dist/{chunk-4NHES7VK.mjs → chunk-7JIJOVCT.js} +27 -13
- package/dist/chunk-A2OM6NEH.mjs +194 -0
- package/dist/chunk-AGR5B2BC.cjs +683 -0
- package/dist/chunk-AVNQLJ5V.js +777 -0
- package/dist/chunk-B33ICAKP.js +313 -0
- package/dist/{chunk-ELOOF35R.mjs → chunk-B5JD23U7.mjs} +1 -1
- package/dist/chunk-BABBZK4Y.js +2024 -0
- package/dist/chunk-C3MDXTRZ.js +354 -0
- package/dist/chunk-CIZFIMK5.js +2193 -0
- package/dist/chunk-CZIVE6NT.cjs +354 -0
- package/dist/chunk-DNFJLJMW.mjs +354 -0
- package/dist/chunk-DNFO2EIZ.mjs +777 -0
- package/dist/chunk-EJ6BPYVR.mjs +416 -0
- package/dist/chunk-ENKODRU3.cjs +2193 -0
- package/dist/chunk-EOC4UHBS.mjs +229 -0
- package/dist/{chunk-BMH5AV44.js → chunk-FH2X7BVP.js} +756 -440
- package/dist/{chunk-PPUXIH5R.js → chunk-FHQGHPMO.mjs} +27 -13
- package/dist/{chunk-TGIFUAK4.cjs → chunk-GLE2WY7Z.cjs} +951 -635
- package/dist/{chunk-BDF4AMWX.mjs → chunk-GYM3LLGS.mjs} +756 -440
- package/dist/chunk-HLWLMW2F.mjs +2024 -0
- package/dist/chunk-JF5WGYJJ.cjs +194 -0
- package/dist/chunk-KH4SYAOS.mjs +1629 -0
- package/dist/chunk-KN32XNTH.mjs +313 -0
- package/dist/chunk-KQLYONSE.cjs +2871 -0
- package/dist/{chunk-STVLQ3XD.cjs → chunk-KZJQ723N.cjs} +92 -78
- package/dist/chunk-L2SYFEBS.js +194 -0
- package/dist/chunk-L6VB5N7Q.cjs +104 -0
- package/dist/{chunk-K6M7MDZ4.mjs → chunk-MBEJI5HF.mjs} +9 -5
- package/dist/chunk-MIIYDLGM.js +2874 -0
- package/dist/chunk-MOO4L7F4.mjs +104 -0
- package/dist/chunk-MT3OWDPC.mjs +2193 -0
- package/dist/chunk-MVGUEJ5Z.cjs +370 -0
- package/dist/chunk-OBGZSXTJ.cjs +10 -0
- package/dist/chunk-PD4EJTQC.cjs +229 -0
- package/dist/chunk-PWC3RBQE.mjs +300 -0
- package/dist/chunk-Q2I37RP3.cjs +1629 -0
- package/dist/chunk-RKGKFN2A.js +416 -0
- package/dist/{chunk-R3R2FVLG.cjs → chunk-SA6HUJVI.cjs} +5 -5
- package/dist/chunk-TRM4JUZQ.js +104 -0
- package/dist/chunk-UB4B6OFY.js +370 -0
- package/dist/{chunk-TO7IKXYT.js → chunk-UCUBNWM2.js} +1 -1
- package/dist/chunk-VN44DYYT.cjs +2024 -0
- package/dist/chunk-Y6FXYEAI.mjs +10 -0
- package/dist/client-CZHU674n.d.ts +820 -0
- package/dist/core/index.cjs +198 -4
- package/dist/core/index.d.ts +311 -212
- package/dist/core/index.js +237 -43
- package/dist/core/index.mjs +237 -43
- package/dist/{effect-CMOQKX8y.d.ts → effect-DIUHZ9IN.d.ts} +195 -1
- package/dist/effectRunner-CFLC32IK.cjs +8 -0
- package/dist/effectRunner-L4S7IPT3.js +8 -0
- package/dist/effectRunner-NNGG75QA.mjs +8 -0
- package/dist/http/index.cjs +1227 -2971
- package/dist/http/index.d.ts +826 -280
- package/dist/http/index.js +1089 -2833
- package/dist/http/index.mjs +1089 -2833
- package/dist/http/testing.cjs +161 -0
- package/dist/http/testing.d.ts +43 -0
- package/dist/http/testing.js +161 -0
- package/dist/http/testing.mjs +161 -0
- package/dist/index.cjs +486 -250
- package/dist/index.d.ts +87 -95
- package/dist/index.js +391 -155
- package/dist/index.mjs +391 -155
- package/dist/observability/index.cjs +162 -0
- package/dist/observability/index.d.ts +152 -0
- package/dist/observability/index.js +162 -0
- package/dist/observability/index.mjs +162 -0
- package/dist/perf/cli.cjs +401 -0
- package/dist/perf/cli.d.ts +1 -0
- package/dist/perf/cli.js +401 -0
- package/dist/perf/cli.mjs +401 -0
- package/dist/perf/index.cjs +141 -0
- package/dist/perf/index.d.ts +483 -0
- package/dist/perf/index.js +141 -0
- package/dist/perf/index.mjs +141 -0
- package/dist/schedule-CK3Ml_7p.d.ts +259 -0
- package/dist/schema/index.cjs +29 -0
- package/dist/schema/index.d.ts +179 -0
- package/dist/schema/index.js +29 -0
- package/dist/schema/index.mjs +29 -0
- package/dist/server-GJPg8ZSG.d.ts +675 -0
- package/dist/{stream-FQm9h4Mg.d.ts → stream-B4oK9JFP.d.ts} +1 -1
- package/dist/tracer-Hwt1cl7h.d.ts +189 -0
- package/dist/tracing-DqbTKGcf.d.ts +148 -0
- package/docs/ARCHITECTURE.md +292 -0
- package/docs/README.md +63 -0
- package/docs/adr/0001-ai-context-pack.md +32 -0
- package/docs/agent-apply-mode.md +104 -0
- package/docs/agent-approvals.md +110 -0
- package/docs/agent-batch.md +185 -0
- package/docs/agent-boundaries.md +112 -0
- package/docs/agent-chat-sessions.md +160 -0
- package/docs/agent-ci.md +17 -0
- package/docs/agent-cli.md +405 -0
- package/docs/agent-config.md +480 -0
- package/docs/agent-context-discovery.md +159 -0
- package/docs/agent-copilot-like-dx.md +126 -0
- package/docs/agent-declarative-optimized-planning.md +138 -0
- package/docs/agent-dx.md +224 -0
- package/docs/agent-env-files.md +126 -0
- package/docs/agent-follow-up-context.md +43 -0
- package/docs/agent-global-usage.md +180 -0
- package/docs/agent-init.md +109 -0
- package/docs/agent-install-and-configure.md +516 -0
- package/docs/agent-language-workspace-ux.md +99 -0
- package/docs/agent-llm-adapters.md +123 -0
- package/docs/agent-local-install.md +190 -0
- package/docs/agent-local-tests.md +51 -0
- package/docs/agent-observability.md +155 -0
- package/docs/agent-patch-quality-loop.md +162 -0
- package/docs/agent-presets.md +22 -0
- package/docs/agent-project-commands.md +237 -0
- package/docs/agent-project-intelligence.md +156 -0
- package/docs/agent-redaction.md +18 -0
- package/docs/agent-release-readiness.md +76 -0
- package/docs/agent-rollback-safety.md +162 -0
- package/docs/agent-rollback.md +23 -0
- package/docs/agent-run-artifacts.md +16 -0
- package/docs/agent-vscode-auto-discovery.md +137 -0
- package/docs/agent-vscode-batch-runner.md +100 -0
- package/docs/agent-vscode-chat-layout.md +90 -0
- package/docs/agent-vscode-clean-install.md +147 -0
- package/docs/agent-vscode-code-actions.md +70 -0
- package/docs/agent-vscode-diff-preview.md +45 -0
- package/docs/agent-vscode-inline-assist.md +56 -0
- package/docs/agent-vscode-install.md +186 -0
- package/docs/agent-vscode-model-setup.md +97 -0
- package/docs/agent-vscode-patch-preview.md +92 -0
- package/docs/agent-vscode-problems.md +79 -0
- package/docs/agent-vscode-project-dashboard.md +106 -0
- package/docs/agent-vscode-run-history.md +92 -0
- package/docs/agent-vscode-ux.md +73 -0
- package/docs/ai/INVARIANTS.md +84 -0
- package/docs/ai/PROJECT_MAP.md +338 -0
- package/docs/ai/PUBLIC_API.md +336 -0
- package/docs/ai/VALIDATION_MATRIX.md +67 -0
- package/docs/api-polish.md +37 -0
- package/docs/cancellation.md +162 -0
- package/docs/coverage.md +46 -0
- package/docs/getting-started.md +159 -0
- package/docs/guides/README.md +40 -0
- package/docs/guides/circuit-breaker.md +89 -0
- package/docs/guides/error-handling.md +91 -0
- package/docs/guides/getting-started.md +107 -0
- package/docs/guides/layers.md +189 -0
- package/docs/guides/metrics.md +101 -0
- package/docs/guides/resource-management.md +141 -0
- package/docs/guides/retry.md +215 -0
- package/docs/guides/semaphore.md +66 -0
- package/docs/guides/streams.md +117 -0
- package/docs/guides/supervisors.md +98 -0
- package/docs/guides/testing.md +162 -0
- package/docs/guides/tracing.md +71 -0
- package/docs/http-recipes.md +399 -0
- package/docs/http.md +749 -0
- package/docs/modules.md +285 -0
- package/docs/observability-collector-smoke.md +31 -0
- package/docs/observability-framework-examples.md +98 -0
- package/docs/observability.md +542 -0
- package/docs/otel-collector-smoke.yaml +27 -0
- package/docs/performance-profiler.md +199 -0
- package/docs/production-readiness.md +73 -0
- package/docs/recipes/README.md +12 -0
- package/docs/recipes/http-server.md +45 -0
- package/docs/recipes/layers.md +44 -0
- package/docs/recipes/performance.md +47 -0
- package/docs/recipes/runtime.md +41 -0
- package/docs/recipes/testing.md +41 -0
- package/docs/release.md +53 -0
- package/docs/wasm-bounded-queues.md +44 -0
- package/docs/wasm-engine-observability-benchmarks.md +85 -0
- package/docs/wasm-fiber-engine.md +117 -0
- package/docs/wasm-scheduler-state-machine.md +122 -0
- package/docs/wasm-stream-chunks.md +54 -0
- package/package.json +48 -2
- package/dist/chunk-AR22SXML.js +0 -1043
- package/dist/chunk-BDYEENHT.js +0 -224
- package/dist/chunk-JFPU5GQI.mjs +0 -1043
- package/dist/chunk-MS34J5LY.cjs +0 -224
- package/dist/chunk-UMAZLXAB.mjs +0 -224
- package/dist/chunk-XPZNXSVN.cjs +0 -1043
- package/dist/tracing-DNT9jEbr.d.ts +0 -106
|
@@ -0,0 +1,1629 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ensuring
|
|
3
|
+
} from "./chunk-KN32XNTH.mjs";
|
|
4
|
+
import {
|
|
5
|
+
makeScheduleDriver
|
|
6
|
+
} from "./chunk-2HQTDLHF.mjs";
|
|
7
|
+
import {
|
|
8
|
+
makeRuntimeEventRecord
|
|
9
|
+
} from "./chunk-EJ6BPYVR.mjs";
|
|
10
|
+
import {
|
|
11
|
+
Runtime,
|
|
12
|
+
getCurrentFiber,
|
|
13
|
+
liveClock,
|
|
14
|
+
runtimeClockFromEnv,
|
|
15
|
+
toPromise,
|
|
16
|
+
unsafeRunAsync
|
|
17
|
+
} from "./chunk-GYM3LLGS.mjs";
|
|
18
|
+
import {
|
|
19
|
+
Cause,
|
|
20
|
+
Exit,
|
|
21
|
+
asyncEffect,
|
|
22
|
+
asyncFail,
|
|
23
|
+
asyncFlatMap,
|
|
24
|
+
asyncFold,
|
|
25
|
+
asyncMap,
|
|
26
|
+
asyncSucceed,
|
|
27
|
+
asyncSync,
|
|
28
|
+
unit
|
|
29
|
+
} from "./chunk-36I3M4UC.mjs";
|
|
30
|
+
|
|
31
|
+
// src/core/types/cancel.ts
|
|
32
|
+
function makeCancelToken() {
|
|
33
|
+
let cancelled = false;
|
|
34
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
35
|
+
const cancel = () => {
|
|
36
|
+
if (cancelled) return;
|
|
37
|
+
cancelled = true;
|
|
38
|
+
listeners.forEach((f) => f());
|
|
39
|
+
listeners.clear();
|
|
40
|
+
};
|
|
41
|
+
return {
|
|
42
|
+
isCancelled: () => cancelled,
|
|
43
|
+
onCancel: (f) => {
|
|
44
|
+
if (cancelled) {
|
|
45
|
+
try {
|
|
46
|
+
f();
|
|
47
|
+
} catch {
|
|
48
|
+
}
|
|
49
|
+
return () => {
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
listeners.add(f);
|
|
53
|
+
return () => {
|
|
54
|
+
listeners.delete(f);
|
|
55
|
+
};
|
|
56
|
+
},
|
|
57
|
+
cancel
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
function linkAbortController(token, ac) {
|
|
61
|
+
return token.onCancel(() => ac.abort());
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// src/core/runtime/dx.ts
|
|
65
|
+
function makeRuntime(env = {}, options = {}) {
|
|
66
|
+
return new Runtime({ ...options, env });
|
|
67
|
+
}
|
|
68
|
+
function runPromise(effect, envOrRuntime) {
|
|
69
|
+
if (envOrRuntime instanceof Runtime) return envOrRuntime.toPromise(effect);
|
|
70
|
+
return toPromise(effect, envOrRuntime);
|
|
71
|
+
}
|
|
72
|
+
function runExit(effect, envOrRuntime) {
|
|
73
|
+
return new Promise((resolve) => {
|
|
74
|
+
if (envOrRuntime instanceof Runtime) {
|
|
75
|
+
envOrRuntime.unsafeRunAsync(effect, resolve);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
unsafeRunAsync(effect, envOrRuntime, resolve);
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
var runEffect = runPromise;
|
|
82
|
+
|
|
83
|
+
// src/core/runtime/linkedQueue.ts
|
|
84
|
+
var LinkedQueue = class {
|
|
85
|
+
head = null;
|
|
86
|
+
tail = null;
|
|
87
|
+
len = 0;
|
|
88
|
+
get length() {
|
|
89
|
+
return this.len;
|
|
90
|
+
}
|
|
91
|
+
isEmpty() {
|
|
92
|
+
return this.len === 0;
|
|
93
|
+
}
|
|
94
|
+
push(value) {
|
|
95
|
+
const node = { value, next: null, prev: this.tail, removed: false };
|
|
96
|
+
if (this.tail) this.tail.next = node;
|
|
97
|
+
else this.head = node;
|
|
98
|
+
this.tail = node;
|
|
99
|
+
this.len++;
|
|
100
|
+
return node;
|
|
101
|
+
}
|
|
102
|
+
shift() {
|
|
103
|
+
const h = this.head;
|
|
104
|
+
if (!h) return void 0;
|
|
105
|
+
this.unlink(h);
|
|
106
|
+
return h.value;
|
|
107
|
+
}
|
|
108
|
+
remove(node) {
|
|
109
|
+
if (node.removed) return;
|
|
110
|
+
this.unlink(node);
|
|
111
|
+
}
|
|
112
|
+
unlink(node) {
|
|
113
|
+
node.removed = true;
|
|
114
|
+
const { prev, next } = node;
|
|
115
|
+
if (prev) prev.next = next;
|
|
116
|
+
else this.head = next;
|
|
117
|
+
if (next) next.prev = prev;
|
|
118
|
+
else this.tail = prev;
|
|
119
|
+
node.next = null;
|
|
120
|
+
node.prev = null;
|
|
121
|
+
this.len--;
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
// src/core/runtime/semaphore.ts
|
|
126
|
+
function makeSemaphore(n) {
|
|
127
|
+
const capacity = Math.max(1, Math.floor(n));
|
|
128
|
+
let available = capacity;
|
|
129
|
+
let totalAcquired = 0;
|
|
130
|
+
let totalReleased = 0;
|
|
131
|
+
const waiters = new LinkedQueue();
|
|
132
|
+
const acquire = () => {
|
|
133
|
+
return asyncEffect((_env, cb) => {
|
|
134
|
+
if (available > 0) {
|
|
135
|
+
available--;
|
|
136
|
+
totalAcquired++;
|
|
137
|
+
cb({ _tag: "Success", value: void 0 });
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
const node = waiters.push(cb);
|
|
141
|
+
return () => {
|
|
142
|
+
waiters.remove(node);
|
|
143
|
+
};
|
|
144
|
+
});
|
|
145
|
+
};
|
|
146
|
+
const release = () => {
|
|
147
|
+
totalReleased++;
|
|
148
|
+
if (waiters.length > 0) {
|
|
149
|
+
const waiter = waiters.shift();
|
|
150
|
+
totalAcquired++;
|
|
151
|
+
waiter({ _tag: "Success", value: void 0 });
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
available++;
|
|
155
|
+
};
|
|
156
|
+
const acquirePermit = () => asyncFlatMap(
|
|
157
|
+
acquire(),
|
|
158
|
+
() => asyncEffect((_env, cb) => {
|
|
159
|
+
let released = false;
|
|
160
|
+
const releaseOnce = () => {
|
|
161
|
+
if (released) return;
|
|
162
|
+
released = true;
|
|
163
|
+
release();
|
|
164
|
+
};
|
|
165
|
+
const fiber = getCurrentFiber();
|
|
166
|
+
fiber?.addFinalizer(() => {
|
|
167
|
+
releaseOnce();
|
|
168
|
+
});
|
|
169
|
+
cb({ _tag: "Success", value: releaseOnce });
|
|
170
|
+
})
|
|
171
|
+
);
|
|
172
|
+
const withPermit = (effect) => asyncFlatMap(
|
|
173
|
+
acquirePermit(),
|
|
174
|
+
(releaseOnce) => asyncFold(
|
|
175
|
+
effect,
|
|
176
|
+
(error) => {
|
|
177
|
+
releaseOnce();
|
|
178
|
+
return asyncFail(error);
|
|
179
|
+
},
|
|
180
|
+
(value) => {
|
|
181
|
+
releaseOnce();
|
|
182
|
+
return asyncSucceed(value);
|
|
183
|
+
}
|
|
184
|
+
)
|
|
185
|
+
);
|
|
186
|
+
return {
|
|
187
|
+
capacity,
|
|
188
|
+
available: () => available,
|
|
189
|
+
waiting: () => waiters.length,
|
|
190
|
+
withPermit,
|
|
191
|
+
acquire,
|
|
192
|
+
release
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// src/core/runtime/ref.ts
|
|
197
|
+
function makeRef(initial) {
|
|
198
|
+
let value = initial;
|
|
199
|
+
return {
|
|
200
|
+
get: () => asyncSync(() => value),
|
|
201
|
+
set: (v) => asyncSync(() => {
|
|
202
|
+
value = v;
|
|
203
|
+
}),
|
|
204
|
+
update: (f) => asyncSync(() => {
|
|
205
|
+
value = f(value);
|
|
206
|
+
return value;
|
|
207
|
+
}),
|
|
208
|
+
modify: (f) => asyncSync(() => {
|
|
209
|
+
const [result, next] = f(value);
|
|
210
|
+
value = next;
|
|
211
|
+
return result;
|
|
212
|
+
}),
|
|
213
|
+
unsafeGet: () => value
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
function derivedRef(parent, get, set) {
|
|
217
|
+
return {
|
|
218
|
+
get: () => asyncSync(() => get(parent.unsafeGet())),
|
|
219
|
+
set: (b) => asyncFlatMap(parent.get(), (current) => parent.set(set(current, b))),
|
|
220
|
+
update: (f) => asyncFlatMap(parent.get(), (parentVal) => {
|
|
221
|
+
const newB = f(get(parentVal));
|
|
222
|
+
return asyncMap(parent.set(set(parentVal, newB)), () => newB);
|
|
223
|
+
}),
|
|
224
|
+
modify: (f) => asyncFlatMap(parent.get(), (parentVal) => {
|
|
225
|
+
const [result, newB] = f(get(parentVal));
|
|
226
|
+
return asyncMap(parent.set(set(parentVal, newB)), () => result);
|
|
227
|
+
}),
|
|
228
|
+
unsafeGet: () => get(parent.unsafeGet())
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// src/core/runtime/shutdown.ts
|
|
233
|
+
async function gracefulShutdown(runtime, config = {}) {
|
|
234
|
+
const timeoutMs = config.timeoutMs ?? 3e4;
|
|
235
|
+
const startedAt = Date.now();
|
|
236
|
+
config.onStart?.();
|
|
237
|
+
let timedOut = false;
|
|
238
|
+
const shutdownPromise = (async () => {
|
|
239
|
+
try {
|
|
240
|
+
await runtime.shutdown();
|
|
241
|
+
} catch {
|
|
242
|
+
}
|
|
243
|
+
})();
|
|
244
|
+
const timeoutPromise = new Promise((resolve) => {
|
|
245
|
+
setTimeout(() => {
|
|
246
|
+
timedOut = true;
|
|
247
|
+
resolve();
|
|
248
|
+
}, timeoutMs);
|
|
249
|
+
});
|
|
250
|
+
await Promise.race([shutdownPromise, timeoutPromise]);
|
|
251
|
+
const completedAt = Date.now();
|
|
252
|
+
const stats = {
|
|
253
|
+
startedAt,
|
|
254
|
+
completedAt,
|
|
255
|
+
elapsedMs: completedAt - startedAt,
|
|
256
|
+
timedOut
|
|
257
|
+
};
|
|
258
|
+
if (timedOut) {
|
|
259
|
+
config.onTimeout?.(stats);
|
|
260
|
+
} else {
|
|
261
|
+
config.onComplete?.(stats);
|
|
262
|
+
}
|
|
263
|
+
return stats;
|
|
264
|
+
}
|
|
265
|
+
function registerShutdownHooks(runtime, config = {}) {
|
|
266
|
+
let shuttingDown = false;
|
|
267
|
+
const handler = (signal) => {
|
|
268
|
+
if (shuttingDown) {
|
|
269
|
+
process.exit(1);
|
|
270
|
+
}
|
|
271
|
+
shuttingDown = true;
|
|
272
|
+
console.log(`
|
|
273
|
+
[brass-runtime] Received ${signal}, shutting down gracefully...`);
|
|
274
|
+
gracefulShutdown(runtime, {
|
|
275
|
+
...config,
|
|
276
|
+
onComplete: (stats) => {
|
|
277
|
+
config.onComplete?.(stats);
|
|
278
|
+
if (!config.onComplete) {
|
|
279
|
+
console.log(`[brass-runtime] Shutdown complete (${stats.elapsedMs}ms)`);
|
|
280
|
+
process.exit(0);
|
|
281
|
+
}
|
|
282
|
+
},
|
|
283
|
+
onTimeout: (stats) => {
|
|
284
|
+
config.onTimeout?.(stats);
|
|
285
|
+
if (!config.onTimeout) {
|
|
286
|
+
console.log(`[brass-runtime] Shutdown timed out after ${stats.elapsedMs}ms, forcing exit`);
|
|
287
|
+
process.exit(1);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
});
|
|
291
|
+
};
|
|
292
|
+
process.on("SIGTERM", () => handler("SIGTERM"));
|
|
293
|
+
process.on("SIGINT", () => handler("SIGINT"));
|
|
294
|
+
return () => {
|
|
295
|
+
process.removeAllListeners("SIGTERM");
|
|
296
|
+
process.removeAllListeners("SIGINT");
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// src/core/runtime/testing.ts
|
|
301
|
+
var TestScheduler = class {
|
|
302
|
+
constructor(options = {}) {
|
|
303
|
+
this.options = options;
|
|
304
|
+
this.maxSteps = options.maxSteps ?? 1e4;
|
|
305
|
+
}
|
|
306
|
+
options;
|
|
307
|
+
queue = [];
|
|
308
|
+
maxSteps;
|
|
309
|
+
autoFlushScheduled = false;
|
|
310
|
+
flushing = false;
|
|
311
|
+
enqueuedTasks = 0;
|
|
312
|
+
executedTasks = 0;
|
|
313
|
+
droppedTasks = 0;
|
|
314
|
+
scheduledFlushes = 0;
|
|
315
|
+
completedFlushes = 0;
|
|
316
|
+
schedule(task, tag = "anonymous") {
|
|
317
|
+
if (typeof task !== "function") {
|
|
318
|
+
this.droppedTasks += 1;
|
|
319
|
+
return "dropped";
|
|
320
|
+
}
|
|
321
|
+
this.queue.push({ tag, run: task });
|
|
322
|
+
this.enqueuedTasks += 1;
|
|
323
|
+
this.requestAutoFlush();
|
|
324
|
+
return "accepted";
|
|
325
|
+
}
|
|
326
|
+
scheduleBatch(tasks) {
|
|
327
|
+
return tasks.map(({ fn, tag }) => this.schedule(fn, tag));
|
|
328
|
+
}
|
|
329
|
+
stats() {
|
|
330
|
+
return {
|
|
331
|
+
engine: "ts",
|
|
332
|
+
fallbackUsed: false,
|
|
333
|
+
data: {
|
|
334
|
+
len: this.queue.length,
|
|
335
|
+
phase: this.flushing ? "flushing" : this.autoFlushScheduled ? "scheduled" : "idle",
|
|
336
|
+
scheduledFlushes: this.scheduledFlushes,
|
|
337
|
+
completedFlushes: this.completedFlushes,
|
|
338
|
+
enqueuedTasks: this.enqueuedTasks,
|
|
339
|
+
executedTasks: this.executedTasks,
|
|
340
|
+
droppedTasks: this.droppedTasks,
|
|
341
|
+
yieldedByBudget: 0,
|
|
342
|
+
lanes: [{
|
|
343
|
+
key: "test",
|
|
344
|
+
len: this.queue.length,
|
|
345
|
+
capacity: Number.POSITIVE_INFINITY,
|
|
346
|
+
enqueuedTasks: this.enqueuedTasks,
|
|
347
|
+
executedTasks: this.executedTasks,
|
|
348
|
+
droppedTasks: this.droppedTasks
|
|
349
|
+
}]
|
|
350
|
+
}
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
pending() {
|
|
354
|
+
return this.queue.slice();
|
|
355
|
+
}
|
|
356
|
+
size() {
|
|
357
|
+
return this.queue.length;
|
|
358
|
+
}
|
|
359
|
+
flush(maxTasks = 1) {
|
|
360
|
+
if (this.flushing) return 0;
|
|
361
|
+
this.flushing = true;
|
|
362
|
+
this.autoFlushScheduled = false;
|
|
363
|
+
let ran = 0;
|
|
364
|
+
try {
|
|
365
|
+
while (ran < maxTasks) {
|
|
366
|
+
const next = this.queue.shift();
|
|
367
|
+
if (!next) break;
|
|
368
|
+
ran += 1;
|
|
369
|
+
this.executedTasks += 1;
|
|
370
|
+
try {
|
|
371
|
+
next.run();
|
|
372
|
+
} catch (error) {
|
|
373
|
+
console.error(`[TestScheduler] task threw (tag=${next.tag})`, error);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
return ran;
|
|
377
|
+
} finally {
|
|
378
|
+
this.flushing = false;
|
|
379
|
+
this.completedFlushes += ran > 0 ? 1 : 0;
|
|
380
|
+
if (this.queue.length > 0) this.requestAutoFlush();
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
flushAll(maxSteps = this.maxSteps) {
|
|
384
|
+
let ran = 0;
|
|
385
|
+
while (this.queue.length > 0) {
|
|
386
|
+
if (ran >= maxSteps) {
|
|
387
|
+
throw new Error(`TestScheduler.flushAll exceeded ${maxSteps} steps; possible runaway fiber loop`);
|
|
388
|
+
}
|
|
389
|
+
ran += this.flush(Math.max(1, maxSteps - ran));
|
|
390
|
+
}
|
|
391
|
+
return ran;
|
|
392
|
+
}
|
|
393
|
+
requestAutoFlush() {
|
|
394
|
+
const autoFlush = this.options.autoFlush ?? this.options.synchronous ?? true;
|
|
395
|
+
if (!autoFlush || this.autoFlushScheduled || this.flushing) return;
|
|
396
|
+
this.autoFlushScheduled = true;
|
|
397
|
+
this.scheduledFlushes += 1;
|
|
398
|
+
queueMicrotask(() => {
|
|
399
|
+
if (!this.autoFlushScheduled) return;
|
|
400
|
+
this.flushAll();
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
};
|
|
404
|
+
var TestClock = class {
|
|
405
|
+
constructor(initialTimeMs = 0, flushScheduler = () => void 0, maxSteps = 1e4) {
|
|
406
|
+
this.flushScheduler = flushScheduler;
|
|
407
|
+
this.maxSteps = maxSteps;
|
|
408
|
+
this.nowMs = Math.max(0, Math.floor(initialTimeMs));
|
|
409
|
+
}
|
|
410
|
+
flushScheduler;
|
|
411
|
+
maxSteps;
|
|
412
|
+
nowMs;
|
|
413
|
+
nextId = 1;
|
|
414
|
+
nextSeq = 1;
|
|
415
|
+
timers = /* @__PURE__ */ new Map();
|
|
416
|
+
now() {
|
|
417
|
+
return this.nowMs;
|
|
418
|
+
}
|
|
419
|
+
setTimeout(task, ms) {
|
|
420
|
+
const id = this.nextId++;
|
|
421
|
+
const delay = Math.max(0, Math.floor(ms));
|
|
422
|
+
this.timers.set(id, {
|
|
423
|
+
id,
|
|
424
|
+
dueAt: this.nowMs + delay,
|
|
425
|
+
seq: this.nextSeq++,
|
|
426
|
+
task
|
|
427
|
+
});
|
|
428
|
+
return id;
|
|
429
|
+
}
|
|
430
|
+
clearTimeout(timer) {
|
|
431
|
+
if (typeof timer === "number") this.timers.delete(timer);
|
|
432
|
+
}
|
|
433
|
+
pendingTimers() {
|
|
434
|
+
return Array.from(this.timers.values()).sort(compareTimers).map((timer) => ({
|
|
435
|
+
id: timer.id,
|
|
436
|
+
dueAt: timer.dueAt,
|
|
437
|
+
delayMs: Math.max(0, timer.dueAt - this.nowMs)
|
|
438
|
+
}));
|
|
439
|
+
}
|
|
440
|
+
adjust(ms) {
|
|
441
|
+
return this.advance(ms);
|
|
442
|
+
}
|
|
443
|
+
advance(ms) {
|
|
444
|
+
return this.advanceTo(this.nowMs + Math.max(0, Math.floor(ms)));
|
|
445
|
+
}
|
|
446
|
+
advanceTo(targetMs) {
|
|
447
|
+
const target = Math.max(this.nowMs, Math.floor(targetMs));
|
|
448
|
+
let ran = 0;
|
|
449
|
+
while (true) {
|
|
450
|
+
if (ran >= this.maxSteps) {
|
|
451
|
+
throw new Error(`TestClock.advanceTo exceeded ${this.maxSteps} timers; possible runaway timer loop`);
|
|
452
|
+
}
|
|
453
|
+
const next = this.nextDueTimer(target);
|
|
454
|
+
if (!next) break;
|
|
455
|
+
this.timers.delete(next.id);
|
|
456
|
+
this.nowMs = next.dueAt;
|
|
457
|
+
ran += 1;
|
|
458
|
+
next.task();
|
|
459
|
+
this.flushScheduler();
|
|
460
|
+
}
|
|
461
|
+
this.nowMs = target;
|
|
462
|
+
this.flushScheduler();
|
|
463
|
+
return ran;
|
|
464
|
+
}
|
|
465
|
+
runDue() {
|
|
466
|
+
return this.advanceTo(this.nowMs);
|
|
467
|
+
}
|
|
468
|
+
runAll(maxSteps = this.maxSteps) {
|
|
469
|
+
let ran = 0;
|
|
470
|
+
while (this.timers.size > 0) {
|
|
471
|
+
if (ran >= maxSteps) {
|
|
472
|
+
throw new Error(`TestClock.runAll exceeded ${maxSteps} timers; possible runaway timer loop`);
|
|
473
|
+
}
|
|
474
|
+
const next = this.nextDueTimer(Number.POSITIVE_INFINITY);
|
|
475
|
+
if (!next) break;
|
|
476
|
+
ran += this.advanceTo(next.dueAt);
|
|
477
|
+
}
|
|
478
|
+
return ran;
|
|
479
|
+
}
|
|
480
|
+
clear() {
|
|
481
|
+
this.timers.clear();
|
|
482
|
+
}
|
|
483
|
+
nextDueTimer(targetMs) {
|
|
484
|
+
let selected;
|
|
485
|
+
for (const timer of this.timers.values()) {
|
|
486
|
+
if (timer.dueAt > targetMs) continue;
|
|
487
|
+
if (!selected || compareTimers(timer, selected) < 0) selected = timer;
|
|
488
|
+
}
|
|
489
|
+
return selected;
|
|
490
|
+
}
|
|
491
|
+
};
|
|
492
|
+
function compareTimers(a, b) {
|
|
493
|
+
return a.dueAt === b.dueAt ? a.seq - b.seq : a.dueAt - b.dueAt;
|
|
494
|
+
}
|
|
495
|
+
function makeTestRuntime(env, options = {}) {
|
|
496
|
+
const scheduler = new TestScheduler(options);
|
|
497
|
+
const clock = new TestClock(options.initialTimeMs, () => scheduler.flushAll(options.maxSteps), options.maxSteps);
|
|
498
|
+
const testEnv = withTestClock(env ?? {}, clock);
|
|
499
|
+
const runtime = Runtime.makeWithEngine(testEnv, "ts", { scheduler });
|
|
500
|
+
const flush = (maxTasks) => scheduler.flush(maxTasks);
|
|
501
|
+
const flushAll = (maxSteps) => scheduler.flushAll(maxSteps);
|
|
502
|
+
const advance = (ms) => clock.advance(ms);
|
|
503
|
+
const advanceTo = (targetMs) => clock.advanceTo(targetMs);
|
|
504
|
+
const runDueTimers = () => clock.runDue();
|
|
505
|
+
const runAllTimers = (maxSteps) => clock.runAll(maxSteps);
|
|
506
|
+
const runExit2 = (effect) => {
|
|
507
|
+
const promise = new Promise((resolve) => {
|
|
508
|
+
runtime.unsafeRunAsync(effect, resolve);
|
|
509
|
+
});
|
|
510
|
+
flushAll();
|
|
511
|
+
return promise;
|
|
512
|
+
};
|
|
513
|
+
const run = async (effect) => exitToPromise(await runExit2(effect));
|
|
514
|
+
const fork = (effect) => {
|
|
515
|
+
const fiber = runtime.fork(effect);
|
|
516
|
+
flushAll();
|
|
517
|
+
return fiber;
|
|
518
|
+
};
|
|
519
|
+
return {
|
|
520
|
+
env: testEnv,
|
|
521
|
+
runtime,
|
|
522
|
+
scheduler,
|
|
523
|
+
clock,
|
|
524
|
+
run,
|
|
525
|
+
runExit: runExit2,
|
|
526
|
+
fork,
|
|
527
|
+
flush,
|
|
528
|
+
flushAll,
|
|
529
|
+
advance,
|
|
530
|
+
advanceTo,
|
|
531
|
+
runDueTimers,
|
|
532
|
+
runAllTimers
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
function withTestClock(env, clock) {
|
|
536
|
+
const current = env;
|
|
537
|
+
return {
|
|
538
|
+
...env,
|
|
539
|
+
brass: {
|
|
540
|
+
...current.brass ?? {},
|
|
541
|
+
clock
|
|
542
|
+
}
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
function exitToPromise(exit) {
|
|
546
|
+
if (exit._tag === "Success") return exit.value;
|
|
547
|
+
const failure = Cause.firstFailure(exit.cause);
|
|
548
|
+
if (failure._tag === "Some") throw failure.value;
|
|
549
|
+
const defect = Cause.firstDefect(exit.cause);
|
|
550
|
+
if (defect._tag === "Some") {
|
|
551
|
+
throw defect.value instanceof Error ? defect.value : new Error(String(defect.value));
|
|
552
|
+
}
|
|
553
|
+
if (Cause.containsInterrupt(exit.cause)) throw new Error("Interrupted");
|
|
554
|
+
throw Cause.toError(exit.cause);
|
|
555
|
+
}
|
|
556
|
+
function runExitWithRuntime(runtime, effect) {
|
|
557
|
+
return new Promise((resolve) => {
|
|
558
|
+
runtime.unsafeRunAsync(effect, resolve);
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
function stableJson(value) {
|
|
562
|
+
return JSON.stringify(value);
|
|
563
|
+
}
|
|
564
|
+
function firstFailureValue(exit) {
|
|
565
|
+
if (exit._tag !== "Failure") return void 0;
|
|
566
|
+
const failure = Cause.firstFailure(exit.cause);
|
|
567
|
+
return failure._tag === "Some" ? failure.value : void 0;
|
|
568
|
+
}
|
|
569
|
+
function makeAssertionRuntime(runtime) {
|
|
570
|
+
return runtime ?? Runtime.make({});
|
|
571
|
+
}
|
|
572
|
+
async function assertSucceeds(effect, expected, runtime) {
|
|
573
|
+
const rt = makeAssertionRuntime(runtime);
|
|
574
|
+
const exit = await runExitWithRuntime(rt, effect);
|
|
575
|
+
if (exit._tag !== "Success") {
|
|
576
|
+
throw new Error(`Expected success with ${stableJson(expected)}, got failure: ${stableJson(exit.cause)}`);
|
|
577
|
+
}
|
|
578
|
+
if (stableJson(exit.value) !== stableJson(expected)) {
|
|
579
|
+
throw new Error(`Expected ${stableJson(expected)}, got ${stableJson(exit.value)}`);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
async function assertFails(effect, expectedError, runtime) {
|
|
583
|
+
const rt = makeAssertionRuntime(runtime);
|
|
584
|
+
const exit = await runExitWithRuntime(rt, effect);
|
|
585
|
+
if (exit._tag !== "Failure") {
|
|
586
|
+
throw new Error(`Expected failure with ${stableJson(expectedError)}, got success: ${stableJson(exit.value)}`);
|
|
587
|
+
}
|
|
588
|
+
const error = firstFailureValue(exit);
|
|
589
|
+
if (stableJson(error) !== stableJson(expectedError)) {
|
|
590
|
+
throw new Error(`Expected error ${stableJson(expectedError)}, got ${stableJson(error)}`);
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
async function assertFailsWith(effect, predicate, runtime) {
|
|
594
|
+
const rt = makeAssertionRuntime(runtime);
|
|
595
|
+
const exit = await runExitWithRuntime(rt, effect);
|
|
596
|
+
if (exit._tag !== "Failure") {
|
|
597
|
+
throw new Error(`Expected failure, got success: ${stableJson(exit.value)}`);
|
|
598
|
+
}
|
|
599
|
+
const error = firstFailureValue(exit);
|
|
600
|
+
if (error === void 0 || !predicate(error)) {
|
|
601
|
+
throw new Error(`Error did not match predicate: ${stableJson(error)}`);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
async function assertCompletesWithin(effect, maxMs, runtime) {
|
|
605
|
+
const rt = makeAssertionRuntime(runtime);
|
|
606
|
+
const start = runtimeClockFromEnv(rt.env).now();
|
|
607
|
+
const result = await rt.toPromise(effect);
|
|
608
|
+
const elapsed = runtimeClockFromEnv(rt.env).now() - start;
|
|
609
|
+
if (elapsed > maxMs) {
|
|
610
|
+
throw new Error(`Effect took ${elapsed.toFixed(1)}ms, expected < ${maxMs}ms`);
|
|
611
|
+
}
|
|
612
|
+
return result;
|
|
613
|
+
}
|
|
614
|
+
function flakyEffect(failCount, successValue, errorValue) {
|
|
615
|
+
let calls = 0;
|
|
616
|
+
return asyncEffect((_env, cb) => {
|
|
617
|
+
calls++;
|
|
618
|
+
if (calls <= failCount) {
|
|
619
|
+
cb(Exit.failCause(Cause.fail(errorValue)));
|
|
620
|
+
} else {
|
|
621
|
+
cb(Exit.succeed(successValue));
|
|
622
|
+
}
|
|
623
|
+
});
|
|
624
|
+
}
|
|
625
|
+
function delayedEffect(ms, value) {
|
|
626
|
+
return asyncEffect((env, cb) => {
|
|
627
|
+
const clock = runtimeClockFromEnv(env);
|
|
628
|
+
const id = clock.setTimeout(() => cb(Exit.succeed(value)), ms);
|
|
629
|
+
return () => clock.clearTimeout(id);
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
function neverEffect() {
|
|
633
|
+
return asyncEffect(() => {
|
|
634
|
+
return () => {
|
|
635
|
+
};
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
// src/core/runtime/layer.ts
|
|
640
|
+
var MissingLayerServiceError = class extends Error {
|
|
641
|
+
_tag = "MissingLayerService";
|
|
642
|
+
serviceName;
|
|
643
|
+
constructor(serviceName) {
|
|
644
|
+
super(`Missing layer service '${serviceName}'. Add a layer that provides this ServiceTag or pass a LayerContext containing it.`);
|
|
645
|
+
this.name = "MissingLayerServiceError";
|
|
646
|
+
this.serviceName = serviceName;
|
|
647
|
+
}
|
|
648
|
+
};
|
|
649
|
+
function formatLayerError(error) {
|
|
650
|
+
if (error instanceof MissingLayerServiceError) return error.message;
|
|
651
|
+
if (isObjectRecord(error) && error._tag === "MissingLayerService" && typeof error.serviceName === "string") {
|
|
652
|
+
return `Missing layer service '${error.serviceName}'. Add the provider layer before using the service.`;
|
|
653
|
+
}
|
|
654
|
+
return error instanceof Error ? error.message : String(error);
|
|
655
|
+
}
|
|
656
|
+
function makeServiceTag(name) {
|
|
657
|
+
return {
|
|
658
|
+
_tag: "ServiceTag",
|
|
659
|
+
key: Symbol(name),
|
|
660
|
+
name
|
|
661
|
+
};
|
|
662
|
+
}
|
|
663
|
+
var serviceTag = makeServiceTag;
|
|
664
|
+
var defineService = makeServiceTag;
|
|
665
|
+
var LayerContext = class _LayerContext {
|
|
666
|
+
services;
|
|
667
|
+
constructor(entries) {
|
|
668
|
+
if (entries instanceof Map) {
|
|
669
|
+
this.services = new Map(entries);
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
this.services = /* @__PURE__ */ new Map();
|
|
673
|
+
if (!entries) return;
|
|
674
|
+
for (const [tag, service] of entries) this.services.set(tag.key, service);
|
|
675
|
+
}
|
|
676
|
+
static empty() {
|
|
677
|
+
return new _LayerContext();
|
|
678
|
+
}
|
|
679
|
+
get(tag) {
|
|
680
|
+
return this.services.get(tag.key);
|
|
681
|
+
}
|
|
682
|
+
unsafeGet(tag) {
|
|
683
|
+
if (!this.services.has(tag.key)) {
|
|
684
|
+
throw new MissingLayerServiceError(tag.name);
|
|
685
|
+
}
|
|
686
|
+
return this.services.get(tag.key);
|
|
687
|
+
}
|
|
688
|
+
has(tag) {
|
|
689
|
+
return this.services.has(tag.key);
|
|
690
|
+
}
|
|
691
|
+
add(tag, service) {
|
|
692
|
+
const next = new Map(this.services);
|
|
693
|
+
next.set(tag.key, service);
|
|
694
|
+
return new _LayerContext(next);
|
|
695
|
+
}
|
|
696
|
+
merge(other) {
|
|
697
|
+
const next = new Map(this.services);
|
|
698
|
+
for (const [key, service] of other.services) next.set(key, service);
|
|
699
|
+
return new _LayerContext(next);
|
|
700
|
+
}
|
|
701
|
+
size() {
|
|
702
|
+
return this.services.size;
|
|
703
|
+
}
|
|
704
|
+
};
|
|
705
|
+
function makeLayerScope() {
|
|
706
|
+
const cache = /* @__PURE__ */ new WeakMap();
|
|
707
|
+
const finalizers = [];
|
|
708
|
+
let closed = false;
|
|
709
|
+
const scope = {
|
|
710
|
+
get: (l, deps) => {
|
|
711
|
+
if (closed) return asyncFail(new Error("LayerScope is closed"));
|
|
712
|
+
if (cache.has(l)) return asyncSucceed(cache.get(l));
|
|
713
|
+
const built = l.buildScoped ? l.buildScoped(deps, scope) : asyncFlatMap(
|
|
714
|
+
l.build(deps),
|
|
715
|
+
({ service, release }) => asyncFlatMap(scope.addFinalizer(release), () => asyncSucceed(service))
|
|
716
|
+
);
|
|
717
|
+
return asyncFlatMap(
|
|
718
|
+
built,
|
|
719
|
+
(service) => asyncSync(() => {
|
|
720
|
+
cache.set(l, service);
|
|
721
|
+
return service;
|
|
722
|
+
})
|
|
723
|
+
);
|
|
724
|
+
},
|
|
725
|
+
close: () => {
|
|
726
|
+
if (closed) return unit();
|
|
727
|
+
closed = true;
|
|
728
|
+
return releaseAll(finalizers);
|
|
729
|
+
},
|
|
730
|
+
size: () => finalizers.length,
|
|
731
|
+
addFinalizer: (release) => asyncSync(() => {
|
|
732
|
+
if (!closed) finalizers.push(release);
|
|
733
|
+
})
|
|
734
|
+
};
|
|
735
|
+
return scope;
|
|
736
|
+
}
|
|
737
|
+
function releaseAll(finalizers) {
|
|
738
|
+
const next = finalizers.pop();
|
|
739
|
+
if (!next) return unit();
|
|
740
|
+
return asyncFold(
|
|
741
|
+
next(),
|
|
742
|
+
() => releaseAll(finalizers),
|
|
743
|
+
() => releaseAll(finalizers)
|
|
744
|
+
);
|
|
745
|
+
}
|
|
746
|
+
function mergeServices(a, b) {
|
|
747
|
+
if (a instanceof LayerContext && b instanceof LayerContext) {
|
|
748
|
+
return a.merge(b);
|
|
749
|
+
}
|
|
750
|
+
if (isObjectRecord(a) && isObjectRecord(b)) {
|
|
751
|
+
return { ...a, ...b };
|
|
752
|
+
}
|
|
753
|
+
return Object.assign({}, a, b);
|
|
754
|
+
}
|
|
755
|
+
function isObjectRecord(value) {
|
|
756
|
+
return typeof value === "object" && value !== null;
|
|
757
|
+
}
|
|
758
|
+
function layer(acquire, release) {
|
|
759
|
+
return {
|
|
760
|
+
_tag: "Layer",
|
|
761
|
+
build: (_deps) => asyncFlatMap(acquire(), (service) => asyncSucceed({
|
|
762
|
+
service,
|
|
763
|
+
release: release ? () => release(service) : () => unit()
|
|
764
|
+
}))
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
function layerValue(tag, value) {
|
|
768
|
+
return layerEffect(tag, () => asyncSucceed(value));
|
|
769
|
+
}
|
|
770
|
+
function layerEffect(tag, acquire, release) {
|
|
771
|
+
return {
|
|
772
|
+
_tag: "Layer",
|
|
773
|
+
build: (deps = LayerContext.empty()) => asyncFlatMap(acquire(deps), (service) => asyncSucceed({
|
|
774
|
+
service: deps.add(tag, service),
|
|
775
|
+
release: release ? () => release(service) : () => unit()
|
|
776
|
+
}))
|
|
777
|
+
};
|
|
778
|
+
}
|
|
779
|
+
var layerFromContext = layerEffect;
|
|
780
|
+
var defineLayer = layerEffect;
|
|
781
|
+
function getService(tag) {
|
|
782
|
+
return asyncSync((context) => context.unsafeGet(tag));
|
|
783
|
+
}
|
|
784
|
+
function layerFrom() {
|
|
785
|
+
return (acquire, release) => ({
|
|
786
|
+
_tag: "Layer",
|
|
787
|
+
build: (deps) => asyncFlatMap(acquire(deps), (service) => asyncSucceed({
|
|
788
|
+
service,
|
|
789
|
+
release: release ? () => release(service) : () => unit()
|
|
790
|
+
}))
|
|
791
|
+
});
|
|
792
|
+
}
|
|
793
|
+
function layerSucceed(value) {
|
|
794
|
+
return {
|
|
795
|
+
_tag: "Layer",
|
|
796
|
+
build: () => asyncSucceed({ service: value, release: () => unit() })
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
function layerFail(error) {
|
|
800
|
+
return {
|
|
801
|
+
_tag: "Layer",
|
|
802
|
+
build: () => asyncFail(error)
|
|
803
|
+
};
|
|
804
|
+
}
|
|
805
|
+
function compose(from, to) {
|
|
806
|
+
return {
|
|
807
|
+
_tag: "Layer",
|
|
808
|
+
buildScoped: (deps, scope) => asyncFlatMap(
|
|
809
|
+
scope.get(from, deps),
|
|
810
|
+
(mid) => scope.get(to, mid)
|
|
811
|
+
),
|
|
812
|
+
build: (deps) => asyncFlatMap(
|
|
813
|
+
from.build(deps),
|
|
814
|
+
({ service: mid, release: releaseMid }) => asyncFold(
|
|
815
|
+
to.build(mid),
|
|
816
|
+
(error) => asyncFlatMap(releaseMid(), () => asyncFail(error)),
|
|
817
|
+
({ service: out, release: releaseOut }) => asyncSucceed({
|
|
818
|
+
service: out,
|
|
819
|
+
release: () => asyncFlatMap(releaseOut(), () => releaseMid())
|
|
820
|
+
})
|
|
821
|
+
)
|
|
822
|
+
)
|
|
823
|
+
};
|
|
824
|
+
}
|
|
825
|
+
function merge(left, right) {
|
|
826
|
+
return {
|
|
827
|
+
_tag: "Layer",
|
|
828
|
+
buildScoped: (deps, scope) => asyncFlatMap(
|
|
829
|
+
scope.get(left, deps),
|
|
830
|
+
(a) => asyncFlatMap(
|
|
831
|
+
scope.get(right, deps),
|
|
832
|
+
(b) => asyncSucceed(mergeServices(a, b))
|
|
833
|
+
)
|
|
834
|
+
),
|
|
835
|
+
build: (deps) => asyncFlatMap(
|
|
836
|
+
left.build(deps),
|
|
837
|
+
({ service: a, release: releaseA }) => asyncFold(
|
|
838
|
+
right.build(deps),
|
|
839
|
+
(error) => asyncFlatMap(releaseA(), () => asyncFail(error)),
|
|
840
|
+
({ service: b, release: releaseB }) => asyncSucceed({
|
|
841
|
+
service: mergeServices(a, b),
|
|
842
|
+
release: () => asyncFlatMap(releaseB(), () => releaseA())
|
|
843
|
+
})
|
|
844
|
+
)
|
|
845
|
+
)
|
|
846
|
+
};
|
|
847
|
+
}
|
|
848
|
+
function mapLayer(l, f) {
|
|
849
|
+
return {
|
|
850
|
+
_tag: "Layer",
|
|
851
|
+
buildScoped: (deps, scope) => asyncFlatMap(
|
|
852
|
+
scope.get(l, deps),
|
|
853
|
+
(service) => asyncSucceed(f(service))
|
|
854
|
+
),
|
|
855
|
+
build: (deps) => asyncFlatMap(
|
|
856
|
+
l.build(deps),
|
|
857
|
+
({ service, release }) => asyncSucceed({ service: f(service), release })
|
|
858
|
+
)
|
|
859
|
+
};
|
|
860
|
+
}
|
|
861
|
+
function buildLayer(l, deps) {
|
|
862
|
+
const scope = makeLayerScope();
|
|
863
|
+
return asyncFold(
|
|
864
|
+
scope.get(l, deps),
|
|
865
|
+
(error) => asyncFlatMap(scope.close(), () => asyncFail(error)),
|
|
866
|
+
(service) => asyncSucceed({
|
|
867
|
+
service,
|
|
868
|
+
scope,
|
|
869
|
+
close: scope.close,
|
|
870
|
+
use: (body) => body(service)
|
|
871
|
+
})
|
|
872
|
+
);
|
|
873
|
+
}
|
|
874
|
+
function provideLayer(l, use, deps) {
|
|
875
|
+
return asyncFlatMap(
|
|
876
|
+
buildLayer(l, deps ?? {}),
|
|
877
|
+
({ service, close }) => ensuring(
|
|
878
|
+
use(service),
|
|
879
|
+
() => close()
|
|
880
|
+
)
|
|
881
|
+
);
|
|
882
|
+
}
|
|
883
|
+
function provideLayerContext(l, use, deps = LayerContext.empty()) {
|
|
884
|
+
return provideLayer(l, use, deps);
|
|
885
|
+
}
|
|
886
|
+
var provide = provideLayer;
|
|
887
|
+
var provideContext = provideLayerContext;
|
|
888
|
+
var Layer = Object.freeze({
|
|
889
|
+
make: layer,
|
|
890
|
+
from: layerFrom,
|
|
891
|
+
succeed: layerSucceed,
|
|
892
|
+
fail: layerFail,
|
|
893
|
+
value: layerValue,
|
|
894
|
+
effect: layerEffect,
|
|
895
|
+
define: defineLayer,
|
|
896
|
+
fromContext: layerFromContext,
|
|
897
|
+
compose,
|
|
898
|
+
merge,
|
|
899
|
+
map: mapLayer,
|
|
900
|
+
provide: provideLayer,
|
|
901
|
+
provideContext: provideLayerContext,
|
|
902
|
+
build: buildLayer,
|
|
903
|
+
scope: makeLayerScope,
|
|
904
|
+
context: LayerContext.empty,
|
|
905
|
+
tag: makeServiceTag,
|
|
906
|
+
service: getService
|
|
907
|
+
});
|
|
908
|
+
|
|
909
|
+
// src/core/runtime/workerPool.ts
|
|
910
|
+
function makeWorkerPool(config = {}) {
|
|
911
|
+
const size = config.size ?? 4;
|
|
912
|
+
const maxQueue = config.maxQueue ?? 1e3;
|
|
913
|
+
const taskTimeoutMs = config.taskTimeoutMs ?? 3e4;
|
|
914
|
+
let closed = false;
|
|
915
|
+
let busy = 0;
|
|
916
|
+
let completed = 0;
|
|
917
|
+
let failed = 0;
|
|
918
|
+
let timedOut = 0;
|
|
919
|
+
const queue = [];
|
|
920
|
+
const processNext = () => {
|
|
921
|
+
if (queue.length === 0 || busy >= size) return;
|
|
922
|
+
const task = queue.shift();
|
|
923
|
+
busy++;
|
|
924
|
+
setImmediate(() => {
|
|
925
|
+
if (task.timeoutId) clearTimeout(task.timeoutId);
|
|
926
|
+
try {
|
|
927
|
+
const result = task.fn();
|
|
928
|
+
busy--;
|
|
929
|
+
completed++;
|
|
930
|
+
task.resolve(result);
|
|
931
|
+
processNext();
|
|
932
|
+
} catch (e) {
|
|
933
|
+
busy--;
|
|
934
|
+
failed++;
|
|
935
|
+
task.reject({ _tag: "WorkerTaskError", message: String(e) });
|
|
936
|
+
processNext();
|
|
937
|
+
}
|
|
938
|
+
});
|
|
939
|
+
};
|
|
940
|
+
const execute = (fn) => {
|
|
941
|
+
if (closed) return asyncFail({ _tag: "WorkerPoolClosed" });
|
|
942
|
+
if (queue.length >= maxQueue) {
|
|
943
|
+
return asyncFail({ _tag: "WorkerPoolFull", queued: queue.length });
|
|
944
|
+
}
|
|
945
|
+
return asyncEffect((_env, cb) => {
|
|
946
|
+
const task = {
|
|
947
|
+
fn,
|
|
948
|
+
resolve: (value) => cb({ _tag: "Success", value }),
|
|
949
|
+
reject: (error) => cb({ _tag: "Failure", cause: { _tag: "Fail", error } })
|
|
950
|
+
};
|
|
951
|
+
task.timeoutId = setTimeout(() => {
|
|
952
|
+
const idx = queue.indexOf(task);
|
|
953
|
+
if (idx >= 0) {
|
|
954
|
+
queue.splice(idx, 1);
|
|
955
|
+
timedOut++;
|
|
956
|
+
task.reject({ _tag: "WorkerTaskTimeout", ms: taskTimeoutMs });
|
|
957
|
+
}
|
|
958
|
+
}, taskTimeoutMs);
|
|
959
|
+
queue.push(task);
|
|
960
|
+
processNext();
|
|
961
|
+
return () => {
|
|
962
|
+
const idx = queue.indexOf(task);
|
|
963
|
+
if (idx >= 0) {
|
|
964
|
+
queue.splice(idx, 1);
|
|
965
|
+
if (task.timeoutId) clearTimeout(task.timeoutId);
|
|
966
|
+
}
|
|
967
|
+
};
|
|
968
|
+
});
|
|
969
|
+
};
|
|
970
|
+
const run = (taskSource, args = []) => {
|
|
971
|
+
return execute(() => {
|
|
972
|
+
const fn = new Function(...args.map((_, i) => `arg${i}`), taskSource);
|
|
973
|
+
return fn(...args);
|
|
974
|
+
});
|
|
975
|
+
};
|
|
976
|
+
return {
|
|
977
|
+
execute,
|
|
978
|
+
run,
|
|
979
|
+
stats: () => ({
|
|
980
|
+
size,
|
|
981
|
+
busy,
|
|
982
|
+
idle: size - busy,
|
|
983
|
+
queued: queue.length,
|
|
984
|
+
completed,
|
|
985
|
+
failed,
|
|
986
|
+
timedOut
|
|
987
|
+
}),
|
|
988
|
+
shutdown: async () => {
|
|
989
|
+
closed = true;
|
|
990
|
+
while (queue.length > 0) {
|
|
991
|
+
const task = queue.shift();
|
|
992
|
+
if (task.timeoutId) clearTimeout(task.timeoutId);
|
|
993
|
+
task.reject({ _tag: "WorkerPoolClosed" });
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
};
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
// src/core/runtime/tracing.ts
|
|
1000
|
+
var idCounter = 0;
|
|
1001
|
+
function generateId() {
|
|
1002
|
+
return (++idCounter).toString(16).padStart(16, "0");
|
|
1003
|
+
}
|
|
1004
|
+
function makeTracer(config) {
|
|
1005
|
+
const completedSpans = [];
|
|
1006
|
+
const sampleRate = config.sampleRate ?? 1;
|
|
1007
|
+
const shouldSample = () => {
|
|
1008
|
+
if (sampleRate >= 1) return true;
|
|
1009
|
+
if (sampleRate <= 0) return false;
|
|
1010
|
+
return Math.random() < sampleRate;
|
|
1011
|
+
};
|
|
1012
|
+
const span = (name, effect, attributes) => {
|
|
1013
|
+
if (!shouldSample()) return effect;
|
|
1014
|
+
const spanObj = {
|
|
1015
|
+
name,
|
|
1016
|
+
context: {
|
|
1017
|
+
traceId: generateId(),
|
|
1018
|
+
spanId: generateId()
|
|
1019
|
+
},
|
|
1020
|
+
startTime: performance.now(),
|
|
1021
|
+
status: "unset",
|
|
1022
|
+
attributes: { "service.name": config.serviceName, ...attributes },
|
|
1023
|
+
events: []
|
|
1024
|
+
};
|
|
1025
|
+
return asyncFold(
|
|
1026
|
+
effect,
|
|
1027
|
+
(error) => {
|
|
1028
|
+
spanObj.endTime = performance.now();
|
|
1029
|
+
spanObj.status = "error";
|
|
1030
|
+
spanObj.events.push({
|
|
1031
|
+
name: "error",
|
|
1032
|
+
time: performance.now(),
|
|
1033
|
+
attributes: { "error.message": String(error) }
|
|
1034
|
+
});
|
|
1035
|
+
completedSpans.push(spanObj);
|
|
1036
|
+
config.onSpanEnd?.(spanObj);
|
|
1037
|
+
return asyncFail(error);
|
|
1038
|
+
},
|
|
1039
|
+
(value) => {
|
|
1040
|
+
spanObj.endTime = performance.now();
|
|
1041
|
+
spanObj.status = "ok";
|
|
1042
|
+
completedSpans.push(spanObj);
|
|
1043
|
+
config.onSpanEnd?.(spanObj);
|
|
1044
|
+
return asyncSucceed(value);
|
|
1045
|
+
}
|
|
1046
|
+
);
|
|
1047
|
+
};
|
|
1048
|
+
return {
|
|
1049
|
+
span,
|
|
1050
|
+
spans: () => completedSpans,
|
|
1051
|
+
clear: () => {
|
|
1052
|
+
completedSpans.length = 0;
|
|
1053
|
+
}
|
|
1054
|
+
};
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
// src/core/runtime/loggerSink.ts
|
|
1058
|
+
function consoleJsonLogger() {
|
|
1059
|
+
return {
|
|
1060
|
+
emit(ev, ctx) {
|
|
1061
|
+
if (ev.type !== "log") return;
|
|
1062
|
+
const wallTs = Date.now();
|
|
1063
|
+
const out = {
|
|
1064
|
+
level: ev.level,
|
|
1065
|
+
msg: ev.message,
|
|
1066
|
+
wallTs,
|
|
1067
|
+
fiberId: ctx.fiberId,
|
|
1068
|
+
scopeId: ctx.scopeId,
|
|
1069
|
+
traceId: ctx.traceId,
|
|
1070
|
+
spanId: ctx.spanId,
|
|
1071
|
+
parentSpanId: ctx.parentSpanId,
|
|
1072
|
+
...ev.fields ?? {}
|
|
1073
|
+
};
|
|
1074
|
+
if (ev.level === "error") console.error(JSON.stringify(out));
|
|
1075
|
+
else console.log(JSON.stringify(out));
|
|
1076
|
+
}
|
|
1077
|
+
};
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
// src/core/runtime/registry.ts
|
|
1081
|
+
var RuntimeRegistry = class {
|
|
1082
|
+
fibers = /* @__PURE__ */ new Map();
|
|
1083
|
+
scopes = /* @__PURE__ */ new Map();
|
|
1084
|
+
seq = 1;
|
|
1085
|
+
recent = [];
|
|
1086
|
+
recentCap = 2e3;
|
|
1087
|
+
emit(ev, ctx) {
|
|
1088
|
+
const rec = makeRuntimeEventRecord(ev, ctx, this.seq++);
|
|
1089
|
+
this.recent.push(rec);
|
|
1090
|
+
if (this.recent.length > this.recentCap) this.recent.shift();
|
|
1091
|
+
switch (rec.type) {
|
|
1092
|
+
case "fiber.start": {
|
|
1093
|
+
const id = rec.fiberId;
|
|
1094
|
+
this.fibers.set(id, {
|
|
1095
|
+
fiberId: id,
|
|
1096
|
+
parentFiberId: rec.parentFiberId,
|
|
1097
|
+
name: rec.name,
|
|
1098
|
+
runState: "Running",
|
|
1099
|
+
status: "Running",
|
|
1100
|
+
createdAt: rec.wallTs,
|
|
1101
|
+
lastActiveAt: rec.wallTs,
|
|
1102
|
+
scopeId: rec.scopeId,
|
|
1103
|
+
traceId: rec.traceId,
|
|
1104
|
+
spanId: rec.spanId
|
|
1105
|
+
});
|
|
1106
|
+
break;
|
|
1107
|
+
}
|
|
1108
|
+
case "fiber.suspend": {
|
|
1109
|
+
const f = this.fibers.get(rec.fiberId);
|
|
1110
|
+
if (f) {
|
|
1111
|
+
f.runState = "Suspended";
|
|
1112
|
+
f.lastActiveAt = rec.wallTs;
|
|
1113
|
+
f.awaiting = { reason: rec.reason ?? "unknown" };
|
|
1114
|
+
}
|
|
1115
|
+
break;
|
|
1116
|
+
}
|
|
1117
|
+
case "fiber.resume": {
|
|
1118
|
+
const f = this.fibers.get(rec.fiberId);
|
|
1119
|
+
if (f) {
|
|
1120
|
+
f.runState = "Running";
|
|
1121
|
+
f.lastActiveAt = rec.wallTs;
|
|
1122
|
+
f.awaiting = void 0;
|
|
1123
|
+
}
|
|
1124
|
+
break;
|
|
1125
|
+
}
|
|
1126
|
+
case "fiber.end": {
|
|
1127
|
+
const f = this.fibers.get(rec.fiberId);
|
|
1128
|
+
if (f) {
|
|
1129
|
+
f.runState = "Done";
|
|
1130
|
+
f.lastActiveAt = rec.wallTs;
|
|
1131
|
+
f.status = rec.status === "interrupted" ? "Interrupted" : "Done";
|
|
1132
|
+
f.lastEnd = { status: rec.status, error: formatRegistryError(rec.error) };
|
|
1133
|
+
}
|
|
1134
|
+
break;
|
|
1135
|
+
}
|
|
1136
|
+
case "scope.open": {
|
|
1137
|
+
const sid = rec.scopeId;
|
|
1138
|
+
this.scopes.set(sid, {
|
|
1139
|
+
scopeId: sid,
|
|
1140
|
+
parentScopeId: rec.parentScopeId,
|
|
1141
|
+
ownerFiberId: rec.fiberId,
|
|
1142
|
+
openAt: rec.wallTs,
|
|
1143
|
+
finalizers: []
|
|
1144
|
+
});
|
|
1145
|
+
break;
|
|
1146
|
+
}
|
|
1147
|
+
case "scope.close": {
|
|
1148
|
+
const s = this.scopes.get(rec.scopeId);
|
|
1149
|
+
if (s) s.closedAt = rec.wallTs;
|
|
1150
|
+
break;
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
getRecentEvents() {
|
|
1155
|
+
return this.recent.slice();
|
|
1156
|
+
}
|
|
1157
|
+
};
|
|
1158
|
+
function formatRegistryError(error) {
|
|
1159
|
+
if (error === void 0) return void 0;
|
|
1160
|
+
if (Cause.isCause(error)) return Cause.pretty(error, { singleLine: true });
|
|
1161
|
+
if (error instanceof Error) return error.message;
|
|
1162
|
+
if (typeof error === "string") return error;
|
|
1163
|
+
try {
|
|
1164
|
+
return JSON.stringify(error);
|
|
1165
|
+
} catch {
|
|
1166
|
+
return String(error);
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
// src/core/runtime/dump.ts
|
|
1171
|
+
function dumpAllFibers(reg) {
|
|
1172
|
+
const fibers = Array.from(reg.fibers.values());
|
|
1173
|
+
fibers.sort((a, b) => a.runState === b.runState ? b.lastActiveAt - a.lastActiveAt : a.runState.localeCompare(b.runState));
|
|
1174
|
+
const lines = [];
|
|
1175
|
+
lines.push(`=== Fiber Dump (${(/* @__PURE__ */ new Date()).toISOString()}) ===`);
|
|
1176
|
+
for (const f of fibers) {
|
|
1177
|
+
lines.push(
|
|
1178
|
+
`fiber#${f.fiberId} ${f.name ?? ""} run=${f.runState} status=${f.status} scope=${f.scopeId ?? "-"} trace=${f.traceId ?? "-"} span=${f.spanId ?? "-"} last=${new Date(f.lastActiveAt).toISOString()}`
|
|
1179
|
+
);
|
|
1180
|
+
if (f.awaiting) lines.push(` awaiting: ${f.awaiting.reason}${f.awaiting.detail ? ` (${f.awaiting.detail})` : ""}`);
|
|
1181
|
+
if (f.lastEnd?.error) lines.push(` end.error: ${f.lastEnd.error}`);
|
|
1182
|
+
}
|
|
1183
|
+
lines.push(`=== Recent Events ===`);
|
|
1184
|
+
for (const ev of reg.getRecentEvents().slice(-80)) {
|
|
1185
|
+
lines.push(
|
|
1186
|
+
`${ev.seq} ${new Date(ev.wallTs).toISOString()} ${ev.type} fiber=${ev.fiberId ?? "-"} scope=${ev.scopeId ?? "-"} trace=${ev.traceId ?? "-"}`
|
|
1187
|
+
);
|
|
1188
|
+
}
|
|
1189
|
+
return lines.join("\n");
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
// src/core/runtime/tracer.ts
|
|
1193
|
+
var defaultTracer = {
|
|
1194
|
+
newTraceId: () => crypto.randomUUID(),
|
|
1195
|
+
newSpanId: () => crypto.randomUUID()
|
|
1196
|
+
};
|
|
1197
|
+
|
|
1198
|
+
// src/core/types/typedError.ts
|
|
1199
|
+
function catchTag(effect, tag, handler) {
|
|
1200
|
+
return asyncFold(
|
|
1201
|
+
effect,
|
|
1202
|
+
(error) => {
|
|
1203
|
+
if (typeof error === "object" && error !== null && "_tag" in error && error._tag === tag) {
|
|
1204
|
+
return handler(error);
|
|
1205
|
+
}
|
|
1206
|
+
return asyncFail(error);
|
|
1207
|
+
},
|
|
1208
|
+
(value) => asyncSucceed(value)
|
|
1209
|
+
);
|
|
1210
|
+
}
|
|
1211
|
+
function catchTags(effect, handlers) {
|
|
1212
|
+
return asyncFold(
|
|
1213
|
+
effect,
|
|
1214
|
+
(error) => {
|
|
1215
|
+
if (typeof error === "object" && error !== null && "_tag" in error) {
|
|
1216
|
+
const handler = handlers[error._tag];
|
|
1217
|
+
if (handler) return handler(error);
|
|
1218
|
+
}
|
|
1219
|
+
return asyncFail(error);
|
|
1220
|
+
},
|
|
1221
|
+
(value) => asyncSucceed(value)
|
|
1222
|
+
);
|
|
1223
|
+
}
|
|
1224
|
+
function mapError(effect, f) {
|
|
1225
|
+
return asyncFold(effect, (error) => asyncFail(f(error)), asyncSucceed);
|
|
1226
|
+
}
|
|
1227
|
+
function tagError(effect, tag, enrich) {
|
|
1228
|
+
return asyncFold(
|
|
1229
|
+
effect,
|
|
1230
|
+
(error) => {
|
|
1231
|
+
const fields = enrich ? enrich(error) : {};
|
|
1232
|
+
return asyncFail({ _tag: tag, ...fields });
|
|
1233
|
+
},
|
|
1234
|
+
asyncSucceed
|
|
1235
|
+
);
|
|
1236
|
+
}
|
|
1237
|
+
function orElse(effect, fallback) {
|
|
1238
|
+
return asyncFold(effect, fallback, asyncSucceed);
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
// src/core/runtime/supervisor.ts
|
|
1242
|
+
var nextSupervisorId = 1;
|
|
1243
|
+
var nextChildId = 1;
|
|
1244
|
+
var Supervisor = class {
|
|
1245
|
+
constructor(runtime, config = {}) {
|
|
1246
|
+
this.runtime = runtime;
|
|
1247
|
+
this.strategy = config.strategy ?? "one-for-one";
|
|
1248
|
+
this.restart = resolveRestartPolicy(config.restart ?? "on-failure");
|
|
1249
|
+
this.escalation = config.escalation ?? "shutdown";
|
|
1250
|
+
this.clock = config.clock ?? Date.now;
|
|
1251
|
+
this.onEvent = config.onEvent;
|
|
1252
|
+
}
|
|
1253
|
+
runtime;
|
|
1254
|
+
id = nextSupervisorId++;
|
|
1255
|
+
records = /* @__PURE__ */ new Map();
|
|
1256
|
+
strategy;
|
|
1257
|
+
restart;
|
|
1258
|
+
escalation;
|
|
1259
|
+
clock;
|
|
1260
|
+
onEvent;
|
|
1261
|
+
closed = false;
|
|
1262
|
+
start(spec) {
|
|
1263
|
+
if (this.closed) throw new Error("Supervisor is shut down");
|
|
1264
|
+
const record = {
|
|
1265
|
+
id: nextChildId++,
|
|
1266
|
+
name: spec.name,
|
|
1267
|
+
spec,
|
|
1268
|
+
restart: resolveRestartPolicy(spec.restart ?? this.restart),
|
|
1269
|
+
status: "running",
|
|
1270
|
+
restartCount: 0,
|
|
1271
|
+
restartTimes: [],
|
|
1272
|
+
generation: 0,
|
|
1273
|
+
plannedRestart: false,
|
|
1274
|
+
joiners: []
|
|
1275
|
+
};
|
|
1276
|
+
this.records.set(record.id, record);
|
|
1277
|
+
this.launch(record);
|
|
1278
|
+
return this.handle(record);
|
|
1279
|
+
}
|
|
1280
|
+
startAll(specs) {
|
|
1281
|
+
return specs.map((spec) => this.start(spec));
|
|
1282
|
+
}
|
|
1283
|
+
shutdown() {
|
|
1284
|
+
return asyncEffect((_env, cb) => {
|
|
1285
|
+
this.closed = true;
|
|
1286
|
+
this.emit({ type: "shutdown", supervisorId: this.id });
|
|
1287
|
+
const records = [...this.records.values()];
|
|
1288
|
+
let remaining = records.filter((record) => record.current !== void 0).length;
|
|
1289
|
+
for (const record of records) {
|
|
1290
|
+
if (record.timer) {
|
|
1291
|
+
clearTimeout(record.timer);
|
|
1292
|
+
record.timer = void 0;
|
|
1293
|
+
}
|
|
1294
|
+
record.plannedRestart = false;
|
|
1295
|
+
if (record.current) {
|
|
1296
|
+
record.status = "interrupted";
|
|
1297
|
+
record.current.interrupt();
|
|
1298
|
+
} else if (!record.terminalExit) {
|
|
1299
|
+
this.finish(record, interruptExit());
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
if (remaining === 0) {
|
|
1303
|
+
cb({ _tag: "Success", value: void 0 });
|
|
1304
|
+
return;
|
|
1305
|
+
}
|
|
1306
|
+
for (const record of records) {
|
|
1307
|
+
record.current?.join(() => {
|
|
1308
|
+
remaining--;
|
|
1309
|
+
if (remaining === 0) cb({ _tag: "Success", value: void 0 });
|
|
1310
|
+
});
|
|
1311
|
+
}
|
|
1312
|
+
});
|
|
1313
|
+
}
|
|
1314
|
+
handle(record) {
|
|
1315
|
+
return {
|
|
1316
|
+
id: record.id,
|
|
1317
|
+
name: record.name,
|
|
1318
|
+
current: () => record.current,
|
|
1319
|
+
status: () => record.status,
|
|
1320
|
+
restartCount: () => record.restartCount,
|
|
1321
|
+
interrupt: () => {
|
|
1322
|
+
record.plannedRestart = false;
|
|
1323
|
+
if (record.timer) {
|
|
1324
|
+
clearTimeout(record.timer);
|
|
1325
|
+
record.timer = void 0;
|
|
1326
|
+
}
|
|
1327
|
+
if (record.current) {
|
|
1328
|
+
record.current.interrupt();
|
|
1329
|
+
} else if (!record.terminalExit) {
|
|
1330
|
+
this.finish(record, interruptExit());
|
|
1331
|
+
}
|
|
1332
|
+
},
|
|
1333
|
+
join: (cb) => {
|
|
1334
|
+
if (record.terminalExit) cb(record.terminalExit);
|
|
1335
|
+
else record.joiners.push(cb);
|
|
1336
|
+
}
|
|
1337
|
+
};
|
|
1338
|
+
}
|
|
1339
|
+
launch(record) {
|
|
1340
|
+
if (this.closed) return;
|
|
1341
|
+
record.generation++;
|
|
1342
|
+
record.status = "running";
|
|
1343
|
+
record.plannedRestart = false;
|
|
1344
|
+
record.terminalExit = void 0;
|
|
1345
|
+
const generation = record.generation;
|
|
1346
|
+
const effect = typeof record.spec.effect === "function" ? record.spec.effect() : record.spec.effect;
|
|
1347
|
+
const fiber = this.runtime.fork(effect);
|
|
1348
|
+
record.current = fiber;
|
|
1349
|
+
this.emit({
|
|
1350
|
+
type: "child-start",
|
|
1351
|
+
supervisorId: this.id,
|
|
1352
|
+
childId: record.id,
|
|
1353
|
+
name: record.name,
|
|
1354
|
+
status: "running",
|
|
1355
|
+
restartCount: record.restartCount
|
|
1356
|
+
});
|
|
1357
|
+
fiber.join((exit) => this.onChildExit(record, generation, exit));
|
|
1358
|
+
}
|
|
1359
|
+
onChildExit(record, generation, exit) {
|
|
1360
|
+
if (generation !== record.generation) return;
|
|
1361
|
+
record.current = void 0;
|
|
1362
|
+
if (this.closed) {
|
|
1363
|
+
this.finish(record, exit);
|
|
1364
|
+
return;
|
|
1365
|
+
}
|
|
1366
|
+
if (record.plannedRestart) {
|
|
1367
|
+
this.scheduleRestart(record, exit, "all-for-one");
|
|
1368
|
+
return;
|
|
1369
|
+
}
|
|
1370
|
+
this.emit({
|
|
1371
|
+
type: "child-end",
|
|
1372
|
+
supervisorId: this.id,
|
|
1373
|
+
childId: record.id,
|
|
1374
|
+
name: record.name,
|
|
1375
|
+
status: statusFromExit(exit),
|
|
1376
|
+
restartCount: record.restartCount,
|
|
1377
|
+
exit
|
|
1378
|
+
});
|
|
1379
|
+
if (!shouldRestart(record.restart.mode, exit)) {
|
|
1380
|
+
this.finish(record, exit);
|
|
1381
|
+
return;
|
|
1382
|
+
}
|
|
1383
|
+
if (this.strategy === "all-for-one") {
|
|
1384
|
+
this.restartAll(record, exit);
|
|
1385
|
+
return;
|
|
1386
|
+
}
|
|
1387
|
+
this.scheduleRestart(record, exit, "one-for-one");
|
|
1388
|
+
}
|
|
1389
|
+
restartAll(failed, exit) {
|
|
1390
|
+
for (const record of this.records.values()) {
|
|
1391
|
+
if (record.id === failed.id) continue;
|
|
1392
|
+
if (!record.current) continue;
|
|
1393
|
+
record.plannedRestart = true;
|
|
1394
|
+
record.status = "restarting";
|
|
1395
|
+
record.current.interrupt();
|
|
1396
|
+
}
|
|
1397
|
+
this.scheduleRestart(failed, exit, "all-for-one");
|
|
1398
|
+
}
|
|
1399
|
+
scheduleRestart(record, exit, reason) {
|
|
1400
|
+
const context = this.restartContext(record, exit);
|
|
1401
|
+
const delay = this.nextDelay(record, context);
|
|
1402
|
+
if (delay === void 0) {
|
|
1403
|
+
this.escalate(record, exit, "restart policy exhausted");
|
|
1404
|
+
return;
|
|
1405
|
+
}
|
|
1406
|
+
record.status = "restarting";
|
|
1407
|
+
record.restartCount++;
|
|
1408
|
+
this.emit({
|
|
1409
|
+
type: "child-restart",
|
|
1410
|
+
supervisorId: this.id,
|
|
1411
|
+
childId: record.id,
|
|
1412
|
+
name: record.name,
|
|
1413
|
+
status: "restarting",
|
|
1414
|
+
restartCount: record.restartCount,
|
|
1415
|
+
delayMs: delay,
|
|
1416
|
+
exit,
|
|
1417
|
+
reason
|
|
1418
|
+
});
|
|
1419
|
+
record.timer = setTimeout(() => {
|
|
1420
|
+
record.timer = void 0;
|
|
1421
|
+
this.launch(record);
|
|
1422
|
+
}, delay);
|
|
1423
|
+
}
|
|
1424
|
+
nextDelay(record, context) {
|
|
1425
|
+
const now = this.clock();
|
|
1426
|
+
const windowStart = record.restart.withinMs === void 0 ? Number.NEGATIVE_INFINITY : now - record.restart.withinMs;
|
|
1427
|
+
record.restartTimes = record.restartTimes.filter((ts) => ts >= windowStart);
|
|
1428
|
+
if (record.restart.maxRestarts !== void 0 && record.restartTimes.length >= record.restart.maxRestarts) {
|
|
1429
|
+
return void 0;
|
|
1430
|
+
}
|
|
1431
|
+
record.restartTimes.push(now);
|
|
1432
|
+
if (record.restart.schedule) {
|
|
1433
|
+
record.scheduleDriver ??= makeScheduleDriver(record.restart.schedule, {
|
|
1434
|
+
name: record.restart.schedule.name ?? "supervisor.restart",
|
|
1435
|
+
clock: this.scheduleClock()
|
|
1436
|
+
});
|
|
1437
|
+
const decision = record.scheduleDriver.next(context);
|
|
1438
|
+
return decision.continue ? Math.max(0, Math.floor(decision.delayMs)) : void 0;
|
|
1439
|
+
}
|
|
1440
|
+
const raw = typeof record.restart.delayMs === "function" ? record.restart.delayMs(context) : record.restart.delayMs ?? 0;
|
|
1441
|
+
return Number.isFinite(raw) ? Math.max(0, Math.floor(raw)) : 0;
|
|
1442
|
+
}
|
|
1443
|
+
escalate(record, exit, reason) {
|
|
1444
|
+
this.emit({
|
|
1445
|
+
type: "child-escalate",
|
|
1446
|
+
supervisorId: this.id,
|
|
1447
|
+
childId: record.id,
|
|
1448
|
+
name: record.name,
|
|
1449
|
+
status: statusFromExit(exit),
|
|
1450
|
+
restartCount: record.restartCount,
|
|
1451
|
+
exit,
|
|
1452
|
+
reason
|
|
1453
|
+
});
|
|
1454
|
+
if (this.escalation === "shutdown") {
|
|
1455
|
+
for (const child of this.records.values()) {
|
|
1456
|
+
if (child.id !== record.id) child.current?.interrupt();
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
this.finish(record, exit);
|
|
1460
|
+
}
|
|
1461
|
+
finish(record, exit) {
|
|
1462
|
+
record.status = statusFromExit(exit);
|
|
1463
|
+
record.terminalExit = exit;
|
|
1464
|
+
const joiners = record.joiners.splice(0);
|
|
1465
|
+
for (const joiner of joiners) joiner(exit);
|
|
1466
|
+
}
|
|
1467
|
+
restartContext(record, exit) {
|
|
1468
|
+
return {
|
|
1469
|
+
supervisorId: this.id,
|
|
1470
|
+
childId: record.id,
|
|
1471
|
+
name: record.name,
|
|
1472
|
+
restartCount: record.restartCount,
|
|
1473
|
+
exit
|
|
1474
|
+
};
|
|
1475
|
+
}
|
|
1476
|
+
emit(event) {
|
|
1477
|
+
this.onEvent?.(event);
|
|
1478
|
+
this.runtime.emit(toRuntimeEvent(event));
|
|
1479
|
+
}
|
|
1480
|
+
scheduleClock() {
|
|
1481
|
+
return {
|
|
1482
|
+
now: this.clock,
|
|
1483
|
+
setTimeout: liveClock.setTimeout,
|
|
1484
|
+
clearTimeout: liveClock.clearTimeout
|
|
1485
|
+
};
|
|
1486
|
+
}
|
|
1487
|
+
};
|
|
1488
|
+
function makeSupervisor(runtime, config = {}) {
|
|
1489
|
+
return new Supervisor(runtime, config);
|
|
1490
|
+
}
|
|
1491
|
+
function supervise(runtime, spec, config = {}) {
|
|
1492
|
+
return new Supervisor(runtime, config).start(spec);
|
|
1493
|
+
}
|
|
1494
|
+
function joinSupervised(fiber) {
|
|
1495
|
+
return asyncEffect((_env, cb) => fiber.join(cb));
|
|
1496
|
+
}
|
|
1497
|
+
function resolveRestartPolicy(policy) {
|
|
1498
|
+
if (typeof policy === "string") return { mode: policy };
|
|
1499
|
+
return {
|
|
1500
|
+
mode: policy.mode ?? "on-failure",
|
|
1501
|
+
maxRestarts: policy.maxRestarts,
|
|
1502
|
+
withinMs: policy.withinMs,
|
|
1503
|
+
delayMs: policy.delayMs,
|
|
1504
|
+
schedule: policy.schedule
|
|
1505
|
+
};
|
|
1506
|
+
}
|
|
1507
|
+
function shouldRestart(mode, exit) {
|
|
1508
|
+
if (exit._tag === "Failure" && Cause.isInterruptedOnly(exit.cause)) return false;
|
|
1509
|
+
if (mode === "never") return false;
|
|
1510
|
+
if (mode === "always") return true;
|
|
1511
|
+
return exit._tag === "Failure";
|
|
1512
|
+
}
|
|
1513
|
+
function statusFromExit(exit) {
|
|
1514
|
+
if (exit._tag === "Success") return "succeeded";
|
|
1515
|
+
return Cause.isInterruptedOnly(exit.cause) ? "interrupted" : "failed";
|
|
1516
|
+
}
|
|
1517
|
+
function toRuntimeEvent(event) {
|
|
1518
|
+
switch (event.type) {
|
|
1519
|
+
case "child-start":
|
|
1520
|
+
return {
|
|
1521
|
+
type: "supervisor.child.start",
|
|
1522
|
+
supervisorId: event.supervisorId,
|
|
1523
|
+
childId: event.childId,
|
|
1524
|
+
name: event.name,
|
|
1525
|
+
restartCount: event.restartCount ?? 0
|
|
1526
|
+
};
|
|
1527
|
+
case "child-end":
|
|
1528
|
+
return {
|
|
1529
|
+
type: "supervisor.child.end",
|
|
1530
|
+
supervisorId: event.supervisorId,
|
|
1531
|
+
childId: event.childId,
|
|
1532
|
+
name: event.name,
|
|
1533
|
+
status: event.status === "succeeded" ? "success" : event.status === "interrupted" ? "interrupted" : "failure",
|
|
1534
|
+
error: event.exit?._tag === "Failure" ? event.exit.cause : void 0
|
|
1535
|
+
};
|
|
1536
|
+
case "child-restart":
|
|
1537
|
+
return {
|
|
1538
|
+
type: "supervisor.child.restart",
|
|
1539
|
+
supervisorId: event.supervisorId,
|
|
1540
|
+
childId: event.childId,
|
|
1541
|
+
name: event.name,
|
|
1542
|
+
restartCount: event.restartCount ?? 0,
|
|
1543
|
+
delayMs: event.delayMs ?? 0,
|
|
1544
|
+
reason: event.reason
|
|
1545
|
+
};
|
|
1546
|
+
case "child-escalate":
|
|
1547
|
+
return {
|
|
1548
|
+
type: "supervisor.child.escalate",
|
|
1549
|
+
supervisorId: event.supervisorId,
|
|
1550
|
+
childId: event.childId,
|
|
1551
|
+
name: event.name,
|
|
1552
|
+
reason: event.reason,
|
|
1553
|
+
error: event.exit?._tag === "Failure" ? event.exit.cause : void 0
|
|
1554
|
+
};
|
|
1555
|
+
case "shutdown":
|
|
1556
|
+
return {
|
|
1557
|
+
type: "supervisor.shutdown",
|
|
1558
|
+
supervisorId: event.supervisorId
|
|
1559
|
+
};
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
function interruptExit() {
|
|
1563
|
+
return { _tag: "Failure", cause: { _tag: "Interrupt" } };
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
export {
|
|
1567
|
+
makeCancelToken,
|
|
1568
|
+
linkAbortController,
|
|
1569
|
+
makeRuntime,
|
|
1570
|
+
runPromise,
|
|
1571
|
+
runExit,
|
|
1572
|
+
runEffect,
|
|
1573
|
+
LinkedQueue,
|
|
1574
|
+
makeSemaphore,
|
|
1575
|
+
makeRef,
|
|
1576
|
+
derivedRef,
|
|
1577
|
+
gracefulShutdown,
|
|
1578
|
+
registerShutdownHooks,
|
|
1579
|
+
TestScheduler,
|
|
1580
|
+
TestClock,
|
|
1581
|
+
makeTestRuntime,
|
|
1582
|
+
assertSucceeds,
|
|
1583
|
+
assertFails,
|
|
1584
|
+
assertFailsWith,
|
|
1585
|
+
assertCompletesWithin,
|
|
1586
|
+
flakyEffect,
|
|
1587
|
+
delayedEffect,
|
|
1588
|
+
neverEffect,
|
|
1589
|
+
MissingLayerServiceError,
|
|
1590
|
+
formatLayerError,
|
|
1591
|
+
makeServiceTag,
|
|
1592
|
+
serviceTag,
|
|
1593
|
+
defineService,
|
|
1594
|
+
LayerContext,
|
|
1595
|
+
makeLayerScope,
|
|
1596
|
+
layer,
|
|
1597
|
+
layerValue,
|
|
1598
|
+
layerEffect,
|
|
1599
|
+
layerFromContext,
|
|
1600
|
+
defineLayer,
|
|
1601
|
+
getService,
|
|
1602
|
+
layerFrom,
|
|
1603
|
+
layerSucceed,
|
|
1604
|
+
layerFail,
|
|
1605
|
+
compose,
|
|
1606
|
+
merge,
|
|
1607
|
+
mapLayer,
|
|
1608
|
+
buildLayer,
|
|
1609
|
+
provideLayer,
|
|
1610
|
+
provideLayerContext,
|
|
1611
|
+
provide,
|
|
1612
|
+
provideContext,
|
|
1613
|
+
Layer,
|
|
1614
|
+
makeWorkerPool,
|
|
1615
|
+
makeTracer,
|
|
1616
|
+
consoleJsonLogger,
|
|
1617
|
+
RuntimeRegistry,
|
|
1618
|
+
dumpAllFibers,
|
|
1619
|
+
defaultTracer,
|
|
1620
|
+
catchTag,
|
|
1621
|
+
catchTags,
|
|
1622
|
+
mapError,
|
|
1623
|
+
tagError,
|
|
1624
|
+
orElse,
|
|
1625
|
+
Supervisor,
|
|
1626
|
+
makeSupervisor,
|
|
1627
|
+
supervise,
|
|
1628
|
+
joinSupervised
|
|
1629
|
+
};
|