@brickkit/effect 0.16.0-beta.8 → 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.
@@ -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
- const isFailure = (value) => value instanceof BrickError || value instanceof ValidationError;
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.code === "INTERNAL_SERVER_ERROR" ? "InternalServerError" : "ActionExecutionError",
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 is kept; anything else (an
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 found = Cause.findError(cause);
83
- if (Result.isSuccess(found) && isFailure(found.success)) return found.success;
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
- return new BrickError({
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 failure = toFailure(cause, context);
99
- if (failure.status >= 500 && failure.code !== "INTERNAL_SERVER_ERROR") context.logger.error("Server action error", { requestId: context.requestId }, Cause.pretty(cause));
208
+ const known = failureOfCause(cause);
209
+ if (known) logServerFailure(known, cause, context);
100
210
  return {
101
- ...toWireError(failure),
211
+ ...toWireError(known ?? toFailure(cause, context)),
102
212
  requestId: context.requestId ?? ""
103
213
  };
104
214
  }
@@ -339,7 +449,6 @@ const truncate = (text, limit = MAX_TEXT_LENGTH) => text.length > limit ? `${tex
339
449
  const toMs = (nanos) => Number(nanos) / 1e6;
340
450
  const nowNanos = () => BigInt(Math.round((performance.timeOrigin + performance.now()) * 1e6));
341
451
  const messageOf = (error) => error instanceof Error ? error.message : String(error);
342
- const isHandled = (error) => error instanceof BrickError || error instanceof ValidationError;
343
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. */
344
453
  var BrickSpan = class extends Tracer.NativeSpan {
345
454
  #sql;
@@ -409,8 +518,8 @@ var BrickSpan = class extends Tracer.NativeSpan {
409
518
  }
410
519
  #record(cause, endTime) {
411
520
  const found = Cause.findError(cause);
412
- const error = Result.isSuccess(found) ? found.success : void 0;
413
- if (isHandled(error)) {
521
+ const error = failureOfCause(cause);
522
+ if (error) {
414
523
  super.attribute(ATTR.errorCode, error.code);
415
524
  super.attribute(ATTR.errorStatus, error.status);
416
525
  super.attribute(ATTR.errorMessage, truncate(error.message));
@@ -2151,7 +2260,7 @@ const holdsMark = (ast, seen = /* @__PURE__ */ new Set()) => {
2151
2260
  if (isMarked(ast)) return true;
2152
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));
2153
2262
  };
2154
- function collect(ast, segments, optional, walk) {
2263
+ function collect$1(ast, segments, optional, walk) {
2155
2264
  if (isMarked(ast)) {
2156
2265
  walk.paths.push({
2157
2266
  segments,
@@ -2164,11 +2273,11 @@ function collect(ast, segments, optional, walk) {
2164
2273
  return;
2165
2274
  }
2166
2275
  if (ast._tag === "Union") {
2167
- for (const branch of ast.types) collect(branch, segments, optional, walk);
2276
+ for (const branch of ast.types) collect$1(branch, segments, optional, walk);
2168
2277
  return;
2169
2278
  }
2170
2279
  if (ast._tag === "Declaration") {
2171
- for (const part of ast.typeParameters) collect(part, segments, optional, walk);
2280
+ for (const part of ast.typeParameters) collect$1(part, segments, optional, walk);
2172
2281
  return;
2173
2282
  }
2174
2283
  if (ast._tag === "Objects") {
@@ -2180,9 +2289,9 @@ function collect(ast, segments, optional, walk) {
2180
2289
  segments: here,
2181
2290
  required: !absentable
2182
2291
  });
2183
- collect(type, here, absentable, walk);
2292
+ collect$1(type, here, absentable, walk);
2184
2293
  }
2185
- 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);
2186
2295
  return;
2187
2296
  }
2188
2297
  if (ast._tag === "Arrays") {
@@ -2192,7 +2301,7 @@ function collect(ast, segments, optional, walk) {
2192
2301
  segments: [...segments, segment],
2193
2302
  required: true
2194
2303
  });
2195
- collect(item, [...segments, segment], false, walk);
2304
+ collect$1(item, [...segments, segment], false, walk);
2196
2305
  }
2197
2306
  }
2198
2307
  }
@@ -2204,7 +2313,7 @@ function analyze(ast) {
2204
2313
  paths: [],
2205
2314
  publics: []
2206
2315
  };
2207
- collect(ast, [], false, analysis);
2316
+ collect$1(ast, [], false, analysis);
2208
2317
  analyses.set(ast, analysis);
2209
2318
  }
2210
2319
  return analysis;
@@ -2482,11 +2591,9 @@ function sensitiveStage(config, owner) {
2482
2591
  logger: call.ctx.logger,
2483
2592
  requestId: call.ctx.requestId
2484
2593
  });
2485
- return Effect.fail(failure instanceof BrickError ? new BrickError({
2486
- code: failure.code,
2487
- status: failure.status,
2594
+ return Effect.fail(failure instanceof BrickError || failure instanceof ValidationError ? redactedCopy(failure, {
2488
2595
  message: redactText(set, failure.message),
2489
- details: redactDetails(set, failure.details)
2596
+ details: failure instanceof BrickError ? redactDetails(set, failure.details) : void 0
2490
2597
  }) : failure);
2491
2598
  }), Effect.provideService(Redactions, set));
2492
2599
  const paths = (call.wire ? wireOutputs : outputs)?.paths;
@@ -2508,6 +2615,167 @@ function sensitiveStage(config, owner) {
2508
2615
  })
2509
2616
  };
2510
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
+ }
2511
2779
  // src/action.ts
2512
2780
  /** The HTTP methods an action can use. */
2513
2781
  const HTTP_METHODS = [
@@ -2531,14 +2799,6 @@ function errorHelpers(errors) {
2531
2799
  }));
2532
2800
  return helpers;
2533
2801
  }
2534
- const pointer = (path) => path.map((item) => String(typeof item === "object" && item !== null && "key" in item ? item.key : item)).map((key) => `/${key}`).join("");
2535
- /** The `{ path, message }` items of a schema failure. Paths are JSON pointers, as in core; messages never carry the rejected value. */
2536
- function issuesOf(error) {
2537
- return SchemaIssue.makeFormatterStandardSchemaV1()(error.issue).issues.map(({ path, message }) => ({
2538
- path: pointer(path ?? []),
2539
- message
2540
- }));
2541
- }
2542
2802
  /** The error for input (400) or output (500) that fails its schema. */
2543
2803
  function invalid$1(action, stage, errors) {
2544
2804
  return new ValidationError({
@@ -2572,7 +2832,8 @@ function stagesOf(config, host, action) {
2572
2832
  value: Schema.decodeUnknownEffect(Schema.toType(input)),
2573
2833
  json: Schema.decodeUnknownEffect(Schema.toCodecJson(input)),
2574
2834
  query: Schema.decodeUnknownEffect(Schema.toCodecArrayFromSingle(Schema.toCodecStringTree(input))),
2575
- form: formDecoder(input)
2835
+ form: formDecoder(input),
2836
+ absent: Schema.decodeUnknownEffect(input)
2576
2837
  };
2577
2838
  const check = output && {
2578
2839
  value: Schema.decodeUnknownEffect(Schema.toType(output)),
@@ -2601,7 +2862,7 @@ function stagesOf(config, host, action) {
2601
2862
  }] : [],
2602
2863
  ...decode ? [{
2603
2864
  name: "input",
2604
- 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({
2605
2866
  ...call,
2606
2867
  input: decoded
2607
2868
  })))
@@ -2615,7 +2876,7 @@ function stagesOf(config, host, action) {
2615
2876
  ...audit ? [audit] : [],
2616
2877
  ...check ? [{
2617
2878
  name: "output",
2618
- 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))))))
2619
2880
  }] : [],
2620
2881
  {
2621
2882
  name: "execute",
@@ -5338,11 +5599,12 @@ const brokenRetry = /* @__PURE__ */ new WeakSet();
5338
5599
  /** Asks the listener's `retry` what to do with a failure. A `retry` that throws counts as "retry", and is logged once. */
5339
5600
  function decideRetry(name, listener, error) {
5340
5601
  if (!listener.retry) return "retry";
5602
+ const declared = asFailure(error);
5341
5603
  try {
5342
- return listener.retry(error instanceof BrickError && listener.errors?.[error.code] ? {
5343
- code: error.code,
5344
- message: error.message,
5345
- details: error.details
5604
+ return listener.retry(declared instanceof BrickError && listener.errors?.[declared.code] ? {
5605
+ code: declared.code,
5606
+ message: declared.message,
5607
+ details: declared.details
5346
5608
  } : {
5347
5609
  code: "UNKNOWN",
5348
5610
  message: error instanceof Error ? error.message : String(error),
@@ -5523,26 +5785,28 @@ const RunFields = {
5523
5785
  trigger: Schema.Literals(["schedule", "manual"]),
5524
5786
  runKey: Schema.String
5525
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;
5526
5790
  /**
5527
5791
  * Registers `run` as a durable workflow on the app's `WorkflowEngine`, for the
5528
5792
  * listener or schedule `kind`/`name`. The run is named after `key`, so a delivery
5529
5793
  * or a due time that is tried again finds the run it started instead of
5530
- * starting another. A failure of `run` ends the run and is logged: the workflow
5531
- * 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.
5532
5796
  *
5533
5797
  * @param context - The app's context, which holds the engine and what `run` needs.
5534
5798
  * @throws (as a defect) When the app has no `WorkflowEngine`.
5535
5799
  */
5536
5800
  function register(kind, name, fields, key, run, context) {
5537
5801
  return Effect.gen(function* () {
5538
- if (Context.getOption(context(), WorkflowEngine$1.WorkflowEngine)._tag === "None") return yield* 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 })\`.`));
5802
+ yield* requireEngine(kind, name, context());
5539
5803
  const workflow = Workflow$1.make(`Brick${kind}/${name}`, {
5540
5804
  payload: fields,
5541
5805
  idempotencyKey: key
5542
5806
  });
