@orthograph/language-effect 0.0.0-stage → 0.1.0-next.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +2 -2
- package/dist/device.d.ts +5 -0
- package/dist/device.js +6 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +25 -0
- package/dist/modules/access/internal/path.d.ts +3 -0
- package/dist/modules/access/internal/path.js +11 -0
- package/dist/modules/access/service.d.ts +5 -0
- package/dist/modules/access/service.js +111 -0
- package/dist/modules/access/types.d.ts +38 -0
- package/dist/modules/access/types.js +3 -0
- package/dist/modules/auth/service.d.ts +4 -0
- package/dist/modules/auth/service.js +19 -0
- package/dist/modules/auth/types.d.ts +38 -0
- package/dist/modules/auth/types.js +8 -0
- package/dist/modules/calls/internal/run.d.ts +2 -0
- package/dist/modules/calls/internal/run.js +28 -0
- package/dist/modules/calls/service.d.ts +2 -0
- package/dist/modules/calls/service.js +2 -0
- package/dist/modules/calls/types.d.ts +32 -0
- package/dist/modules/calls/types.js +1 -0
- package/dist/modules/handler/internal/attributes.d.ts +17 -0
- package/dist/modules/handler/internal/attributes.js +46 -0
- package/dist/modules/handler/internal/call-id.d.ts +2 -0
- package/dist/modules/handler/internal/call-id.js +5 -0
- package/dist/modules/handler/internal/call-metrics.d.ts +17 -0
- package/dist/modules/handler/internal/call-metrics.js +35 -0
- package/dist/modules/handler/internal/decided.d.ts +14 -0
- package/dist/modules/handler/internal/decided.js +106 -0
- package/dist/modules/handler/internal/defect.d.ts +4 -0
- package/dist/modules/handler/internal/defect.js +19 -0
- package/dist/modules/handler/internal/derived.d.ts +21 -0
- package/dist/modules/handler/internal/derived.js +96 -0
- package/dist/modules/handler/internal/device.d.ts +3 -0
- package/dist/modules/handler/internal/device.js +46 -0
- package/dist/modules/handler/internal/digest.d.ts +3 -0
- package/dist/modules/handler/internal/digest.js +52 -0
- package/dist/modules/handler/internal/environment.d.ts +3 -0
- package/dist/modules/handler/internal/environment.js +3 -0
- package/dist/modules/handler/internal/invariants.d.ts +12 -0
- package/dist/modules/handler/internal/invariants.js +28 -0
- package/dist/modules/handler/internal/move.d.ts +32 -0
- package/dist/modules/handler/internal/move.js +84 -0
- package/dist/modules/handler/internal/prehandle.d.ts +23 -0
- package/dist/modules/handler/internal/prehandle.js +34 -0
- package/dist/modules/handler/internal/read.d.ts +3 -0
- package/dist/modules/handler/internal/read.js +79 -0
- package/dist/modules/handler/internal/signal.d.ts +3 -0
- package/dist/modules/handler/internal/signal.js +10 -0
- package/dist/modules/handler/internal/span.d.ts +8 -0
- package/dist/modules/handler/internal/span.js +14 -0
- package/dist/modules/handler/service.d.ts +7 -0
- package/dist/modules/handler/service.js +163 -0
- package/dist/modules/handler/types.d.ts +217 -0
- package/dist/modules/handler/types.js +24 -0
- package/dist/modules/ids/service.d.ts +2 -0
- package/dist/modules/ids/service.js +11 -0
- package/dist/modules/ids/types.d.ts +8 -0
- package/dist/modules/ids/types.js +1 -0
- package/dist/modules/journal/service.d.ts +6 -0
- package/dist/modules/journal/service.js +4 -0
- package/dist/modules/journal/types.d.ts +22 -0
- package/dist/modules/journal/types.js +5 -0
- package/dist/modules/mcp/internal/input.d.ts +15 -0
- package/dist/modules/mcp/internal/input.js +35 -0
- package/dist/modules/mcp/internal/output.d.ts +16 -0
- package/dist/modules/mcp/internal/output.js +50 -0
- package/dist/modules/mcp/internal/tool.d.ts +4 -0
- package/dist/modules/mcp/internal/tool.js +56 -0
- package/dist/modules/mcp/service.d.ts +2 -0
- package/dist/modules/mcp/service.js +38 -0
- package/dist/modules/mcp/types.d.ts +101 -0
- package/dist/modules/mcp/types.js +1 -0
- package/dist/modules/mount/internal/none.d.ts +2 -0
- package/dist/modules/mount/internal/none.js +1 -0
- package/dist/modules/mount/service.d.ts +2 -0
- package/dist/modules/mount/service.js +12 -0
- package/dist/modules/mount/types.d.ts +11 -0
- package/dist/modules/mount/types.js +4 -0
- package/dist/modules/principals/service.d.ts +4 -0
- package/dist/modules/principals/service.js +4 -0
- package/dist/modules/principals/types.d.ts +15 -0
- package/dist/modules/principals/types.js +4 -0
- package/dist/modules/records/internal/holder.d.ts +16 -0
- package/dist/modules/records/internal/holder.js +55 -0
- package/dist/modules/records/internal/list.d.ts +12 -0
- package/dist/modules/records/internal/list.js +65 -0
- package/dist/modules/records/internal/order.d.ts +18 -0
- package/dist/modules/records/internal/order.js +41 -0
- package/dist/modules/records/internal/unique.d.ts +31 -0
- package/dist/modules/records/internal/unique.js +49 -0
- package/dist/modules/records/internal/unit.d.ts +3 -0
- package/dist/modules/records/internal/unit.js +135 -0
- package/dist/modules/records/service.d.ts +22 -0
- package/dist/modules/records/service.js +102 -0
- package/dist/modules/records/types.d.ts +170 -0
- package/dist/modules/records/types.js +9 -0
- package/dist/modules/timers/internal/world.d.ts +4 -0
- package/dist/modules/timers/internal/world.js +64 -0
- package/dist/modules/timers/service.d.ts +18 -0
- package/dist/modules/timers/service.js +125 -0
- package/dist/modules/timers/types.d.ts +102 -0
- package/dist/modules/timers/types.js +40 -0
- package/dist/modules/versions/internal/handlers.d.ts +6 -0
- package/dist/modules/versions/internal/handlers.js +36 -0
- package/dist/modules/versions/internal/keep.d.ts +21 -0
- package/dist/modules/versions/internal/keep.js +36 -0
- package/dist/modules/versions/service.d.ts +2 -0
- package/dist/modules/versions/service.js +14 -0
- package/dist/modules/versions/types.d.ts +27 -0
- package/dist/modules/versions/types.js +1 -0
- package/dist/modules/visibility/internal/rule.d.ts +7 -0
- package/dist/modules/visibility/internal/rule.js +23 -0
- package/dist/modules/visibility/internal/schema.d.ts +5 -0
- package/dist/modules/visibility/internal/schema.js +12 -0
- package/dist/modules/visibility/service.d.ts +15 -0
- package/dist/modules/visibility/service.js +27 -0
- package/dist/modules/visibility/types.d.ts +60 -0
- package/dist/modules/visibility/types.js +1 -0
- package/dist/modules/wire/internal/call-telemetry.d.ts +15 -0
- package/dist/modules/wire/internal/call-telemetry.js +31 -0
- package/dist/modules/wire/internal/refused-payload.d.ts +7 -0
- package/dist/modules/wire/internal/refused-payload.js +25 -0
- package/dist/modules/wire/internal/shown.d.ts +9 -0
- package/dist/modules/wire/internal/shown.js +32 -0
- package/dist/modules/wire/service.d.ts +3 -0
- package/dist/modules/wire/service.js +14 -0
- package/dist/modules/wire/types.d.ts +30 -0
- package/dist/modules/wire/types.js +1 -0
- package/dist/modules/work/internal/fake-world.d.ts +17 -0
- package/dist/modules/work/internal/fake-world.js +43 -0
- package/dist/modules/work/internal/fibers.d.ts +2 -0
- package/dist/modules/work/internal/fibers.js +5 -0
- package/dist/modules/work/service.d.ts +6 -0
- package/dist/modules/work/service.js +249 -0
- package/dist/modules/work/types.d.ts +103 -0
- package/dist/modules/work/types.js +19 -0
- package/dist/visibility.d.ts +1 -0
- package/dist/visibility.js +3 -0
- package/package.json +34 -3
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// What a span may say about a call, from the declaration's visibility and text opt-in (O2).
|
|
2
|
+
import { BigDecimal } from "effect";
|
|
3
|
+
import { decimalText } from "orthograph/server";
|
|
4
|
+
import { Audience, Visibility } from "#modules/visibility/service.js";
|
|
5
|
+
// A bigint reads as its digits and a decimal as its wire text, also inside JSON. The replacer reads a decimal from its
|
|
6
|
+
// holder, since the value it is given is already the BigDecimal's `toJSON` object.
|
|
7
|
+
const text = (v) => typeof v === "string" ? v
|
|
8
|
+
: typeof v === "bigint" ? v.toString()
|
|
9
|
+
: BigDecimal.isBigDecimal(v) ? decimalText(v)
|
|
10
|
+
: JSON.stringify(v, function (k, x) {
|
|
11
|
+
const held = this[k];
|
|
12
|
+
return BigDecimal.isBigDecimal(held) ? decimalText(held) : typeof x === "bigint" ? x.toString() : x;
|
|
13
|
+
});
|
|
14
|
+
const canTrace = (key, fields) => Object.hasOwn(fields, key) && Visibility.sees(Audience.telemetry, fields[key]);
|
|
15
|
+
const tracedEntries = (values, fields) => Object.entries(values).filter(([k]) => canTrace(k, fields));
|
|
16
|
+
/** A payload as span attributes: `payload.<field>`, every value as text so bigints and ids read the same everywhere. */
|
|
17
|
+
export const payloadAttributes = (payload, fields) => Object.fromEntries(tracedEntries(payload, fields).map(([k, v]) => [`payload.${k}`, text(v)]));
|
|
18
|
+
/**
|
|
19
|
+
* Who called, on every span of a call: the kind, the way in a person or agent used, and what names them (M2-auth, "Smaller calls" 2).
|
|
20
|
+
* A refused call names its kind and way in, never the person (G8); an accepted one of a person or an agent also names the person.
|
|
21
|
+
*/
|
|
22
|
+
export const principalAttributes = (principal, refused = false) => ({
|
|
23
|
+
"principal.kind": principal.kind,
|
|
24
|
+
...("via" in principal ? { "principal.via": principal.via } : {}),
|
|
25
|
+
...(!refused && "person" in principal ? { "principal.person": principal.person } : {}),
|
|
26
|
+
...(principal.kind === "service" ? { "principal.mount": principal.mount } : {}),
|
|
27
|
+
});
|
|
28
|
+
/** The request key a call was made with, as the caller sent it (never the store's `<op>|<who>|<key>`): an id, so traced. Only a key the operation honours (M1.12a). */
|
|
29
|
+
export const requestAttributes = (request) => (request === undefined ? {} : { "request.key": request });
|
|
30
|
+
/**
|
|
31
|
+
* An answer as span attributes, `answer.<field>`, kept as it came (a number stays a number) so a wrong shape shows.
|
|
32
|
+
* A list's `items` are whole instances, so each is cut down to the thing's traceable fields (and `state`) first.
|
|
33
|
+
*/
|
|
34
|
+
export const answerAttributes = (answer, fields, items) => {
|
|
35
|
+
if (typeof answer !== "object" || answer === null)
|
|
36
|
+
return {};
|
|
37
|
+
const shown = (k, v) => k === "items" && items !== undefined && Array.isArray(v)
|
|
38
|
+
? v.map((i) => Object.fromEntries(Object.entries(i).filter(([f]) => f === "state" || canTrace(f, items))))
|
|
39
|
+
: v;
|
|
40
|
+
return Object.fromEntries(tracedEntries(answer, fields).map(([k, v]) => {
|
|
41
|
+
const x = shown(k, v);
|
|
42
|
+
return [`answer.${k}`, typeof x === "bigint" || typeof x === "object" ? text(x) : x];
|
|
43
|
+
}));
|
|
44
|
+
};
|
|
45
|
+
/** Whether a field of an event may be written to the journal. */
|
|
46
|
+
export const journalled = (fields, key) => Object.hasOwn(fields, key) && Visibility.sees(Audience.public, fields[key]);
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// The name of one call (O3): made once, before its first attempt, from Effect's own Random (so a world can seed it), and written on every
|
|
2
|
+
// span of the call's attempts as `call.id`. A reader groups attempts by it; nothing else in a trace says which attempts belong together.
|
|
3
|
+
import { Ids } from "#modules/ids/service.js";
|
|
4
|
+
export const CALL_ID = "call.id";
|
|
5
|
+
export const newCallId = Ids.make("call");
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Context, Effect } from "effect";
|
|
2
|
+
import type { Principal } from "orthograph";
|
|
3
|
+
type Outcome = {
|
|
4
|
+
readonly outcome: "answered" | "defect";
|
|
5
|
+
} | {
|
|
6
|
+
readonly outcome: "refused";
|
|
7
|
+
readonly refusal: string;
|
|
8
|
+
};
|
|
9
|
+
/** The HTTP decoder and the wrapper share this marker during one routed request. */
|
|
10
|
+
export declare const RoutedCall: Context.Reference<{
|
|
11
|
+
readonly operation: string;
|
|
12
|
+
started: boolean;
|
|
13
|
+
} | undefined>;
|
|
14
|
+
export declare const recordCall: (operation: string, kind: Principal["kind"] | "unknown", start: bigint, outcome: Outcome, budgetMs?: number) => Effect.Effect<void, never, never>;
|
|
15
|
+
/** Wrap the whole call, including decoding when this wrapper owns it and all internal attempts. */
|
|
16
|
+
export declare const measureCall: (operation: string, principal: Principal, refusals: ReadonlySet<string>, budgetMs?: number) => <A, E, R>(work: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
|
|
17
|
+
export {};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { Cause, Clock, Context, Effect, Exit, Metric, Option } from "effect";
|
|
2
|
+
const calls = Metric.counter("ortho.calls", { incremental: true });
|
|
3
|
+
const duration = Metric.histogram("ortho.call.duration", {
|
|
4
|
+
attributes: { unit: "ms" },
|
|
5
|
+
boundaries: [1, 5, 10, 25, 50, 75, 100, 125, 150, 200, 300, 500, 1000, 2000, 5000],
|
|
6
|
+
});
|
|
7
|
+
/** The HTTP decoder and the wrapper share this marker during one routed request. */
|
|
8
|
+
export const RoutedCall = Context.Reference("@orthograph/language-effect/RoutedCall", { defaultValue: () => undefined });
|
|
9
|
+
/** One per call that took longer than its operation's declared `budget.p95`: a target for review, never a failure. */
|
|
10
|
+
const breaches = Metric.counter("ortho.budget.breaches", { incremental: true });
|
|
11
|
+
export const recordCall = (operation, kind, start, outcome, budgetMs) => Effect.gen(function* () {
|
|
12
|
+
const end = yield* Clock.monotonicTimeNanos;
|
|
13
|
+
const took = Number(end - start) / 1e6;
|
|
14
|
+
yield* Metric.update(Metric.withAttributes(calls, { operation, "principal.kind": kind, ...outcome }), 1);
|
|
15
|
+
yield* Metric.update(Metric.withAttributes(duration, { operation }), took);
|
|
16
|
+
if (budgetMs !== undefined && took > budgetMs)
|
|
17
|
+
yield* Metric.update(Metric.withAttributes(breaches, { operation }), 1);
|
|
18
|
+
});
|
|
19
|
+
const outcomeOf = (exit, refusals) => {
|
|
20
|
+
if (Exit.isSuccess(exit))
|
|
21
|
+
return { outcome: "answered" };
|
|
22
|
+
if (Cause.hasDies(exit.cause))
|
|
23
|
+
return { outcome: "defect" };
|
|
24
|
+
const failure = Option.getOrUndefined(Cause.findErrorOption(exit.cause));
|
|
25
|
+
const tag = typeof failure === "object" && failure !== null && "_tag" in failure ? failure._tag : undefined;
|
|
26
|
+
return typeof tag === "string" && refusals.has(tag) ? { outcome: "refused", refusal: tag } : { outcome: "defect" };
|
|
27
|
+
};
|
|
28
|
+
/** Wrap the whole call, including decoding when this wrapper owns it and all internal attempts. */
|
|
29
|
+
export const measureCall = (operation, principal, refusals, budgetMs) => (work) => Effect.gen(function* () {
|
|
30
|
+
const routed = yield* RoutedCall;
|
|
31
|
+
if (routed?.operation === operation)
|
|
32
|
+
routed.started = true;
|
|
33
|
+
const start = yield* Clock.monotonicTimeNanos;
|
|
34
|
+
return yield* work.pipe(Effect.onExit((exit) => recordCall(operation, principal.kind, start, outcomeOf(exit, refusals), budgetMs)));
|
|
35
|
+
});
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import type { FieldsInput } from "orthograph";
|
|
3
|
+
import type { Records } from "#modules/records/types.js";
|
|
4
|
+
/**
|
|
5
|
+
* Run `work` with a logger that remembers the last message, redacting what the telemetry audience is not shown before it
|
|
6
|
+
* becomes an attribute: every payload field the declaration does not let out, and the value of any field the handler loads or writes that the declaration
|
|
7
|
+
* does not let out, of any type and length (found by value in the message, and by the field's name or value in its
|
|
8
|
+
* annotations). `last` reads it afterwards. One per attempt, so a retried attempt never sees an earlier attempt's log.
|
|
9
|
+
*/
|
|
10
|
+
export declare const recordingLogs: (payload: object, fields: FieldsInput) => Effect.Effect<{
|
|
11
|
+
around: <A, E, R>(work: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, never>>;
|
|
12
|
+
last: Effect.Effect<string | undefined, never, never>;
|
|
13
|
+
watching: (records: Records["Service"]) => Records["Service"];
|
|
14
|
+
}, never, never>;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// The log that decided a refusal: the last thing the handler logged before it refused, written on the operation's span.
|
|
2
|
+
// And the logs' side of the one visibility rule: a value the telemetry audience is not shown never reaches a logger.
|
|
3
|
+
import { Effect, Logger } from "effect";
|
|
4
|
+
import { CurrentLogAnnotations } from "effect/References";
|
|
5
|
+
import { traceable } from "orthograph/server";
|
|
6
|
+
const text = (message) => Array.isArray(message) ? message.map(text).join(" ") : typeof message === "string" ? message : JSON.stringify(message) ?? String(message);
|
|
7
|
+
/** A value this short or this plain (a flag, a count) is hidden only as a whole word: it would garble every line holding it. */
|
|
8
|
+
const SHORT = 3;
|
|
9
|
+
const escaped = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
10
|
+
const word = "[A-Za-z0-9_]";
|
|
11
|
+
/** What a value looks like inside a log line: text and numbers as themselves, a flag as its word, an object as its JSON and its parts. */
|
|
12
|
+
const appearances = (value, nested = false) => {
|
|
13
|
+
if (typeof value === "string")
|
|
14
|
+
return value.length === 0 ? [] : [{ text: value, whole: value.length < SHORT }, ...(value === JSON.stringify(value).slice(1, -1) ? [] : [{ text: JSON.stringify(value).slice(1, -1), whole: value.length < SHORT }])];
|
|
15
|
+
if (typeof value === "number" || typeof value === "bigint")
|
|
16
|
+
return [{ text: String(value), whole: String(value).length < SHORT }];
|
|
17
|
+
// A flag inside an object is covered by the object's JSON: hidden alone it would redact every "true" in the line.
|
|
18
|
+
if (typeof value === "boolean")
|
|
19
|
+
return nested ? [] : [{ text: String(value), whole: true }];
|
|
20
|
+
if (typeof value !== "object" || value === null)
|
|
21
|
+
return [];
|
|
22
|
+
const json = JSON.stringify(value, (_, v) => (typeof v === "bigint" ? v.toString() : v));
|
|
23
|
+
return [{ text: json, whole: false }, { text: JSON.stringify(json).slice(1, -1), whole: false },
|
|
24
|
+
...Object.values(value).flatMap((part) => appearances(part, true))];
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Run `work` with a logger that remembers the last message, redacting what the telemetry audience is not shown before it
|
|
28
|
+
* becomes an attribute: every payload field the declaration does not let out, and the value of any field the handler loads or writes that the declaration
|
|
29
|
+
* does not let out, of any type and length (found by value in the message, and by the field's name or value in its
|
|
30
|
+
* annotations). `last` reads it afterwards. One per attempt, so a retried attempt never sees an earlier attempt's log.
|
|
31
|
+
*/
|
|
32
|
+
export const recordingLogs = (payload, fields) => Effect.sync(() => {
|
|
33
|
+
const hidden = [];
|
|
34
|
+
const hiddenKeys = new Set();
|
|
35
|
+
const hide = (values) => {
|
|
36
|
+
for (const v of values)
|
|
37
|
+
if (!hidden.some((h) => h.text === v.text && h.whole === v.whole))
|
|
38
|
+
hidden.push(v);
|
|
39
|
+
hidden.sort((a, b) => b.text.length - a.text.length);
|
|
40
|
+
};
|
|
41
|
+
for (const [key, value] of Object.entries(payload)) {
|
|
42
|
+
if (!Object.hasOwn(fields, key) || traceable(fields[key]))
|
|
43
|
+
continue;
|
|
44
|
+
hiddenKeys.add(key);
|
|
45
|
+
// Text is found as a substring; anything else follows `appearances`' own rules.
|
|
46
|
+
hide(appearances(value).map((h) => (typeof value === "string" ? { ...h, whole: false } : h)));
|
|
47
|
+
}
|
|
48
|
+
/** What a handler loads or stores of a thing, so far as the declaration keeps it out of telemetry, is hidden. */
|
|
49
|
+
const learn = (thing, values) => {
|
|
50
|
+
for (const [key, value] of Object.entries(values)) {
|
|
51
|
+
if (Object.hasOwn(thing.fields, key) && !traceable(thing.fields[key])) {
|
|
52
|
+
hiddenKeys.add(key);
|
|
53
|
+
hide(appearances(value));
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
const watching = (records) => ({
|
|
58
|
+
find: (thing, id) => records.find(thing, id).pipe(Effect.tap((found) => Effect.sync(() => { if (found)
|
|
59
|
+
learn(thing, found); }))),
|
|
60
|
+
findBy: ((rule, value) => {
|
|
61
|
+
// `findBy(rule, value)` (G5): the thing is the rule's key's.
|
|
62
|
+
const thing = rule.fields[0].of;
|
|
63
|
+
return records.findBy(rule, value).pipe(Effect.tap((found) => Effect.sync(() => { if (found)
|
|
64
|
+
learn(thing, found); })));
|
|
65
|
+
}),
|
|
66
|
+
list: (query) => records.list(query).pipe(Effect.tap(({ items }) => Effect.sync(() => { for (const found of items)
|
|
67
|
+
learn(query.thing, found); }))),
|
|
68
|
+
insert: (thing, values, state) => { learn(thing, values); return records.insert(thing, values, state); },
|
|
69
|
+
update: (thing, id, changes, state) => { learn(thing, changes); return records.update(thing, id, changes, state); },
|
|
70
|
+
});
|
|
71
|
+
const redact = (line) => hidden.reduce((out, h) => h.whole ? out.replace(new RegExp(`(?<!${word})${escaped(h.text)}(?!${word})`, "g"), "[redacted]") : out.replaceAll(h.text, "[redacted]"), line);
|
|
72
|
+
// Each part of a message: a string redacted in place, anything else that holds hidden text replaced by its redacted text.
|
|
73
|
+
const scrub = (message) => Array.isArray(message) ? message.map(scrub)
|
|
74
|
+
: typeof message === "string" ? redact(message)
|
|
75
|
+
: hidden.length > 0 && redact(text(message)) !== text(message) ? redact(text(message)) : message;
|
|
76
|
+
const seen = { last: undefined };
|
|
77
|
+
// A step signal (K5 seam 10) is evidence for the portal, never the log that decided a refusal.
|
|
78
|
+
const recorder = Logger.make(({ message, fiber }) => {
|
|
79
|
+
const annotations = fiber.getRef(CurrentLogAnnotations);
|
|
80
|
+
if ("step" in annotations && "phase" in annotations)
|
|
81
|
+
return;
|
|
82
|
+
seen.last = text(scrub(message));
|
|
83
|
+
});
|
|
84
|
+
// The annotations an exporter reads from the fiber, with their values redacted too.
|
|
85
|
+
const annotated = (fiber) => new Proxy(fiber, {
|
|
86
|
+
get: (target, property) => {
|
|
87
|
+
const value = Reflect.get(target, property);
|
|
88
|
+
if (property !== "getRef")
|
|
89
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
90
|
+
return (ref) => {
|
|
91
|
+
const got = value.call(target, ref);
|
|
92
|
+
// An annotation named for a hidden field is replaced whole, so a value too short to find in text is still kept out.
|
|
93
|
+
return ref === CurrentLogAnnotations && hidden.length > 0
|
|
94
|
+
? Object.fromEntries(Object.entries(got).map(([k, v]) => [k, hiddenKeys.has(k) ? "[redacted]" : scrub(v)]))
|
|
95
|
+
: got;
|
|
96
|
+
};
|
|
97
|
+
},
|
|
98
|
+
});
|
|
99
|
+
// Every logger sees the redacted message, the exporters included, never only the recorder (M1.19).
|
|
100
|
+
const redacting = (logger) => Logger.make((options) => logger.log({ ...options, message: scrub(options.message), fiber: annotated(options.fiber) }));
|
|
101
|
+
const around = (work) => Effect.gen(function* () {
|
|
102
|
+
const current = yield* Logger.CurrentLoggers;
|
|
103
|
+
return yield* Effect.provideService(work, Logger.CurrentLoggers, new Set([...[...current].map(redacting), recorder]));
|
|
104
|
+
});
|
|
105
|
+
return { around, last: Effect.sync(() => seen.last), watching };
|
|
106
|
+
});
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { Cause } from "effect";
|
|
2
|
+
export declare const defectAttributes: (cause: Cause.Cause<unknown>) => Record<string, string>;
|
|
3
|
+
/** The tag alone, for the span a defect passes through (a step's, a commit's): it is what lets a reader tell the step that carried this call's failure from one that errored and was recovered. */
|
|
4
|
+
export declare const defectTag: (cause: Cause.Cause<unknown>) => Record<string, string>;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// What a defect writes on the span it ends as an error: the first line of its cause (`defect`), and the error's tag (`error.tag`, M1.49), which is what an
|
|
2
|
+
// issue is grouped by (K18). The first line of a cause is `Error: ...` and names no tag; the tag is the error's `_tag`, else its constructor's name, else `Error`.
|
|
3
|
+
// A value, a statement or a payload never reaches it: the tag is a name, and the line is what it always was.
|
|
4
|
+
import { Cause } from "effect";
|
|
5
|
+
const tagOf = (error) => {
|
|
6
|
+
if (typeof error !== "object" || error === null)
|
|
7
|
+
return "Error";
|
|
8
|
+
const tag = error._tag;
|
|
9
|
+
if (typeof tag === "string" && tag !== "")
|
|
10
|
+
return tag;
|
|
11
|
+
const name = error.constructor?.name;
|
|
12
|
+
return typeof name === "string" && name !== "" && name !== "Object" ? name : "Error";
|
|
13
|
+
};
|
|
14
|
+
export const defectAttributes = (cause) => ({
|
|
15
|
+
defect: Cause.pretty(cause).split("\n")[0] ?? "",
|
|
16
|
+
"error.tag": tagOf(Cause.squash(cause)),
|
|
17
|
+
});
|
|
18
|
+
/** The tag alone, for the span a defect passes through (a step's, a commit's): it is what lets a reader tell the step that carried this call's failure from one that errored and was recovered. */
|
|
19
|
+
export const defectTag = (cause) => ({ "error.tag": tagOf(Cause.squash(cause)) });
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import { NotAllowed, type AnyDerive, type Read } from "orthograph";
|
|
3
|
+
import { Store, type Instance } from "#modules/records/types.js";
|
|
4
|
+
import { ReadNotServed, type ReadAnswer } from "../types.ts";
|
|
5
|
+
/** How many roots a page of a derived list reads before it stops, kept or not (GOAL17-derived-reads, section 6). */
|
|
6
|
+
export declare const SCAN = 200;
|
|
7
|
+
/** A cursor is the position of the last instance of the page before; anything else is not one this read handed out. */
|
|
8
|
+
export declare const CURSOR: RegExp;
|
|
9
|
+
/** Does the derive look at something a store cannot list (the problems every plugin declares)? Such a read is not served yet. */
|
|
10
|
+
export declare const unserved: (derive: AnyDerive) => boolean;
|
|
11
|
+
/** The root with the fields a derive adds, worked out now. */
|
|
12
|
+
export declare const withAdds: (derive: AnyDerive, root: Instance) => Effect.Effect<Instance, never, Store>;
|
|
13
|
+
/**
|
|
14
|
+
* A page of a derived list, in steps: a page of roots from the store (stored `where` and `state`), each worked out, those that
|
|
15
|
+
* hold what `only` pins and the filters on derived fields kept. It reads roots until the page is full, the roots end, or `SCAN`
|
|
16
|
+
* roots have been read. So a page can hold fewer rows than `page` and still have a `next`: a caller keeps going until `next` is null.
|
|
17
|
+
*/
|
|
18
|
+
export declare const derivedPage: (read: Read<any, any, any>, payload: ReadAnswer) => Effect.Effect<ReadAnswer, NotAllowed, Store>;
|
|
19
|
+
/** A read by id whose answer adds what a derive works out. */
|
|
20
|
+
export declare const derivedOne: (read: Read<any, any, any>, root: Instance) => Effect.Effect<ReadAnswer, never, Store>;
|
|
21
|
+
export declare const notServed: (name: string) => ReadNotServed;
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// A derived read (GOAL17-derived-reads): the records it looks at, then the pure function that works its answer out. Nothing is
|
|
2
|
+
// kept: each call reads the records again, so an answer never drifts from them.
|
|
3
|
+
import { Effect, Option, Schema } from "effect";
|
|
4
|
+
import { NotAllowed } from "orthograph";
|
|
5
|
+
import { Store } from "#modules/records/types.js";
|
|
6
|
+
import { ReadNotServed } from "../types.js";
|
|
7
|
+
/** How many roots a page of a derived list reads before it stops, kept or not (GOAL17-derived-reads, section 6). */
|
|
8
|
+
export const SCAN = 200;
|
|
9
|
+
/** A cursor is the position of the last instance of the page before; anything else is not one this read handed out. */
|
|
10
|
+
export const CURSOR = /^[0-9]{1,15}$/;
|
|
11
|
+
const isLook = (l) => typeof l === "object" && l !== null && l.kind === "look";
|
|
12
|
+
/** Does the derive look at something a store cannot list (the problems every plugin declares)? Such a read is not served yet. */
|
|
13
|
+
export const unserved = (derive) => Object.values(derive.looks).some((l) => !isLook(l));
|
|
14
|
+
/** What each look finds for one root: its newest record or none, or the newest few. Looked up by the field that holds the root's id. */
|
|
15
|
+
const found = (derive, root) => Effect.gen(function* () {
|
|
16
|
+
const store = yield* Store;
|
|
17
|
+
const out = {};
|
|
18
|
+
for (const [name, look] of Object.entries(derive.looks)) {
|
|
19
|
+
const l = look;
|
|
20
|
+
const listed = yield* store.list({
|
|
21
|
+
thing: l.thing,
|
|
22
|
+
where: { ...(l.where ?? {}), [l.by.key]: root["id"] },
|
|
23
|
+
state: l.state,
|
|
24
|
+
order: "newest",
|
|
25
|
+
limit: l.take === "newest" ? 1 : l.max,
|
|
26
|
+
after: undefined,
|
|
27
|
+
});
|
|
28
|
+
out[name] = l.take === "newest" ? listed.items[0] : listed.items;
|
|
29
|
+
}
|
|
30
|
+
return out;
|
|
31
|
+
});
|
|
32
|
+
/** The root with the fields a derive adds, worked out now. */
|
|
33
|
+
export const withAdds = (derive, root) => Effect.gen(function* () {
|
|
34
|
+
const looked = yield* found(derive, root);
|
|
35
|
+
const adds = derive.is(root, looked);
|
|
36
|
+
return { ...root, ...adds };
|
|
37
|
+
});
|
|
38
|
+
const listed = (item) => ({ ...item, state: item.state ?? "none" });
|
|
39
|
+
/** A derived field's value as its schema writes it on the wire, as text; none when the schema doesn't take it (an unset optional). */
|
|
40
|
+
const wireOf = (derive, field, value) => {
|
|
41
|
+
const encoded = Schema.encodeUnknownOption(derive.adds[field].schema)(value);
|
|
42
|
+
return Option.isSome(encoded) && encoded.value !== undefined ? JSON.stringify(encoded.value) : undefined;
|
|
43
|
+
};
|
|
44
|
+
/** Does a worked-out row hold the values a read pins, and the filters its caller gave on derived fields? Equal when written alike. */
|
|
45
|
+
const matches = (derive, row, wanted) => Object.entries(wanted).every(([k, v]) => {
|
|
46
|
+
const held = wireOf(derive, k, row[k]);
|
|
47
|
+
return held !== undefined && held === wireOf(derive, k, v);
|
|
48
|
+
});
|
|
49
|
+
/**
|
|
50
|
+
* A page of a derived list, in steps: a page of roots from the store (stored `where` and `state`), each worked out, those that
|
|
51
|
+
* hold what `only` pins and the filters on derived fields kept. It reads roots until the page is full, the roots end, or `SCAN`
|
|
52
|
+
* roots have been read. So a page can hold fewer rows than `page` and still have a `next`: a caller keeps going until `next` is null.
|
|
53
|
+
*/
|
|
54
|
+
export const derivedPage = (read, payload) => Effect.gen(function* () {
|
|
55
|
+
const derive = read.derive;
|
|
56
|
+
const store = yield* Store;
|
|
57
|
+
const { cursor, state, ...filters } = payload;
|
|
58
|
+
if (cursor !== undefined && !CURSOR.test(cursor))
|
|
59
|
+
return yield* new NotAllowed();
|
|
60
|
+
const pinned = (read.only ?? {});
|
|
61
|
+
const wanted = { ...Object.fromEntries(Object.entries(filters).filter(([k, v]) => read.where.includes(k) && v !== undefined)), ...pinned };
|
|
62
|
+
const storedFields = read.thing.fields;
|
|
63
|
+
const storedWhere = Object.fromEntries(Object.entries(wanted).filter(([k]) => k in storedFields && k !== "state"));
|
|
64
|
+
const derivedWhere = Object.fromEntries(Object.entries(wanted).filter(([k]) => !(k in storedFields) && k !== "state"));
|
|
65
|
+
const wantedState = wanted["state"] ?? state;
|
|
66
|
+
const size = read.page ?? 50;
|
|
67
|
+
const kept = [];
|
|
68
|
+
let after = cursor;
|
|
69
|
+
let next = null;
|
|
70
|
+
let scanned = 0;
|
|
71
|
+
while (kept.length < size && scanned < SCAN) {
|
|
72
|
+
const roots = yield* store.list({
|
|
73
|
+
thing: read.thing, where: storedWhere, state: wantedState, order: read.order ?? "newest",
|
|
74
|
+
limit: Math.min(size - kept.length, SCAN - scanned), after,
|
|
75
|
+
});
|
|
76
|
+
scanned += roots.items.length;
|
|
77
|
+
for (const root of roots.items) {
|
|
78
|
+
const row = yield* withAdds(derive, root);
|
|
79
|
+
if (matches(derive, row, derivedWhere))
|
|
80
|
+
kept.push(listed(row));
|
|
81
|
+
}
|
|
82
|
+
next = roots.next;
|
|
83
|
+
after = roots.next ?? undefined;
|
|
84
|
+
if (roots.next === null)
|
|
85
|
+
break;
|
|
86
|
+
}
|
|
87
|
+
return { items: kept, next };
|
|
88
|
+
});
|
|
89
|
+
/** A read by id whose answer adds what a derive works out. */
|
|
90
|
+
export const derivedOne = (read, root) => Effect.gen(function* () {
|
|
91
|
+
const row = yield* withAdds(read.derive, root);
|
|
92
|
+
const names = [...read.fields, ...Object.keys(read.derive.adds)];
|
|
93
|
+
// As a plain read by id: an optional field, the thing's or an add, with no value is left out (#1018).
|
|
94
|
+
return Object.fromEntries(names.map((f) => [f, f === "state" ? (root.state ?? "none") : row[f]]).filter(([, v]) => v !== undefined));
|
|
95
|
+
});
|
|
96
|
+
export const notServed = (name) => new ReadNotServed({ read: name, message: `${name}: a derive that looks at problems is not served yet` });
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// An operation that runs on the device (M1.27): the same handler, steps and spans as a served one, in the caller's own
|
|
2
|
+
// process, with no store, no journal and no one to ask who is calling. Its spans leave as OTLP/HTTP from here, and are
|
|
3
|
+
// flushed before the call returns, because a CLI may exit the moment it does.
|
|
4
|
+
import { Cause, Effect, Layer, Schema } from "effect";
|
|
5
|
+
import { FetchHttpClient } from "effect/http";
|
|
6
|
+
import { OtlpLogger, OtlpSerialization, OtlpTracer } from "effect/observability";
|
|
7
|
+
import { answerAttributes, payloadAttributes, principalAttributes } from "./attributes.js";
|
|
8
|
+
import { CALL_ID, newCallId } from "./call-id.js";
|
|
9
|
+
import { spanned } from "./span.js";
|
|
10
|
+
import { cutAnswer } from "#modules/visibility/service.js";
|
|
11
|
+
import { defectAttributes } from "./defect.js";
|
|
12
|
+
/** On a device nobody can say who is calling, so every caller is anonymous and an operation is open to anyone. */
|
|
13
|
+
const principal = { kind: "anonymous" };
|
|
14
|
+
/**
|
|
15
|
+
* The spans of one call, and the logs written inside them (the log that decided a refusal is one, and the explainability
|
|
16
|
+
* eval looks for it), sent to the collector at `otlp`; closing the layer is the flush.
|
|
17
|
+
*/
|
|
18
|
+
const exporter = (otlp, service) => {
|
|
19
|
+
const base = otlp.replace(/\/+$/, "");
|
|
20
|
+
const options = { resource: { serviceName: service }, exportInterval: "100 millis", maxBatchSize: 64, shutdownTimeout: "3 seconds" };
|
|
21
|
+
return Layer.mergeAll(OtlpTracer.layer({ url: `${base}/v1/traces`, ...options }), OtlpLogger.layer({ url: `${base}/v1/logs`, ...options })).pipe(Layer.provide(OtlpSerialization.layerJson), Layer.provide(FetchHttpClient.layer));
|
|
22
|
+
};
|
|
23
|
+
const tagOf = (e) => typeof e === "object" && e !== null && typeof e._tag === "string" ? e._tag : String(e);
|
|
24
|
+
const device = ({ name, operation, handler }) => {
|
|
25
|
+
const op = operation;
|
|
26
|
+
const check = Schema.encodeEffect(op.answerSchema);
|
|
27
|
+
// Every step is its own span, marked with its kind, as a served operation's are.
|
|
28
|
+
const steps = Object.fromEntries(Object.entries(op.steps).map(([key, step]) => [key, (work) => spanned(`${name}.${key}`, { "step.kind": step.type })(work)]));
|
|
29
|
+
const move = () => Effect.void;
|
|
30
|
+
return {
|
|
31
|
+
name,
|
|
32
|
+
run: (payload, where) => Effect.flatMap(newCallId, (callId) => Effect.gen(function* () {
|
|
33
|
+
yield* Effect.annotateCurrentSpan(payloadAttributes(payload, op.payload));
|
|
34
|
+
const answer = yield* handler(payload, { principal, steps, refs: {}, move });
|
|
35
|
+
yield* Effect.annotateCurrentSpan(answerAttributes(answer, op.answer));
|
|
36
|
+
// An answer that breaks its declaration is the handler's bug: it dies, loudly.
|
|
37
|
+
yield* check(answer).pipe(Effect.mapError((e) => new Error(`${name} answered outside its declaration: ${e.message}`)), Effect.orDie);
|
|
38
|
+
// A device has no roles to hold: its caller is shown what the one rule shows a caller with none.
|
|
39
|
+
return cutAnswer(op, answer, []);
|
|
40
|
+
}).pipe(Effect.tapCause((cause) => Cause.hasDies(cause)
|
|
41
|
+
? Effect.annotateCurrentSpan(defectAttributes(cause))
|
|
42
|
+
: Effect.annotateCurrentSpan({ refusal: tagOf(Cause.squash(cause)) })), spanned(name, { operation: name, [CALL_ID]: callId, ...principalAttributes(principal) }), where.otlp === undefined ? (effect) => effect : Effect.provide(exporter(where.otlp, where.service)))),
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
/** Typed at the edge (`DeviceApi`); inside, one untyped implementation serves every operation. */
|
|
46
|
+
export const Device = { serve: device };
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// A SHA-256 of a call's payload, kept beside the answer stored for its request key: pure, so it runs in any host and needs no clock.
|
|
2
|
+
const K = Array.from({ length: 64 }, (_, i) => {
|
|
3
|
+
let n = 2, count = 0;
|
|
4
|
+
const primes = [];
|
|
5
|
+
for (; primes.length <= i; n++) {
|
|
6
|
+
if (primes.every((p) => n % p !== 0))
|
|
7
|
+
primes.push(n);
|
|
8
|
+
}
|
|
9
|
+
count = primes[i];
|
|
10
|
+
return Math.floor((Math.cbrt(count) % 1) * 2 ** 32) >>> 0;
|
|
11
|
+
});
|
|
12
|
+
const H0 = [2, 3, 5, 7, 11, 13, 17, 19].map((p) => Math.floor((Math.sqrt(p) % 1) * 2 ** 32) >>> 0);
|
|
13
|
+
const rotr = (x, n) => (x >>> n) | (x << (32 - n));
|
|
14
|
+
export const sha256 = (text) => {
|
|
15
|
+
const bytes = new TextEncoder().encode(text);
|
|
16
|
+
const padded = new Uint8Array(((bytes.length + 9 + 63) >> 6) << 6);
|
|
17
|
+
padded.set(bytes);
|
|
18
|
+
padded[bytes.length] = 0x80;
|
|
19
|
+
const view = new DataView(padded.buffer);
|
|
20
|
+
view.setUint32(padded.length - 8, Math.floor((bytes.length * 8) / 2 ** 32));
|
|
21
|
+
view.setUint32(padded.length - 4, (bytes.length * 8) >>> 0);
|
|
22
|
+
const h = [...H0];
|
|
23
|
+
const w = new Array(64);
|
|
24
|
+
for (let block = 0; block < padded.length; block += 64) {
|
|
25
|
+
for (let i = 0; i < 16; i++)
|
|
26
|
+
w[i] = view.getUint32(block + i * 4);
|
|
27
|
+
for (let i = 16; i < 64; i++) {
|
|
28
|
+
const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3);
|
|
29
|
+
const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10);
|
|
30
|
+
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
|
|
31
|
+
}
|
|
32
|
+
let [a, b, c, d, e, f, g, hh] = h;
|
|
33
|
+
for (let i = 0; i < 64; i++) {
|
|
34
|
+
const t1 = (hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + w[i]) >>> 0;
|
|
35
|
+
const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) >>> 0;
|
|
36
|
+
hh = g;
|
|
37
|
+
g = f;
|
|
38
|
+
f = e;
|
|
39
|
+
e = (d + t1) >>> 0;
|
|
40
|
+
d = c;
|
|
41
|
+
c = b;
|
|
42
|
+
b = a;
|
|
43
|
+
a = (t1 + t2) >>> 0;
|
|
44
|
+
}
|
|
45
|
+
[a, b, c, d, e, f, g, hh].forEach((v, i) => { h[i] = (h[i] + v) >>> 0; });
|
|
46
|
+
}
|
|
47
|
+
return h.map((v) => v.toString(16).padStart(8, "0")).join("");
|
|
48
|
+
};
|
|
49
|
+
/** A payload as text with its keys in order, so the same payload always hashes the same. */
|
|
50
|
+
export const canonical = (value) => JSON.stringify(value, (_, v) => typeof v === "bigint" ? v.toString()
|
|
51
|
+
: v !== null && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
|
|
52
|
+
: v);
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { Context } from "effect";
|
|
2
|
+
/** The environment this world or deployment stands for, written on every operation span as `environment`. `local` when nobody says. */
|
|
3
|
+
export const Environment = Context.Reference("@orthograph/language-effect/Environment", { defaultValue: () => "local" });
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import type { Violation } from "#modules/records/types.js";
|
|
3
|
+
/**
|
|
4
|
+
* Settle a violation for `operation`. `invariants` is the operation's own list, from the model: each refusal's tag to the rule it refuses for. A rule the
|
|
5
|
+
* operation does not list (a breaker the compiler could not see, G5 section 3), a rule with no refusal, and a clash among the call's own rows are all the
|
|
6
|
+
* handler's bug: they die, naming the rule and the operation, and never reach the wire as a refusal nobody declared.
|
|
7
|
+
*/
|
|
8
|
+
export declare const settleViolation: <L extends {
|
|
9
|
+
readonly around: <A, E, R>(work: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
|
|
10
|
+
}>(operation: string, invariants: Readonly<Record<string, string>>, logs: L,
|
|
11
|
+
/** What a lost race becomes: the call's retry, which meets what the winner made (a version save is then refused as stale). */
|
|
12
|
+
retry: () => unknown) => (violation: Violation) => Effect.Effect<never, unknown, never>;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// A rule the call's rows break (G5): the runtime's own refusal, or a defect when no refusal can be made. The refusal is the rule's own error, filled from the
|
|
2
|
+
// caller's row (never the holder's, which would say who holds the name), counted as a refusal, with the rule on the span and the log that decided it.
|
|
3
|
+
import { Effect } from "effect";
|
|
4
|
+
/** What the runtime logs when it refuses for a rule: the rule's name and that another holds its key. The key's value is never in it. */
|
|
5
|
+
const decidingLog = (rule) => `${rule}: another instance already holds this key`;
|
|
6
|
+
/**
|
|
7
|
+
* Settle a violation for `operation`. `invariants` is the operation's own list, from the model: each refusal's tag to the rule it refuses for. A rule the
|
|
8
|
+
* operation does not list (a breaker the compiler could not see, G5 section 3), a rule with no refusal, and a clash among the call's own rows are all the
|
|
9
|
+
* handler's bug: they die, naming the rule and the operation, and never reach the wire as a refusal nobody declared.
|
|
10
|
+
*/
|
|
11
|
+
export const settleViolation = (operation, invariants, logs,
|
|
12
|
+
/** What a lost race becomes: the call's retry, which meets what the winner made (a version save is then refused as stale). */
|
|
13
|
+
retry) => (violation) => Effect.gen(function* () {
|
|
14
|
+
const { rule, refuse, row, own, retry: lost } = violation;
|
|
15
|
+
if (own)
|
|
16
|
+
return yield* Effect.die(new Error(`${operation} wrote two rows that hold one key of the unique rule ${rule}: that is the handler's bug, not a race`));
|
|
17
|
+
if (lost === true && refuse === undefined)
|
|
18
|
+
return yield* Effect.fail(retry());
|
|
19
|
+
if (refuse === undefined)
|
|
20
|
+
return yield* Effect.die(new Error(`${operation} broke ${rule}, which names no refusal: that is the app's own bug`));
|
|
21
|
+
if (!Object.values(invariants).includes(rule)) {
|
|
22
|
+
return yield* Effect.die(new Error(`${operation} broke ${rule}, which the compiler did not list it as able to break: declare \`writes\` on the step that writes it`));
|
|
23
|
+
}
|
|
24
|
+
const fields = Object.fromEntries(Object.keys(refuse.fields).map((key) => [key, row[key]]));
|
|
25
|
+
yield* Effect.annotateCurrentSpan({ "refusal.invariant": rule });
|
|
26
|
+
yield* logs.around(Effect.logInfo(decidingLog(rule)));
|
|
27
|
+
return yield* Effect.fail(new refuse(fields));
|
|
28
|
+
});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { Effect, type Tracer } from "effect";
|
|
2
|
+
import type { Operation } from "orthograph";
|
|
3
|
+
import type { Instance, Unit } from "#modules/records/types.js";
|
|
4
|
+
import { NotFrom } from "../types.ts";
|
|
5
|
+
/** The instance that moves: the answer's or the payload's field declared as the thing's own id. */
|
|
6
|
+
export declare const subjectOf: (op: Operation, payload: object, answer?: object) => string | undefined;
|
|
7
|
+
/**
|
|
8
|
+
* The machine's own refusal, before the handler: the subject exists but is in a state the move can't start from. The
|
|
9
|
+
* subject is the one read before the handler (`prehandle`), which also fixed the version the commit is guarded by.
|
|
10
|
+
* Gives back the state the subject was in (the span's `move.from`), or nothing when the move creates or the subject is absent.
|
|
11
|
+
*/
|
|
12
|
+
export declare const checkFrom: (op: Operation, refusal: string | undefined, subject: Instance | undefined) => Effect.Effect<string | undefined, NotFrom, never>;
|
|
13
|
+
/**
|
|
14
|
+
* The outcome a handler asked for: one of the move's `to`, or it dies naming what it asked for. The move is written on
|
|
15
|
+
* the operation's span, not on the step span the handler may be inside when it moves.
|
|
16
|
+
*/
|
|
17
|
+
export declare const chooseOutcome: (name: string, op: Operation, to: string | undefined, span: Tracer.Span) => Effect.Effect<string, never, never>;
|
|
18
|
+
/**
|
|
19
|
+
* Set the subject's state in this attempt's unit, and give back the journal entry the commit writes with it. A creating
|
|
20
|
+
* move's subject is the id the answer gives, else the one minted for it; when the handler stored nothing under it, the
|
|
21
|
+
* runtime stores the instance from the thing's fields the payload and the answer fill.
|
|
22
|
+
*/
|
|
23
|
+
export declare const applyMove: (name: string, op: Operation, payload: object, answer: object, outcome: string, unit: Unit, minted?: string) => Effect.Effect<{
|
|
24
|
+
trace: string;
|
|
25
|
+
operation: string;
|
|
26
|
+
move: string;
|
|
27
|
+
subject: string;
|
|
28
|
+
event: string;
|
|
29
|
+
fields: {
|
|
30
|
+
[k: string]: unknown;
|
|
31
|
+
};
|
|
32
|
+
}, never, never>;
|