@brickkit/effect 0.16.0-beta.7 → 0.16.0-beta.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +20 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +157 -32
- package/dist/index.js.map +1 -1
- package/dist/{server-BK0CrkGH.js → server-B1gl742e.js} +1274 -152
- package/dist/server-B1gl742e.js.map +1 -0
- package/dist/{server-tJhU9lsW.d.ts → server-CxyGTnai.d.ts} +297 -28
- package/dist/server-CxyGTnai.d.ts.map +1 -0
- package/dist/testing.d.ts +3 -3
- package/dist/testing.d.ts.map +1 -1
- package/dist/testing.js +2 -2
- package/dist/testing.js.map +1 -1
- package/package.json +1 -1
- package/dist/server-BK0CrkGH.js.map +0 -1
- package/dist/server-tJhU9lsW.d.ts.map +0 -1
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { Cause, Clock, Context, Data, Deferred, Duration, Effect, Exit, Fiber, FiberMap, Layer, ManagedRuntime, Option, Result, Schedule, Schema, SchemaIssue, SchemaTransformation, Scope, Semaphore, Tracer } from "effect";
|
|
2
|
-
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
3
3
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
4
|
import { formatWithOptions, inspect } from "node:util";
|
|
5
5
|
import { FetchHttpClient, HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
|
|
6
6
|
import { OtlpSerialization, OtlpTracer } from "effect/observability";
|
|
7
7
|
import { Statement } from "effect/sql";
|
|
8
8
|
import { and, asc, eq, getTableColumns, inArray, isNull, like, lt, lte, or, sql } from "drizzle-orm";
|
|
9
|
-
import { bigserial, index, integer, jsonb, pgTable, text, timestamp } from "drizzle-orm/pg-core";
|
|
9
|
+
import { bigint, bigserial, index, integer, jsonb, pgTable, text, timestamp } from "drizzle-orm/pg-core";
|
|
10
10
|
import { index as index$1, integer as integer$1, sqliteTable, text as text$1 } from "drizzle-orm/sqlite-core";
|
|
11
11
|
import { lstat, mkdir, readFile, realpath, rm } from "node:fs/promises";
|
|
12
12
|
import { basename, dirname, join, relative, resolve, sep } from "node:path";
|
|
@@ -55,18 +55,119 @@ var ValidationError = class extends Data.TaggedError("ValidationError") {
|
|
|
55
55
|
var DuplicateNameError = class extends Error {
|
|
56
56
|
name = "DuplicateNameError";
|
|
57
57
|
};
|
|
58
|
-
|
|
58
|
+
/**
|
|
59
|
+
* Whether `value` is an error of core's class `name`, or of a subclass: core's
|
|
60
|
+
* `instanceof`, without importing core (a second copy of core has its own
|
|
61
|
+
* classes). Core sets `name` in its constructors, which a minifier cannot
|
|
62
|
+
* rename, so that settles it for an `Error`. A class name does not survive
|
|
63
|
+
* minification, so the prototype chain is only the fallback for a subclass that
|
|
64
|
+
* sets its own `name`.
|
|
65
|
+
*/
|
|
66
|
+
const inheritsFrom = (value, name) => {
|
|
67
|
+
if (value instanceof Error && value.name === name) return true;
|
|
68
|
+
for (let at = Object.getPrototypeOf(value); at; at = Object.getPrototypeOf(at)) if (Object.hasOwn(at, "constructor") && at.constructor?.name === name) return true;
|
|
69
|
+
return false;
|
|
70
|
+
};
|
|
71
|
+
const isHttpStatus = (status) => Number.isInteger(status) && status >= 400 && status < 600;
|
|
72
|
+
const isIssue = (item) => item !== null && typeof item === "object" && typeof item.path === "string" && typeof item.message === "string";
|
|
73
|
+
/** The `name` of the core error a failure stands for, as core answers the error's `name`. */
|
|
74
|
+
const names = /* @__PURE__ */ new WeakMap();
|
|
75
|
+
function named(failure, core) {
|
|
76
|
+
const { name } = core;
|
|
77
|
+
if (typeof name === "string") names.set(failure, name);
|
|
78
|
+
return failure;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* The failure `value` stands for, or `undefined`. Besides this package's own
|
|
82
|
+
* errors it takes an error of `@brickkit/core`, which core answers with its code,
|
|
83
|
+
* status and details wherever it came from: an `ActionExecutionError` (or a
|
|
84
|
+
* subclass of it) with a string `code` and `message` and a 4xx or 5xx `status`,
|
|
85
|
+
* and a `ValidationError` with its `errors`. Core checks the class and nothing
|
|
86
|
+
* else, so any other value that carries a `status` (an Elysia or third-party
|
|
87
|
+
* error, a plain `Error`) is not one.
|
|
88
|
+
*/
|
|
89
|
+
function asFailure(value) {
|
|
90
|
+
if (value instanceof BrickError || value instanceof ValidationError) return value;
|
|
91
|
+
if (value === null || typeof value !== "object") return void 0;
|
|
92
|
+
const { code, message, status, details, errors } = value;
|
|
93
|
+
if (typeof message !== "string" || !isHttpStatus(status)) return void 0;
|
|
94
|
+
if (inheritsFrom(value, "ActionExecutionError") && typeof code === "string") return named(new BrickError({
|
|
95
|
+
code,
|
|
96
|
+
message,
|
|
97
|
+
status,
|
|
98
|
+
details,
|
|
99
|
+
cause: value
|
|
100
|
+
}), value);
|
|
101
|
+
if (inheritsFrom(value, "ValidationError") && code === "VALIDATION_FAILED" && Array.isArray(errors) && errors.every(isIssue)) return named(new ValidationError({
|
|
102
|
+
cause: value,
|
|
103
|
+
message,
|
|
104
|
+
status,
|
|
105
|
+
errors: errors.map(({ path, message, type }) => ({
|
|
106
|
+
path,
|
|
107
|
+
message,
|
|
108
|
+
...typeof type === "number" && { type }
|
|
109
|
+
}))
|
|
110
|
+
}), value);
|
|
111
|
+
}
|
|
112
|
+
/** The first failure in `cause`, typed or a defect, that `asFailure` recognises. */
|
|
113
|
+
function failureOfCause(cause) {
|
|
114
|
+
for (const reason of cause.reasons) {
|
|
115
|
+
const failure = asFailure(Cause.isFailReason(reason) ? reason.error : Cause.isDieReason(reason) ? reason.defect : void 0);
|
|
116
|
+
if (failure) return failure;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/** The 500s `toFailure` built: named `InternalServerError`, as core names its own. */
|
|
120
|
+
const built$1 = /* @__PURE__ */ new WeakSet();
|
|
121
|
+
/** The 5xx failures already logged, so they are logged once. */
|
|
122
|
+
const logged$1 = /* @__PURE__ */ new WeakSet();
|
|
123
|
+
/**
|
|
124
|
+
* A copy of `failure` with other `message` and `details`, which is the same
|
|
125
|
+
* failure as far as its name and its logging go. The copy leaves out the
|
|
126
|
+
* `cause`: it was logged with `failure`, and holds what the caller redacted.
|
|
127
|
+
*/
|
|
128
|
+
function redactedCopy(failure, { message, details }) {
|
|
129
|
+
const copy = failure instanceof ValidationError ? new ValidationError({
|
|
130
|
+
message,
|
|
131
|
+
status: failure.status,
|
|
132
|
+
errors: failure.errors
|
|
133
|
+
}) : new BrickError({
|
|
134
|
+
code: failure.code,
|
|
135
|
+
status: failure.status,
|
|
136
|
+
message,
|
|
137
|
+
details
|
|
138
|
+
});
|
|
139
|
+
const name = names.get(failure);
|
|
140
|
+
if (name !== void 0) names.set(copy, name);
|
|
141
|
+
if (built$1.has(failure)) built$1.add(copy);
|
|
142
|
+
if (logged$1.has(failure)) logged$1.add(copy);
|
|
143
|
+
return copy;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* `prefixed` stands for `failure` with a longer message. Core logs the error a nested action passes through
|
|
147
|
+
* once, when it is answered, and the one it built after an unexpected throw twice, so only the first
|
|
148
|
+
* carries its log over.
|
|
149
|
+
*/
|
|
150
|
+
function prefixedFailure(failure, prefixed) {
|
|
151
|
+
if (logged$1.has(failure) && !built$1.has(failure)) logged$1.add(prefixed);
|
|
152
|
+
return prefixed;
|
|
153
|
+
}
|
|
154
|
+
/** Logs a recognised failure with status 500 or more, as core does, once. */
|
|
155
|
+
function logServerFailure(failure, cause, { logger, requestId }) {
|
|
156
|
+
if (failure.status < 500 || logged$1.has(failure)) return;
|
|
157
|
+
logged$1.add(failure);
|
|
158
|
+
logger.error("Server action error", { requestId }, Cause.pretty(cause));
|
|
159
|
+
}
|
|
59
160
|
/** A failure as JSON. A failed output check (status 500) leaves out its `errors`, which describe internals. */
|
|
60
161
|
function toWireError(error) {
|
|
61
162
|
if (error instanceof ValidationError) return {
|
|
62
|
-
name: "ValidationError",
|
|
163
|
+
name: names.get(error) ?? "ValidationError",
|
|
63
164
|
code: error.code,
|
|
64
165
|
message: error.message,
|
|
65
166
|
status: error.status,
|
|
66
167
|
...error.status < 500 && { errors: [...error.errors] }
|
|
67
168
|
};
|
|
68
169
|
return {
|
|
69
|
-
name: error
|
|
170
|
+
name: names.get(error) ?? (built$1.has(error) ? "InternalServerError" : "ActionExecutionError"),
|
|
70
171
|
code: error.code,
|
|
71
172
|
message: error.message,
|
|
72
173
|
status: error.status,
|
|
@@ -74,18 +175,27 @@ function toWireError(error) {
|
|
|
74
175
|
};
|
|
75
176
|
}
|
|
76
177
|
/**
|
|
77
|
-
* The failure a cause stands for: a declared one
|
|
78
|
-
* unknown failure or a defect) is logged and becomes `INTERNAL_SERVER_ERROR`
|
|
178
|
+
* The failure a cause stands for: a declared one, or a core error (see
|
|
179
|
+
* `asFailure`), is kept; anything else (an unknown failure or a defect) is logged and becomes `INTERNAL_SERVER_ERROR`
|
|
79
180
|
* (500), with the cause kept out of the result.
|
|
80
181
|
*/
|
|
81
182
|
function toFailure(cause, { logger, requestId }) {
|
|
82
|
-
const
|
|
83
|
-
if (
|
|
183
|
+
const known = failureOfCause(cause);
|
|
184
|
+
if (known) {
|
|
185
|
+
logServerFailure(known, cause, {
|
|
186
|
+
logger,
|
|
187
|
+
requestId
|
|
188
|
+
});
|
|
189
|
+
return known;
|
|
190
|
+
}
|
|
84
191
|
logger.error("Unexpected action error", { requestId }, Cause.pretty(cause));
|
|
85
|
-
|
|
192
|
+
const failure = new BrickError({
|
|
86
193
|
...STANDARD_ERRORS.INTERNAL_SERVER_ERROR,
|
|
87
194
|
code: "INTERNAL_SERVER_ERROR"
|
|
88
195
|
});
|
|
196
|
+
built$1.add(failure);
|
|
197
|
+
logged$1.add(failure);
|
|
198
|
+
return failure;
|
|
89
199
|
}
|
|
90
200
|
/** Turns whatever fails in `self` into a declared failure, except interruption. */
|
|
91
201
|
const normalizeFailures = (context) => (self) => Effect.catchCause(self, (cause) => Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.fail(toFailure(cause, context)));
|
|
@@ -95,10 +205,10 @@ const normalizeFailures = (context) => (self) => Effect.catchCause(self, (cause)
|
|
|
95
205
|
* generic `INTERNAL_SERVER_ERROR` (500), so internals are never exposed.
|
|
96
206
|
*/
|
|
97
207
|
function toErrorResponse(cause, context) {
|
|
98
|
-
const
|
|
99
|
-
if (
|
|
208
|
+
const known = failureOfCause(cause);
|
|
209
|
+
if (known) logServerFailure(known, cause, context);
|
|
100
210
|
return {
|
|
101
|
-
...toWireError(
|
|
211
|
+
...toWireError(known ?? toFailure(cause, context)),
|
|
102
212
|
requestId: context.requestId ?? ""
|
|
103
213
|
};
|
|
104
214
|
}
|
|
@@ -115,6 +225,8 @@ const SPAN = {
|
|
|
115
225
|
actionPrefix: "action ",
|
|
116
226
|
/** `rpc <service>.<action>` */
|
|
117
227
|
rpcPrefix: "rpc ",
|
|
228
|
+
/** `socket <service>.<name>`: a raw socket connection, from upgrade to close. */
|
|
229
|
+
socketPrefix: "socket ",
|
|
118
230
|
exceptionEvent: "exception",
|
|
119
231
|
/** The span event a `ctx.logger` line becomes. */
|
|
120
232
|
logEvent: "log"
|
|
@@ -139,6 +251,12 @@ const ATTR = {
|
|
|
139
251
|
scheduleAttempt: "brick.schedule.attempt",
|
|
140
252
|
scheduleSlot: "brick.schedule.slot",
|
|
141
253
|
scheduleOutcome: "brick.schedule.outcome",
|
|
254
|
+
/** A raw socket connection: its route name, id, frames and bytes received, and close code. */
|
|
255
|
+
socketName: "brick.socket.name",
|
|
256
|
+
socketId: "brick.socket.id",
|
|
257
|
+
socketMessages: "brick.socket.messages",
|
|
258
|
+
socketBytes: "brick.socket.bytes",
|
|
259
|
+
socketCloseCode: "brick.socket.close_code",
|
|
142
260
|
traceId: "brick.trace_id",
|
|
143
261
|
errorCode: "brick.error.code",
|
|
144
262
|
errorMessage: "brick.error.message",
|
|
@@ -331,7 +449,6 @@ const truncate = (text, limit = MAX_TEXT_LENGTH) => text.length > limit ? `${tex
|
|
|
331
449
|
const toMs = (nanos) => Number(nanos) / 1e6;
|
|
332
450
|
const nowNanos = () => BigInt(Math.round((performance.timeOrigin + performance.now()) * 1e6));
|
|
333
451
|
const messageOf = (error) => error instanceof Error ? error.message : String(error);
|
|
334
|
-
const isHandled = (error) => error instanceof BrickError || error instanceof ValidationError;
|
|
335
452
|
/** A span of the app's tracer: records what the dashboard reads when it starts and ends, and hands it to the OTLP tracer when there is one. */
|
|
336
453
|
var BrickSpan = class extends Tracer.NativeSpan {
|
|
337
454
|
#sql;
|
|
@@ -401,8 +518,8 @@ var BrickSpan = class extends Tracer.NativeSpan {
|
|
|
401
518
|
}
|
|
402
519
|
#record(cause, endTime) {
|
|
403
520
|
const found = Cause.findError(cause);
|
|
404
|
-
const error =
|
|
405
|
-
if (
|
|
521
|
+
const error = failureOfCause(cause);
|
|
522
|
+
if (error) {
|
|
406
523
|
super.attribute(ATTR.errorCode, error.code);
|
|
407
524
|
super.attribute(ATTR.errorStatus, error.status);
|
|
408
525
|
super.attribute(ATTR.errorMessage, truncate(error.message));
|
|
@@ -541,6 +658,46 @@ function traceRequest(request, method, route, body) {
|
|
|
541
658
|
}, (span) => body(span).pipe(Effect.withParentSpan(span, { captureStackTrace: false })));
|
|
542
659
|
}
|
|
543
660
|
/**
|
|
661
|
+
* Start `name` as a server span for a WebSocket upgrade, continuing the
|
|
662
|
+
* caller's trace when a W3C `traceparent` arrives. It stays open until `end`,
|
|
663
|
+
* so it is made by hand: `Effect.useSpan` would end it with its first callback.
|
|
664
|
+
*/
|
|
665
|
+
function startSocketSpan(name, request, attributes, tracer = brickTracer) {
|
|
666
|
+
const parent = externalParent(request.headers.get("traceparent"));
|
|
667
|
+
const span = tracer.span({
|
|
668
|
+
name,
|
|
669
|
+
parent: parent ? Option.some(parent) : Option.none(),
|
|
670
|
+
annotations: Context.empty(),
|
|
671
|
+
links: [],
|
|
672
|
+
startTime: nowNanos(),
|
|
673
|
+
kind: "server",
|
|
674
|
+
root: !parent,
|
|
675
|
+
sampled: parent?.sampled ?? true
|
|
676
|
+
});
|
|
677
|
+
const record = (values) => {
|
|
678
|
+
for (const [key, value] of Object.entries(values)) span.attribute(key, value);
|
|
679
|
+
};
|
|
680
|
+
record({
|
|
681
|
+
[ATTR.httpMethod]: "GET",
|
|
682
|
+
[ATTR.urlPath]: new URL(request.url).pathname,
|
|
683
|
+
...attributes
|
|
684
|
+
});
|
|
685
|
+
return {
|
|
686
|
+
span,
|
|
687
|
+
link(traceparent) {
|
|
688
|
+
const linked = externalParent(traceparent);
|
|
689
|
+
if (linked) span.addLinks([{
|
|
690
|
+
span: linked,
|
|
691
|
+
attributes: {}
|
|
692
|
+
}]);
|
|
693
|
+
},
|
|
694
|
+
end(final, failure) {
|
|
695
|
+
record(final);
|
|
696
|
+
span.end(nowNanos(), failure === void 0 ? Exit.void : Exit.die(failure));
|
|
697
|
+
}
|
|
698
|
+
};
|
|
699
|
+
}
|
|
700
|
+
/**
|
|
544
701
|
* Wrap a raw route handler so each of its requests gets a server span in
|
|
545
702
|
* Brick's span store (`spanStore`, which `brick dev` and the dashboard read).
|
|
546
703
|
* For routes you serve yourself around `app.fetch`: they are outside actions
|
|
@@ -2103,7 +2260,7 @@ const holdsMark = (ast, seen = /* @__PURE__ */ new Set()) => {
|
|
|
2103
2260
|
if (isMarked(ast)) return true;
|
|
2104
2261
|
return (ast._tag === "Objects" ? [...ast.propertySignatures.map(({ type }) => type), ...ast.indexSignatures.map(({ type }) => type)] : ast._tag === "Arrays" ? [...ast.elements, ...ast.rest] : ast._tag === "Union" ? ast.types : ast._tag === "Suspend" ? [ast.thunk()] : ast._tag === "Declaration" ? ast.typeParameters : []).some((child) => holdsMark(child, seen));
|
|
2105
2262
|
};
|
|
2106
|
-
function collect(ast, segments, optional, walk) {
|
|
2263
|
+
function collect$1(ast, segments, optional, walk) {
|
|
2107
2264
|
if (isMarked(ast)) {
|
|
2108
2265
|
walk.paths.push({
|
|
2109
2266
|
segments,
|
|
@@ -2116,11 +2273,11 @@ function collect(ast, segments, optional, walk) {
|
|
|
2116
2273
|
return;
|
|
2117
2274
|
}
|
|
2118
2275
|
if (ast._tag === "Union") {
|
|
2119
|
-
for (const branch of ast.types) collect(branch, segments, optional, walk);
|
|
2276
|
+
for (const branch of ast.types) collect$1(branch, segments, optional, walk);
|
|
2120
2277
|
return;
|
|
2121
2278
|
}
|
|
2122
2279
|
if (ast._tag === "Declaration") {
|
|
2123
|
-
for (const part of ast.typeParameters) collect(part, segments, optional, walk);
|
|
2280
|
+
for (const part of ast.typeParameters) collect$1(part, segments, optional, walk);
|
|
2124
2281
|
return;
|
|
2125
2282
|
}
|
|
2126
2283
|
if (ast._tag === "Objects") {
|
|
@@ -2132,9 +2289,9 @@ function collect(ast, segments, optional, walk) {
|
|
|
2132
2289
|
segments: here,
|
|
2133
2290
|
required: !absentable
|
|
2134
2291
|
});
|
|
2135
|
-
collect(type, here, absentable, walk);
|
|
2292
|
+
collect$1(type, here, absentable, walk);
|
|
2136
2293
|
}
|
|
2137
|
-
for (const { type } of ast.indexSignatures) collect(type, [...segments, declared.length ? { except: declared } : null], true, walk);
|
|
2294
|
+
for (const { type } of ast.indexSignatures) collect$1(type, [...segments, declared.length ? { except: declared } : null], true, walk);
|
|
2138
2295
|
return;
|
|
2139
2296
|
}
|
|
2140
2297
|
if (ast._tag === "Arrays") {
|
|
@@ -2144,7 +2301,7 @@ function collect(ast, segments, optional, walk) {
|
|
|
2144
2301
|
segments: [...segments, segment],
|
|
2145
2302
|
required: true
|
|
2146
2303
|
});
|
|
2147
|
-
collect(item, [...segments, segment], false, walk);
|
|
2304
|
+
collect$1(item, [...segments, segment], false, walk);
|
|
2148
2305
|
}
|
|
2149
2306
|
}
|
|
2150
2307
|
}
|
|
@@ -2156,7 +2313,7 @@ function analyze(ast) {
|
|
|
2156
2313
|
paths: [],
|
|
2157
2314
|
publics: []
|
|
2158
2315
|
};
|
|
2159
|
-
collect(ast, [], false, analysis);
|
|
2316
|
+
collect$1(ast, [], false, analysis);
|
|
2160
2317
|
analyses.set(ast, analysis);
|
|
2161
2318
|
}
|
|
2162
2319
|
return analysis;
|
|
@@ -2434,11 +2591,9 @@ function sensitiveStage(config, owner) {
|
|
|
2434
2591
|
logger: call.ctx.logger,
|
|
2435
2592
|
requestId: call.ctx.requestId
|
|
2436
2593
|
});
|
|
2437
|
-
return Effect.fail(failure instanceof BrickError ?
|
|
2438
|
-
code: failure.code,
|
|
2439
|
-
status: failure.status,
|
|
2594
|
+
return Effect.fail(failure instanceof BrickError || failure instanceof ValidationError ? redactedCopy(failure, {
|
|
2440
2595
|
message: redactText(set, failure.message),
|
|
2441
|
-
details: redactDetails(set, failure.details)
|
|
2596
|
+
details: failure instanceof BrickError ? redactDetails(set, failure.details) : void 0
|
|
2442
2597
|
}) : failure);
|
|
2443
2598
|
}), Effect.provideService(Redactions, set));
|
|
2444
2599
|
const paths = (call.wire ? wireOutputs : outputs)?.paths;
|
|
@@ -2460,6 +2615,167 @@ function sensitiveStage(config, owner) {
|
|
|
2460
2615
|
})
|
|
2461
2616
|
};
|
|
2462
2617
|
}
|
|
2618
|
+
// src/validation-issues.ts
|
|
2619
|
+
const stock = SchemaIssue.makeFormatterStandardSchemaV1();
|
|
2620
|
+
/** The message Effect would give a leaf or a filter, for what has no core wording. */
|
|
2621
|
+
const stockMessage = (issue) => stock(issue).issues[0]?.message ?? "Expected a valid value";
|
|
2622
|
+
const hasCheck = (ast, expected) => ast.checks?.some((check) => check.annotations?.expected === expected) ?? false;
|
|
2623
|
+
const unit = (ast) => ast?._tag === "Number" && hasCheck(ast, "an integer") ? "integer" : "number";
|
|
2624
|
+
/** The message of a value of the wrong type, as core words it; `undefined` for a type core has no wording for. */
|
|
2625
|
+
function typeMessage(ast) {
|
|
2626
|
+
switch (ast._tag) {
|
|
2627
|
+
case "String": return "Expected string";
|
|
2628
|
+
case "Number": return `Expected ${unit(ast)}`;
|
|
2629
|
+
case "Boolean": return "Expected boolean";
|
|
2630
|
+
case "Arrays": return ast.rest.length === 0 ? "Expected tuple" : "Expected array";
|
|
2631
|
+
case "Objects": return "Expected object";
|
|
2632
|
+
case "Null": return "Expected null";
|
|
2633
|
+
case "Undefined": return "Expected undefined";
|
|
2634
|
+
case "Literal": return `Expected ${typeof ast.literal === "string" ? `'${ast.literal}'` : String(ast.literal)}`;
|
|
2635
|
+
case "Union": {
|
|
2636
|
+
const rest = ast.types.filter((type) => type._tag !== "Undefined");
|
|
2637
|
+
return rest.length === 1 && ast.types.length === 2 ? typeMessage(rest[0]) : "Expected union value";
|
|
2638
|
+
}
|
|
2639
|
+
default: return;
|
|
2640
|
+
}
|
|
2641
|
+
}
|
|
2642
|
+
const bound = (word, orEqual) => `${word}${orEqual ? " or equal to" : " than"}`;
|
|
2643
|
+
/** The message of a failed check, as core words it; `undefined` for a check core has no wording for. */
|
|
2644
|
+
function checkMessage(issue, parent) {
|
|
2645
|
+
const custom = SchemaIssue.defaultCheckHook(issue);
|
|
2646
|
+
if (custom !== void 0) return custom;
|
|
2647
|
+
const expected = issue.filter.annotations?.expected;
|
|
2648
|
+
if (typeof expected !== "string") return void 0;
|
|
2649
|
+
const kind = parent?._tag;
|
|
2650
|
+
let match = /^a value with a length of at (least|most) (\d+)$/.exec(expected);
|
|
2651
|
+
if (match) {
|
|
2652
|
+
const cmp = bound(match[1] === "least" ? "greater" : "less", true);
|
|
2653
|
+
if (kind === "String") return `Expected string length ${cmp} ${match[2]}`;
|
|
2654
|
+
if (kind === "Arrays") return `Expected array length to be ${cmp} ${match[2]}`;
|
|
2655
|
+
return;
|
|
2656
|
+
}
|
|
2657
|
+
if (kind === "Number") {
|
|
2658
|
+
match = /^a value (greater|less) than( or equal to)? (.+)$/.exec(expected);
|
|
2659
|
+
if (match) return `Expected ${unit(parent)} to be ${bound(match[1], Boolean(match[2]))} ${match[3]}`;
|
|
2660
|
+
match = /^a value that is a multiple of (.+)$/.exec(expected);
|
|
2661
|
+
if (match) return `Expected ${unit(parent)} to be a multiple of ${match[1]}`;
|
|
2662
|
+
if (expected === "an integer") return "Expected integer";
|
|
2663
|
+
}
|
|
2664
|
+
if (kind === "String") {
|
|
2665
|
+
match = /^a string matching the RegExp (.+)$/.exec(expected);
|
|
2666
|
+
if (match) return `Expected string to match '${match[1]}'`;
|
|
2667
|
+
if (expected === "a UUID") return "Expected string to match 'uuid' format";
|
|
2668
|
+
}
|
|
2669
|
+
if (kind === "Arrays" && expected === "an array with unique items") return "Expected array elements to be unique";
|
|
2670
|
+
}
|
|
2671
|
+
const notUndefined = (issue) => !(issue._tag === "InvalidType" && issue.ast._tag === "Undefined");
|
|
2672
|
+
const isMissing = (issue) => issue._tag === "Pointer" && issue.issue._tag === "MissingKey";
|
|
2673
|
+
const isExtra = (issue) => issue._tag === "Pointer" && issue.issue._tag === "UnexpectedKey";
|
|
2674
|
+
const expectedOf = (issue) => issue._tag === "Filter" ? issue.filter.annotations?.expected : void 0;
|
|
2675
|
+
const filtersOf = (checks) => checks.flatMap((check) => check._tag === "FilterGroup" ? filtersOf(check.checks) : [check]);
|
|
2676
|
+
const valueAt = (input, path) => path.reduce((value, key) => value?.[key], input);
|
|
2677
|
+
/**
|
|
2678
|
+
* The children of a Composite issue on a number or an array, in TypeBox's order.
|
|
2679
|
+
* TypeBox stops at a failed integer check; Effect also reports the bounds.
|
|
2680
|
+
* Effect skips an array's own checks once an item fails; TypeBox reports the
|
|
2681
|
+
* lengths first and uniqueness last.
|
|
2682
|
+
*/
|
|
2683
|
+
function childrenOf(issue, path, input) {
|
|
2684
|
+
const { ast } = issue;
|
|
2685
|
+
if (ast._tag === "Number") {
|
|
2686
|
+
const integer = issue.issues.filter((child) => expectedOf(child) === "an integer");
|
|
2687
|
+
return integer.length ? integer : issue.issues;
|
|
2688
|
+
}
|
|
2689
|
+
const value = valueAt(input, path);
|
|
2690
|
+
if (ast._tag !== "Arrays" || !Array.isArray(value) || issue.issues.some((child) => child._tag === "Filter")) return issue.issues;
|
|
2691
|
+
const known = (check) => /^a value with a length of at (least|most) \d+$|^an array with unique items$/.test(check.annotations?.expected);
|
|
2692
|
+
const failed = filtersOf(ast.checks ?? []).filter(known).flatMap((check) => {
|
|
2693
|
+
const found = check.run(value, ast, { errors: "all" });
|
|
2694
|
+
return found ? [new SchemaIssue.Filter(check, found, value, {})] : [];
|
|
2695
|
+
});
|
|
2696
|
+
const unique = (child) => expectedOf(child) === "an array with unique items";
|
|
2697
|
+
return [
|
|
2698
|
+
...failed.filter((child) => !unique(child)),
|
|
2699
|
+
...issue.issues,
|
|
2700
|
+
...failed.filter(unique)
|
|
2701
|
+
];
|
|
2702
|
+
}
|
|
2703
|
+
function collect(issue, path, parent, override, out, phase) {
|
|
2704
|
+
const add = (message) => {
|
|
2705
|
+
out.items.push({
|
|
2706
|
+
path,
|
|
2707
|
+
message
|
|
2708
|
+
});
|
|
2709
|
+
};
|
|
2710
|
+
switch (issue._tag) {
|
|
2711
|
+
case "Filter": return collect(issue.issue, path, parent, override ?? checkMessage(issue, parent) ?? stockMessage(issue), out);
|
|
2712
|
+
case "Encoding": {
|
|
2713
|
+
const message = (issue.ast._tag === "Number" || issue.ast._tag === "Boolean") && typeof issue.ast.annotations?.message !== "string" ? typeMessage(issue.ast) : void 0;
|
|
2714
|
+
if (message !== void 0) return add(override ?? message);
|
|
2715
|
+
return collect(issue.issue, path, parent, override, out);
|
|
2716
|
+
}
|
|
2717
|
+
case "Pointer": return collect(issue.issue, [...path, ...issue.path], parent, override, out, phase);
|
|
2718
|
+
case "Composite": {
|
|
2719
|
+
if (issue.ast._tag !== "Objects") {
|
|
2720
|
+
const { ast } = issue;
|
|
2721
|
+
const value = valueAt(out.input, path);
|
|
2722
|
+
if (ast._tag === "Arrays" && ast.rest.length === 0 && Array.isArray(value) && value.length !== ast.elements.length) return add(override ?? `Expected tuple to have ${ast.elements.length} elements`);
|
|
2723
|
+
for (const child of childrenOf(issue, path, out.input)) collect(child, path, ast, override, out);
|
|
2724
|
+
return;
|
|
2725
|
+
}
|
|
2726
|
+
const missing = issue.issues.filter((child) => isMissing(child));
|
|
2727
|
+
const extra = issue.issues.filter((child) => isExtra(child));
|
|
2728
|
+
for (const child of missing) collect(child, path, issue.ast, override, out, "required");
|
|
2729
|
+
for (const child of extra) collect(child, path, issue.ast, override, out);
|
|
2730
|
+
for (const child of issue.issues) if (!extra.includes(child)) collect(child, path, issue.ast, override, out, isMissing(child) ? "type" : void 0);
|
|
2731
|
+
return;
|
|
2732
|
+
}
|
|
2733
|
+
case "AnyOf": {
|
|
2734
|
+
if (override !== void 0) return add(override);
|
|
2735
|
+
if (typeof issue.ast.annotations?.message === "string") return add(stockMessage(issue));
|
|
2736
|
+
const { types } = issue.ast;
|
|
2737
|
+
if (types.length === 2 && types.some((type) => type._tag === "Undefined")) {
|
|
2738
|
+
const issues = issue.issues.filter(notUndefined);
|
|
2739
|
+
if (issues.length) return issues.forEach((child) => collect(child, path, parent, override, out));
|
|
2740
|
+
}
|
|
2741
|
+
return add(typeMessage(issue.ast) ?? stockMessage(issue));
|
|
2742
|
+
}
|
|
2743
|
+
case "InvalidType": return add(override ?? (typeof issue.ast.annotations?.message === "string" ? void 0 : typeMessage(issue.ast)) ?? stockMessage(issue));
|
|
2744
|
+
case "MissingKey": {
|
|
2745
|
+
if (override !== void 0 || typeof issue.annotations?.messageMissingKey === "string") return phase === "type" ? void 0 : add(override ?? stockMessage(issue));
|
|
2746
|
+
if (phase !== "type") add("Expected required property");
|
|
2747
|
+
if (phase === "required") return;
|
|
2748
|
+
const key = path[path.length - 1];
|
|
2749
|
+
const property = parent?._tag === "Objects" ? parent.propertySignatures.find((item) => item.name === key) : void 0;
|
|
2750
|
+
const message = property && typeMessage(property.type);
|
|
2751
|
+
if (message) add(message);
|
|
2752
|
+
return;
|
|
2753
|
+
}
|
|
2754
|
+
case "UnexpectedKey": return add(override ?? (typeof issue.ast.annotations?.messageUnexpectedKey === "string" ? stockMessage(issue) : "Unexpected property"));
|
|
2755
|
+
default: return add(override ?? stockMessage(issue));
|
|
2756
|
+
}
|
|
2757
|
+
}
|
|
2758
|
+
const pointer = (path) => path.map((item) => String(typeof item === "object" && item !== null && "key" in item ? item.key : item).replaceAll("~", "~0").replaceAll("/", "~1")).map((key) => `/${key}`).join("");
|
|
2759
|
+
/**
|
|
2760
|
+
* The `{ path, message }` items of a schema failure, worded as `@brickkit/core`
|
|
2761
|
+
* words TypeBox's: a missing key is "Expected required property" and then the
|
|
2762
|
+
* type of the absent value, an extra key is "Unexpected property", and string,
|
|
2763
|
+
* number and array bounds, patterns, literals and unions use TypeBox's text.
|
|
2764
|
+
* Paths are JSON pointers, and messages never carry the rejected value.
|
|
2765
|
+
* A custom `message` annotation wins; a check or schema core has no wording for
|
|
2766
|
+
* keeps Effect's own text.
|
|
2767
|
+
*/
|
|
2768
|
+
function issuesOf(error, input) {
|
|
2769
|
+
const out = {
|
|
2770
|
+
input,
|
|
2771
|
+
items: []
|
|
2772
|
+
};
|
|
2773
|
+
collect(error.issue, [], void 0, void 0, out);
|
|
2774
|
+
return out.items.map(({ path, message }) => ({
|
|
2775
|
+
path: pointer(path),
|
|
2776
|
+
message
|
|
2777
|
+
}));
|
|
2778
|
+
}
|
|
2463
2779
|
// src/action.ts
|
|
2464
2780
|
/** The HTTP methods an action can use. */
|
|
2465
2781
|
const HTTP_METHODS = [
|
|
@@ -2483,14 +2799,6 @@ function errorHelpers(errors) {
|
|
|
2483
2799
|
}));
|
|
2484
2800
|
return helpers;
|
|
2485
2801
|
}
|
|
2486
|
-
const pointer = (path) => path.map((item) => String(typeof item === "object" && item !== null && "key" in item ? item.key : item)).map((key) => `/${key}`).join("");
|
|
2487
|
-
/** The `{ path, message }` items of a schema failure. Paths are JSON pointers, as in core; messages never carry the rejected value. */
|
|
2488
|
-
function issuesOf(error) {
|
|
2489
|
-
return SchemaIssue.makeFormatterStandardSchemaV1()(error.issue).issues.map(({ path, message }) => ({
|
|
2490
|
-
path: pointer(path ?? []),
|
|
2491
|
-
message
|
|
2492
|
-
}));
|
|
2493
|
-
}
|
|
2494
2802
|
/** The error for input (400) or output (500) that fails its schema. */
|
|
2495
2803
|
function invalid$1(action, stage, errors) {
|
|
2496
2804
|
return new ValidationError({
|
|
@@ -2524,7 +2832,8 @@ function stagesOf(config, host, action) {
|
|
|
2524
2832
|
value: Schema.decodeUnknownEffect(Schema.toType(input)),
|
|
2525
2833
|
json: Schema.decodeUnknownEffect(Schema.toCodecJson(input)),
|
|
2526
2834
|
query: Schema.decodeUnknownEffect(Schema.toCodecArrayFromSingle(Schema.toCodecStringTree(input))),
|
|
2527
|
-
form: formDecoder(input)
|
|
2835
|
+
form: formDecoder(input),
|
|
2836
|
+
absent: Schema.decodeUnknownEffect(input)
|
|
2528
2837
|
};
|
|
2529
2838
|
const check = output && {
|
|
2530
2839
|
value: Schema.decodeUnknownEffect(Schema.toType(output)),
|
|
@@ -2553,7 +2862,7 @@ function stagesOf(config, host, action) {
|
|
|
2553
2862
|
}] : [],
|
|
2554
2863
|
...decode ? [{
|
|
2555
2864
|
name: "input",
|
|
2556
|
-
run: (call, next) => decode[call.wire ?? "value"](call.input, strictInput).pipe(Effect.mapError((error) => invalid$1(name, "input", issuesOf(error))), Effect.flatMap((decoded) => next({
|
|
2865
|
+
run: (call, next) => decode[call.input === void 0 ? call.wire ? "absent" : "value" : call.wire ?? "value"](call.input, strictInput).pipe(Effect.mapError((error) => invalid$1(name, "input", issuesOf(error, call.input))), Effect.flatMap((decoded) => next({
|
|
2557
2866
|
...call,
|
|
2558
2867
|
input: decoded
|
|
2559
2868
|
})))
|
|
@@ -2567,7 +2876,7 @@ function stagesOf(config, host, action) {
|
|
|
2567
2876
|
...audit ? [audit] : [],
|
|
2568
2877
|
...check ? [{
|
|
2569
2878
|
name: "output",
|
|
2570
|
-
run: (call, next) => next(call).pipe(Effect.flatMap((result) => check[call.wire ? "json" : "value"](result, all).pipe(Effect.mapError((error) => invalid$1(name, "output", issuesOf(error))))))
|
|
2879
|
+
run: (call, next) => next(call).pipe(Effect.flatMap((result) => check[call.wire ? "json" : "value"](result, all).pipe(Effect.mapError((error) => invalid$1(name, "output", issuesOf(error, result))))))
|
|
2571
2880
|
}] : [],
|
|
2572
2881
|
{
|
|
2573
2882
|
name: "execute",
|
|
@@ -3921,6 +4230,8 @@ const SOCKET_CONTROL = {
|
|
|
3921
4230
|
const isControlEvent = (event) => event.startsWith("$");
|
|
3922
4231
|
const SOCKET_CLOSE = {
|
|
3923
4232
|
normal: 1e3,
|
|
4233
|
+
/** The server is draining: a raw socket still open at the drain deadline. */
|
|
4234
|
+
goingAway: 1001,
|
|
3924
4235
|
unsupportedData: 1003,
|
|
3925
4236
|
invalidPayload: 1007,
|
|
3926
4237
|
policy: 1008,
|
|
@@ -4178,6 +4489,368 @@ function socketPath(prefix, service, { schema: { name, path } }) {
|
|
|
4178
4489
|
const base = `${prefix.replace(/\/$/, "")}/${kebabCase(service)}`;
|
|
4179
4490
|
return path === void 0 ? `${base}/${kebabCase(name)}` : `${base}${path === "/" ? "" : path}`;
|
|
4180
4491
|
}
|
|
4492
|
+
// src/raw-socket.ts
|
|
4493
|
+
/** Frames one connection may have waiting for its handlers. */
|
|
4494
|
+
const RAW_QUEUE_FRAMES = 1024;
|
|
4495
|
+
/** After the drain deadline closes what is left with 1001, time for their `close` callbacks. */
|
|
4496
|
+
const DRAIN_CLOSE_GRACE_MS = 1e3;
|
|
4497
|
+
function defineRawSocket(config, resolve) {
|
|
4498
|
+
if (!config.name || config.name.split(".").some((part) => !/^[a-zA-Z_][\w-]*$/.test(part))) throw new Error("Invalid socket name");
|
|
4499
|
+
if (config.path !== void 0 && (!config.path.startsWith("/") || /[?#*]/.test(config.path) || config.path.split("/").some((segment) => segment.startsWith(":")))) throw new Error("Socket path must be a static route (relative to its service) without a query or fragment");
|
|
4500
|
+
if (config.schema && config.parse) throw new Error("A raw socket takes a schema or a parse, not both");
|
|
4501
|
+
const positive = (value, what) => {
|
|
4502
|
+
if (value !== void 0 && !(Number.isInteger(value) && value > 0)) throw new Error(`Raw socket ${what} must be a positive integer`);
|
|
4503
|
+
};
|
|
4504
|
+
positive(config.maxConnections, "maxConnections");
|
|
4505
|
+
positive(config.maxPayloadBytes, "maxPayloadBytes");
|
|
4506
|
+
if (config.preAuth && !(config.preAuth.timeoutMs > 0 && Number.isFinite(config.preAuth.timeoutMs))) throw new Error("Raw socket preAuth.timeoutMs must be a positive number");
|
|
4507
|
+
const decodeJson = config.schema && Schema.decodeUnknownOption(Schema.toCodecJson(config.schema));
|
|
4508
|
+
const mounts = /* @__PURE__ */ new Set();
|
|
4509
|
+
return {
|
|
4510
|
+
schema: {
|
|
4511
|
+
name: config.name,
|
|
4512
|
+
path: config.path
|
|
4513
|
+
},
|
|
4514
|
+
config,
|
|
4515
|
+
maxPayloadBytes: config.maxPayloadBytes ?? 65536,
|
|
4516
|
+
max: config.maxConnections,
|
|
4517
|
+
mounts,
|
|
4518
|
+
handle: {
|
|
4519
|
+
get live() {
|
|
4520
|
+
let live = 0;
|
|
4521
|
+
for (const mount of mounts) live += mount.live;
|
|
4522
|
+
return live;
|
|
4523
|
+
},
|
|
4524
|
+
max: config.maxConnections
|
|
4525
|
+
},
|
|
4526
|
+
decode: decodeJson && ((value) => {
|
|
4527
|
+
const decoded = decodeJson(value);
|
|
4528
|
+
return decoded._tag === "Some" ? { value: decoded.value } : void 0;
|
|
4529
|
+
}),
|
|
4530
|
+
resolve
|
|
4531
|
+
};
|
|
4532
|
+
}
|
|
4533
|
+
/** Turns a failed run into what its callbacks threw: the typed failure, else the defect. */
|
|
4534
|
+
function thrown(cause) {
|
|
4535
|
+
const found = Cause.findError(cause);
|
|
4536
|
+
if (Result.isSuccess(found)) return found.success;
|
|
4537
|
+
const defect = Cause.findDefect(cause);
|
|
4538
|
+
return Result.isSuccess(defect) ? defect.success : Cause.squash(cause);
|
|
4539
|
+
}
|
|
4540
|
+
/**
|
|
4541
|
+
* Mounts the raw routes of the services: each answers a plain WebSocket upgrade
|
|
4542
|
+
* (no subprotocol, no `brick.v1`) and hands its callbacks the frames exactly as
|
|
4543
|
+
* the client sent them. One context is resolved at upgrade and reused for every
|
|
4544
|
+
* callback.
|
|
4545
|
+
*/
|
|
4546
|
+
function mountRawSockets(options) {
|
|
4547
|
+
const { run, telemetry } = options;
|
|
4548
|
+
let tracer;
|
|
4549
|
+
const appTracer = () => tracer ??= run(Effect.tracer).then((exit) => Exit.isSuccess(exit) ? exit.value : void 0);
|
|
4550
|
+
const routes = options.services.flatMap((service) => service.listRawSockets().map((definition) => ({
|
|
4551
|
+
service: service.name,
|
|
4552
|
+
path: socketPath(options.prefix, service.name, definition),
|
|
4553
|
+
definition,
|
|
4554
|
+
live: 0,
|
|
4555
|
+
pending: 0,
|
|
4556
|
+
connections: /* @__PURE__ */ new Set()
|
|
4557
|
+
})));
|
|
4558
|
+
const byPath = /* @__PURE__ */ new Map();
|
|
4559
|
+
for (const route of routes) {
|
|
4560
|
+
if (byPath.has(route.path)) throw new Error(`Brick: duplicate socket route '${route.path}'`);
|
|
4561
|
+
byPath.set(route.path, route);
|
|
4562
|
+
}
|
|
4563
|
+
let draining = false;
|
|
4564
|
+
const quiet = /* @__PURE__ */ new Set();
|
|
4565
|
+
const total = () => routes.reduce((n, r) => n + r.live + r.pending, 0);
|
|
4566
|
+
const settled = () => {
|
|
4567
|
+
if (!total()) for (const wake of quiet) wake();
|
|
4568
|
+
};
|
|
4569
|
+
/** Resolves once no connection is open or upgrading, or after `ms`. */
|
|
4570
|
+
const empty = (ms) => total() === 0 ? Promise.resolve() : new Promise((resolve) => {
|
|
4571
|
+
const done = () => {
|
|
4572
|
+
clearTimeout(timer);
|
|
4573
|
+
quiet.delete(done);
|
|
4574
|
+
resolve();
|
|
4575
|
+
};
|
|
4576
|
+
const timer = setTimeout(done, ms);
|
|
4577
|
+
quiet.add(done);
|
|
4578
|
+
});
|
|
4579
|
+
let drained;
|
|
4580
|
+
const drain = (timeoutMs = options.drainTimeoutMs) => drained ??= (async () => {
|
|
4581
|
+
draining = true;
|
|
4582
|
+
await empty(timeoutMs);
|
|
4583
|
+
for (const route of routes) for (const connection of route.connections) connection.close(SOCKET_CLOSE.goingAway, "Server is shutting down");
|
|
4584
|
+
await empty(DRAIN_CLOSE_GRACE_MS);
|
|
4585
|
+
})();
|
|
4586
|
+
const stats = () => {
|
|
4587
|
+
const capped = routes.length > 0 && routes.every((r) => r.definition.max);
|
|
4588
|
+
return {
|
|
4589
|
+
draining,
|
|
4590
|
+
live: routes.reduce((n, r) => n + r.live, 0),
|
|
4591
|
+
...capped ? { max: routes.reduce((n, r) => n + r.definition.max, 0) } : {},
|
|
4592
|
+
routes: routes.map((r) => ({
|
|
4593
|
+
service: r.service,
|
|
4594
|
+
name: r.definition.schema.name,
|
|
4595
|
+
path: r.path,
|
|
4596
|
+
live: r.live,
|
|
4597
|
+
...r.definition.max ? { max: r.definition.max } : {}
|
|
4598
|
+
}))
|
|
4599
|
+
};
|
|
4600
|
+
};
|
|
4601
|
+
for (const route of routes) route.definition.mounts.add(route);
|
|
4602
|
+
const refuse = (status, text) => new Response(text, {
|
|
4603
|
+
status,
|
|
4604
|
+
headers: status === 503 ? { "Retry-After": "1" } : void 0
|
|
4605
|
+
});
|
|
4606
|
+
/** The handlers Bun calls for a connection of `route`, through `ws.data.mounted`. */
|
|
4607
|
+
const mountRoute = (route) => {
|
|
4608
|
+
const { service, path, definition } = route;
|
|
4609
|
+
const { config } = definition;
|
|
4610
|
+
const name = definition.schema.name;
|
|
4611
|
+
const origins = config.allowedOrigins ?? [];
|
|
4612
|
+
const fallbackLogger = createLogger();
|
|
4613
|
+
const traced = (conn, effect) => conn.span ? Effect.withParentSpan(effect, conn.span.span, { captureStackTrace: false }) : effect;
|
|
4614
|
+
/** A callback failed: the `error` hook decides, and by default the connection closes with 1011. */
|
|
4615
|
+
const failed = async (conn, at, cause) => {
|
|
4616
|
+
const error = thrown(cause);
|
|
4617
|
+
conn.failure ??= { error };
|
|
4618
|
+
const logger = conn.ctx?.logger ?? fallbackLogger;
|
|
4619
|
+
let outcome;
|
|
4620
|
+
try {
|
|
4621
|
+
if (config.error) {
|
|
4622
|
+
const hook = await run(traced(conn, config.error({
|
|
4623
|
+
ctx: conn.ctx,
|
|
4624
|
+
socket: conn.socket,
|
|
4625
|
+
error,
|
|
4626
|
+
phase: at
|
|
4627
|
+
})));
|
|
4628
|
+
if (Exit.isSuccess(hook)) outcome = hook.value;
|
|
4629
|
+
else if (!Cause.hasInterruptsOnly(hook.cause)) logger.error({
|
|
4630
|
+
error: thrown(hook.cause),
|
|
4631
|
+
service,
|
|
4632
|
+
socket: name
|
|
4633
|
+
});
|
|
4634
|
+
} else logger.error({
|
|
4635
|
+
error,
|
|
4636
|
+
service,
|
|
4637
|
+
socket: name,
|
|
4638
|
+
phase: at
|
|
4639
|
+
});
|
|
4640
|
+
} catch (hookError) {
|
|
4641
|
+
logger.error({
|
|
4642
|
+
error: hookError,
|
|
4643
|
+
service,
|
|
4644
|
+
socket: name
|
|
4645
|
+
});
|
|
4646
|
+
}
|
|
4647
|
+
if (outcome !== "continue" && at !== "close") conn.close(SOCKET_CLOSE.serverError, "Socket handler failed");
|
|
4648
|
+
};
|
|
4649
|
+
/** Runs `work` after the connection's earlier callbacks, in the connection's span. */
|
|
4650
|
+
const enqueue = (conn, phase, work, size = 0) => {
|
|
4651
|
+
conn.frames++;
|
|
4652
|
+
conn.queued += size;
|
|
4653
|
+
conn.tail = conn.tail.then(async () => {
|
|
4654
|
+
try {
|
|
4655
|
+
const at = typeof phase === "function" ? phase() : phase;
|
|
4656
|
+
const exit = await run(traced(conn, Effect.suspend(() => work() ?? Effect.void)));
|
|
4657
|
+
if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)) await failed(conn, at, exit.cause);
|
|
4658
|
+
} finally {
|
|
4659
|
+
conn.frames--;
|
|
4660
|
+
conn.queued -= size;
|
|
4661
|
+
}
|
|
4662
|
+
});
|
|
4663
|
+
};
|
|
4664
|
+
/** The frame as `message` gets it, or the close it earns. */
|
|
4665
|
+
const decode = (raw) => {
|
|
4666
|
+
if (config.parse) return { data: config.parse(raw) };
|
|
4667
|
+
if (!definition.decode) return { data: raw };
|
|
4668
|
+
if (typeof raw !== "string") return {
|
|
4669
|
+
close: SOCKET_CLOSE.unsupportedData,
|
|
4670
|
+
reason: "Only JSON text is supported"
|
|
4671
|
+
};
|
|
4672
|
+
let json;
|
|
4673
|
+
try {
|
|
4674
|
+
json = JSON.parse(raw);
|
|
4675
|
+
} catch {
|
|
4676
|
+
return {
|
|
4677
|
+
close: SOCKET_CLOSE.invalidPayload,
|
|
4678
|
+
reason: "Invalid JSON"
|
|
4679
|
+
};
|
|
4680
|
+
}
|
|
4681
|
+
const decoded = definition.decode(json);
|
|
4682
|
+
return decoded ? { data: decoded.value } : {
|
|
4683
|
+
close: SOCKET_CLOSE.invalidPayload,
|
|
4684
|
+
reason: "Invalid message"
|
|
4685
|
+
};
|
|
4686
|
+
};
|
|
4687
|
+
const receive = (conn, raw) => {
|
|
4688
|
+
if (conn.closed) return;
|
|
4689
|
+
const { socket } = conn;
|
|
4690
|
+
const size = typeof raw === "string" ? Buffer.byteLength(raw) : raw.byteLength;
|
|
4691
|
+
conn.messages++;
|
|
4692
|
+
conn.bytes += size;
|
|
4693
|
+
if (size > definition.maxPayloadBytes) return conn.close(SOCKET_CLOSE.tooLarge, "Message too large");
|
|
4694
|
+
if (conn.frames >= RAW_QUEUE_FRAMES || conn.queued + size > Math.max(1048576, definition.maxPayloadBytes)) return conn.close(SOCKET_CLOSE.tryAgainLater, "Socket queue full");
|
|
4695
|
+
let decoded;
|
|
4696
|
+
try {
|
|
4697
|
+
decoded = decode(raw);
|
|
4698
|
+
} catch {
|
|
4699
|
+
return conn.close(SOCKET_CLOSE.invalidPayload, "Invalid message");
|
|
4700
|
+
}
|
|
4701
|
+
if ("close" in decoded) return conn.close(decoded.close, decoded.reason);
|
|
4702
|
+
const early = () => config.preAuth && !socket.authenticated ? "preAuth" : "message";
|
|
4703
|
+
enqueue(conn, early, () => {
|
|
4704
|
+
if (conn.ws.readyState !== 1) return;
|
|
4705
|
+
const frame = {
|
|
4706
|
+
data: decoded.data,
|
|
4707
|
+
ctx: conn.ctx,
|
|
4708
|
+
socket
|
|
4709
|
+
};
|
|
4710
|
+
return early() === "preAuth" ? config.preAuth.message(frame) : config.message(frame);
|
|
4711
|
+
}, size);
|
|
4712
|
+
};
|
|
4713
|
+
/** Gives up a slot taken at upgrade that never became a connection. */
|
|
4714
|
+
const abandon = (conn, status) => {
|
|
4715
|
+
route.pending--;
|
|
4716
|
+
conn.span?.end({ [ATTR.httpStatus]: status }, conn.failure?.error);
|
|
4717
|
+
settled();
|
|
4718
|
+
};
|
|
4719
|
+
const handlers = {
|
|
4720
|
+
open(ws) {
|
|
4721
|
+
const conn = ws.data.connection;
|
|
4722
|
+
conn.ws = ws;
|
|
4723
|
+
route.pending--;
|
|
4724
|
+
route.live++;
|
|
4725
|
+
route.connections.add(conn);
|
|
4726
|
+
if (config.preAuth) conn.deadline = setTimeout(() => conn.close(SOCKET_CLOSE.policy, "Authentication timeout"), config.preAuth.timeoutMs);
|
|
4727
|
+
if (config.open) enqueue(conn, "open", () => config.open({
|
|
4728
|
+
ctx: conn.ctx,
|
|
4729
|
+
socket: conn.socket
|
|
4730
|
+
}));
|
|
4731
|
+
},
|
|
4732
|
+
message(ws, value) {
|
|
4733
|
+
receive(ws.data.connection, value);
|
|
4734
|
+
},
|
|
4735
|
+
async close(ws, code, reason) {
|
|
4736
|
+
const conn = ws.data.connection;
|
|
4737
|
+
if (conn.closed) return;
|
|
4738
|
+
conn.closed = true;
|
|
4739
|
+
clearTimeout(conn.deadline);
|
|
4740
|
+
if (config.close) enqueue(conn, "close", () => config.close({
|
|
4741
|
+
ctx: conn.ctx,
|
|
4742
|
+
socket: conn.socket,
|
|
4743
|
+
code,
|
|
4744
|
+
reason
|
|
4745
|
+
}));
|
|
4746
|
+
await conn.tail;
|
|
4747
|
+
conn.span?.end({
|
|
4748
|
+
[ATTR.httpStatus]: 101,
|
|
4749
|
+
[ATTR.socketMessages]: conn.messages,
|
|
4750
|
+
[ATTR.socketBytes]: conn.bytes,
|
|
4751
|
+
[ATTR.socketCloseCode]: code
|
|
4752
|
+
}, conn.failure?.error);
|
|
4753
|
+
route.connections.delete(conn);
|
|
4754
|
+
route.live--;
|
|
4755
|
+
settled();
|
|
4756
|
+
}
|
|
4757
|
+
};
|
|
4758
|
+
return async (request, server) => {
|
|
4759
|
+
if (draining) return refuse(503, "Server is shutting down");
|
|
4760
|
+
const origin = request.headers.get("origin");
|
|
4761
|
+
if (origin && !origins.includes(origin)) return refuse(403, "Socket origin refused");
|
|
4762
|
+
if (definition.max !== void 0 && route.live + route.pending >= definition.max) return refuse(503, "Too many connections");
|
|
4763
|
+
route.pending++;
|
|
4764
|
+
const id = crypto.randomUUID();
|
|
4765
|
+
const span = telemetry ? startSocketSpan(`${SPAN.socketPrefix}${service}.${name}`, request, {
|
|
4766
|
+
[ATTR.httpRoute]: path,
|
|
4767
|
+
[ATTR.service]: service,
|
|
4768
|
+
[ATTR.socketName]: name,
|
|
4769
|
+
[ATTR.socketId]: id
|
|
4770
|
+
}, await appTracer()) : void 0;
|
|
4771
|
+
const conn = {
|
|
4772
|
+
ctx: void 0,
|
|
4773
|
+
span,
|
|
4774
|
+
closed: false,
|
|
4775
|
+
tail: Promise.resolve(),
|
|
4776
|
+
frames: 0,
|
|
4777
|
+
queued: 0,
|
|
4778
|
+
messages: 0,
|
|
4779
|
+
bytes: 0,
|
|
4780
|
+
socket: void 0,
|
|
4781
|
+
close: (code = SOCKET_CLOSE.normal, reason = "") => conn.ws?.close(code, reason)
|
|
4782
|
+
};
|
|
4783
|
+
let authenticated = !config.preAuth;
|
|
4784
|
+
const socket = {
|
|
4785
|
+
id,
|
|
4786
|
+
request,
|
|
4787
|
+
get authenticated() {
|
|
4788
|
+
return authenticated;
|
|
4789
|
+
},
|
|
4790
|
+
state: void 0,
|
|
4791
|
+
send: (data) => Effect.sync(() => !conn.closed && (conn.ws?.send(data) ?? 0) !== 0),
|
|
4792
|
+
close: (code, reason) => Effect.sync(() => conn.close(code, reason)),
|
|
4793
|
+
authenticate: (patch) => Effect.sync(() => {
|
|
4794
|
+
authenticated = true;
|
|
4795
|
+
clearTimeout(conn.deadline);
|
|
4796
|
+
if (patch) Object.assign(socket.state, patch);
|
|
4797
|
+
}),
|
|
4798
|
+
link: (traceparent) => Effect.sync(() => span?.link(traceparent))
|
|
4799
|
+
};
|
|
4800
|
+
conn.socket = socket;
|
|
4801
|
+
const upgrading = Effect.gen(function* () {
|
|
4802
|
+
conn.ctx = yield* definition.resolve(request);
|
|
4803
|
+
if (config.authorize && !(yield* config.authorize({
|
|
4804
|
+
ctx: conn.ctx,
|
|
4805
|
+
request
|
|
4806
|
+
}))) return 403;
|
|
4807
|
+
socket.state = (config.state ? yield* config.state({
|
|
4808
|
+
ctx: conn.ctx,
|
|
4809
|
+
request
|
|
4810
|
+
}) : void 0) ?? {};
|
|
4811
|
+
return draining ? 503 : void 0;
|
|
4812
|
+
});
|
|
4813
|
+
const exit = await run(traced(conn, upgrading));
|
|
4814
|
+
let status;
|
|
4815
|
+
if (Exit.isSuccess(exit)) status = exit.value;
|
|
4816
|
+
else {
|
|
4817
|
+
const error = thrown(exit.cause);
|
|
4818
|
+
conn.failure = { error };
|
|
4819
|
+
(conn.ctx?.logger ?? fallbackLogger).error({
|
|
4820
|
+
error,
|
|
4821
|
+
service,
|
|
4822
|
+
socket: name
|
|
4823
|
+
});
|
|
4824
|
+
status = 500;
|
|
4825
|
+
}
|
|
4826
|
+
if (status === void 0) try {
|
|
4827
|
+
status = server.upgrade(request, { data: {
|
|
4828
|
+
mounted: handlers,
|
|
4829
|
+
connection: conn
|
|
4830
|
+
} }) ? void 0 : 400;
|
|
4831
|
+
} catch {
|
|
4832
|
+
status = 400;
|
|
4833
|
+
}
|
|
4834
|
+
if (status !== void 0) {
|
|
4835
|
+
abandon(conn, status);
|
|
4836
|
+
return refuse(status, status === 403 ? "Socket connection refused" : status === 503 ? "Server is shutting down" : status === 400 ? "Socket upgrade failed" : "Socket connection failed");
|
|
4837
|
+
}
|
|
4838
|
+
};
|
|
4839
|
+
};
|
|
4840
|
+
const upgrades = new Map(routes.map((route) => [route, mountRoute(route)]));
|
|
4841
|
+
const find = (request) => request.method === "GET" && request.headers.get("upgrade")?.toLowerCase() === "websocket" ? byPath.get(new URL(request.url).pathname) : void 0;
|
|
4842
|
+
return {
|
|
4843
|
+
paths: [...byPath.keys()],
|
|
4844
|
+
maxPayloadBytes: Math.max(SOCKET_MAX_BYTES, ...routes.map(({ definition }) => definition.maxPayloadBytes)),
|
|
4845
|
+
matches: (request) => find(request) !== void 0,
|
|
4846
|
+
upgrade: (request, server) => upgrades.get(find(request))(request, server),
|
|
4847
|
+
drain,
|
|
4848
|
+
stats,
|
|
4849
|
+
dispose() {
|
|
4850
|
+
for (const route of routes) route.definition.mounts.delete(route);
|
|
4851
|
+
}
|
|
4852
|
+
};
|
|
4853
|
+
}
|
|
4181
4854
|
// src/events/query.ts
|
|
4182
4855
|
/** A drizzle query on an untyped `db`, as the Effect it is. */
|
|
4183
4856
|
const query = (builder) => builder;
|
|
@@ -4926,11 +5599,12 @@ const brokenRetry = /* @__PURE__ */ new WeakSet();
|
|
|
4926
5599
|
/** Asks the listener's `retry` what to do with a failure. A `retry` that throws counts as "retry", and is logged once. */
|
|
4927
5600
|
function decideRetry(name, listener, error) {
|
|
4928
5601
|
if (!listener.retry) return "retry";
|
|
5602
|
+
const declared = asFailure(error);
|
|
4929
5603
|
try {
|
|
4930
|
-
return listener.retry(
|
|
4931
|
-
code:
|
|
4932
|
-
message:
|
|
4933
|
-
details:
|
|
5604
|
+
return listener.retry(declared instanceof BrickError && listener.errors?.[declared.code] ? {
|
|
5605
|
+
code: declared.code,
|
|
5606
|
+
message: declared.message,
|
|
5607
|
+
details: declared.details
|
|
4934
5608
|
} : {
|
|
4935
5609
|
code: "UNKNOWN",
|
|
4936
5610
|
message: error instanceof Error ? error.message : String(error),
|
|
@@ -5111,26 +5785,28 @@ const RunFields = {
|
|
|
5111
5785
|
trigger: Schema.Literals(["schedule", "manual"]),
|
|
5112
5786
|
runKey: Schema.String
|
|
5113
5787
|
};
|
|
5788
|
+
/** Dies when the app has no `WorkflowEngine` for the listener or schedule `kind`/`name`, which runs a workflow. */
|
|
5789
|
+
const requireEngine = (kind, name, context) => Context.getOption(context, WorkflowEngine$1.WorkflowEngine)._tag === "None" ? Effect.die(/* @__PURE__ */ new Error(`${kind === "Listener" ? "Event listener" : "Schedule"} '${name}' runs a workflow, so the app's layer needs a workflow engine: add workflowEngine(database) to \`brick({ layer })\`.`)) : Effect.void;
|
|
5114
5790
|
/**
|
|
5115
5791
|
* Registers `run` as a durable workflow on the app's `WorkflowEngine`, for the
|
|
5116
5792
|
* listener or schedule `kind`/`name`. The run is named after `key`, so a delivery
|
|
5117
5793
|
* or a due time that is tried again finds the run it started instead of
|
|
5118
|
-
* starting another. A failure of `run` ends the run
|
|
5119
|
-
* retries its own steps, not the delivery.
|
|
5794
|
+
* starting another. A failure of `run` ends the run as failed, with its cause,
|
|
5795
|
+
* and is logged: the workflow retries its own steps, not the delivery.
|
|
5120
5796
|
*
|
|
5121
5797
|
* @param context - The app's context, which holds the engine and what `run` needs.
|
|
5122
5798
|
* @throws (as a defect) When the app has no `WorkflowEngine`.
|
|
5123
5799
|
*/
|
|
5124
5800
|
function register(kind, name, fields, key, run, context) {
|
|
5125
5801
|
return Effect.gen(function* () {
|
|
5126
|
-
|
|
5802
|
+
yield* requireEngine(kind, name, context());
|
|
5127
5803
|
const workflow = Workflow$1.make(`Brick${kind}/${name}`, {
|
|
5128
5804
|
payload: fields,
|
|
5129
5805
|
idempotencyKey: key
|
|
5130
5806
|
});
|
|
5131
5807
|
const handler = (input) => Effect.suspend(() => run(input)).pipe(Effect.provideContext(context()), Effect.tapCause((cause) => Effect.sync(() => {
|
|
5132
5808
|
if (!Cause.hasInterruptsOnly(cause)) console.error(`[Brick] ${kind === "Listener" ? "Workflow listener" : "Workflow schedule"} '${name}' failed:`, Cause.pretty(cause));
|
|
5133
|
-
}))
|
|
5809
|
+
})));
|
|
5134
5810
|
yield* Layer.build(workflow.toLayer(handler)).pipe(Effect.provideContext(context()));
|
|
5135
5811
|
return {
|
|
5136
5812
|
name,
|
|
@@ -5267,8 +5943,16 @@ function createEvents(options, services, telemetry = false) {
|
|
|
5267
5943
|
let context = yield* Effect.context();
|
|
5268
5944
|
const deliverables = /* @__PURE__ */ new Map();
|
|
5269
5945
|
const starters = /* @__PURE__ */ new Map();
|
|
5270
|
-
|
|
5271
|
-
|
|
5946
|
+
const registering = Semaphore.makeUnsafe(1);
|
|
5947
|
+
const starter = (key) => registering.withPermits(1)(Effect.suspend(() => {
|
|
5948
|
+
const found = starters.get(key);
|
|
5949
|
+
if (found) return Effect.succeed(found);
|
|
5950
|
+
const name = key.slice(key.indexOf(":") + 1);
|
|
5951
|
+
const made = key.startsWith("listener:") ? listenerWorkflow(byName.get(name), () => context) : scheduleWorkflow(schedules.find((schedule) => schedule.name === name), () => context);
|
|
5952
|
+
return Effect.tap(Effect.provideService(made, Scope.Scope, scope), (made) => Effect.sync(() => starters.set(key, made)));
|
|
5953
|
+
}));
|
|
5954
|
+
for (const listener of byName.values()) if (listener.workflow) yield* dispatch !== false ? starter(`listener:${listener.name}`) : requireEngine("Listener", listener.name, context);
|
|
5955
|
+
for (const schedule of schedules) if (schedule.workflow) yield* dispatch !== false ? starter(`schedule:${schedule.name}`) : requireEngine("Schedule", schedule.name, context);
|
|
5272
5956
|
const deliverable = (name) => {
|
|
5273
5957
|
const listener = byName.get(name);
|
|
5274
5958
|
if (!listener) return void 0;
|
|
@@ -5279,7 +5963,7 @@ function createEvents(options, services, telemetry = false) {
|
|
|
5279
5963
|
...errors ? { errors } : {},
|
|
5280
5964
|
...retry ? { retry } : {},
|
|
5281
5965
|
...maxAttempts !== void 0 ? { maxAttempts } : {},
|
|
5282
|
-
run: listener.workflow ? ({ attempt: _attempt, ...event }) =>
|
|
5966
|
+
run: listener.workflow ? ({ attempt: _attempt, ...event }) => Effect.flatMap(starter(`listener:${name}`), (found) => found.start(event)) : (delivery) => Effect.suspend(() => run(delivery)).pipe(Effect.provideContext(context))
|
|
5283
5967
|
};
|
|
5284
5968
|
deliverables.set(name, found);
|
|
5285
5969
|
}
|
|
@@ -5312,7 +5996,7 @@ function createEvents(options, services, telemetry = false) {
|
|
|
5312
5996
|
runner: (schedule, run) => {
|
|
5313
5997
|
const ran = schedule.workflow ? Effect.suspend(() => {
|
|
5314
5998
|
const { attempt: _attempt, ...started } = run;
|
|
5315
|
-
return
|
|
5999
|
+
return Effect.flatMap(starter(`schedule:${schedule.name}`), (found) => found.start(started));
|
|
5316
6000
|
}) : Effect.suspend(() => schedule.run(run)).pipe(Effect.provideContext(context));
|
|
5317
6001
|
return telemetry ? traceScheduleRun(run, ran) : ran;
|
|
5318
6002
|
},
|
|
@@ -5579,7 +6263,8 @@ function defineCommand(service, resource, name, config) {
|
|
|
5579
6263
|
const id = row[resource.idField];
|
|
5580
6264
|
for (const child of loaded) row[child.name] = yield* tx.select().from(child.table).where(eq(child.parent, id));
|
|
5581
6265
|
const decision = decide(row, input);
|
|
5582
|
-
|
|
6266
|
+
const rejected = asFailure(decision);
|
|
6267
|
+
if (rejected instanceof BrickError) return yield* Effect.fail(rejected);
|
|
5583
6268
|
const { set, children, emit } = decision ?? {};
|
|
5584
6269
|
const declared = service.events;
|
|
5585
6270
|
const emits = [];
|
|
@@ -5801,18 +6486,24 @@ const MIN_TOKEN_LENGTH = 16;
|
|
|
5801
6486
|
*/
|
|
5802
6487
|
function normalizeDashboard(options) {
|
|
5803
6488
|
if (options === void 0) return void 0;
|
|
5804
|
-
const { port, host, auth, historyDays, inspector, mcp } = options;
|
|
6489
|
+
const { port, host, auth, historyDays, inspector, mcp, name, peers, peerSyncMinutes } = options;
|
|
5805
6490
|
if (port !== void 0 && (!Number.isInteger(port) || port < 1 || port > 65535)) throw new Error(`Brick: dashboard port must be an integer from 1 to 65535, not ${String(port)}.`);
|
|
5806
6491
|
if (host !== void 0 && (typeof host !== "string" || host.trim() === "")) throw new Error("Brick: dashboard host must be an address, such as '0.0.0.0'.");
|
|
5807
6492
|
if (historyDays !== void 0 && (!Number.isInteger(historyDays) || historyDays < 0)) throw new Error(`Brick: dashboard historyDays must be a whole number of days, not ${String(historyDays)}.`);
|
|
5808
6493
|
if (inspector !== void 0 && typeof inspector !== "boolean") throw new Error("Brick: dashboard inspector must be true or false.");
|
|
5809
6494
|
if (mcp !== void 0 && typeof mcp !== "boolean") throw new Error("Brick: dashboard mcp must be true or false.");
|
|
6495
|
+
if (name !== void 0 && (typeof name !== "string" || !INSTANCE_NAME.test(name))) throw new Error(`Brick: dashboard name must be letters, digits, '-' and '_', not ${JSON.stringify(name)}.`);
|
|
6496
|
+
const peerList = peers === void 0 ? void 0 : normalizePeers(peers, name);
|
|
6497
|
+
if (peerList && peerList.length > 0 && !(Number(historyDays) > 0)) throw new Error("Brick: dashboard peers need historyDays: the copies of their requests are kept on disk.");
|
|
6498
|
+
if (peerSyncMinutes !== void 0 && (typeof peerSyncMinutes !== "number" || !(peerSyncMinutes > 0 && peerSyncMinutes <= MAX_SYNC_MINUTES))) throw new Error(`Brick: dashboard peerSyncMinutes must be more than 0 and at most ${MAX_SYNC_MINUTES} minutes, not ${String(peerSyncMinutes)}.`);
|
|
5810
6499
|
const normalized = {
|
|
5811
6500
|
...port !== void 0 ? { port } : {},
|
|
5812
6501
|
...host !== void 0 ? { host: host.trim() } : {},
|
|
5813
6502
|
...historyDays !== void 0 ? { historyDays } : {},
|
|
5814
6503
|
...inspector !== void 0 ? { inspector } : {},
|
|
5815
|
-
...mcp !== void 0 ? { mcp } : {}
|
|
6504
|
+
...mcp !== void 0 ? { mcp } : {},
|
|
6505
|
+
...name !== void 0 ? { name } : {},
|
|
6506
|
+
...peerSyncMinutes !== void 0 ? { peerSyncMinutes } : {}
|
|
5816
6507
|
};
|
|
5817
6508
|
if (auth !== void 0) {
|
|
5818
6509
|
if (typeof auth !== "object" || auth === null) throw new Error("Brick: dashboard auth must be an object.");
|
|
@@ -5830,8 +6521,38 @@ function normalizeDashboard(options) {
|
|
|
5830
6521
|
get: () => secrets
|
|
5831
6522
|
});
|
|
5832
6523
|
}
|
|
6524
|
+
if (peerList !== void 0) Object.defineProperty(normalized, "peers", {
|
|
6525
|
+
enumerable: false,
|
|
6526
|
+
get: () => peerList
|
|
6527
|
+
});
|
|
5833
6528
|
return Object.freeze(normalized);
|
|
5834
6529
|
}
|
|
6530
|
+
/** The longest timer interval Node and Bun keep (2^31 - 1 ms), in whole minutes. */
|
|
6531
|
+
const MAX_SYNC_MINUTES = 35791;
|
|
6532
|
+
const INSTANCE_NAME = /^[\w-]{1,64}$/;
|
|
6533
|
+
function normalizePeers(peers, self) {
|
|
6534
|
+
if (!Array.isArray(peers)) throw new Error("Brick: dashboard peers must be an array.");
|
|
6535
|
+
const names = /* @__PURE__ */ new Set([self ?? "local"]);
|
|
6536
|
+
return Object.freeze(peers.map((peer) => {
|
|
6537
|
+
const { name, url, token } = peer ?? {};
|
|
6538
|
+
if (typeof name !== "string" || !INSTANCE_NAME.test(name)) throw new Error(`Brick: a dashboard peer's name must be letters, digits, '-' and '_', not ${JSON.stringify(name)}.`);
|
|
6539
|
+
if (names.has(name)) throw new Error(`Brick: dashboard peer '${name}' has the name of another instance; give each its own.`);
|
|
6540
|
+
names.add(name);
|
|
6541
|
+
let parsed;
|
|
6542
|
+
try {
|
|
6543
|
+
parsed = new URL(url);
|
|
6544
|
+
} catch {
|
|
6545
|
+
throw new Error(`Brick: dashboard peer '${name}' needs a url, such as 'https://brick-in.example.com'.`);
|
|
6546
|
+
}
|
|
6547
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") throw new Error(`Brick: dashboard peer '${name}' url must be http or https.`);
|
|
6548
|
+
if (typeof token !== "string" || token.length < MIN_TOKEN_LENGTH) throw new Error(`Brick: dashboard peer '${name}' needs its dashboard token (at least ${MIN_TOKEN_LENGTH} characters).`);
|
|
6549
|
+
return Object.freeze({
|
|
6550
|
+
name,
|
|
6551
|
+
url: parsed.origin + parsed.pathname.replace(/\/+$/, ""),
|
|
6552
|
+
token
|
|
6553
|
+
});
|
|
6554
|
+
}));
|
|
6555
|
+
}
|
|
5835
6556
|
// src/mcp.ts
|
|
5836
6557
|
var UnknownToolError = class extends Error {
|
|
5837
6558
|
name = "UnknownToolError";
|
|
@@ -6172,6 +6893,9 @@ const seqAfter = (a, b) => {
|
|
|
6172
6893
|
* broker with them, and builds the `Bun.serve` handlers that speak the
|
|
6173
6894
|
* `brick.v1` protocol.
|
|
6174
6895
|
*
|
|
6896
|
+
* `raw` brings the raw routes in: they share the route checks, the `websocket`
|
|
6897
|
+
* config and the close tracking, and are upgraded by the same `fetch`.
|
|
6898
|
+
*
|
|
6175
6899
|
* @throws When two sockets share a route, a socket shares one with an action,
|
|
6176
6900
|
* or a socket has replay and the broker has no history.
|
|
6177
6901
|
*/
|
|
@@ -6184,9 +6908,10 @@ function mountSockets(options) {
|
|
|
6184
6908
|
path: socketPath(prefix, service.name, definition),
|
|
6185
6909
|
definition
|
|
6186
6910
|
})));
|
|
6187
|
-
|
|
6911
|
+
const { raw } = options;
|
|
6912
|
+
if (!sockets.length && !raw?.paths.length && !options.sockets) return void 0;
|
|
6188
6913
|
const taken = /* @__PURE__ */ new Set();
|
|
6189
|
-
for (const
|
|
6914
|
+
for (const path of [...sockets.map((socket) => socket.path), ...raw?.paths ?? []]) {
|
|
6190
6915
|
if (taken.has(path)) throw new Error(`Brick: duplicate socket route '${path}'`);
|
|
6191
6916
|
taken.add(path);
|
|
6192
6917
|
}
|
|
@@ -6209,13 +6934,14 @@ function mountSockets(options) {
|
|
|
6209
6934
|
const byPath = new Map(mounted.map(({ path, socket }) => [path, socket]));
|
|
6210
6935
|
const find = (request) => request.method === "GET" && request.headers.get("upgrade")?.toLowerCase() === "websocket" ? byPath.get(new URL(request.url).pathname) : void 0;
|
|
6211
6936
|
return {
|
|
6212
|
-
matches: (request) => find(request) !== void 0,
|
|
6937
|
+
matches: (request) => find(request) !== void 0 || raw?.matches(request) === true,
|
|
6213
6938
|
async upgrade(request, bun) {
|
|
6214
6939
|
server = bun;
|
|
6215
|
-
|
|
6940
|
+
const brickSocket = find(request);
|
|
6941
|
+
return brickSocket ? brickSocket.upgrade(request, bun) : raw.upgrade(request, bun);
|
|
6216
6942
|
},
|
|
6217
6943
|
websocket: {
|
|
6218
|
-
maxPayloadLength: SOCKET_MAX_BYTES,
|
|
6944
|
+
maxPayloadLength: Math.max(SOCKET_MAX_BYTES, raw?.maxPayloadBytes ?? 0),
|
|
6219
6945
|
backpressureLimit: SOCKET_BUFFER_BYTES,
|
|
6220
6946
|
closeOnBackpressureLimit: true,
|
|
6221
6947
|
open: (ws) => ws.data.mounted.open(ws),
|
|
@@ -6228,6 +6954,7 @@ function mountSockets(options) {
|
|
|
6228
6954
|
},
|
|
6229
6955
|
async dispose() {
|
|
6230
6956
|
await Promise.all(closing);
|
|
6957
|
+
raw?.dispose();
|
|
6231
6958
|
for (const { definition } of sockets) definition.brokers.delete(broker);
|
|
6232
6959
|
await broker.close?.();
|
|
6233
6960
|
}
|
|
@@ -6247,9 +6974,11 @@ function mountSocket({ service, definition }, broker, run, getServer, sign, veri
|
|
|
6247
6974
|
if (Exit.isSuccess(exit)) return exit.value;
|
|
6248
6975
|
throw new Failed(exit.cause);
|
|
6249
6976
|
};
|
|
6250
|
-
/** The
|
|
6977
|
+
/** The declared or core failure of a run, else the typed failure, else what was thrown. */
|
|
6251
6978
|
const failureOf = (error) => {
|
|
6252
6979
|
if (!(error instanceof Failed)) return error;
|
|
6980
|
+
const known = failureOfCause(error.cause);
|
|
6981
|
+
if (known) return known;
|
|
6253
6982
|
const found = Cause.findError(error.cause);
|
|
6254
6983
|
return Result.isSuccess(found) ? found.success : error;
|
|
6255
6984
|
};
|
|
@@ -6479,9 +7208,194 @@ function mountSocket({ service, definition }, broker, run, getServer, sign, veri
|
|
|
6479
7208
|
};
|
|
6480
7209
|
return mounted;
|
|
6481
7210
|
}
|
|
6482
|
-
// src/
|
|
6483
|
-
/** The table the database-backed engine keeps its state in. It creates it when missing. */
|
|
7211
|
+
// src/workflow-store.ts
|
|
7212
|
+
/** The table the database-backed workflow engine keeps its state in. It creates it when missing. */
|
|
6484
7213
|
const WORKFLOW_TABLE = "brick_workflow_state";
|
|
7214
|
+
/** The columns the engine added to `key` and `value`, with their SQL types. All are NULL on rows an older version wrote. */
|
|
7215
|
+
const ADDED_COLUMNS = {
|
|
7216
|
+
run_id: "text",
|
|
7217
|
+
parent_id: "text",
|
|
7218
|
+
status: "text",
|
|
7219
|
+
owner: "text",
|
|
7220
|
+
lease_until: "bigint",
|
|
7221
|
+
finished_at: "bigint"
|
|
7222
|
+
};
|
|
7223
|
+
/** The Postgres advisory lock key `ensure` holds while it changes the table. */
|
|
7224
|
+
const ENSURE_LOCK = 7240815302;
|
|
7225
|
+
/**
|
|
7226
|
+
* The run a state row belongs to, from its key: `execution/<workflow>/<id>`
|
|
7227
|
+
* (a workflow's name may hold slashes, an id does not), or `<kind>/<id>/...`.
|
|
7228
|
+
* `undefined` for a key that belongs to no run.
|
|
7229
|
+
*/
|
|
7230
|
+
function runIdOf(key) {
|
|
7231
|
+
if (key.startsWith("execution/")) return key.slice(key.lastIndexOf("/") + 1);
|
|
7232
|
+
const [kind, id] = key.split("/");
|
|
7233
|
+
return [
|
|
7234
|
+
"activity",
|
|
7235
|
+
"activity-at",
|
|
7236
|
+
"deferred",
|
|
7237
|
+
"clock",
|
|
7238
|
+
"sleep"
|
|
7239
|
+
].includes(kind) ? id : void 0;
|
|
7240
|
+
}
|
|
7241
|
+
/** What an execution row written before the engine kept `status` says about the run. */
|
|
7242
|
+
const legacyStatus = (value) => {
|
|
7243
|
+
if (!value.done) return "running";
|
|
7244
|
+
try {
|
|
7245
|
+
return JSON.parse(value.result ?? "null")?.exit?._tag === "Failure" ? "failed" : "done";
|
|
7246
|
+
} catch {
|
|
7247
|
+
return "done";
|
|
7248
|
+
}
|
|
7249
|
+
};
|
|
7250
|
+
/**
|
|
7251
|
+
* The engine's rows: `key` and `value` hold the state, one kind of record per
|
|
7252
|
+
* key prefix. An execution's row also carries what the engine asks of a whole
|
|
7253
|
+
* run, in columns it can index: `status`, `owner` and `lease_until` (the
|
|
7254
|
+
* process that runs it, and until when), and `finished_at`. Every row of a run
|
|
7255
|
+
* carries its `run_id`, so retention removes the run in one statement.
|
|
7256
|
+
*/
|
|
7257
|
+
function makeStore(database, db) {
|
|
7258
|
+
const postgres = database.engine !== "sqlite";
|
|
7259
|
+
const table = postgres ? pgTable(WORKFLOW_TABLE, {
|
|
7260
|
+
key: text("key").primaryKey(),
|
|
7261
|
+
value: text("value").notNull(),
|
|
7262
|
+
runId: text("run_id"),
|
|
7263
|
+
parentId: text("parent_id"),
|
|
7264
|
+
status: text("status"),
|
|
7265
|
+
owner: text("owner"),
|
|
7266
|
+
leaseUntil: bigint("lease_until", { mode: "number" }),
|
|
7267
|
+
finishedAt: bigint("finished_at", { mode: "number" })
|
|
7268
|
+
}) : sqliteTable(WORKFLOW_TABLE, {
|
|
7269
|
+
key: text$1("key").primaryKey(),
|
|
7270
|
+
value: text$1("value").notNull(),
|
|
7271
|
+
runId: text$1("run_id"),
|
|
7272
|
+
parentId: text$1("parent_id"),
|
|
7273
|
+
status: text$1("status"),
|
|
7274
|
+
owner: text$1("owner"),
|
|
7275
|
+
leaseUntil: integer$1("lease_until"),
|
|
7276
|
+
finishedAt: integer$1("finished_at")
|
|
7277
|
+
});
|
|
7278
|
+
const dead = (effect) => Effect.orDie(effect);
|
|
7279
|
+
const statement = (text, handle = db) => dead(postgres ? handle.execute(sql.raw(text)) : handle.run(sql.raw(text)));
|
|
7280
|
+
/** A run no process holds: no owner, or one whose lease ran out. */
|
|
7281
|
+
const free = (now) => or(isNull(table.owner), lt(table.leaseUntil, now));
|
|
7282
|
+
const unfinished = or(isNull(table.status), eq(table.status, "running"));
|
|
7283
|
+
const columns = (handle = db) => Effect.gen(function* () {
|
|
7284
|
+
if (postgres) {
|
|
7285
|
+
const found = yield* dead(handle.execute(sql`select column_name as name from information_schema.columns where table_name = ${WORKFLOW_TABLE} and table_schema = current_schema()`));
|
|
7286
|
+
return new Set(found.rows.map((row) => row.name));
|
|
7287
|
+
}
|
|
7288
|
+
const found = yield* dead(handle.all(sql.raw(`pragma table_info(${WORKFLOW_TABLE})`)));
|
|
7289
|
+
return new Set(found.map((row) => row.name));
|
|
7290
|
+
});
|
|
7291
|
+
const set = (key, value) => dead(db.insert(table).values({
|
|
7292
|
+
key,
|
|
7293
|
+
value,
|
|
7294
|
+
runId: runIdOf(key) ?? ""
|
|
7295
|
+
}).onConflictDoUpdate({
|
|
7296
|
+
target: table.key,
|
|
7297
|
+
set: { value }
|
|
7298
|
+
}));
|
|
7299
|
+
/**
|
|
7300
|
+
* Rows an older version wrote have no `run_id`: give each its run, and each
|
|
7301
|
+
* execution its status. Cheap when there are none, which is every start but
|
|
7302
|
+
* the first after an upgrade (or a process of the old version still running).
|
|
7303
|
+
*/
|
|
7304
|
+
const backfill = () => Effect.gen(function* () {
|
|
7305
|
+
for (;;) {
|
|
7306
|
+
const rows = yield* dead(db.select({
|
|
7307
|
+
key: table.key,
|
|
7308
|
+
value: table.value
|
|
7309
|
+
}).from(table).where(isNull(table.runId)).orderBy(table.key).limit(500));
|
|
7310
|
+
if (rows.length === 0) return;
|
|
7311
|
+
for (const { key, value } of rows) {
|
|
7312
|
+
const execution = key.startsWith("execution/") ? JSON.parse(value) : void 0;
|
|
7313
|
+
const status = execution && legacyStatus(execution);
|
|
7314
|
+
yield* dead(db.update(table).set({
|
|
7315
|
+
runId: runIdOf(key) ?? "",
|
|
7316
|
+
...status && {
|
|
7317
|
+
status,
|
|
7318
|
+
...status !== "running" && { finishedAt: execution.completedAt ?? Date.now() }
|
|
7319
|
+
}
|
|
7320
|
+
}).where(eq(table.key, key)));
|
|
7321
|
+
}
|
|
7322
|
+
}
|
|
7323
|
+
});
|
|
7324
|
+
const upgrade = (handle = db) => Effect.gen(function* () {
|
|
7325
|
+
yield* statement(`create table if not exists ${WORKFLOW_TABLE} (key text primary key, value text not null, ${Object.entries(ADDED_COLUMNS).map(([name, type]) => `${name} ${type}`).join(", ")})`, handle);
|
|
7326
|
+
const present = yield* columns(handle);
|
|
7327
|
+
for (const [name, type] of Object.entries(ADDED_COLUMNS)) if (!present.has(name)) yield* Effect.catchCause(statement(`alter table ${WORKFLOW_TABLE} add column ${postgres ? "if not exists " : ""}${name} ${type}`, handle), () => Effect.void);
|
|
7328
|
+
yield* statement(`create index if not exists ${WORKFLOW_TABLE}_status on ${WORKFLOW_TABLE} (status, finished_at)`, handle);
|
|
7329
|
+
yield* statement(`create index if not exists ${WORKFLOW_TABLE}_run on ${WORKFLOW_TABLE} (run_id)`, handle);
|
|
7330
|
+
});
|
|
7331
|
+
return {
|
|
7332
|
+
/**
|
|
7333
|
+
* Make the table, add the columns an older version lacks, index them, and
|
|
7334
|
+
* backfill the rows already there. Safe to run from several processes at once:
|
|
7335
|
+
* on Postgres they take turns, because concurrent `create ... if not exists`
|
|
7336
|
+
* statements still fail with a unique violation on its catalog. Only that
|
|
7337
|
+
* part holds the lock: the backfill is batches that commit on their own, so
|
|
7338
|
+
* a big legacy table blocks neither other engines nor the rows they write.
|
|
7339
|
+
*/
|
|
7340
|
+
ensure: () => Effect.andThen(postgres ? db.transaction((tx) => Effect.andThen(dead(tx.execute(sql`select pg_advisory_xact_lock(${ENSURE_LOCK})`)), upgrade(tx))).pipe(Effect.orDie) : upgrade(), backfill()),
|
|
7341
|
+
/** Give the rows an older version wrote after this process started their run and status, so they are taken, renewed and swept. */
|
|
7342
|
+
backfill: backfill(),
|
|
7343
|
+
get: (key) => dead(db.select().from(table).where(eq(table.key, key))).pipe(Effect.map((rows) => rows[0]?.value)),
|
|
7344
|
+
set,
|
|
7345
|
+
list: (prefix) => dead(db.select().from(table).where(like(table.key, `${prefix}%`))).pipe(Effect.map((rows) => rows.filter((r) => r.key.startsWith(prefix)))),
|
|
7346
|
+
/** Insert a run held by `owner` until `until`, started by the run `parentId`, if any. `false` when the run already has a row. */
|
|
7347
|
+
begin: (key, value, owner, until, parentId) => dead(db.insert(table).values({
|
|
7348
|
+
key,
|
|
7349
|
+
value,
|
|
7350
|
+
runId: runIdOf(key) ?? "",
|
|
7351
|
+
parentId,
|
|
7352
|
+
status: "running",
|
|
7353
|
+
owner,
|
|
7354
|
+
leaseUntil: until
|
|
7355
|
+
}).onConflictDoNothing().returning({ key: table.key })).pipe(Effect.map((rows) => rows.length > 0)),
|
|
7356
|
+
/**
|
|
7357
|
+
* Take a run no process holds. `false` when it is finished or another process holds it.
|
|
7358
|
+
* A row a process of an older version wrote has no `status` or `run_id` yet: they are set here, or the renewal and the retention would pass it by.
|
|
7359
|
+
*/
|
|
7360
|
+
claim: (key, owner, now, until) => dead(db.update(table).set({
|
|
7361
|
+
owner,
|
|
7362
|
+
leaseUntil: until,
|
|
7363
|
+
status: "running",
|
|
7364
|
+
runId: runIdOf(key) ?? ""
|
|
7365
|
+
}).where(and(eq(table.key, key), unfinished, free(now))).returning({ key: table.key })).pipe(Effect.map((rows) => rows.length > 0)),
|
|
7366
|
+
/** Extend every lease `owner` holds. Returns the keys it still holds. */
|
|
7367
|
+
renew: (owner, until) => dead(db.update(table).set({ leaseUntil: until }).where(and(eq(table.owner, owner), eq(table.status, "running"))).returning({ key: table.key })).pipe(Effect.map((rows) => new Set(rows.map((row) => row.key)))),
|
|
7368
|
+
/** Let go of every lease `owner` holds, so another process takes those runs without waiting. */
|
|
7369
|
+
release: (owner) => dead(db.update(table).set({
|
|
7370
|
+
owner: null,
|
|
7371
|
+
leaseUntil: null
|
|
7372
|
+
}).where(and(eq(table.owner, owner), eq(table.status, "running")))),
|
|
7373
|
+
/** End a run: its final value, its status and when it ended, and nobody holds it. */
|
|
7374
|
+
finish: (key, value, status, at) => dead(db.update(table).set({
|
|
7375
|
+
value,
|
|
7376
|
+
status,
|
|
7377
|
+
finishedAt: at,
|
|
7378
|
+
owner: null,
|
|
7379
|
+
leaseUntil: null
|
|
7380
|
+
}).where(eq(table.key, key))),
|
|
7381
|
+
/** Unfinished runs nobody holds. */
|
|
7382
|
+
unheld: (now) => dead(db.select({
|
|
7383
|
+
key: table.key,
|
|
7384
|
+
value: table.value
|
|
7385
|
+
}).from(table).where(and(eq(table.status, "running"), free(now)))),
|
|
7386
|
+
/**
|
|
7387
|
+
* The ids of up to `limit` runs that ended with `status` before `before`,
|
|
7388
|
+
* and whose parent run, if any, is not running: the parent's replay reads
|
|
7389
|
+
* what its children ended with.
|
|
7390
|
+
*/
|
|
7391
|
+
endedBefore: (status, before, limit) => dead(db.select({ runId: table.runId }).from(table).where(and(eq(table.status, status), lt(table.finishedAt, before), sql`not exists (select 1 from ${sql.raw(WORKFLOW_TABLE)} parent where parent.run_id = ${table.parentId} and parent.status = 'running')`)).limit(limit)).pipe(Effect.map((rows) => rows.map((row) => row.runId))),
|
|
7392
|
+
/** Delete every row of these runs. */
|
|
7393
|
+
remove: (runIds) => dead(db.delete(table).where(inArray(table.runId, [...runIds]))),
|
|
7394
|
+
/** The keys of the durable deferreds saved for these runs. */
|
|
7395
|
+
deferreds: (runIds) => dead(db.select({ key: table.key }).from(table).where(and(inArray(table.runId, [...runIds]), like(table.key, "deferred/%")))).pipe(Effect.map((rows) => rows.map((row) => row.key)))
|
|
7396
|
+
};
|
|
7397
|
+
}
|
|
7398
|
+
// src/workflows.ts
|
|
6485
7399
|
const AnyOrVoid = Schema.Union([Schema.Any, Schema.Void]);
|
|
6486
7400
|
const resultCodec = Schema.toCodecJson(Workflow$1.Result({
|
|
6487
7401
|
success: AnyOrVoid,
|
|
@@ -6503,64 +7417,71 @@ const stateKeys = {
|
|
|
6503
7417
|
activity: (id, name, attempt) => `activity/${id}/${name}/${attempt}`,
|
|
6504
7418
|
activityAt: (id, name, attempt) => `activity-at/${id}/${name}/${attempt}`
|
|
6505
7419
|
};
|
|
6506
|
-
/** Rows of `key` and `value`: one kind of record per key prefix. */
|
|
6507
|
-
function makeStore(database, db) {
|
|
6508
|
-
const table = database.engine === "sqlite" ? sqliteTable(WORKFLOW_TABLE, {
|
|
6509
|
-
key: text$1("key").primaryKey(),
|
|
6510
|
-
value: text$1("value").notNull()
|
|
6511
|
-
}) : pgTable(WORKFLOW_TABLE, {
|
|
6512
|
-
key: text("key").primaryKey(),
|
|
6513
|
-
value: text("value").notNull()
|
|
6514
|
-
});
|
|
6515
|
-
const create = sql.raw(`create table if not exists ${WORKFLOW_TABLE} (key text primary key, value text not null)`);
|
|
6516
|
-
const dead = (effect) => Effect.orDie(effect);
|
|
6517
|
-
return {
|
|
6518
|
-
create: () => dead(database.engine === "sqlite" ? db.run(create) : db.execute(create)),
|
|
6519
|
-
get: (key) => dead(Effect.map(db.select().from(table).where(eq(table.key, key)), (rows) => rows[0]?.value)),
|
|
6520
|
-
set: (key, value) => dead(db.insert(table).values({
|
|
6521
|
-
key,
|
|
6522
|
-
value
|
|
6523
|
-
}).onConflictDoUpdate({
|
|
6524
|
-
target: table.key,
|
|
6525
|
-
set: { value }
|
|
6526
|
-
})),
|
|
6527
|
-
list: (prefix) => dead(Effect.map(db.select().from(table).where(like(table.key, `${prefix}%`)), (rows) => rows.filter((row) => row.key.startsWith(prefix))))
|
|
6528
|
-
};
|
|
6529
|
-
}
|
|
6530
7420
|
const RetryingExecution = Context.Reference("effect/workflow/Activity/RetryingExecution", { defaultValue: () => void 0 });
|
|
6531
7421
|
/** Reuses `prev` while it is still an empty child of `parent`, so replays that register nothing do not grow `parent`. */
|
|
6532
7422
|
const reuseOrForkScope = (prev, parent) => prev !== void 0 && prev.parent === parent && prev.state._tag === "Empty" ? prev : Scope.forkUnsafe(parent);
|
|
6533
7423
|
const isUnwakeable = (result, mode) => result._tag === "Complete" || mode === "automatic" && result.failed === true;
|
|
7424
|
+
const DAY = 864e5;
|
|
6534
7425
|
/**
|
|
6535
7426
|
* A workflow engine that keeps its state in the app's database, so a run
|
|
6536
7427
|
* survives a restart. It runs workflows as the in-memory engine of
|
|
6537
7428
|
* `effect/workflow` does, and writes through what a restart needs:
|
|
6538
7429
|
*
|
|
6539
|
-
* - each execution with its payload, until it finishes;
|
|
7430
|
+
* - each execution with its payload, until it finishes, and then its result;
|
|
6540
7431
|
* - the result of each activity attempt that finished;
|
|
6541
7432
|
* - each durable deferred that completed;
|
|
6542
7433
|
* - the wake time of each durable clock.
|
|
6543
7434
|
*
|
|
6544
|
-
*
|
|
6545
|
-
*
|
|
6546
|
-
*
|
|
7435
|
+
* A run ends `done`, or `failed` when it fails (its handler fails or dies, or an
|
|
7436
|
+
* activity's retries run out and the failure escapes). The `status` column and
|
|
7437
|
+
* the run's value hold which, and the cause.
|
|
6547
7438
|
*
|
|
6548
|
-
*
|
|
6549
|
-
* `
|
|
7439
|
+
* One process runs a run at a time. A process takes a run by writing its own
|
|
7440
|
+
* `owner` and a `lease_until` on it, and renews that while the run lives; other
|
|
7441
|
+
* processes leave it alone. When a workflow registers (its `toLayer`), and then
|
|
7442
|
+
* on every renewal, the process takes the unfinished runs of its workflows that
|
|
7443
|
+
* nobody holds: ones a process released when it stopped, or whose lease ran out
|
|
7444
|
+
* because it died. They replay, reading the saved results, so an activity that
|
|
7445
|
+
* finished does not run twice; a durable clock sleeps only what was left. Run
|
|
7446
|
+
* workflows only in the processes that should run them: a process that does not
|
|
7447
|
+
* register a workflow never takes its runs.
|
|
7448
|
+
*
|
|
7449
|
+
* Finished runs are deleted by a periodic sweep: see `retention`.
|
|
7450
|
+
*
|
|
7451
|
+
* It creates the `brick_workflow_state` table on first use, and adds the columns
|
|
7452
|
+
* it needs to one an older version made. Put it in the app's `layer`, with the
|
|
7453
|
+
* workflows' `toLayer` layers provided by it.
|
|
6550
7454
|
*
|
|
6551
7455
|
* @example
|
|
6552
|
-
* const engine = workflowEngine(database);
|
|
7456
|
+
* const engine = workflowEngine(database, { retention: { doneDays: 3 } });
|
|
6553
7457
|
* brick({ services, layer: Layer.mergeAll(engine, Layer.provide(OrderFlow.toLayer(run), engine)) });
|
|
6554
7458
|
*/
|
|
6555
|
-
function workflowEngine(database) {
|
|
7459
|
+
function workflowEngine(database, options = {}) {
|
|
7460
|
+
const leaseMs = options.leaseMs ?? 3e4;
|
|
7461
|
+
const retention = options.retention === false ? void 0 : {
|
|
7462
|
+
doneDays: options.retention?.doneDays ?? 7,
|
|
7463
|
+
failedDays: options.retention?.failedDays ?? 30,
|
|
7464
|
+
intervalMs: options.retention?.intervalMs ?? 36e5
|
|
7465
|
+
};
|
|
6556
7466
|
const build = Effect.gen(function* () {
|
|
6557
7467
|
const store = makeStore(database, yield* database.Database);
|
|
6558
|
-
yield* store.
|
|
7468
|
+
yield* store.ensure();
|
|
6559
7469
|
const scope = yield* Effect.scope;
|
|
7470
|
+
const owner = randomUUID();
|
|
7471
|
+
yield* Effect.addFinalizer(() => Effect.catchCause(store.release(owner), () => Effect.void));
|
|
6560
7472
|
const executionKey = stateKeys.execution;
|
|
6561
7473
|
const activityKey = stateKeys.activity;
|
|
6562
7474
|
const deferredKey = (id, name) => `deferred/${id}/${name}`;
|
|
6563
7475
|
const clockKey = (id, name) => `clock/${id}/${name}`;
|
|
7476
|
+
const seenDeferreds = /* @__PURE__ */ new Map();
|
|
7477
|
+
const sawDeferred = (key) => {
|
|
7478
|
+
const runId = runIdOf(key);
|
|
7479
|
+
const state = executions.get(runId);
|
|
7480
|
+
if (!state || state.finished) return;
|
|
7481
|
+
const seen = seenDeferreds.get(runId) ?? /* @__PURE__ */ new Set();
|
|
7482
|
+
seenDeferreds.set(runId, seen);
|
|
7483
|
+
seen.add(key);
|
|
7484
|
+
};
|
|
6564
7485
|
const sleepKey = (id, name, attempt) => `sleep/${id}/${name}/${attempt}`;
|
|
6565
7486
|
/**
|
|
6566
7487
|
* `DurableClock.sleep` of at most 60 seconds is an in-memory sleep inside an
|
|
@@ -6578,17 +7499,37 @@ function workflowEngine(database) {
|
|
|
6578
7499
|
const activities = /* @__PURE__ */ new Map();
|
|
6579
7500
|
const deferredState = WorkflowEngine$1.makeDeferredState();
|
|
6580
7501
|
const deferredResults = /* @__PURE__ */ new Map();
|
|
7502
|
+
/** Drops a run that leaves this process, with what it cached, so a later run of the same id reads the store. */
|
|
7503
|
+
const forget = (executionId) => {
|
|
7504
|
+
executions.delete(executionId);
|
|
7505
|
+
const prefix = `${executionId}/`;
|
|
7506
|
+
for (const cache of [activities, deferredResults]) for (const key of cache.keys()) if (key.startsWith(prefix)) cache.delete(key);
|
|
7507
|
+
};
|
|
6581
7508
|
const clocks = yield* FiberMap.make();
|
|
6582
7509
|
const runSetup = Semaphore.makeUnsafe(1);
|
|
7510
|
+
const unsaved = /* @__PURE__ */ new Map();
|
|
7511
|
+
const awaitedElsewhere = /* @__PURE__ */ new Map();
|
|
7512
|
+
const lost = /* @__PURE__ */ new Map();
|
|
6583
7513
|
let lastStamp = 0;
|
|
6584
7514
|
const stamp = () => lastStamp = Math.max(Date.now(), lastStamp + .001);
|
|
6585
|
-
/**
|
|
6586
|
-
|
|
6587
|
-
|
|
6588
|
-
|
|
6589
|
-
|
|
6590
|
-
|
|
6591
|
-
|
|
7515
|
+
/**
|
|
7516
|
+
* Ends the execution, `failed` when its result is a failure, with the result,
|
|
7517
|
+
* which `poll` reads once the process that ran it is gone, and the cause.
|
|
7518
|
+
*/
|
|
7519
|
+
const finish = (name, executionId, result) => Effect.flatMap(store.get(executionKey(name, executionId)), (row) => row === void 0 ? Effect.void : Effect.flatMap(encodeResult(result), (saved) => {
|
|
7520
|
+
const failed = result._tag === "Complete" && Exit.isFailure(result.exit);
|
|
7521
|
+
const at = Date.now();
|
|
7522
|
+
return Effect.asVoid(store.finish(executionKey(name, executionId), JSON.stringify({
|
|
7523
|
+
...JSON.parse(row),
|
|
7524
|
+
done: true,
|
|
7525
|
+
...failed && {
|
|
7526
|
+
failed: true,
|
|
7527
|
+
error: Cause.pretty(result.exit.cause).slice(0, 4e3)
|
|
7528
|
+
},
|
|
7529
|
+
result: saved,
|
|
7530
|
+
completedAt: at
|
|
7531
|
+
}), failed ? "failed" : "done", at));
|
|
7532
|
+
}));
|
|
6592
7533
|
/** The result of an execution that finished before this process started, if it did. */
|
|
6593
7534
|
const saved = (name, executionId) => Effect.gen(function* () {
|
|
6594
7535
|
const row = yield* store.get(executionKey(name, executionId));
|
|
@@ -6626,9 +7567,45 @@ function workflowEngine(database) {
|
|
|
6626
7567
|
const close = Scope.close(executionScope, Exit.void);
|
|
6627
7568
|
if (Exit.isFailure(exit)) return close;
|
|
6628
7569
|
const wakeParents = (fiber) => Fiber.await(fiber).pipe(Effect.flatMap(() => Effect.forEach(state.parents, (parent) => Effect.forkIn(resume(parent, "automatic"), scope), { discard: true })), Effect.forkIn(scope));
|
|
6629
|
-
return close.pipe(Effect.andThen(
|
|
7570
|
+
return close.pipe(Effect.andThen(Effect.suspend(() => {
|
|
7571
|
+
state.finished = true;
|
|
7572
|
+
seenDeferreds.delete(instance.executionId);
|
|
7573
|
+
const write = finish(instance.workflow._tag, instance.executionId, exit.value);
|
|
7574
|
+
return write.pipe(Effect.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.sync(() => {
|
|
7575
|
+
console.error(`[Brick] Workflow run ${instance.executionId} ended, but its end could not be saved; trying again:`, Cause.pretty(cause));
|
|
7576
|
+
unsaved.set(instance.executionId, write);
|
|
7577
|
+
})));
|
|
7578
|
+
})), Effect.andThen(Deferred.succeed(state.done, void 0)), Effect.andThen(Effect.sync(() => {
|
|
7579
|
+
if (!unsaved.has(instance.executionId) && executions.get(instance.executionId) === state) forget(instance.executionId);
|
|
7580
|
+
})), Effect.ensuring(Effect.withFiber(wakeParents)));
|
|
6630
7581
|
}), Effect.forkIn(entry.scope));
|
|
6631
7582
|
}, runSetup.withPermits(1));
|
|
7583
|
+
/**
|
|
7584
|
+
* What a start that did not take the run waits for: its result, once the
|
|
7585
|
+
* process that holds it has finished it, or its state here, if this process
|
|
7586
|
+
* takes it over meanwhile. A parent run does not wait: it suspends, and is
|
|
7587
|
+
* woken when the result is there (see `awaitedElsewhere`).
|
|
7588
|
+
*/
|
|
7589
|
+
const held = (name, executionId, parentId) => Effect.gen(function* () {
|
|
7590
|
+
for (let delay = 20;; delay = Math.min(delay * 2, 500)) {
|
|
7591
|
+
const state = executions.get(executionId);
|
|
7592
|
+
if (state?.fiber) return { state };
|
|
7593
|
+
const row = yield* store.get(executionKey(name, executionId));
|
|
7594
|
+
if (row === void 0) return yield* Effect.die(/* @__PURE__ */ new Error(`Workflow run "${executionId}" was deleted`));
|
|
7595
|
+
const { result } = JSON.parse(row);
|
|
7596
|
+
if (result !== void 0) return { result: yield* decodeResult(result) };
|
|
7597
|
+
if (parentId !== void 0) {
|
|
7598
|
+
const waiting = awaitedElsewhere.get(executionId);
|
|
7599
|
+
if (waiting) waiting.parents.add(parentId);
|
|
7600
|
+
else awaitedElsewhere.set(executionId, {
|
|
7601
|
+
name,
|
|
7602
|
+
parents: /* @__PURE__ */ new Set([parentId])
|
|
7603
|
+
});
|
|
7604
|
+
return { suspended: true };
|
|
7605
|
+
}
|
|
7606
|
+
yield* Effect.sleep(delay);
|
|
7607
|
+
}
|
|
7608
|
+
});
|
|
6632
7609
|
const start = (workflow, options) => Effect.gen(function* () {
|
|
6633
7610
|
const entry = workflows.get(workflow._tag);
|
|
6634
7611
|
if (!entry) return yield* Effect.orDie(Effect.fail(`Workflow ${workflow._tag} is not registered`));
|
|
@@ -6636,55 +7613,177 @@ function workflowEngine(database) {
|
|
|
6636
7613
|
let state = executions.get(options.executionId);
|
|
6637
7614
|
if (!state) {
|
|
6638
7615
|
const key = executionKey(workflow._tag, options.executionId);
|
|
6639
|
-
|
|
7616
|
+
const now = Date.now();
|
|
7617
|
+
if (!((yield* store.begin(key, JSON.stringify({
|
|
6640
7618
|
payload: options.payload,
|
|
6641
7619
|
done: false,
|
|
6642
|
-
startedAt:
|
|
6643
|
-
}))
|
|
6644
|
-
|
|
6645
|
-
|
|
6646
|
-
|
|
6647
|
-
|
|
6648
|
-
|
|
6649
|
-
|
|
6650
|
-
|
|
6651
|
-
|
|
6652
|
-
|
|
6653
|
-
|
|
6654
|
-
|
|
6655
|
-
|
|
6656
|
-
|
|
6657
|
-
|
|
7620
|
+
startedAt: now
|
|
7621
|
+
}), owner, now + leaseMs, options.parent?.executionId)) || (yield* store.claim(key, owner, now, now + leaseMs)))) {
|
|
7622
|
+
if (options.discard) return;
|
|
7623
|
+
const found = yield* held(workflow._tag, options.executionId, parentId);
|
|
7624
|
+
if ("suspended" in found) return new Workflow$1.Suspended({});
|
|
7625
|
+
if ("result" in found) return found.result;
|
|
7626
|
+
state = found.state;
|
|
7627
|
+
} else {
|
|
7628
|
+
state = {
|
|
7629
|
+
payload: options.payload,
|
|
7630
|
+
execute: entry.execute,
|
|
7631
|
+
instance: WorkflowEngine$1.WorkflowInstance.initial(workflow, options.executionId),
|
|
7632
|
+
interrupted: false,
|
|
7633
|
+
interruptedUnsafe: false,
|
|
7634
|
+
resumeRequested: void 0,
|
|
7635
|
+
fiber: void 0,
|
|
7636
|
+
done: Deferred.makeUnsafe(),
|
|
7637
|
+
scope: Scope.makeUnsafe(),
|
|
7638
|
+
finished: false,
|
|
7639
|
+
parents: new Set(parentId === void 0 ? [] : [parentId])
|
|
7640
|
+
};
|
|
7641
|
+
executions.set(options.executionId, state);
|
|
7642
|
+
yield* resume(options.executionId, "explicit");
|
|
7643
|
+
}
|
|
6658
7644
|
} else if (parentId !== void 0) state.parents.add(parentId);
|
|
6659
7645
|
if (options.discard) return;
|
|
6660
|
-
|
|
6661
|
-
|
|
6662
|
-
|
|
6663
|
-
|
|
7646
|
+
for (;;) {
|
|
7647
|
+
const instance = state.instance;
|
|
7648
|
+
const exit = yield* Fiber.await(state.fiber);
|
|
7649
|
+
if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)) {
|
|
7650
|
+
if (instance.suspended) return new Workflow$1.Suspended({});
|
|
7651
|
+
if (executions.get(options.executionId) !== state) {
|
|
7652
|
+
const found = yield* held(workflow._tag, options.executionId, parentId);
|
|
7653
|
+
if ("suspended" in found) return new Workflow$1.Suspended({});
|
|
7654
|
+
if ("result" in found) return found.result;
|
|
7655
|
+
state = found.state;
|
|
7656
|
+
continue;
|
|
7657
|
+
}
|
|
7658
|
+
}
|
|
7659
|
+
return yield* exit;
|
|
7660
|
+
}
|
|
7661
|
+
});
|
|
7662
|
+
/** Takes the unfinished runs of the registered workflows that no process holds, and runs them. */
|
|
7663
|
+
const recover = Effect.gen(function* () {
|
|
7664
|
+
for (const { key, value } of yield* store.unheld(Date.now())) {
|
|
7665
|
+
const rest = key.slice(10);
|
|
7666
|
+
const slash = rest.lastIndexOf("/");
|
|
7667
|
+
const entry = workflows.get(rest.slice(0, slash));
|
|
7668
|
+
const executionId = rest.slice(slash + 1);
|
|
7669
|
+
if (!entry || executions.has(executionId)) continue;
|
|
7670
|
+
yield* start(entry.workflow, {
|
|
7671
|
+
executionId,
|
|
7672
|
+
payload: JSON.parse(value).payload,
|
|
7673
|
+
discard: true
|
|
7674
|
+
});
|
|
7675
|
+
}
|
|
7676
|
+
});
|
|
7677
|
+
/** Extends the leases this process holds. A run it no longer holds was taken by another process, which found its lease run out: stop running it here. */
|
|
7678
|
+
const renew = Effect.gen(function* () {
|
|
7679
|
+
const before = [...executions.keys()];
|
|
7680
|
+
const kept = yield* store.renew(owner, Date.now() + leaseMs);
|
|
7681
|
+
for (const executionId of before) {
|
|
7682
|
+
const state = executions.get(executionId);
|
|
7683
|
+
if (!state || state.finished || kept.has(executionKey(state.instance.workflow._tag, executionId))) continue;
|
|
7684
|
+
forget(executionId);
|
|
7685
|
+
seenDeferreds.delete(executionId);
|
|
7686
|
+
console.warn(`[Brick] Workflow run ${executionId} was taken by another process: its lease ran out here.`);
|
|
7687
|
+
if (state.fiber) yield* Fiber.interrupt(state.fiber);
|
|
7688
|
+
const waiting = lost.get(executionId);
|
|
7689
|
+
if (waiting) waiting.dones.push(state.done);
|
|
7690
|
+
else lost.set(executionId, {
|
|
7691
|
+
name: state.instance.workflow._tag,
|
|
7692
|
+
dones: [state.done]
|
|
7693
|
+
});
|
|
7694
|
+
}
|
|
7695
|
+
});
|
|
7696
|
+
/** Completes the `done` of the lost runs that have ended, here or in the process that took them: one read of each per turn, and none for a run this process took back. */
|
|
7697
|
+
const settleLost = Effect.gen(function* () {
|
|
7698
|
+
for (const [executionId, { name, dones }] of lost) {
|
|
7699
|
+
const here = executions.get(executionId);
|
|
7700
|
+
if (here && !here.finished) continue;
|
|
7701
|
+
if (!here) {
|
|
7702
|
+
const row = yield* store.get(executionKey(name, executionId));
|
|
7703
|
+
if (row !== void 0 && JSON.parse(row).result === void 0) continue;
|
|
7704
|
+
}
|
|
7705
|
+
lost.delete(executionId);
|
|
7706
|
+
for (const done of dones) yield* Deferred.succeed(done, void 0);
|
|
7707
|
+
}
|
|
7708
|
+
});
|
|
7709
|
+
/** Writes the end of the runs whose write failed. */
|
|
7710
|
+
const saveUnsaved = Effect.gen(function* () {
|
|
7711
|
+
for (const [executionId, write] of unsaved) {
|
|
7712
|
+
const exit = yield* Effect.exit(write);
|
|
7713
|
+
if (Exit.isSuccess(exit)) {
|
|
7714
|
+
unsaved.delete(executionId);
|
|
7715
|
+
if (executions.get(executionId)?.finished) forget(executionId);
|
|
7716
|
+
} else if (Cause.hasInterruptsOnly(exit.cause)) return yield* Effect.failCause(exit.cause);
|
|
7717
|
+
}
|
|
7718
|
+
});
|
|
7719
|
+
/**
|
|
7720
|
+
* A durable deferred another process completed was saved, but only the
|
|
7721
|
+
* process that holds a suspended run can wake it: look for those. A parent
|
|
7722
|
+
* suspended on a child another process runs is woken when the child ends.
|
|
7723
|
+
*/
|
|
7724
|
+
const wake = Effect.gen(function* () {
|
|
7725
|
+
for (const [executionId, { name, parents }] of awaitedElsewhere) {
|
|
7726
|
+
const row = yield* store.get(executionKey(name, executionId));
|
|
7727
|
+
if (row !== void 0 && JSON.parse(row).result === void 0) continue;
|
|
7728
|
+
awaitedElsewhere.delete(executionId);
|
|
7729
|
+
for (const parent of parents) yield* Effect.forkIn(resume(parent, "automatic"), scope);
|
|
7730
|
+
}
|
|
7731
|
+
const suspended = [...executions].filter(([, state]) => {
|
|
7732
|
+
const exit = state.fiber?.pollUnsafe();
|
|
7733
|
+
return !state.finished && exit?._tag === "Success" && exit.value._tag === "Suspended";
|
|
7734
|
+
}).map(([executionId]) => executionId);
|
|
7735
|
+
for (let i = 0; i < suspended.length; i += 200) for (const key of yield* store.deferreds(suspended.slice(i, i + 200))) {
|
|
7736
|
+
if (seenDeferreds.get(runIdOf(key))?.has(key)) continue;
|
|
7737
|
+
sawDeferred(key);
|
|
7738
|
+
yield* resume(runIdOf(key), "automatic");
|
|
7739
|
+
}
|
|
7740
|
+
});
|
|
7741
|
+
/** Deletes the runs that ended before the retention allows. */
|
|
7742
|
+
const sweep = Effect.gen(function* () {
|
|
7743
|
+
if (!retention) return;
|
|
7744
|
+
for (const [status, days] of [["done", retention.doneDays], ["failed", retention.failedDays]]) for (;;) {
|
|
7745
|
+
const ids = yield* store.endedBefore(status, Date.now() - days * DAY, 500);
|
|
7746
|
+
if (ids.length === 0) break;
|
|
7747
|
+
yield* store.remove(ids);
|
|
7748
|
+
}
|
|
7749
|
+
});
|
|
7750
|
+
const guarded = (what, effect) => Effect.catchCause(effect, (cause) => Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.sync(() => console.error(`[Brick] Workflow engine ${what} failed:`, Cause.pretty(cause))));
|
|
7751
|
+
let lastSweep = 0;
|
|
7752
|
+
const turn = Effect.gen(function* () {
|
|
7753
|
+
yield* guarded("saving the end of runs", saveUnsaved);
|
|
7754
|
+
yield* guarded("backfill", store.backfill);
|
|
7755
|
+
yield* guarded("recovery", recover);
|
|
7756
|
+
yield* guarded("deferred check", wake);
|
|
7757
|
+
yield* guarded("lost runs", settleLost);
|
|
7758
|
+
if (Date.now() - lastSweep >= (retention?.intervalMs ?? 0)) {
|
|
7759
|
+
lastSweep = Date.now();
|
|
7760
|
+
yield* guarded("retention sweep", sweep);
|
|
7761
|
+
}
|
|
7762
|
+
});
|
|
7763
|
+
let maintaining = false;
|
|
7764
|
+
/** What a process does once it runs workflows: take what is free now, and go on renewing, taking and sweeping. A process that registers none never starts it. */
|
|
7765
|
+
const maintain = Effect.gen(function* () {
|
|
7766
|
+
yield* recover;
|
|
7767
|
+
if (maintaining) return;
|
|
7768
|
+
maintaining = true;
|
|
7769
|
+
const every = Schedule.spaced(Math.max(10, Math.floor(leaseMs / 3)));
|
|
7770
|
+
yield* Effect.forkIn(pollUnref(guarded("lease renewal", renew), every), scope);
|
|
7771
|
+
yield* Effect.forkIn(pollUnref(turn, every), scope);
|
|
6664
7772
|
});
|
|
6665
7773
|
const engine = WorkflowEngine$1.makeUnsafe({
|
|
6666
7774
|
register: Effect.fnUntraced(function* (workflow, execute) {
|
|
6667
|
-
|
|
7775
|
+
workflows.set(workflow._tag, {
|
|
6668
7776
|
workflow,
|
|
6669
7777
|
execute,
|
|
6670
7778
|
scope: yield* Effect.scope
|
|
6671
|
-
};
|
|
6672
|
-
|
|
6673
|
-
const prefix = executionKey(workflow._tag, "");
|
|
6674
|
-
for (const { key, value } of yield* store.list(prefix)) {
|
|
6675
|
-
const row = JSON.parse(value);
|
|
6676
|
-
if (row.done) continue;
|
|
6677
|
-
yield* start(workflow, {
|
|
6678
|
-
executionId: key.slice(prefix.length),
|
|
6679
|
-
payload: row.payload,
|
|
6680
|
-
discard: true
|
|
6681
|
-
});
|
|
6682
|
-
}
|
|
7779
|
+
});
|
|
7780
|
+
yield* maintain;
|
|
6683
7781
|
}),
|
|
6684
7782
|
execute: start,
|
|
6685
|
-
awaitComplete: (
|
|
7783
|
+
awaitComplete: (workflow, executionId) => Effect.suspend(() => {
|
|
6686
7784
|
const state = executions.get(executionId);
|
|
6687
|
-
|
|
7785
|
+
if (state) return Deferred.await(state.done);
|
|
7786
|
+
return saved(workflow._tag, executionId).pipe(Effect.flatMap((result) => Option.isSome(result) ? Effect.void : Effect.never));
|
|
6688
7787
|
}),
|
|
6689
7788
|
interrupt: Effect.fnUntraced(function* (_workflow, executionId) {
|
|
6690
7789
|
const state = executions.get(executionId);
|
|
@@ -6737,8 +7836,10 @@ function workflowEngine(database) {
|
|
|
6737
7836
|
const id = `${instance.executionId}/${deferred.name}`;
|
|
6738
7837
|
const known = deferredResults.get(id);
|
|
6739
7838
|
if (known) return Option.some(known);
|
|
6740
|
-
const
|
|
7839
|
+
const key = deferredKey(instance.executionId, deferred.name);
|
|
7840
|
+
const saved = yield* store.get(key);
|
|
6741
7841
|
if (saved === void 0) return Option.none();
|
|
7842
|
+
sawDeferred(key);
|
|
6742
7843
|
const result = yield* decodeResult(saved);
|
|
6743
7844
|
if (result._tag !== "Complete") return Option.none();
|
|
6744
7845
|
deferredResults.set(id, result.exit);
|
|
@@ -6748,6 +7849,7 @@ function workflowEngine(database) {
|
|
|
6748
7849
|
const id = `${options.executionId}/${options.deferredName}`;
|
|
6749
7850
|
if (deferredResults.has(id)) return Effect.void;
|
|
6750
7851
|
deferredResults.set(id, options.exit);
|
|
7852
|
+
sawDeferred(deferredKey(options.executionId, options.deferredName));
|
|
6751
7853
|
const wake = Effect.andThen(deferredState.deferredDone(options.executionId, options.deferredName), resume(options.executionId, "automatic"));
|
|
6752
7854
|
return Effect.flatMap(Effect.flatMap(encodeResult(new Workflow$1.Complete({ exit: options.exit })), (saved) => store.set(deferredKey(options.executionId, options.deferredName), saved)), () => Effect.flatMap(Effect.serviceOption(WorkflowEngine$1.WorkflowInstance), (instance) => Option.isSome(instance) && instance.value.executionId === options.executionId ? wake.pipe(Effect.forkIn(scope), Effect.asVoid) : wake));
|
|
6753
7855
|
}),
|
|
@@ -7014,7 +8116,7 @@ const isPlainObject = (value) => typeof value === "object" && value !== null &&
|
|
|
7014
8116
|
const readBody = (web) => web.method === "GET" || web.method === "HEAD" ? Effect.succeed(void 0) : Effect.gen(function* () {
|
|
7015
8117
|
const text = yield* Effect.promise(() => web.clone().text());
|
|
7016
8118
|
if (!text) return void 0;
|
|
7017
|
-
if (!web.headers.get("content-type")?.includes("json")) return text;
|
|
8119
|
+
if (!web.headers.get("content-type")?.toLowerCase().includes("json")) return text;
|
|
7018
8120
|
try {
|
|
7019
8121
|
return JSON.parse(text);
|
|
7020
8122
|
} catch {
|
|
@@ -7074,9 +8176,11 @@ const readInput = (route, action, web) => Effect.gen(function* () {
|
|
|
7074
8176
|
};
|
|
7075
8177
|
const bounded = route.bodyLimit !== void 0 && web.body ? yield* Effect.promise(() => readBounded(web.body, route.bodyLimit)) : void 0;
|
|
7076
8178
|
if (route.bodyLimit !== void 0 && web.body && !bounded) return yield* tooLarge();
|
|
7077
|
-
|
|
8179
|
+
const contentType = web.headers.get("content-type") ?? "";
|
|
8180
|
+
const type = contentType.toLowerCase();
|
|
8181
|
+
if (type.startsWith("multipart/form-data")) {
|
|
7078
8182
|
const form = yield* Effect.tryPromise({
|
|
7079
|
-
try: () => (bounded ? new Response(bounded, { headers: { "content-type":
|
|
8183
|
+
try: () => (bounded ? new Response(bounded, { headers: { "content-type": contentType } }) : web).formData(),
|
|
7080
8184
|
catch: () => invalid$1(action.name, "input", [{
|
|
7081
8185
|
path: "",
|
|
7082
8186
|
message: "Body is not valid multipart/form-data"
|
|
@@ -7093,14 +8197,16 @@ const readInput = (route, action, web) => Effect.gen(function* () {
|
|
|
7093
8197
|
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
7094
8198
|
const text = bounded ? new TextDecoder().decode(bounded) : yield* request.text;
|
|
7095
8199
|
let body;
|
|
7096
|
-
if (
|
|
7097
|
-
body = JSON.parse(text);
|
|
8200
|
+
if (type.includes("json")) try {
|
|
8201
|
+
body = text ? JSON.parse(text) ?? void 0 : void 0;
|
|
7098
8202
|
} catch {
|
|
7099
8203
|
return yield* invalid$1(action.name, "input", [{
|
|
7100
8204
|
path: "",
|
|
7101
8205
|
message: "Body is not valid JSON"
|
|
7102
8206
|
}]);
|
|
7103
8207
|
}
|
|
8208
|
+
else if (type.startsWith("application/x-www-form-urlencoded")) body = text ? formObject(new URLSearchParams(text)) : void 0;
|
|
8209
|
+
else body = type.startsWith("text/") ? text || void 0 : void 0;
|
|
7104
8210
|
return {
|
|
7105
8211
|
input: Object.keys(params).length && (body === void 0 || isPlainObject(body)) ? {
|
|
7106
8212
|
...body,
|
|
@@ -7110,7 +8216,7 @@ const readInput = (route, action, web) => Effect.gen(function* () {
|
|
|
7110
8216
|
};
|
|
7111
8217
|
});
|
|
7112
8218
|
/** The error an endpoint's handler failed with, as a 4xx the way a thrown `{ status }` is in core. */
|
|
7113
|
-
const httpStatusError = (error) => !(error
|
|
8219
|
+
const httpStatusError = (error) => !asFailure(error) && error !== null && typeof error === "object" && "status" in error && typeof error.status === "number" && Number.isInteger(error.status) && error.status >= 400 && error.status < 500 ? new BrickError({
|
|
7114
8220
|
code: "HTTP_ERROR",
|
|
7115
8221
|
message: "message" in error && typeof error.message === "string" ? error.message : "Endpoint error",
|
|
7116
8222
|
status: error.status
|
|
@@ -7363,7 +8469,11 @@ function brick(options = {}) {
|
|
|
7363
8469
|
traceId,
|
|
7364
8470
|
requestId
|
|
7365
8471
|
});
|
|
7366
|
-
}).pipe(Effect.
|
|
8472
|
+
}).pipe(Effect.catchCause((cause) => {
|
|
8473
|
+
const thrown = Cause.findDefect(cause);
|
|
8474
|
+
const failure = Result.isSuccess(thrown) ? httpStatusError(thrown.success) : thrown;
|
|
8475
|
+
return failure instanceof BrickError ? Effect.fail(failure) : Effect.failCause(cause);
|
|
8476
|
+
}), Effect.mapError(httpStatusError), Effect.provideContext(yield* runtime.contextEffect));
|
|
7367
8477
|
return HttpServerResponse.fromWeb(answer(result, set));
|
|
7368
8478
|
}), {
|
|
7369
8479
|
method: def.method,
|
|
@@ -7493,12 +8603,21 @@ function brick(options = {}) {
|
|
|
7493
8603
|
headers
|
|
7494
8604
|
});
|
|
7495
8605
|
};
|
|
8606
|
+
const run = (effect) => runtime.runPromiseExit(effect);
|
|
8607
|
+
const raw = mountRawSockets({
|
|
8608
|
+
services,
|
|
8609
|
+
prefix,
|
|
8610
|
+
run,
|
|
8611
|
+
telemetry,
|
|
8612
|
+
drainTimeoutMs: options.drainTimeoutMs ?? 3e4
|
|
8613
|
+
});
|
|
7496
8614
|
const sockets = mountSockets({
|
|
7497
8615
|
services,
|
|
7498
8616
|
prefix,
|
|
7499
8617
|
routes: [...routes, ...endpointDefs],
|
|
7500
8618
|
sockets: options.sockets,
|
|
7501
|
-
|
|
8619
|
+
raw,
|
|
8620
|
+
run
|
|
7502
8621
|
});
|
|
7503
8622
|
const plugged = pluginLifecycle(plugins.lifecycles, (effect) => runtime.runPromise(effect));
|
|
7504
8623
|
let server;
|
|
@@ -7526,7 +8645,8 @@ function brick(options = {}) {
|
|
|
7526
8645
|
else startEvents();
|
|
7527
8646
|
return server;
|
|
7528
8647
|
},
|
|
7529
|
-
async stop() {
|
|
8648
|
+
async stop(force) {
|
|
8649
|
+
if (force !== true) await raw.drain();
|
|
7530
8650
|
await server?.stop(true);
|
|
7531
8651
|
server = void 0;
|
|
7532
8652
|
try {
|
|
@@ -7553,7 +8673,9 @@ function brick(options = {}) {
|
|
|
7553
8673
|
app.listen(port);
|
|
7554
8674
|
return app;
|
|
7555
8675
|
},
|
|
7556
|
-
shutdown: () => app.stop(),
|
|
8676
|
+
shutdown: (force) => app.stop(force),
|
|
8677
|
+
drain: raw.drain,
|
|
8678
|
+
rawSockets: raw.stats,
|
|
7557
8679
|
openApiDocument,
|
|
7558
8680
|
architecture: () => JSON.parse(architectureJson()),
|
|
7559
8681
|
clientContract: () => describeClientContract(services, routes, prefix),
|
|
@@ -7579,7 +8701,7 @@ function brick(options = {}) {
|
|
|
7579
8701
|
endpoint(def) {
|
|
7580
8702
|
if (routeKey(def.method, def.path) === mcpKey) throw mcpRouteTaken();
|
|
7581
8703
|
if (def.database && !databases.has(def.database.layer)) throw new Error(`Brick: the endpoint '${def.method} ${def.path}' names a database the app does not hold: give it to a service, or pass the endpoint in brick({ endpoints }).`);
|
|
7582
|
-
if (def.method === "GET" && definition.sockets.some((socket) => socket.path === def.path)) throw new DuplicateNameError(`Brick: route '${def.method} ${def.path}' conflicts with a socket`);
|
|
8704
|
+
if (def.method === "GET" && (definition.sockets.some((socket) => socket.path === def.path) || raw.paths.includes(def.path))) throw new DuplicateNameError(`Brick: route '${def.method} ${def.path}' conflicts with a socket`);
|
|
7583
8705
|
if (mountEndpoint(def)) {
|
|
7584
8706
|
lateRoutes.push(endpointRoute(def));
|
|
7585
8707
|
stale = true;
|
|
@@ -7590,6 +8712,6 @@ function brick(options = {}) {
|
|
|
7590
8712
|
};
|
|
7591
8713
|
return app;
|
|
7592
8714
|
}
|
|
7593
|
-
export {
|
|
8715
|
+
export { PLUGIN_KIND as $, toErrorResponse as $n, envSource as $t, onTransactionCommit as A, telemetryLayer as An, errorHelpers as At, scalarDocsHTML as B, signDashboardIdentity as Bn, defineStorage as Bt, scheduleTable as C, baseContext as Cn, kindOf as Ct, defineServiceSocket as D, Telemetry as Dn, RESET_STAGES as Dt, SocketDenied as E, SpanStore as En, HTTP_METHODS as Et, encodePayload as F, dashboardIdentity as Fn, hasSensitive as Ft, getPluginActionRoute as G, actionMeta as Gn, storageKey as Gt, copyControls as H, ATTR as Hn, memory as Ht, isCrudEvent as I, dashboardKey as In, redact as It, installPlugin as J, STANDARD_ERRORS as Jn, scopeFiles as Jt, getPluginEndpoints as K, BrickError as Kn, LOCAL_FILES_ROUTE as Kt, OPENAPI_DEFAULTS as L, dashboardMcpCaller as Ln, sensitivePointer as Lt, crudEventName as M, traceScheduleRun as Mn, runStages as Mt, crudEventSource as N, DASHBOARD_IDENTITY_HEADER as Nn, stagesOf as Nt, localBroker as O, recordWebhook as On, createAction as Ot, defineEvents as P, DASHBOARD_KEY_ENV as Pn, Sensitive as Pt, PLUGIN_COMMIT as Q, prefixedFailure as Qn, defineSecret as Qt, generateOpenApiSpec as R, dashboardUser as Rn, carryClientRequest as Rt, outboxTable as S, actorOf as Sn, jsonValue as St, defineRawSocket as T, defaultLogger as Tn, withoutNull as Tt, defineResourcePlugin as U, GLOBAL_SYMBOL as Un, redis as Ut, claimSegment as V, signDashboardMcp as Vn, frameworkStorage as Vt, defineServicePlugin as W, SPAN as Wn, requireStorage as Wt, internalsOf$1 as X, failureOfCause as Xn, StorageUnavailableError as Xt, validatePath as Y, ValidationError as Yn, StorageError as Yt, setInternals as Z, normalizeFailures as Zn, SecretRef as Zt, idSchema as _, inlineAuditOptions as _n, databaseValue as _t, Workflow as a, definitionSite as an, getActionRoute as at, stopAllEvents as b, recordAudit as bn, idSchema$1 as bt, WORKFLOW_TABLE as c, ownDeps as cn, getActionAccess as ct, createMcpHandler as d, UploadedFile as dn, ORDERED_TYPES as dt, listSecrets as en, toWireError as er, getGlobalRegistry as et, createMcpRegistry as f, UploadedFiles as fn, SORTABLE_TYPES as ft, defineResource as g, bindAuditTarget as gn, columnValue as gt, normalizeDashboard as h, auditTableOf as hn, columnSchema as ht, DurableDeferred as i, claimName as in, actionOwners as it, runInTransaction as j, traceRoute as jn, invalid$1 as jt, splitSeq as k, spanStore as kn, deny as kt, INTERNALS as l, useDeps as ln, setActionAccess as lt, DASHBOARD_MCP_TOOLS as m, auditTable as mn, checkJsonSchema as mt, Activity as n, resetSecrets as nn, exportArchitecture as nt, WorkflowEngine as o, depsOverride as on, isObjectSchema as ot, DASHBOARD_MCP_ROUTE as p, fileFields as pn, UNFILTERABLE_TYPES as pt, hasPlugin as q, DuplicateNameError as qn, s3 as qt, DurableClock as r, resolveSecrets as rn, DEFAULT_PREFIX as rt, workflowEngine as s, freezeAsBuiltDeps as sn, kebabCase as st, brick as t, overrideSecret as tn, resetGlobalRegistry as tt, UnknownToolError as u, withOverride as un, setActionAudit as ut, loadRecord as v, isAuditTable as vn, decodeCursor as vt, defineSchedule as w, createLogger as wn, reject as wt, defineListener as x, recordInline as xn, invalid as xt, Events as y, isInlineAudit as yn, encodeCursor as yt, requestLoggingPlugin as z, markDashboardArrival as zn, clientAddress as zt };
|
|
7594
8716
|
|
|
7595
|
-
//# sourceMappingURL=server-
|
|
8717
|
+
//# sourceMappingURL=server-B1gl742e.js.map
|