5543
5807
  const handler = (input) => Effect.suspend(() => run(input)).pipe(Effect.provideContext(context()), Effect.tapCause((cause) => Effect.sync(() => {
5544
5808
  if (!Cause.hasInterruptsOnly(cause)) console.error(`[Brick] ${kind === "Listener" ? "Workflow listener" : "Workflow schedule"} '${name}' failed:`, Cause.pretty(cause));
5545
- })), Effect.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.void));
5809
+ })));
5546
5810
  yield* Layer.build(workflow.toLayer(handler)).pipe(Effect.provideContext(context()));
5547
5811
  return {
5548
5812
  name,
@@ -5679,8 +5943,16 @@ function createEvents(options, services, telemetry = false) {
5679
5943
  let context = yield* Effect.context();
5680
5944
  const deliverables = /* @__PURE__ */ new Map();
5681
5945
  const starters = /* @__PURE__ */ new Map();
5682
- for (const listener of byName.values()) if (listener.workflow) starters.set(`listener:${listener.name}`, yield* listenerWorkflow(listener, () => context));
5683
- for (const schedule of schedules) if (schedule.workflow) starters.set(`schedule:${schedule.name}`, yield* scheduleWorkflow(schedule, () => context));
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);
5684
5956
  const deliverable = (name) => {
5685
5957
  const listener = byName.get(name);
5686
5958
  if (!listener) return void 0;
@@ -5691,7 +5963,7 @@ function createEvents(options, services, telemetry = false) {
5691
5963
  ...errors ? { errors } : {},
5692
5964
  ...retry ? { retry } : {},
5693
5965
  ...maxAttempts !== void 0 ? { maxAttempts } : {},
5694
- run: listener.workflow ? ({ attempt: _attempt, ...event }) => starters.get(`listener:${name}`).start(event) : (delivery) => Effect.suspend(() => run(delivery)).pipe(Effect.provideContext(context))
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))
5695
5967
  };
