@frondruntime/devtools 0.3.0

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.
@@ -0,0 +1,229 @@
1
+ import type { Graph, Runtime } from "@frondruntime/core";
2
+ import { createValueEncoder, type ValueEncoder } from "./encode.ts";
3
+ import type { EncodePolicy } from "./policy.ts";
4
+ import type { EncodedGraphEdge, EncodedNodeSnapshot, GraphSnapshot } from "./protocol.ts";
5
+
6
+ /**
7
+ * Derived from the snapshot rather than imported by name.
8
+ *
9
+ * `NodeOperationFailure` is exported from core and `NodeLiveFailure` is not,
10
+ * even though both appear on the public `NodeSnapshot`. Reading them off the
11
+ * field keeps this file working either way, and means neither can drift from
12
+ * the shape actually being encoded.
13
+ */
14
+ type OperationFailure = NonNullable<Graph.NodeSnapshot["operationFailure"]>;
15
+ type LiveFailure = NonNullable<Graph.NodeSnapshot["liveFailure"]>;
16
+
17
+ export type SnapshotRequest = {
18
+ readonly policy: EncodePolicy;
19
+ readonly capturedAt: number;
20
+ /**
21
+ * Narrow to one node and include its result.
22
+ *
23
+ * The whole difference between the two queries. A graph read answers a
24
+ * topology question and a few hundred results would drown it; a node read is
25
+ * someone asking what one value currently is, which is the only question a
26
+ * result answers.
27
+ */
28
+ readonly nodeId?: string | undefined;
29
+ };
30
+
31
+ /**
32
+ * The graph as the app sees it right now, reduced to something sendable.
33
+ *
34
+ * The counterpart to {@link encodeRecord}, and deliberately built from the same
35
+ * {@link ValueEncoder}: a node that is failing in a snapshot and the event that
36
+ * failed it should read identically, and the way to guarantee that is for one
37
+ * piece of code to describe both.
38
+ *
39
+ * Two things in a `NodeSnapshot` cannot cross and are dropped rather than
40
+ * approximated. `Pending.attempt` is a `Promise<NodeRead>` — nothing about it
41
+ * survives serialization, and `state: "Pending"` already says the only thing it
42
+ * would have told a reader. And `Ready.node` is the node facade object, which is
43
+ * mostly methods; `result` is the value someone actually meant to ask about.
44
+ *
45
+ * Two more are dropped for costing a line each in every row of a graph read
46
+ * while saying something the row already said: `label` is core's presentation
47
+ * formatting of `tag`, and `key` is the second half of `nodeId`. `kind` stays —
48
+ * `"node"` against `"resource"` is nowhere in the other fields, and it is what
49
+ * tells a reader whether release semantics apply to this row.
50
+ */
51
+ export function encodeGraphSnapshot(
52
+ snapshot: Runtime.RuntimeSnapshot,
53
+ request: SnapshotRequest
54
+ ): GraphSnapshot {
55
+ const encoder = createValueEncoder(request.policy);
56
+
57
+ const nodes =
58
+ request.nodeId === undefined
59
+ ? snapshot.graph.nodes
60
+ : snapshot.graph.nodes.filter((node) => node.nodeId === request.nodeId);
61
+
62
+ // Every edge touching the node, in either direction: "what does this depend
63
+ // on" and "what breaks if this does" are the same question asked twice, and a
64
+ // single-node read that answered only the first would be half a diagnosis.
65
+ const edges =
66
+ request.nodeId === undefined
67
+ ? snapshot.graph.edges
68
+ : snapshot.graph.edges.filter(
69
+ (edge) => edge.from === request.nodeId || edge.to === request.nodeId
70
+ );
71
+
72
+ return {
73
+ capturedAt: request.capturedAt,
74
+ // Absent rather than zero on a runtime that has not emitted: zero is a real
75
+ // position in a log, and claiming one this snapshot does not have would let
76
+ // a reader line it up against events that had not happened yet. Through
77
+ // `absent` for the same reason everything else optional here is — see below.
78
+ ...absent("sequence", snapshot.events.at(-1)?.sequence, identity),
79
+ runtimeId: snapshot.runtimeId,
80
+ runtimeStatus: snapshot.status,
81
+ graphStatus: snapshot.graph.status,
82
+ observedInputs: snapshot.graph.observedInputs,
83
+ values: request.policy,
84
+ nodes: nodes.map((node) => encodeNode(node, encoder, request.nodeId !== undefined)),
85
+ edges: edges.map(encodeEdge),
86
+ };
87
+ }
88
+
89
+ function encodeEdge(edge: Graph.EdgeSnapshot): EncodedGraphEdge {
90
+ return { from: edge.from, to: edge.to, dependency: edge.dependency };
91
+ }
92
+
93
+ /**
94
+ * One node's worth of failure stays one node's worth.
95
+ *
96
+ * The value encoder guards its own walks, so reaching here should take something
97
+ * it does not model at all. But a graph read is the answer to "what is the app
98
+ * doing", and answering it with a single `Failed` because one row of three
99
+ * hundred could not be encoded trades a complete diagnosis for none. The
100
+ * identity fields are the runtime's own struct rather than app data, so a row
101
+ * that keeps them and drops everything else is still a row a reader can act on —
102
+ * and `status` naming the hole is what stops it reading as a healthy node.
103
+ */
104
+ function encodeNode(
105
+ node: Graph.NodeSnapshot,
106
+ encoder: ValueEncoder,
107
+ includeResult: boolean
108
+ ): EncodedNodeSnapshot {
109
+ try {
110
+ return encodeNodeUnguarded(node, encoder, includeResult);
111
+ } catch {
112
+ return {
113
+ nodeId: node.nodeId,
114
+ tag: node.tag,
115
+ kind: node.kind,
116
+ state: node._tag,
117
+ revision: node.revision,
118
+ status: { _: "opaque", type: "unreadable" },
119
+ liveDemand: { _: "opaque", type: "unreadable" },
120
+ operation: { _: "opaque", type: "unreadable" },
121
+ };
122
+ }
123
+ }
124
+
125
+ function encodeNodeUnguarded(
126
+ node: Graph.NodeSnapshot,
127
+ encoder: ValueEncoder,
128
+ includeResult: boolean
129
+ ): EncodedNodeSnapshot {
130
+ const failure = nodeFailure(node);
131
+
132
+ return {
133
+ nodeId: node.nodeId,
134
+ tag: node.tag,
135
+ kind: node.kind,
136
+ state: node._tag,
137
+ revision: node.revision,
138
+ // `status` can carry an error of its own — `Invalid.error`, or a `Wired` run
139
+ // state that is `Error`. Those reach the value encoder, which routes an
140
+ // `Error` to the same cause-chain description at either policy, so they are
141
+ // not lost the way a hand-rolled struct walk would lose them.
142
+ status: encoder.value(node.status),
143
+ liveDemand: encoder.value(node.liveDemand),
144
+ operation: encoder.value(node.operation),
145
+ ...absent("resultValidity", node.resultValidity, encoder.value),
146
+ ...absent("failure", failure, encoder.failure),
147
+ ...absent("operationFailure", encodeOperationFailure(node.operationFailure, encoder), identity),
148
+ ...absent("liveFailure", encodeLiveFailure(node.liveFailure, encoder), identity),
149
+ // Read off the `Ready` arm rather than from a general field walk, because
150
+ // that is the only arm that has one — an unresolved node has no result, and
151
+ // an absent field here means exactly that.
152
+ ...absent(
153
+ "result",
154
+ includeResult && node._tag === "Ready" ? { value: node.result } : undefined,
155
+ (held) => encoder.value(held.value)
156
+ ),
157
+ };
158
+ }
159
+
160
+ const identity = <A>(value: A): A => value;
161
+
162
+ /**
163
+ * Omits the key rather than setting it to `undefined`.
164
+ *
165
+ * Load-bearing, not tidiness. These fields cross as `Schema.optional`, and an
166
+ * explicit `undefined` in that position does not survive the trip — it arrives
167
+ * as `null`, so a healthy node would report `failure: null` and a topology read
168
+ * would report a `result` on every node it deliberately withheld one from. An
169
+ * absent key is the only encoding that still reads as "there is nothing here".
170
+ *
171
+ * The `result` case goes through a wrapper because `undefined` is a legitimate
172
+ * value for a `Ready` node to hold, and unwrapping it here would make "the node
173
+ * resolved to undefined" indistinguishable from "no result was asked for".
174
+ */
175
+ function absent<K extends string, A, B>(
176
+ key: K,
177
+ value: A | undefined,
178
+ encode: (value: A) => B
179
+ ): { [P in K]?: B } {
180
+ return value === undefined ? {} : ({ [key]: encode(value) } as { [P in K]?: B });
181
+ }
182
+
183
+ /**
184
+ * The failure that explains this node's state, if it has one.
185
+ *
186
+ * The arm-specific error wins over the general `failure` field: on a node that
187
+ * is `ReadinessError` or `Invalid`, that error *is* why the node is in that arm,
188
+ * whereas `failure` is whatever was last recorded and can be older.
189
+ */
190
+ function nodeFailure(node: Graph.NodeSnapshot): unknown {
191
+ if (node._tag === "ReadinessError" || node._tag === "Invalid") {
192
+ return node.error;
193
+ }
194
+
195
+ return node.failure;
196
+ }
197
+
198
+ /**
199
+ * Unwrapped rather than handed to the value encoder whole.
200
+ *
201
+ * `NodeOperationFailure` is a struct with an error inside it, and passing the
202
+ * struct as a value would reduce the whole thing to `{operationId,kind,at,error}`
203
+ * at `"shape"` — a key list, with the error behind the last key never described
204
+ * at all. That is the exact loss the failure path exists to prevent. Naming the
205
+ * field explicitly is what keeps the chain crossing at every policy.
206
+ */
207
+ function encodeOperationFailure(
208
+ failure: OperationFailure | undefined,
209
+ encoder: ValueEncoder
210
+ ): unknown | undefined {
211
+ return failure === undefined
212
+ ? undefined
213
+ : {
214
+ operationId: failure.operationId,
215
+ kind: failure.kind,
216
+ at: failure.at,
217
+ error: encoder.failure(failure.error),
218
+ };
219
+ }
220
+
221
+ /** Same reasoning as {@link encodeOperationFailure}, over a list. */
222
+ function encodeLiveFailure(
223
+ failure: LiveFailure | undefined,
224
+ encoder: ValueEncoder
225
+ ): unknown | undefined {
226
+ return failure === undefined
227
+ ? undefined
228
+ : { at: failure.at, failures: failure.failures.map(encoder.failure) };
229
+ }