@orthograph/language-effect 0.0.0-stage → 0.1.0-next.2
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 +39 -3
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// The operation's move: the machine's check before the handler, the outcome the handler chose, and the state and
|
|
2
|
+
// journal entry the commit carries.
|
|
3
|
+
import { Effect, Schema } from "effect";
|
|
4
|
+
import { EventNames } from "orthograph/server";
|
|
5
|
+
import { NotFrom } from "../types.js";
|
|
6
|
+
import { journalled } from "./attributes.js";
|
|
7
|
+
/** The instance that moves: the answer's or the payload's field declared as the thing's own id. */
|
|
8
|
+
export const subjectOf = (op, payload, answer = {}) => {
|
|
9
|
+
const idField = op.thing.fields["id"];
|
|
10
|
+
for (const [fields, values] of [[op.answer, answer], [op.payload, payload]]) {
|
|
11
|
+
for (const [k, f] of Object.entries(fields)) {
|
|
12
|
+
const v = values[k];
|
|
13
|
+
// By place, not by identity: a field marked secret is a copy of the thing's own, and still is it.
|
|
14
|
+
if (f.kind === "field" && idField && f.of === idField.of && f.key === idField.key && typeof v === "string")
|
|
15
|
+
return v;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
return undefined;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* The machine's own refusal, before the handler: the subject exists but is in a state the move can't start from. The
|
|
22
|
+
* subject is the one read before the handler (`prehandle`), which also fixed the version the commit is guarded by.
|
|
23
|
+
* Gives back the state the subject was in (the span's `move.from`), or nothing when the move creates or the subject is absent.
|
|
24
|
+
*/
|
|
25
|
+
export const checkFrom = (op, refusal, subject) => Effect.gen(function* () {
|
|
26
|
+
const move = op.move;
|
|
27
|
+
if (!move || move.from.length === 0 || refusal === undefined || subject === undefined)
|
|
28
|
+
return undefined;
|
|
29
|
+
const state = subject.state ?? "none";
|
|
30
|
+
if (!move.from.includes(state))
|
|
31
|
+
return yield* Effect.fail(new NotFrom({ _tag: refusal, state }));
|
|
32
|
+
return state;
|
|
33
|
+
});
|
|
34
|
+
/**
|
|
35
|
+
* 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
|
|
36
|
+
* the operation's span, not on the step span the handler may be inside when it moves.
|
|
37
|
+
*/
|
|
38
|
+
export const chooseOutcome = (name, op, to, span) => Effect.gen(function* () {
|
|
39
|
+
if (!op.move)
|
|
40
|
+
return yield* Effect.die(new Error(`${name} has no move, so its handler cannot make one`));
|
|
41
|
+
const outcome = to ?? (op.move.to.length === 1 ? op.move.to[0] : undefined);
|
|
42
|
+
// Written before the check, so a wrong outcome is evidence too, not just a crash.
|
|
43
|
+
span.attribute("move.name", op.move.key);
|
|
44
|
+
span.attribute("move.to", String(outcome));
|
|
45
|
+
if (outcome === undefined || !op.move.to.includes(outcome)) {
|
|
46
|
+
return yield* Effect.die(new Error(`${name} moved to ${outcome}, which ${op.move.key} does not declare (${op.move.to.join(", ")})`));
|
|
47
|
+
}
|
|
48
|
+
return outcome;
|
|
49
|
+
});
|
|
50
|
+
/**
|
|
51
|
+
* Set the subject's state in this attempt's unit, and give back the journal entry the commit writes with it. A creating
|
|
52
|
+
* move's subject is the id the answer gives, else the one minted for it; when the handler stored nothing under it, the
|
|
53
|
+
* runtime stores the instance from the thing's fields the payload and the answer fill.
|
|
54
|
+
*/
|
|
55
|
+
export const applyMove = (name, op, payload, answer, outcome, unit, minted) => Effect.gen(function* () {
|
|
56
|
+
const move = op.move;
|
|
57
|
+
const subject = subjectOf(op, payload, answer) ?? minted;
|
|
58
|
+
if (subject === undefined)
|
|
59
|
+
return yield* Effect.die(new Error(`${name} moved, but neither its answer nor its payload names the ${move.key}'s instance`));
|
|
60
|
+
const event = EventNames.nameOf(move.emits) ?? "UnnamedEvent";
|
|
61
|
+
const stored = yield* unit.read(op.thing, subject);
|
|
62
|
+
const created = stored === undefined && move.from.length === 0 ? made(op, subject, payload, answer) : undefined;
|
|
63
|
+
if (created !== undefined)
|
|
64
|
+
yield* unit.records.insert(op.thing, created);
|
|
65
|
+
// An event's fields come from the subject as this call left it (the one just stored, for a creating move), then the
|
|
66
|
+
// payload, then the answer.
|
|
67
|
+
const instance = stored ?? created ?? {};
|
|
68
|
+
const source = { ...instance, ...payload, ...answer };
|
|
69
|
+
const missing = Object.keys(move.emits.fields).filter((k) => !(k in source));
|
|
70
|
+
if (missing.length > 0)
|
|
71
|
+
return yield* Effect.die(new Error(`${name}: ${event} needs ${missing.join(", ")}, found in neither its instance, answer nor payload`));
|
|
72
|
+
const picked = Object.fromEntries(Object.keys(move.emits.fields).map((k) => [k, source[k]]));
|
|
73
|
+
const encoded = yield* Schema.encodeEffect(move.emits.schema)(picked).pipe(Effect.orDie);
|
|
74
|
+
// The journal is a record anyone who reads it can see: a secret or private field of the event is not written to it.
|
|
75
|
+
const fields = Object.fromEntries(Object.entries(encoded).filter(([k]) => journalled(move.emits.fields, k)));
|
|
76
|
+
yield* unit.setState(op.thing, subject, outcome);
|
|
77
|
+
const trace = yield* Effect.currentSpan.pipe(Effect.map((s) => s.traceId), Effect.orElseSucceed(() => ""));
|
|
78
|
+
return { trace, operation: name, move: move.key, subject, event, fields };
|
|
79
|
+
});
|
|
80
|
+
/** A created instance as the call gives it: the id, then each of the thing's fields the payload or the answer holds by name. */
|
|
81
|
+
const made = (op, id, payload, answer) => {
|
|
82
|
+
const given = { ...payload, ...answer, id };
|
|
83
|
+
return Object.fromEntries(Object.keys(op.thing.fields).filter((k) => k in given).map((k) => [k, given[k]]));
|
|
84
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import type { Operation } from "orthograph";
|
|
3
|
+
import type { Instance, Unit } from "#modules/records/types.js";
|
|
4
|
+
import { NotFound } from "../types.ts";
|
|
5
|
+
export interface Prehandled {
|
|
6
|
+
/** The instance the call is about, when the payload names one of its thing by id. */
|
|
7
|
+
readonly subject: Instance | undefined;
|
|
8
|
+
/** Each thing a payload field names by id, keyed by that field; undefined when nothing has that id. */
|
|
9
|
+
readonly refs: Readonly<Record<string, Instance | undefined>>;
|
|
10
|
+
/** A creating move's new id, minted before the handler runs; undefined for any other call. */
|
|
11
|
+
readonly id: string | undefined;
|
|
12
|
+
}
|
|
13
|
+
/** A move with no `from` makes its instance. */
|
|
14
|
+
export declare const creates: (op: Operation) => boolean;
|
|
15
|
+
/**
|
|
16
|
+
* Read what the payload names. A field in `notFound` that names nothing is refused with its `<Thing>NotFound`, carrying
|
|
17
|
+
* the id: the compiler lists only fields no role check reads, since a role-gated miss is already `NotAllowed`.
|
|
18
|
+
*/
|
|
19
|
+
export declare const prehandle: (op: Operation, notFound: Readonly<Record<string, string>>, payload: object, unit: Unit) => Effect.Effect<{
|
|
20
|
+
subject: Instance | undefined;
|
|
21
|
+
refs: Record<string, Instance | undefined>;
|
|
22
|
+
id: string | undefined;
|
|
23
|
+
}, NotFound, never>;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// What the runtime reads and makes before the handler runs (K16, M1.46): the instance the call is about, each thing the
|
|
2
|
+
// payload names by id, and a creating move's new id. Each is read here once, in the call's unit (the role check reads on
|
|
3
|
+
// its own), so the from-check, the commit's version guard and the handler all see the same instance.
|
|
4
|
+
import { Effect } from "effect";
|
|
5
|
+
import { referencedThing } from "#modules/access/service.js";
|
|
6
|
+
import { Ids } from "#modules/ids/service.js";
|
|
7
|
+
import { NotFound } from "../types.js";
|
|
8
|
+
import { subjectOf } from "./move.js";
|
|
9
|
+
/** A move with no `from` makes its instance. */
|
|
10
|
+
export const creates = (op) => op.move !== undefined && op.move.from.length === 0;
|
|
11
|
+
/**
|
|
12
|
+
* Read what the payload names. A field in `notFound` that names nothing is refused with its `<Thing>NotFound`, carrying
|
|
13
|
+
* the id: the compiler lists only fields no role check reads, since a role-gated miss is already `NotAllowed`.
|
|
14
|
+
*/
|
|
15
|
+
export const prehandle = (op, notFound, payload, unit) => Effect.gen(function* () {
|
|
16
|
+
const values = payload;
|
|
17
|
+
const refs = {};
|
|
18
|
+
for (const [key, field] of Object.entries(op.payload)) {
|
|
19
|
+
const thing = referencedThing(field);
|
|
20
|
+
const id = values[key];
|
|
21
|
+
if (thing === undefined || typeof id !== "string")
|
|
22
|
+
continue;
|
|
23
|
+
const found = yield* unit.read(thing, id);
|
|
24
|
+
const tag = notFound[key];
|
|
25
|
+
if (found === undefined && tag !== undefined)
|
|
26
|
+
return yield* Effect.fail(new NotFound({ _tag: tag, id }));
|
|
27
|
+
refs[key] = found;
|
|
28
|
+
}
|
|
29
|
+
const subjectId = creates(op) ? undefined : subjectOf(op, payload);
|
|
30
|
+
const subject = subjectId === undefined ? undefined : yield* unit.read(op.thing, subjectId);
|
|
31
|
+
const idField = op.thing.fields["id"];
|
|
32
|
+
const id = creates(op) && idField !== undefined ? (yield* Ids.of(idField)) : undefined;
|
|
33
|
+
return { subject, refs, id };
|
|
34
|
+
});
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { Cause, Effect, Schema } from "effect";
|
|
2
|
+
import { NotAllowed } from "orthograph";
|
|
3
|
+
import { Access } from "#modules/access/service.js";
|
|
4
|
+
import { Unit } from "#modules/records/service.js";
|
|
5
|
+
import { Records, Store } from "#modules/records/types.js";
|
|
6
|
+
import { CURSOR, derivedOne, derivedPage, notServed, unserved } from "./derived.js";
|
|
7
|
+
import { answerAttributes, payloadAttributes, principalAttributes } from "./attributes.js";
|
|
8
|
+
import { CALL_ID, newCallId } from "./call-id.js";
|
|
9
|
+
import { measureCall } from "./call-metrics.js";
|
|
10
|
+
import { spanned } from "./span.js";
|
|
11
|
+
import { defectAttributes } from "./defect.js";
|
|
12
|
+
const tagOf = (e) => typeof e === "object" && e !== null && typeof e._tag === "string" ? e._tag : String(e);
|
|
13
|
+
/** One instance by its id; a missing one is `NotAllowed`, so a read never says what exists. */
|
|
14
|
+
const byId = (read, payload, unit) => Effect.gen(function* () {
|
|
15
|
+
const found = yield* unit.read(read.thing, String(payload["id"]));
|
|
16
|
+
if (!found)
|
|
17
|
+
return yield* new NotAllowed();
|
|
18
|
+
// An optional field with no value is left out, never answered as `undefined` under its key (#1018).
|
|
19
|
+
return Object.fromEntries(read.fields.map((f) => [f, f === "state" ? (found.state ?? "none") : found[f]]).filter(([, v]) => v !== undefined));
|
|
20
|
+
});
|
|
21
|
+
/** One instance by its id, and what its derive adds; a missing one is `NotAllowed` as well. */
|
|
22
|
+
const derivedById = (read, payload, unit) => Effect.gen(function* () {
|
|
23
|
+
const found = yield* unit.read(read.thing, String(payload["id"]));
|
|
24
|
+
if (!found)
|
|
25
|
+
return yield* new NotAllowed();
|
|
26
|
+
return yield* derivedOne(read, found);
|
|
27
|
+
});
|
|
28
|
+
const refusals = new Set(["NotAllowed", "ReadNotServed"]);
|
|
29
|
+
const callRefusals = new Set([...refusals, "SchemaError"]);
|
|
30
|
+
/** A page: the instances matching the filters the caller gave, `page` of them, in the read's order. */
|
|
31
|
+
const byList = (read, payload) => Effect.gen(function* () {
|
|
32
|
+
const store = yield* Store;
|
|
33
|
+
const { cursor, state, ...filters } = payload;
|
|
34
|
+
if (cursor !== undefined && !CURSOR.test(cursor))
|
|
35
|
+
return yield* new NotAllowed();
|
|
36
|
+
// A field the read pins (`only`) is never the caller's to set: it is the read's own filter, whatever the payload says.
|
|
37
|
+
const { state: pinnedState, ...pinned } = (read.only ?? {});
|
|
38
|
+
const listed = yield* store.list({
|
|
39
|
+
thing: read.thing,
|
|
40
|
+
where: { ...Object.fromEntries(Object.entries(filters).filter(([k]) => read.where.includes(k))), ...pinned },
|
|
41
|
+
state: pinnedState ?? state,
|
|
42
|
+
order: read.order ?? "newest",
|
|
43
|
+
limit: read.page ?? 50,
|
|
44
|
+
after: cursor,
|
|
45
|
+
});
|
|
46
|
+
const items = listed.items.map((i) => ({ ...i, state: i.state ?? "none" }));
|
|
47
|
+
return { items, next: listed.next };
|
|
48
|
+
});
|
|
49
|
+
/** Reads are served beside operations: the same role check, the same span, no handler. */
|
|
50
|
+
export const Reads = {
|
|
51
|
+
serve: ({ name, read, mounts }) => {
|
|
52
|
+
const decode = Schema.decodeUnknownEffect(read.payloadSchema);
|
|
53
|
+
const check = Schema.encodeEffect(read.answerSchema);
|
|
54
|
+
const run = (payload, principal) => Effect.flatMap(newCallId, (callId) => Effect.gen(function* () {
|
|
55
|
+
const unit = yield* Unit.make(yield* Store);
|
|
56
|
+
yield* Access.check({ allowed: read.allowed, payloadFields: read.payload, payload, principal, thing: read.thing, ...(mounts === undefined ? {} : { mounts }) }).pipe(Effect.provideService(Records, unit.records), Effect.withTracerEnabled(false));
|
|
57
|
+
return yield* Effect.gen(function* () {
|
|
58
|
+
yield* Effect.annotateCurrentSpan(payloadAttributes(payload, read.payload));
|
|
59
|
+
// Fail closed: a derive that looks at something no store can list is not served, and serving it as a plain read would drop its adds.
|
|
60
|
+
if (read.derive !== undefined && unserved(read.derive))
|
|
61
|
+
return yield* notServed(name);
|
|
62
|
+
const answer = read.by === "list"
|
|
63
|
+
? (read.derive === undefined ? yield* byList(read, payload) : yield* derivedPage(read, payload))
|
|
64
|
+
: (read.derive === undefined ? yield* byId(read, payload, unit) : yield* derivedById(read, payload, unit));
|
|
65
|
+
yield* Effect.annotateCurrentSpan(answerAttributes(answer, read.answer, read.by === "list" ? read.thing.fields : undefined));
|
|
66
|
+
yield* check(answer).pipe(Effect.mapError((e) => new Error(`${name} answered outside its declaration: ${e.message}`)), Effect.orDie);
|
|
67
|
+
return answer;
|
|
68
|
+
}).pipe(
|
|
69
|
+
// A refusal is written on the span as the handler wrapper does, and ends it ok (O1).
|
|
70
|
+
Effect.tapCause((cause) => (Cause.hasDies(cause) ? Effect.annotateCurrentSpan(defectAttributes(cause)) : Effect.annotateCurrentSpan({ refusal: tagOf(Cause.squash(cause)) }))), spanned(name, { operation: name, [CALL_ID]: callId, ...principalAttributes(principal) }));
|
|
71
|
+
}));
|
|
72
|
+
return {
|
|
73
|
+
name,
|
|
74
|
+
operation: read,
|
|
75
|
+
run: (payload, principal) => run(payload, principal).pipe(measureCall(name, principal, refusals)),
|
|
76
|
+
call: (raw, principal) => decode(raw).pipe(Effect.flatMap((p) => run(p, principal)), measureCall(name, principal, callRefusals)),
|
|
77
|
+
};
|
|
78
|
+
},
|
|
79
|
+
};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
/** `work` with its start and end signalled. Applied inside the step's span, so that the span is the one the signals carry. */
|
|
3
|
+
export declare const signalled: (step: string) => <A, E, R>(work: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// K5 seam 10: a step signal. An OTLP log record written as each step starts and as it ends, inside the step's own span, so
|
|
2
|
+
// its span id is the step's and the portal joins a start to its end and to the span by id. A span is exported only once it
|
|
3
|
+
// has ended, so without these a step still running is invisible; the logger exports on its interval while the request is
|
|
4
|
+
// still held, so the signal is in the Collector's file before the response, not at dispose.
|
|
5
|
+
import { Cause, Effect, Exit } from "effect";
|
|
6
|
+
/** What a step ended as: a refusal is an outcome the operation was built to give (`ok`, as its span ends), a defect is `error`. */
|
|
7
|
+
const outcomeOf = (exit) => Exit.isSuccess(exit) ? "ok" : Cause.hasInterrupts(exit.cause) ? "interrupted" : Cause.hasDies(exit.cause) ? "error" : "ok";
|
|
8
|
+
const signal = (step, phase, outcome) => Effect.logInfo(`${step} ${phase}`).pipe(Effect.annotateLogs({ step, phase, ...(outcome === undefined ? {} : { outcome }) }));
|
|
9
|
+
/** `work` with its start and end signalled. Applied inside the step's span, so that the span is the one the signals carry. */
|
|
10
|
+
export const signalled = (step) => (work) => Effect.andThen(signal(step, "start"), work.pipe(Effect.onExit((exit) => signal(step, "end", outcomeOf(exit)))));
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
/**
|
|
3
|
+
* `work` in a span named `name` that ends ok when the work fails with a typed failure (a refusal), and as an error
|
|
4
|
+
* when it dies. The failure itself still leaves the span, unchanged, for the caller to handle.
|
|
5
|
+
*/
|
|
6
|
+
export declare const spanned: (name: string, attributes: Record<string, unknown>) => <A, E, R>(work: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
|
|
7
|
+
/** A step also signals its start and end (K5 seam 10): see `signal.ts`. */
|
|
8
|
+
export { signalled } from "./signal.ts";
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// O1's conventions for how a span ends. A declared refusal is an outcome the operation was built to give, so its span
|
|
2
|
+
// ends ok (it must not turn a trace red, count in an error list or open an issue); a defect, a failure nothing
|
|
3
|
+
// declared, is the only error. Effect ends a span with the exit of its work, so a refusal would end it as an error.
|
|
4
|
+
import { Cause, Effect, Result } from "effect";
|
|
5
|
+
import { defectTag } from "./defect.js";
|
|
6
|
+
/**
|
|
7
|
+
* `work` in a span named `name` that ends ok when the work fails with a typed failure (a refusal), and as an error
|
|
8
|
+
* when it dies. The failure itself still leaves the span, unchanged, for the caller to handle.
|
|
9
|
+
*/
|
|
10
|
+
export const spanned = (name, attributes) => (work) => work.pipe(
|
|
11
|
+
// A span a defect passes through carries its tag (M1.49): the attempt's own failure is told from a step that died and was recovered by the same tag.
|
|
12
|
+
Effect.tapCause((cause) => (Cause.hasDies(cause) ? Effect.annotateCurrentSpan(defectTag(cause)) : Effect.void)), Effect.result, Effect.withSpan(name, { attributes }), Effect.flatMap((outcome) => (Result.isFailure(outcome) ? Effect.fail(outcome.failure) : Effect.succeed(outcome.success))));
|
|
13
|
+
/** A step also signals its start and end (K5 seam 10): see `signal.ts`. */
|
|
14
|
+
export { signalled } from "./signal.js";
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type HandlerApi } from "./types.ts";
|
|
2
|
+
export { Reads } from "./internal/read.ts";
|
|
3
|
+
export { Environment } from "./internal/environment.ts";
|
|
4
|
+
/** Typed at the edge (`HandlerApi`); inside, one untyped implementation serves every operation. */
|
|
5
|
+
export declare const Handlers: HandlerApi;
|
|
6
|
+
/** Operations that run on the caller's device (M1.27): the generated SDK serves each plugin's `runs: "client"` operation with this. */
|
|
7
|
+
export { Device } from "./internal/device.ts";
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { Cause, Data, Duration, Effect, Ref, Schema } from "effect";
|
|
2
|
+
import { ErrorNames } from "orthograph/server";
|
|
3
|
+
import { Access } from "#modules/access/service.js";
|
|
4
|
+
import { Calls } from "#modules/calls/service.js";
|
|
5
|
+
import { Unit } from "#modules/records/service.js";
|
|
6
|
+
import { Records, Store } from "#modules/records/types.js";
|
|
7
|
+
import { Busy } from "#modules/work/types.js";
|
|
8
|
+
import { CALL_ID, newCallId } from "./internal/call-id.js";
|
|
9
|
+
import { BlankReached, IdempotencyConflict, InvalidPayload } from "./types.js";
|
|
10
|
+
import { canonical, sha256 } from "./internal/digest.js";
|
|
11
|
+
import { answerAttributes, payloadAttributes, principalAttributes, requestAttributes } from "./internal/attributes.js";
|
|
12
|
+
import { measureCall } from "./internal/call-metrics.js";
|
|
13
|
+
import { Environment } from "./internal/environment.js";
|
|
14
|
+
import { applyMove, checkFrom, chooseOutcome } from "./internal/move.js";
|
|
15
|
+
import { prehandle } from "./internal/prehandle.js";
|
|
16
|
+
import { recordingLogs } from "./internal/decided.js";
|
|
17
|
+
import { settleViolation } from "./internal/invariants.js";
|
|
18
|
+
import { signalled, spanned } from "./internal/span.js";
|
|
19
|
+
import { defectAttributes } from "./internal/defect.js";
|
|
20
|
+
export { Reads } from "./internal/read.js";
|
|
21
|
+
export { Environment } from "./internal/environment.js";
|
|
22
|
+
/** An update's version had moved on, so this attempt committed nothing. Never leaves the wrapper. */
|
|
23
|
+
class Conflict extends Data.TaggedError("Conflict") {
|
|
24
|
+
}
|
|
25
|
+
/** Every round of contenders has at least one winner, so this many attempts outlasts any fair race (D2 #36). */
|
|
26
|
+
const ATTEMPTS = 64;
|
|
27
|
+
/** A call step: the adapter's call in a span named after the step, marked `call`. */
|
|
28
|
+
const callStep = (span, run) => (args, failure) => spanned(span, { "step.kind": "call" })(signalled(span)(run(args, failure)));
|
|
29
|
+
const tagOf = (e) => typeof e === "object" && e !== null && typeof e._tag === "string" ? e._tag : String(e);
|
|
30
|
+
const serve = ({ name, operation, handler, notFrom, notFound = {}, calls, codes, invariants = {}, mounts }) => {
|
|
31
|
+
const op = operation;
|
|
32
|
+
const budgetMs = op.budget === undefined ? undefined : Duration.toMillis(op.budget.p95);
|
|
33
|
+
const decode = Schema.decodeUnknownEffect(op.payloadSchema);
|
|
34
|
+
const check = Schema.encodeEffect(op.answerSchema);
|
|
35
|
+
const refusals = new Set(op.errors.map(ErrorNames.nameOf).filter((tag) => tag !== undefined));
|
|
36
|
+
if (notFrom !== undefined)
|
|
37
|
+
refusals.add(notFrom);
|
|
38
|
+
for (const tag of Object.values(notFound))
|
|
39
|
+
refusals.add(tag);
|
|
40
|
+
for (const tag of Object.keys(invariants))
|
|
41
|
+
refusals.add(tag);
|
|
42
|
+
if (op.allowed.some((role) => role.kind !== "anyone"))
|
|
43
|
+
refusals.add("NotAllowed");
|
|
44
|
+
if (op.idempotent === "request")
|
|
45
|
+
refusals.add("IdempotencyConflict");
|
|
46
|
+
const callRefusals = new Set([...refusals, "InvalidPayload"]);
|
|
47
|
+
const steps = Object.fromEntries(
|
|
48
|
+
// Each step is its own span, marked with its kind: a `database` step's work is the store's, a `wait` step's a timer's.
|
|
49
|
+
Object.entries(op.steps).map(([key, step]) => [
|
|
50
|
+
key,
|
|
51
|
+
step.type === "call"
|
|
52
|
+
? callStep(`${name}.${key}`, Calls.runner({ label: `${name}.${key}`, step: step, wiring: calls?.[key] }))
|
|
53
|
+
: (work) => spanned(`${name}.${key}`, { "step.kind": step.type })(signalled(`${name}.${key}`)(work)),
|
|
54
|
+
]));
|
|
55
|
+
// One attempt: who may call, then the operation's own span (opened only once the caller may call, so a refused caller
|
|
56
|
+
// leaves no handler span, only `<operation>.refused`, which carries the refusal), the machine's check, the handler,
|
|
57
|
+
// its answer checked, its move, one commit.
|
|
58
|
+
const refused = (principal, number, callId, request) => (e) => {
|
|
59
|
+
const tag = tagOf(e);
|
|
60
|
+
const code = codes?.[tag];
|
|
61
|
+
return Effect.annotateCurrentSpan({ refusal: tag, ...(code === undefined ? {} : { "refusal.code": code }) }).pipe(spanned(`${name}.refused`, { operation: name, attempt: number, [CALL_ID]: callId, ...principalAttributes(principal, true), ...requestAttributes(request) }));
|
|
62
|
+
};
|
|
63
|
+
const decodeAnswer = Schema.decodeUnknownEffect(op.answerSchema);
|
|
64
|
+
const attempt = (payload, principal, key, request, number, callId) => Effect.gen(function* () {
|
|
65
|
+
const store = yield* Store;
|
|
66
|
+
const unit = yield* Unit.make(store);
|
|
67
|
+
const withRecords = Effect.provideService(Records, unit.records);
|
|
68
|
+
// The check's own reads are not traced: a refusal is, in its own span.
|
|
69
|
+
yield* Access.check({ allowed: op.allowed, payloadFields: op.payload, payload, principal, thing: op.thing, ...(mounts === undefined ? {} : { mounts }) }).pipe(withRecords, Effect.withTracerEnabled(false), Effect.tapError(refused(principal, number, callId, request)));
|
|
70
|
+
const logs = yield* recordingLogs(payload, op.payload);
|
|
71
|
+
// The operation is counted work from its handler to its commit (M8.07): a world is quiet only once its writes are visible.
|
|
72
|
+
const busy = (yield* Busy).as(name);
|
|
73
|
+
return yield* Effect.gen(function* () {
|
|
74
|
+
// The operation's span, which a move's attributes are written on whichever step span the handler is in.
|
|
75
|
+
const operationSpan = yield* Effect.currentSpan;
|
|
76
|
+
yield* Effect.annotateCurrentSpan(payloadAttributes(payload, op.payload));
|
|
77
|
+
// Where the call ran: the world's environment, and the kind of store its thing lives in.
|
|
78
|
+
yield* Effect.annotateCurrentSpan({ environment: yield* Environment, store: op.thing.lives });
|
|
79
|
+
// The same request key from the same caller is one call: answer what was answered, and change nothing.
|
|
80
|
+
const kept = key === undefined ? undefined : yield* store.answered(key);
|
|
81
|
+
if (kept !== undefined) {
|
|
82
|
+
// The kept answer is bound to the payload it was made for: the same key with another payload is another request.
|
|
83
|
+
const { payload: madeFor, answer } = JSON.parse(kept);
|
|
84
|
+
if (madeFor !== sha256(canonical(payload)))
|
|
85
|
+
return yield* new IdempotencyConflict();
|
|
86
|
+
yield* Effect.annotateCurrentSpan({ "request.replayed": true });
|
|
87
|
+
return yield* decodeAnswer(answer).pipe(Effect.orDie);
|
|
88
|
+
}
|
|
89
|
+
// What the payload names, read once and handed in; a missing one is refused before the handler, then the from-check.
|
|
90
|
+
const handed = yield* prehandle(op, notFound, payload, unit);
|
|
91
|
+
const from = yield* checkFrom(op, notFrom, handed.subject);
|
|
92
|
+
const chosen = yield* Ref.make(undefined);
|
|
93
|
+
const move = (to) => chooseOutcome(name, op, to, operationSpan).pipe(Effect.flatMap((o) => Ref.set(chosen, o)));
|
|
94
|
+
const answer = yield* handler(payload, { principal, steps, move, ...handed }).pipe(Effect.provideService(Records, logs.watching(unit.records)), logs.around);
|
|
95
|
+
// Recorded before the check, so an answer outside its declaration is evidence `prove` can name.
|
|
96
|
+
yield* Effect.annotateCurrentSpan(answerAttributes(answer, op.answer));
|
|
97
|
+
// An answer that breaks its declaration is the handler's bug, never the caller's: it dies, loudly.
|
|
98
|
+
const wire = yield* check(answer).pipe(Effect.mapError((e) => new Error(`${name} answered outside its declaration: ${e.message}`)), Effect.orDie);
|
|
99
|
+
const outcome = yield* Ref.get(chosen);
|
|
100
|
+
const entries = outcome === undefined ? [] : [yield* applyMove(name, op, payload, answer, outcome, unit, handed.id)];
|
|
101
|
+
// The state the subject was in, written once the move is made: a refused call made no move.
|
|
102
|
+
if (from !== undefined && outcome !== undefined)
|
|
103
|
+
yield* Effect.annotateCurrentSpan({ "move.from": from });
|
|
104
|
+
const request = key === undefined ? {} : { request: { key, answer: JSON.stringify({ payload: sha256(canonical(payload)), answer: wire }) } };
|
|
105
|
+
// Every rule this call's rows could break, after the move and before the commit: the store's own index then catches the race.
|
|
106
|
+
const broken = yield* unit.check;
|
|
107
|
+
if (broken !== undefined)
|
|
108
|
+
return yield* settleViolation(name, invariants, logs, () => new Conflict())(broken);
|
|
109
|
+
const writes = yield* unit.writes;
|
|
110
|
+
// #764: the lists the handler read, which the store guards like an update's version.
|
|
111
|
+
const lists = yield* unit.lists;
|
|
112
|
+
// #1045: the rows it found, guarded the same way: one another call changed since makes this attempt a `conflict`, and the call runs again.
|
|
113
|
+
const reads = yield* unit.reads;
|
|
114
|
+
const committed = yield* store.commit({ writes, entries, ...request, ...(lists.length > 0 ? { lists } : {}), ...(reads.length > 0 ? { reads } : {}) }).pipe(Effect.tap((outcome) => Effect.annotateCurrentSpan({
|
|
115
|
+
"commit.outcome": outcome,
|
|
116
|
+
// The event the move emitted, named only on the commit that journalled it: a conflicted attempt emitted nothing.
|
|
117
|
+
...(outcome === "committed" && entries[0] !== undefined ? { "event.name": entries[0].event } : {}),
|
|
118
|
+
})), spanned(`${name}.commit`, { "step.kind": "commit", "commit.writes": writes.length, "commit.entries": entries.length }),
|
|
119
|
+
// A write section: the commit happens only while the world still holds this request's token, and a reset waits for it (M8.07).
|
|
120
|
+
busy.fenced);
|
|
121
|
+
if (committed === "conflict")
|
|
122
|
+
return yield* new Conflict();
|
|
123
|
+
return answer;
|
|
124
|
+
}).pipe(
|
|
125
|
+
// Every refusal and every defect is written on the operation's span: what `prove` reads.
|
|
126
|
+
// A refusal also carries the log that decided it, when the handler logged one before refusing.
|
|
127
|
+
Effect.tapCause((cause) => {
|
|
128
|
+
if (Cause.hasDies(cause))
|
|
129
|
+
return Effect.annotateCurrentSpan(defectAttributes(cause));
|
|
130
|
+
const refusal = Cause.squash(cause);
|
|
131
|
+
if (refusal instanceof Conflict)
|
|
132
|
+
return Effect.void;
|
|
133
|
+
const tag = tagOf(refusal);
|
|
134
|
+
const code = codes?.[tag];
|
|
135
|
+
return logs.last.pipe(Effect.flatMap((log) => Effect.annotateCurrentSpan({ refusal: tag, ...(code === undefined ? {} : { "refusal.code": code }), ...(log === undefined ? {} : { "refusal.log": log }) })));
|
|
136
|
+
}), spanned(name, { operation: name, attempt: number, [CALL_ID]: callId, ...principalAttributes(principal), ...requestAttributes(request) }), busy.counted);
|
|
137
|
+
});
|
|
138
|
+
const run = (payload, principal, request) => {
|
|
139
|
+
// Keyed by operation and caller as well, so one caller's key never answers another's call.
|
|
140
|
+
// Each kind is its own: an agent's retries never answer its person's call (M2-auth, "Smaller calls" 1).
|
|
141
|
+
const who = "person" in principal ? `${principal.kind}:${principal.person}` : principal.kind === "service" ? `service:${principal.mount}` : principal.kind;
|
|
142
|
+
const key = op.idempotent === "request" && request !== undefined ? `${name}|${who}|${request}` : undefined;
|
|
143
|
+
// The call is named once, before its first attempt, and every attempt's span carries the name: attempts of one call are sequential, but different
|
|
144
|
+
// calls' attempts overlap, so nothing else in a trace says which attempts belong together (O3).
|
|
145
|
+
const loop = (number, callId) => attempt(payload, principal, key, key === undefined ? undefined : request, number, callId).pipe(Effect.catch((e) => !(e instanceof Conflict) ? Effect.fail(e)
|
|
146
|
+
: number < ATTEMPTS ? loop(number + 1, callId)
|
|
147
|
+
: Effect.die(new Error(`${name} lost its version race ${ATTEMPTS} times in a row`))));
|
|
148
|
+
return Effect.flatMap(newCallId, (callId) => loop(1, callId));
|
|
149
|
+
};
|
|
150
|
+
return {
|
|
151
|
+
name,
|
|
152
|
+
operation,
|
|
153
|
+
call: (raw, principal) => decode(raw).pipe(Effect.mapError((e) => new InvalidPayload({ issues: e.message })), Effect.flatMap((payload) => run(payload, principal)), measureCall(name, principal, callRefusals, budgetMs)),
|
|
154
|
+
run: (payload, principal, request) => run(payload, principal, request).pipe(measureCall(name, principal, refusals, budgetMs)),
|
|
155
|
+
};
|
|
156
|
+
};
|
|
157
|
+
/** Typed at the edge (`HandlerApi`); inside, one untyped implementation serves every operation. */
|
|
158
|
+
export const Handlers = {
|
|
159
|
+
serve: serve,
|
|
160
|
+
blank: ((what, kind) => (kind === "failure" ? () => new BlankReached({ what }) : Effect.die(new BlankReached({ what })))),
|
|
161
|
+
};
|
|
162
|
+
/** Operations that run on the caller's device (M1.27): the generated SDK serves each plugin's `runs: "client"` operation with this. */
|
|
163
|
+
export { Device } from "./internal/device.js";
|