5696
5968
  deliverables.set(name, found);
5697
5969
  }
@@ -5724,7 +5996,7 @@ function createEvents(options, services, telemetry = false) {
5724
5996
  runner: (schedule, run) => {
5725
5997
  const ran = schedule.workflow ? Effect.suspend(() => {
5726
5998
  const { attempt: _attempt, ...started } = run;
5727
- return starters.get(`schedule:${schedule.name}`).start(started);
5999
+ return Effect.flatMap(starter(`schedule:${schedule.name}`), (found) => found.start(started));
5728
6000
  }) : Effect.suspend(() => schedule.run(run)).pipe(Effect.provideContext(context));
5729
6001
  return telemetry ? traceScheduleRun(run, ran) : ran;
5730
6002
  },
@@ -5991,7 +6263,8 @@ function defineCommand(service, resource, name, config) {
5991
6263
  const id = row[resource.idField];
5992
6264
  for (const child of loaded) row[child.name] = yield* tx.select().from(child.table).where(eq(child.parent, id));
5993
6265
  const decision = decide(row, input);
5994
- if (decision instanceof BrickError) return yield* Effect.fail(decision);
6266
+ const rejected = asFailure(decision);
6267
+ if (rejected instanceof BrickError) return yield* Effect.fail(rejected);
5995
6268
  const { set, children, emit } = decision ?? {};
5996
6269
  const declared = service.events;
5997
6270
  const emits = [];
@@ -6213,18 +6486,24 @@ const MIN_TOKEN_LENGTH = 16;
6213
6486
  */
6214
6487
  function normalizeDashboard(options) {
6215
6488
  if (options === void 0) return void 0;
6216
- const { port, host, auth, historyDays, inspector, mcp } = options;
6489
+ const { port, host, auth, historyDays, inspector, mcp, name, peers, peerSyncMinutes } = options;
6217
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)}.`);
6218
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'.");
6219
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)}.`);
6220
6493
  if (inspector !== void 0 && typeof inspector !== "boolean") throw new Error("Brick: dashboard inspector must be true or false.");
6221
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)}.`);
6222
6499
  const normalized = {
6223
6500
  ...port !== void 0 ? { port } : {},
6224
6501
  ...host !== void 0 ? { host: host.trim() } : {},
6225
6502
  ...historyDays !== void 0 ? { historyDays } : {},
6226
6503
  ...inspector !== void 0 ? { inspector } : {},
6227
- ...mcp !== void 0 ? { mcp } : {}
6504
+ ...mcp !== void 0 ? { mcp } : {},
6505
+ ...name !== void 0 ? { name } : {},
6506
+ ...peerSyncMinutes !== void 0 ? { peerSyncMinutes } : {}
6228
6507
  };
6229
6508
  if (auth !== void 0) {
6230
6509
  if (typeof auth !== "object" || auth === null) throw new Error("Brick: dashboard auth must be an object.");
@@ -6242,8 +6521,38 @@ function normalizeDashboard(options) {
6242
6521
  get: () => secrets
6243
6522
  });
6244
6523
  }
6524
+ if (peerList !== void 0) Object.defineProperty(normalized, "peers", {
6525
+ enumerable: false,
6526
+ get: () => peerList
6527
+ });
6245
6528
  return Object.freeze(normalized);
6246
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
+ }
6247
6556
  // src/mcp.ts
6248
6557
  var UnknownToolError = class extends Error {
6249
6558
  name = "UnknownToolError";
@@ -6665,9 +6974,11 @@ function mountSocket({ service, definition }, broker, run, getServer, sign, veri
6665
6974
  if (Exit.isSuccess(exit)) return exit.value;
6666
6975
  throw new Failed(exit.cause);
6667
6976
  };
6668
- /** The typed failure of a run, else what was thrown. */
6977
+ /** The declared or core failure of a run, else the typed failure, else what was thrown. */
6669
6978
  const failureOf = (error) => {
6670
6979
  if (!(error instanceof Failed)) return error;
6980
+ const known = failureOfCause(error.cause);
6981
+ if (known) return known;
6671
6982
  const found = Cause.findError(error.cause);
6672
6983
  return Result.isSuccess(found) ? found.success : error;
6673
6984
  };
@@ -6897,9 +7208,194 @@ function mountSocket({ service, definition }, broker, run, getServer, sign, veri
6897
7208
  };
6898
7209
  return mounted;
6899
7210
  }
6900
- // src/workflows.ts
6901
- /** 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. */
6902
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
6903
7399
  const AnyOrVoid = Schema.Union([Schema.Any, Schema.Void]);
6904
7400
  const resultCodec = Schema.toCodecJson(Workflow$1.Result({
6905
7401
  success: AnyOrVoid,
@@ -6921,64 +7417,71 @@ const stateKeys = {
6921
7417
  activity: (id, name, attempt) => `activity/${id}/${name}/${attempt}`,
6922
7418
  activityAt: (id, name, attempt) => `activity-at/${id}/${name}/${attempt}`
6923
7419
  };
6924
- /** Rows of `key` and `value`: one kind of record per key prefix. */
6925
- function makeStore(database, db) {
6926
- const table = database.engine === "sqlite" ? sqliteTable(WORKFLOW_TABLE, {
6927
- key: text$1("key").primaryKey(),
6928
- value: text$1("value").notNull()
6929
- }) : pgTable(WORKFLOW_TABLE, {
6930
- key: text("key").primaryKey(),
6931
- value: text("value").notNull()
6932
- });
6933
- const create = sql.raw(`create table if not exists ${WORKFLOW_TABLE} (key text primary key, value text not null)`);
6934
- const dead = (effect) => Effect.orDie(effect);
6935
- return {
6936
- create: () => dead(database.engine === "sqlite" ? db.run(create) : db.execute(create)),
6937
- get: (key) => dead(Effect.map(db.select().from(table).where(eq(table.key, key)), (rows) => rows[0]?.value)),
6938
- set: (key, value) => dead(db.insert(table).values({
6939
- key,
6940
- value
6941
- }).onConflictDoUpdate({
6942
- target: table.key,
6943
- set: { value }
6944
- })),
6945
- list: (prefix) => dead(Effect.map(db.select().from(table).where(like(table.key, `${prefix}%`)), (rows) => rows.filter((row) => row.key.startsWith(prefix))))
6946
- };
6947
- }
6948
7420
  const RetryingExecution = Context.Reference("effect/workflow/Activity/RetryingExecution", { defaultValue: () => void 0 });
6949
7421
  /** Reuses `prev` while it is still an empty child of `parent`, so replays that register nothing do not grow `parent`. */
6950
7422
  const reuseOrForkScope = (prev, parent) => prev !== void 0 && prev.parent === parent && prev.state._tag === "Empty" ? prev : Scope.forkUnsafe(parent);
6951
7423
  const isUnwakeable = (result, mode) => result._tag === "Complete" || mode === "automatic" && result.failed === true;
7424
+ const DAY = 864e5;
6952
7425
  /**
6953
7426
  * A workflow engine that keeps its state in the app's database, so a run
6954
7427
  * survives a restart. It runs workflows as the in-memory engine of
6955
7428
  * `effect/workflow` does, and writes through what a restart needs:
6956
7429
  *
6957
- * - each execution with its payload, until it finishes;
7430
+ * - each execution with its payload, until it finishes, and then its result;
6958
7431
  * - the result of each activity attempt that finished;
6959
7432
  * - each durable deferred that completed;
6960
7433
  * - the wake time of each durable clock.
6961
7434
  *
6962
- * When a workflow registers (its `toLayer`), the executions of it that never
6963
- * finished start again. They replay, reading the saved results, so an activity
6964
- * that finished does not run twice; a durable clock sleeps only what was left.
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.
6965
7438
  *
6966
- * It creates the `brick_workflow_state` table on first use. Put it in the app's
6967
- * `layer`, with the workflows' `toLayer` layers provided by it.
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.
6968
7454
  *
6969
7455
  * @example
6970
- * const engine = workflowEngine(database);
7456
+ * const engine = workflowEngine(database, { retention: { doneDays: 3 } });
6971
7457
  * brick({ services, layer: Layer.mergeAll(engine, Layer.provide(OrderFlow.toLayer(run), engine)) });
6972
7458
  */
6973
- 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
+ };
6974
7466
  const build = Effect.gen(function* () {
6975
7467
  const store = makeStore(database, yield* database.Database);
6976
- yield* store.create();
7468
+ yield* store.ensure();
6977
7469
  const scope = yield* Effect.scope;
7470
+ const owner = randomUUID();
7471
+ yield* Effect.addFinalizer(() => Effect.catchCause(store.release(owner), () => Effect.void));
6978
7472
  const executionKey = stateKeys.execution;
6979
7473
  const activityKey = stateKeys.activity;
6980
7474
  const deferredKey = (id, name) => `deferred/${id}/${name}`;
6981
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
+ };
6982
7485
  const sleepKey = (id, name, attempt) => `sleep/${id}/${name}/${attempt}`;
6983
7486
  /**
6984
7487
  * `DurableClock.sleep` of at most 60 seconds is an in-memory sleep inside an
@@ -6996,17 +7499,37 @@ function workflowEngine(database) {
6996
7499
  const activities = /* @__PURE__ */ new Map();
6997
7500
  const deferredState = WorkflowEngine$1.makeDeferredState();
6998
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
+ };
6999
7508
  const clocks = yield* FiberMap.make();
7000
7509
  const runSetup = Semaphore.makeUnsafe(1);
7510
+ const unsaved = /* @__PURE__ */ new Map();
7511
+ const awaitedElsewhere = /* @__PURE__ */ new Map();
7512
+ const lost = /* @__PURE__ */ new Map();
7001
7513
  let lastStamp = 0;
7002
7514
  const stamp = () => lastStamp = Math.max(Date.now(), lastStamp + .001);
7003
- /** Marks the execution done, with its result, which `poll` reads once the process that ran it is gone. */
7004
- const finish = (name, executionId, result) => Effect.flatMap(store.get(executionKey(name, executionId)), (row) => row === void 0 ? Effect.void : Effect.flatMap(encodeResult(result), (saved) => Effect.asVoid(store.set(executionKey(name, executionId), JSON.stringify({
7005
- ...JSON.parse(row),
7006
- done: true,
7007
- result: saved,
7008
- completedAt: Date.now()
7009
- })))));
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
+ }));
7010
7533
  /** The result of an execution that finished before this process started, if it did. */
7011
7534
  const saved = (name, executionId) => Effect.gen(function* () {
7012
7535
  const row = yield* store.get(executionKey(name, executionId));
@@ -7044,9 +7567,45 @@ function workflowEngine(database) {
7044
7567
  const close = Scope.close(executionScope, Exit.void);
7045
7568
  if (Exit.isFailure(exit)) return close;
7046
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));
7047
- return close.pipe(Effect.andThen(finish(instance.workflow._tag, instance.executionId, exit.value)), Effect.andThen(Deferred.succeed(state.done, void 0)), Effect.ensuring(Effect.withFiber(wakeParents)));
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)));
7048
7581
  }), Effect.forkIn(entry.scope));
7049
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
+ });
7050
7609
  const start = (workflow, options) => Effect.gen(function* () {
7051
7610
  const entry = workflows.get(workflow._tag);
7052
7611
  if (!entry) return yield* Effect.orDie(Effect.fail(`Workflow ${workflow._tag} is not registered`));
@@ -7054,55 +7613,177 @@ function workflowEngine(database) {
7054
7613
  let state = executions.get(options.executionId);
7055
7614
  if (!state) {
7056
7615
  const key = executionKey(workflow._tag, options.executionId);
7057
- if ((yield* store.get(key)) === void 0) yield* store.set(key, JSON.stringify({
7616
+ const now = Date.now();
7617
+ if (!((yield* store.begin(key, JSON.stringify({
7058
7618
  payload: options.payload,
7059
7619
  done: false,
7060
- startedAt: Date.now()
7061
- }));
7062
- state = {
7063
- payload: options.payload,
7064
- execute: entry.execute,
7065
- instance: WorkflowEngine$1.WorkflowInstance.initial(workflow, options.executionId),
7066
- interrupted: false,
7067
- interruptedUnsafe: false,
7068
- resumeRequested: void 0,
7069
- fiber: void 0,
7070
- done: Deferred.makeUnsafe(),
7071
- scope: Scope.makeUnsafe(),
7072
- parents: new Set(parentId === void 0 ? [] : [parentId])
7073
- };
7074
- executions.set(options.executionId, state);
7075
- yield* resume(options.executionId, "explicit");
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
+ }
7076
7644
  } else if (parentId !== void 0) state.parents.add(parentId);
7077
7645
  if (options.discard) return;
7078
- const instance = state.instance;
7079
- const exit = yield* Fiber.await(state.fiber);
7080
- if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause) && instance.suspended) return new Workflow$1.Suspended({});
7081
- return yield* exit;
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);
7082
7772
  });
7083
7773
  const engine = WorkflowEngine$1.makeUnsafe({
7084
7774
  register: Effect.fnUntraced(function* (workflow, execute) {
7085
- const entry = {
7775
+ workflows.set(workflow._tag, {
7086
7776
  workflow,
7087
7777
  execute,
7088
7778
  scope: yield* Effect.scope
7089
- };
7090
- workflows.set(workflow._tag, entry);
7091
- const prefix = executionKey(workflow._tag, "");
7092
- for (const { key, value } of yield* store.list(prefix)) {
7093
- const row = JSON.parse(value);
7094
- if (row.done) continue;
7095
- yield* start(workflow, {
7096
- executionId: key.slice(prefix.length),
7097
- payload: row.payload,
7098
- discard: true
7099
- });
7100
- }
7779
+ });
7780
+ yield* maintain;
7101
7781
  }),
7102
7782
  execute: start,
7103
- awaitComplete: (_workflow, executionId) => Effect.suspend(() => {
7783
+ awaitComplete: (workflow, executionId) => Effect.suspend(() => {
7104
7784
  const state = executions.get(executionId);
7105
- return state ? Deferred.await(state.done) : Effect.never;
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));
7106
7787
  }),
7107
7788
  interrupt: Effect.fnUntraced(function* (_workflow, executionId) {
7108
7789
  const state = executions.get(executionId);
@@ -7155,8 +7836,10 @@ function workflowEngine(database) {
7155
7836
  const id = `${instance.executionId}/${deferred.name}`;
7156
7837
  const known = deferredResults.get(id);
7157
7838
  if (known) return Option.some(known);
7158
- const saved = yield* store.get(deferredKey(instance.executionId, deferred.name));
7839
+ const key = deferredKey(instance.executionId, deferred.name);
7840
+ const saved = yield* store.get(key);
7159
7841
  if (saved === void 0) return Option.none();
7842
+ sawDeferred(key);
7160
7843
  const result = yield* decodeResult(saved);
7161
7844
  if (result._tag !== "Complete") return Option.none();
7162
7845
  deferredResults.set(id, result.exit);
@@ -7166,6 +7849,7 @@ function workflowEngine(database) {
7166
7849
  const id = `${options.executionId}/${options.deferredName}`;
7167
7850
  if (deferredResults.has(id)) return Effect.void;
7168
7851
  deferredResults.set(id, options.exit);
7852
+ sawDeferred(deferredKey(options.executionId, options.deferredName));
7169
7853
  const wake = Effect.andThen(deferredState.deferredDone(options.executionId, options.deferredName), resume(options.executionId, "automatic"));
7170
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));
7171
7855
  }),
@@ -7432,7 +8116,7 @@ const isPlainObject = (value) => typeof value === "object" && value !== null &&
7432
8116
  const readBody = (web) => web.method === "GET" || web.method === "HEAD" ? Effect.succeed(void 0) : Effect.gen(function* () {
7433
8117
  const text = yield* Effect.promise(() => web.clone().text());
7434
8118
  if (!text) return void 0;
7435
- if (!web.headers.get("content-type")?.includes("json")) return text;
8119
+ if (!web.headers.get("content-type")?.toLowerCase().includes("json")) return text;
7436
8120
  try {
7437
8121
  return JSON.parse(text);
7438
8122
  } catch {
@@ -7492,9 +8176,11 @@ const readInput = (route, action, web) => Effect.gen(function* () {
7492
8176
  };
7493
8177
  const bounded = route.bodyLimit !== void 0 && web.body ? yield* Effect.promise(() => readBounded(web.body, route.bodyLimit)) : void 0;
7494
8178
  if (route.bodyLimit !== void 0 && web.body && !bounded) return yield* tooLarge();
7495
- if (web.headers.get("content-type")?.startsWith("multipart/form-data")) {
8179
+ const contentType = web.headers.get("content-type") ?? "";
8180
+ const type = contentType.toLowerCase();
8181
+ if (type.startsWith("multipart/form-data")) {
7496
8182
  const form = yield* Effect.tryPromise({
7497
- try: () => (bounded ? new Response(bounded, { headers: { "content-type": web.headers.get("content-type") } }) : web).formData(),
8183
+ try: () => (bounded ? new Response(bounded, { headers: { "content-type": contentType } }) : web).formData(),
7498
8184
  catch: () => invalid$1(action.name, "input", [{
7499
8185
  path: "",
7500
8186
  message: "Body is not valid multipart/form-data"
@@ -7511,14 +8197,16 @@ const readInput = (route, action, web) => Effect.gen(function* () {
7511
8197
  const request = yield* HttpServerRequest.HttpServerRequest;
7512
8198
  const text = bounded ? new TextDecoder().decode(bounded) : yield* request.text;
7513
8199
  let body;
7514
- if (text) try {
7515
- body = JSON.parse(text);
8200
+ if (type.includes("json")) try {
8201
+ body = text ? JSON.parse(text) ?? void 0 : void 0;
7516
8202
  } catch {
7517
8203
  return yield* invalid$1(action.name, "input", [{
7518
8204
  path: "",
7519
8205
  message: "Body is not valid JSON"
7520
8206
  }]);
7521
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;
7522
8210
  return {
7523
8211
  input: Object.keys(params).length && (body === void 0 || isPlainObject(body)) ? {
7524
8212
  ...body,
@@ -7528,7 +8216,7 @@ const readInput = (route, action, web) => Effect.gen(function* () {
7528
8216
  };
7529
8217
  });
7530
8218
  /** The error an endpoint's handler failed with, as a 4xx the way a thrown `{ status }` is in core. */
7531
- const httpStatusError = (error) => !(error instanceof BrickError || error instanceof ValidationError) && error !== null && typeof error === "object" && "status" in error && typeof error.status === "number" && Number.isInteger(error.status) && error.status >= 400 && error.status < 500 ? new BrickError({
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({
7532
8220
  code: "HTTP_ERROR",
7533
8221
  message: "message" in error && typeof error.message === "string" ? error.message : "Endpoint error",
7534
8222
  status: error.status
@@ -7781,7 +8469,11 @@ function brick(options = {}) {
7781
8469
  traceId,
7782
8470
  requestId
7783
8471
  });
7784
- }).pipe(Effect.mapError(httpStatusError), Effect.provideContext(yield* runtime.contextEffect));
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));
7785
8477
  return HttpServerResponse.fromWeb(answer(result, set));
7786
8478
  }), {
7787
8479
  method: def.method,
@@ -8020,6 +8712,6 @@ function brick(options = {}) {
8020
8712
  };
8021
8713
  return app;
8022
8714
  }
8023
- export { PLUGIN_KIND as $, 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, toWireError 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, normalizeFailures as Xn, StorageUnavailableError as Xt, validatePath as Y, ValidationError as Yn, StorageError as Yt, setInternals as Z, toErrorResponse as Zn, SecretRef as Zt, idSchema as _, inlineAuditOptions as _n, databaseValue as _t, WORKFLOW_TABLE as a, definitionSite as an, getActionRoute as at, stopAllEvents as b, recordAudit as bn, idSchema$1 as bt, workflowEngine as c, ownDeps as cn, getActionAccess as ct, createMcpHandler as d, UploadedFile as dn, ORDERED_TYPES as dt, listSecrets as en, 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, Workflow 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 };
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 };
8024
8716
 
8025
- //# sourceMappingURL=server-D-fDM98-.js.map
8717
+ //# sourceMappingURL=server-B1gl742e.js.map