@milaboratories/pl-middle-layer 2.1.2 → 2.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.
Files changed (47) hide show
  1. package/dist/middle_layer/block_status_fold.cjs +382 -0
  2. package/dist/middle_layer/block_status_fold.cjs.map +1 -0
  3. package/dist/middle_layer/block_status_fold.js +373 -0
  4. package/dist/middle_layer/block_status_fold.js.map +1 -0
  5. package/dist/middle_layer/block_status_tree.cjs +287 -0
  6. package/dist/middle_layer/block_status_tree.cjs.map +1 -0
  7. package/dist/middle_layer/block_status_tree.js +283 -0
  8. package/dist/middle_layer/block_status_tree.js.map +1 -0
  9. package/dist/middle_layer/build_stamp.cjs +1 -1
  10. package/dist/middle_layer/build_stamp.js +1 -1
  11. package/dist/middle_layer/instance_stats.cjs +2 -2
  12. package/dist/middle_layer/instance_stats.cjs.map +1 -1
  13. package/dist/middle_layer/instance_stats.js +2 -2
  14. package/dist/middle_layer/instance_stats.js.map +1 -1
  15. package/dist/middle_layer/project.cjs +73 -2
  16. package/dist/middle_layer/project.cjs.map +1 -1
  17. package/dist/middle_layer/project.d.ts +22 -1
  18. package/dist/middle_layer/project.d.ts.map +1 -1
  19. package/dist/middle_layer/project.js +74 -3
  20. package/dist/middle_layer/project.js.map +1 -1
  21. package/dist/model/project_model.cjs +27 -0
  22. package/dist/model/project_model.cjs.map +1 -1
  23. package/dist/model/project_model.js +25 -1
  24. package/dist/model/project_model.js.map +1 -1
  25. package/dist/mutator/project.cjs +2 -1
  26. package/dist/mutator/project.cjs.map +1 -1
  27. package/dist/mutator/project.d.ts.map +1 -1
  28. package/dist/mutator/project.js +3 -2
  29. package/dist/mutator/project.js.map +1 -1
  30. package/dist/mutator/template/render_block.cjs +24 -0
  31. package/dist/mutator/template/render_block.cjs.map +1 -1
  32. package/dist/mutator/template/render_block.js +23 -2
  33. package/dist/mutator/template/render_block.js.map +1 -1
  34. package/package.json +14 -14
  35. package/src/middle_layer/block_status_bench.test.ts +197 -0
  36. package/src/middle_layer/block_status_fold.test.ts +694 -0
  37. package/src/middle_layer/block_status_fold.ts +563 -0
  38. package/src/middle_layer/block_status_tree.test.ts +253 -0
  39. package/src/middle_layer/block_status_tree.ts +391 -0
  40. package/src/middle_layer/instance_stats.test.ts +7 -9
  41. package/src/middle_layer/instance_stats.ts +2 -2
  42. package/src/middle_layer/project.ts +111 -2
  43. package/src/middle_layer/project_pruning.test.ts +59 -0
  44. package/src/model/project_model.ts +30 -0
  45. package/src/mutator/project.ts +7 -1
  46. package/src/mutator/project_action_context.test.ts +13 -3
  47. package/src/mutator/template/render_block.ts +32 -2
@@ -0,0 +1,287 @@
1
+ const require_project_model = require("../model/project_model.cjs");
2
+ const require_render_block = require("../mutator/template/render_block.cjs");
3
+ const require_block_status_fold = require("./block_status_fold.cjs");
4
+ let _milaboratories_pl_model_middle_layer = require("@milaboratories/pl-model-middle-layer");
5
+ let _milaboratories_computable = require("@milaboratories/computable");
6
+ let node_timers_promises = require("node:timers/promises");
7
+ let _milaboratories_pl_client = require("@milaboratories/pl-client");
8
+ let _milaboratories_pl_tree = require("@milaboratories/pl-tree");
9
+ // src/middle_layer/block_status_tree.ts
10
+ /**
11
+ * How long the refetch loop waits between looks at the project's change generation.
12
+ *
13
+ * The tick itself reads an in-memory counter. It opens a read transaction only when the project
14
+ * has changed since the last look, which while a block runs is most ticks: one read transaction
15
+ * per second per watched block, which is the cost of noticing a re-run promptly.
16
+ */
17
+ const RefetchDebounceMs = 1e3;
18
+ /** The poll floor of a status tree, as the spec sets it. */
19
+ const StatusTreePollingIntervalMs = 5e3;
20
+ /**
21
+ * Deadline for the first load of a status tree.
22
+ *
23
+ * Deliberately NOT the project tree's, which disables the timeout outright: a status tree is
24
+ * opened and closed while the app runs, and {@link BlockStatusWatch.terminate} awaits the loop, so
25
+ * an init that never returns would hang a project close and with it the app's shutdown.
26
+ */
27
+ const StatusTreeInitialLoadTimeoutMs = 3e4;
28
+ /** The status tree walks action contexts and nothing else. */
29
+ const statusTreeFieldFilter = _milaboratories_pl_client.treeFilter.resourceTypeEq(_milaboratories_pl_client.ResourceTypeName.ActionContext);
30
+ /**
31
+ * The root action context of a block render, read once from the project.
32
+ *
33
+ * Undefined when the block has no context: it was never rendered, or it ran against a backend or a
34
+ * middle layer that did not create one.
35
+ */
36
+ async function readBlockActionContextRoot(pl, projectRid, blockId, mode) {
37
+ return await pl.withReadTx("readBlockActionContextRoot", async (tx) => {
38
+ const project = await tx.getResourceData(projectRid, true);
39
+ const fieldName = require_project_model.projectFieldName(blockId, mode === "prod" ? "prodActionContext" : "stagingActionContext");
40
+ const statusField = project.fields.find((f) => f.name === fieldName);
41
+ if (statusField === void 0 || (0, _milaboratories_pl_client.isNullSignedResourceId)(statusField.value)) return void 0;
42
+ return statusField.value;
43
+ });
44
+ }
45
+ /** Adapts a tree node accessor to what the fold reads. */
46
+ function actionContextNode(acc) {
47
+ return {
48
+ id: String(acc.id),
49
+ getData: () => acc.getDataAsJson(),
50
+ listKeyValuesAsString: (prefix) => acc.listKeyValuesAsString(prefix),
51
+ listFields: () => acc.listFields(),
52
+ traverse: (field) => {
53
+ const child = acc.traverse({
54
+ field,
55
+ ignoreError: true
56
+ });
57
+ return child === void 0 ? void 0 : actionContextNode(child);
58
+ }
59
+ };
60
+ }
61
+ /**
62
+ * The fold of the context an entry points at and everything under it, one computable per context.
63
+ *
64
+ * A report is a KV write into one context, and only that context's computable reads its KV, so a
65
+ * report re-reads that one context. Each computable above it re-merges its direct children, which
66
+ * are cached, and nothing else in the tree is read again.
67
+ *
68
+ * Undefined when the context cannot be read. A context that is gone is the ordinary case, not a
69
+ * fault: an ephemeral context is dropped as soon as the project stops holding it, which happens the
70
+ * moment the block is run again, and the watch is briefly pointed at it until the next look for a
71
+ * new render. A child that cannot be read is left out rather than breaking the whole run's status.
72
+ * The cause is logged, so a genuine fault is not silent.
73
+ */
74
+ function subtreeFold(entry, path, onError) {
75
+ return _milaboratories_computable.Computable.make((ctx) => {
76
+ try {
77
+ const acc = ctx.accessor(entry).node({ ignoreError: true });
78
+ if (acc === void 0) return void 0;
79
+ const node = actionContextNode(acc);
80
+ const below = new Set(path).add(node.id);
81
+ const children = require_block_status_fold.childContexts(acc.listFields(), (field) => acc.traverse({
82
+ field,
83
+ ignoreError: true
84
+ }), below).map((child) => subtreeFold(child.persist(), below, onError));
85
+ return {
86
+ own: require_block_status_fold.foldContext(node),
87
+ children
88
+ };
89
+ } catch (err) {
90
+ onError(err);
91
+ return;
92
+ }
93
+ }, {
94
+ key: `block-status-context/${entry.id}`,
95
+ postprocessValue: (value) => {
96
+ if (value === void 0) return void 0;
97
+ const children = [];
98
+ for (const child of value.children) if (child !== void 0) children.push(child);
99
+ return require_block_status_fold.mergeSubtree(value.own, children);
100
+ }
101
+ });
102
+ }
103
+ /** The summary of the run whose root context an entry points at. */
104
+ function entrySummary(entry, reportsSupported, onError) {
105
+ return _milaboratories_computable.Computable.make(() => ({ fold: subtreeFold(entry, /* @__PURE__ */ new Set(), onError) }), {
106
+ key: `block-status-summary/${entry.id}`,
107
+ postprocessValue: ({ fold }) => {
108
+ if (fold === void 0) return _milaboratories_pl_model_middle_layer.UnreadableBlockStatusSummary;
109
+ const summary = require_block_status_fold.summarize(fold);
110
+ if (reportsSupported || summary.totalContexts === 0) return summary;
111
+ return {
112
+ ...summary,
113
+ availability: "unsupported"
114
+ };
115
+ }
116
+ });
117
+ }
118
+ /**
119
+ * The live status of one block render.
120
+ *
121
+ * The summary is stable across runs of the block: clicking Run creates a new render with a new
122
+ * status context, and the watch re-seeds itself onto it rather than handing the caller a new
123
+ * computable. The watch is shared between callers and reference counted; the tree lives until the
124
+ * last holder releases it.
125
+ */
126
+ var BlockStatusWatch = class BlockStatusWatch {
127
+ /** The entry of the tree currently seeded, swapped when the block is run again. */
128
+ source = new _milaboratories_computable.WatchableValue(void 0);
129
+ current;
130
+ abortController = new AbortController();
131
+ loop;
132
+ /**
133
+ * Orders the seeds. A reseed that started before the one that last installed a root is stale by
134
+ * the time it finishes, however long its tree took to open, and must not displace it.
135
+ */
136
+ seedSequence = 0;
137
+ installedSeed = -1;
138
+ /** How many callers hold this watch. The tree is terminated when it reaches zero. */
139
+ holders = 0;
140
+ summary;
141
+ env;
142
+ projectRid;
143
+ blockId;
144
+ mode;
145
+ projectGeneration;
146
+ constructor({ env, projectRid, blockId, mode, projectGeneration }) {
147
+ this.env = env;
148
+ this.projectRid = projectRid;
149
+ this.blockId = blockId;
150
+ this.mode = mode;
151
+ this.projectGeneration = projectGeneration;
152
+ const reportsSupported = env.pl.hasCapability(require_render_block.ActionContextLinkCapability);
153
+ this.summary = _milaboratories_computable.Computable.make((ctx) => {
154
+ const entry = this.source.getValue(ctx);
155
+ if (entry === void 0) return reportsSupported ? _milaboratories_pl_model_middle_layer.EmptyBlockStatusSummary : _milaboratories_pl_model_middle_layer.UnsupportedBlockStatusSummary;
156
+ return entrySummary(entry, reportsSupported, (err) => this.env.logger.warn(new Error("block status fold failed", { cause: err })));
157
+ });
158
+ }
159
+ /**
160
+ * Starts watching the status of a block render.
161
+ *
162
+ * The first seed is awaited, so the caller gets a handle that already reports whatever the
163
+ * current render has reported. A block with no status context yet still gets a handle: it
164
+ * reports an empty summary and seeds itself when a render that has one appears.
165
+ *
166
+ * The refetch loop is started only once that first seed has settled. Starting it in the
167
+ * constructor would leave it running with nobody holding a reference to stop it if this throws.
168
+ */
169
+ static async start(params) {
170
+ const watch = new BlockStatusWatch(params);
171
+ try {
172
+ await watch.reseed();
173
+ } catch (err) {
174
+ await watch.terminateNow();
175
+ throw err;
176
+ }
177
+ watch.begin();
178
+ return watch;
179
+ }
180
+ /** Takes the first holder and starts looking for new renders, once the first seed settled. */
181
+ begin() {
182
+ this.holders = 1;
183
+ this.loop = this.refetchLoop().catch((err) => {
184
+ this.env.logger.warn(new Error("block status refetch loop failed", { cause: err }));
185
+ });
186
+ }
187
+ /** Records one more caller holding this watch. */
188
+ retain() {
189
+ this.holders++;
190
+ }
191
+ /**
192
+ * Releases one caller's hold. The tree is terminated, and the watch is finished, only when the
193
+ * last holder lets go; returns true when that happened.
194
+ */
195
+ async release() {
196
+ if (this.holders > 0) this.holders--;
197
+ if (this.holders > 0) return false;
198
+ await this.terminateNow();
199
+ return true;
200
+ }
201
+ /**
202
+ * Stops the watch whatever the holder count, for a project being torn down. An ordinary caller
203
+ * uses {@link release}.
204
+ */
205
+ async terminate() {
206
+ this.holders = 0;
207
+ await this.terminateNow();
208
+ }
209
+ /** Stops the loop, terminates the tree and releases the computable's holders. */
210
+ async terminateNow() {
211
+ this.abortController.abort();
212
+ await this.loop;
213
+ const held = this.current;
214
+ this.current = void 0;
215
+ this.source.setValue(void 0, "block status watch terminated");
216
+ this.summary.resetState();
217
+ await this.terminateTree(held?.tree);
218
+ }
219
+ /**
220
+ * Looks for a new render while the caller watches.
221
+ *
222
+ * The project field holding the root context is pruned from the project tree, so the re-point is
223
+ * not visible there; what is visible is that the project changed at all. A tick that finds the
224
+ * same root installs nothing.
225
+ */
226
+ async refetchLoop() {
227
+ let seen = this.projectGeneration();
228
+ while (!this.abortController.signal.aborted) {
229
+ try {
230
+ await (0, node_timers_promises.setTimeout)(RefetchDebounceMs, void 0, { signal: this.abortController.signal });
231
+ } catch {
232
+ return;
233
+ }
234
+ const generation = this.projectGeneration();
235
+ if (generation === seen) continue;
236
+ try {
237
+ await this.reseed();
238
+ seen = generation;
239
+ } catch (err) {
240
+ if (this.abortController.signal.aborted) return;
241
+ this.env.logger.warn(new Error("block status reseed failed", { cause: err }));
242
+ }
243
+ }
244
+ }
245
+ /** Points the summary at the current render's context, replacing any earlier one. */
246
+ async reseed() {
247
+ const seed = ++this.seedSequence;
248
+ const root = await readBlockActionContextRoot(this.env.pl, this.projectRid, this.blockId, this.mode);
249
+ if (this.abortController.signal.aborted) return;
250
+ if (seed < this.installedSeed) return;
251
+ if (root === this.current?.root) return;
252
+ const tree = root === void 0 ? void 0 : await _milaboratories_pl_tree.SynchronizedTreeState.init(this.env.pl, root, {
253
+ ...this.env.ops.defaultTreeOptions,
254
+ pollingInterval: StatusTreePollingIntervalMs,
255
+ initialTreeLoadingTimeout: StatusTreeInitialLoadTimeoutMs,
256
+ fieldFilter: statusTreeFieldFilter,
257
+ rootsNeverFinal: true
258
+ }, this.env.logger);
259
+ if (this.abortController.signal.aborted || seed < this.installedSeed) {
260
+ await this.terminateTree(tree);
261
+ return;
262
+ }
263
+ const previous = this.current;
264
+ this.installedSeed = seed;
265
+ this.current = root !== void 0 && tree !== void 0 ? {
266
+ root,
267
+ tree
268
+ } : void 0;
269
+ this.source.setValue(tree?.entry(), "block status root changed");
270
+ await this.terminateTree(previous?.tree);
271
+ }
272
+ async terminateTree(tree) {
273
+ if (tree === void 0) return;
274
+ try {
275
+ await tree.terminate();
276
+ } catch (err) {
277
+ this.env.logger.warn(new Error("block status tree termination failed", { cause: err }));
278
+ }
279
+ }
280
+ };
281
+ exports.BlockStatusWatch = BlockStatusWatch;
282
+ exports.actionContextNode = actionContextNode;
283
+ exports.entrySummary = entrySummary;
284
+ exports.readBlockActionContextRoot = readBlockActionContextRoot;
285
+ exports.subtreeFold = subtreeFold;
286
+
287
+ //# sourceMappingURL=block_status_tree.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"block_status_tree.cjs","names":["treeFilter","ResourceTypeName","projectFieldName","isNullSignedResourceId","Computable","childContexts","foldContext","mergeSubtree","UnreadableBlockStatusSummary","summarize","WatchableValue","ActionContextLinkCapability","EmptyBlockStatusSummary","UnsupportedBlockStatusSummary","setTimeout","SynchronizedTreeState"],"sources":["../../src/middle_layer/block_status_tree.ts"],"sourcesContent":["/**\n * The live action-context tree of one block render, and the computable that folds it.\n *\n * A status tree is its own {@link SynchronizedTreeState}, seeded at the root action context of the\n * render rather than at the project. It has to be separate: the project tree prunes the context\n * fields (see `ProjectStatusFieldPattern`), because a context holds the whole subtree of its render\n * and every report into it is a KV write.\n *\n * One tree per watched block, held while anyone watches, terminated when the last holder lets go.\n */\n\nimport type { PlClient, SignedResourceId } from \"@milaboratories/pl-client\";\nimport { isNullSignedResourceId, ResourceTypeName, treeFilter } from \"@milaboratories/pl-client\";\nimport { Computable, WatchableValue } from \"@milaboratories/computable\";\nimport type { PlTreeEntry, PlTreeNodeAccessor } from \"@milaboratories/pl-tree\";\nimport { SynchronizedTreeState } from \"@milaboratories/pl-tree\";\nimport type { BlockStatusSummary } from \"@milaboratories/pl-model-middle-layer\";\nimport {\n EmptyBlockStatusSummary,\n UnreadableBlockStatusSummary,\n UnsupportedBlockStatusSummary,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport { setTimeout } from \"node:timers/promises\";\nimport type { ActionContextNode, SubtreeFold } from \"./block_status_fold\";\nimport { childContexts, foldContext, mergeSubtree, summarize } from \"./block_status_fold\";\nimport type { BlockActionContextMode } from \"./block_action_context\";\nimport { ActionContextLinkCapability } from \"../mutator/template/render_block\";\nimport { projectFieldName } from \"../model/project_model\";\nimport type { MiddleLayerEnvironment } from \"./middle_layer\";\n\n/**\n * How long the refetch loop waits between looks at the project's change generation.\n *\n * The tick itself reads an in-memory counter. It opens a read transaction only when the project\n * has changed since the last look, which while a block runs is most ticks: one read transaction\n * per second per watched block, which is the cost of noticing a re-run promptly.\n */\nconst RefetchDebounceMs = 1_000;\n\n/** The poll floor of a status tree, as the spec sets it. */\nconst StatusTreePollingIntervalMs = 5_000;\n\n/**\n * Deadline for the first load of a status tree.\n *\n * Deliberately NOT the project tree's, which disables the timeout outright: a status tree is\n * opened and closed while the app runs, and {@link BlockStatusWatch.terminate} awaits the loop, so\n * an init that never returns would hang a project close and with it the app's shutdown.\n */\nconst StatusTreeInitialLoadTimeoutMs = 30_000;\n\n/** The status tree walks action contexts and nothing else. */\nconst statusTreeFieldFilter = treeFilter.resourceTypeEq(ResourceTypeName.ActionContext);\n\n/**\n * The root action context of a block render, read once from the project.\n *\n * Undefined when the block has no context: it was never rendered, or it ran against a backend or a\n * middle layer that did not create one.\n */\nexport async function readBlockActionContextRoot(\n pl: PlClient,\n projectRid: SignedResourceId,\n blockId: string,\n mode: BlockActionContextMode,\n): Promise<SignedResourceId | undefined> {\n return await pl.withReadTx(\"readBlockActionContextRoot\", async (tx) => {\n const project = await tx.getResourceData(projectRid, true);\n const fieldName = projectFieldName(\n blockId,\n mode === \"prod\" ? \"prodActionContext\" : \"stagingActionContext\",\n );\n const statusField = project.fields.find((f) => f.name === fieldName);\n if (statusField === undefined || isNullSignedResourceId(statusField.value)) return undefined;\n return statusField.value;\n });\n}\n\n/** Adapts a tree node accessor to what the fold reads. */\nexport function actionContextNode(acc: PlTreeNodeAccessor): ActionContextNode {\n return {\n id: String(acc.id),\n getData: () => acc.getDataAsJson<Record<string, unknown>>(),\n listKeyValuesAsString: (prefix: string) => acc.listKeyValuesAsString(prefix),\n listFields: () => acc.listFields(),\n traverse: (field: string) => {\n // A child that carries an error is skipped rather than thrown: the status surface is\n // diagnostic, and one broken branch must not take the whole line down with it.\n const child = acc.traverse({ field, ignoreError: true });\n return child === undefined ? undefined : actionContextNode(child);\n },\n };\n}\n\n/**\n * The fold of the context an entry points at and everything under it, one computable per context.\n *\n * A report is a KV write into one context, and only that context's computable reads its KV, so a\n * report re-reads that one context. Each computable above it re-merges its direct children, which\n * are cached, and nothing else in the tree is read again.\n *\n * Undefined when the context cannot be read. A context that is gone is the ordinary case, not a\n * fault: an ephemeral context is dropped as soon as the project stops holding it, which happens the\n * moment the block is run again, and the watch is briefly pointed at it until the next look for a\n * new render. A child that cannot be read is left out rather than breaking the whole run's status.\n * The cause is logged, so a genuine fault is not silent.\n */\nexport function subtreeFold(\n entry: PlTreeEntry,\n path: ReadonlySet<string>,\n onError: (err: unknown) => void,\n): Computable<SubtreeFold | undefined> {\n return Computable.make(\n (ctx) => {\n try {\n const acc = ctx.accessor(entry).node({ ignoreError: true });\n if (acc === undefined) return undefined;\n const node = actionContextNode(acc);\n const below = new Set(path).add(node.id);\n const children = childContexts(\n acc.listFields(),\n // A child that carries an error is skipped rather than thrown, as in actionContextNode.\n (field) => acc.traverse({ field, ignoreError: true }),\n below,\n ).map((child) => subtreeFold(child.persist(), below, onError));\n return { own: foldContext(node), children };\n } catch (err: unknown) {\n onError(err);\n return undefined;\n }\n },\n {\n key: `block-status-context/${entry.id}`,\n postprocessValue: (value) => {\n if (value === undefined) return undefined;\n const children: SubtreeFold[] = [];\n for (const child of value.children) if (child !== undefined) children.push(child);\n return mergeSubtree(value.own, children);\n },\n },\n );\n}\n\n/** The summary of the run whose root context an entry points at. */\nexport function entrySummary(\n entry: PlTreeEntry,\n reportsSupported: boolean,\n onError: (err: unknown) => void,\n): Computable<BlockStatusSummary> {\n return Computable.make(() => ({ fold: subtreeFold(entry, new Set(), onError) }), {\n key: `block-status-summary/${entry.id}`,\n postprocessValue: ({ fold }) => {\n // The counters of a context that could not be read are unknown, not zero.\n if (fold === undefined) return UnreadableBlockStatusSummary;\n const summary = summarize(fold);\n if (reportsSupported || summary.totalContexts === 0) return summary;\n // The context exists and carries its data, but no transition can ever arrive.\n return { ...summary, availability: \"unsupported\" as const };\n },\n });\n}\n\n/** What {@link BlockStatusWatch.start} watches. */\nexport type BlockStatusWatchParams = {\n readonly env: MiddleLayerEnvironment;\n readonly projectRid: SignedResourceId;\n readonly blockId: string;\n readonly mode: BlockActionContextMode;\n /** The project tree's change generation, the trigger for looking for a new render. */\n readonly projectGeneration: () => number;\n};\n\n/**\n * The live status of one block render.\n *\n * The summary is stable across runs of the block: clicking Run creates a new render with a new\n * status context, and the watch re-seeds itself onto it rather than handing the caller a new\n * computable. The watch is shared between callers and reference counted; the tree lives until the\n * last holder releases it.\n */\nexport class BlockStatusWatch {\n /** The entry of the tree currently seeded, swapped when the block is run again. */\n private readonly source = new WatchableValue<PlTreeEntry | undefined>(undefined);\n private current?: { readonly root: SignedResourceId; readonly tree: SynchronizedTreeState };\n private readonly abortController = new AbortController();\n private loop?: Promise<void>;\n\n /**\n * Orders the seeds. A reseed that started before the one that last installed a root is stale by\n * the time it finishes, however long its tree took to open, and must not displace it.\n */\n private seedSequence = 0;\n private installedSeed = -1;\n\n /** How many callers hold this watch. The tree is terminated when it reaches zero. */\n private holders = 0;\n\n public readonly summary: Computable<BlockStatusSummary>;\n\n private readonly env: MiddleLayerEnvironment;\n private readonly projectRid: SignedResourceId;\n private readonly blockId: string;\n private readonly mode: BlockActionContextMode;\n private readonly projectGeneration: () => number;\n\n private constructor({\n env,\n projectRid,\n blockId,\n mode,\n projectGeneration,\n }: BlockStatusWatchParams) {\n this.env = env;\n this.projectRid = projectRid;\n this.blockId = blockId;\n this.mode = mode;\n this.projectGeneration = projectGeneration;\n // Without the `actionContext` link a block has no context and nothing is ever reported.\n const reportsSupported = env.pl.hasCapability(ActionContextLinkCapability);\n // One computable for the life of the watch, reading whichever tree is seeded now, so a caller\n // keeps its handle across a re-run of the block.\n this.summary = Computable.make((ctx) => {\n const entry = this.source.getValue(ctx);\n if (entry === undefined)\n return reportsSupported ? EmptyBlockStatusSummary : UnsupportedBlockStatusSummary;\n return entrySummary(entry, reportsSupported, (err) =>\n this.env.logger.warn(new Error(\"block status fold failed\", { cause: err })),\n );\n });\n }\n\n /**\n * Starts watching the status of a block render.\n *\n * The first seed is awaited, so the caller gets a handle that already reports whatever the\n * current render has reported. A block with no status context yet still gets a handle: it\n * reports an empty summary and seeds itself when a render that has one appears.\n *\n * The refetch loop is started only once that first seed has settled. Starting it in the\n * constructor would leave it running with nobody holding a reference to stop it if this throws.\n */\n public static async start(params: BlockStatusWatchParams): Promise<BlockStatusWatch> {\n const watch = new BlockStatusWatch(params);\n try {\n await watch.reseed();\n } catch (err: unknown) {\n await watch.terminateNow();\n throw err;\n }\n watch.begin();\n return watch;\n }\n\n /** Takes the first holder and starts looking for new renders, once the first seed settled. */\n private begin(): void {\n this.holders = 1;\n // The loop handles its own errors; this catch is only a backstop, so the promise kept here\n // never rejects and can be awaited as is.\n this.loop = this.refetchLoop().catch((err: unknown) => {\n this.env.logger.warn(new Error(\"block status refetch loop failed\", { cause: err }));\n });\n }\n\n /** Records one more caller holding this watch. */\n public retain(): void {\n this.holders++;\n }\n\n /**\n * Releases one caller's hold. The tree is terminated, and the watch is finished, only when the\n * last holder lets go; returns true when that happened.\n */\n public async release(): Promise<boolean> {\n if (this.holders > 0) this.holders--;\n if (this.holders > 0) return false;\n await this.terminateNow();\n return true;\n }\n\n /**\n * Stops the watch whatever the holder count, for a project being torn down. An ordinary caller\n * uses {@link release}.\n */\n public async terminate(): Promise<void> {\n this.holders = 0;\n await this.terminateNow();\n }\n\n /** Stops the loop, terminates the tree and releases the computable's holders. */\n private async terminateNow(): Promise<void> {\n this.abortController.abort();\n await this.loop;\n const held = this.current;\n this.current = undefined;\n this.source.setValue(undefined, \"block status watch terminated\");\n this.summary.resetState();\n await this.terminateTree(held?.tree);\n }\n\n /**\n * Looks for a new render while the caller watches.\n *\n * The project field holding the root context is pruned from the project tree, so the re-point is\n * not visible there; what is visible is that the project changed at all. A tick that finds the\n * same root installs nothing.\n */\n private async refetchLoop(): Promise<void> {\n let seen = this.projectGeneration();\n while (!this.abortController.signal.aborted) {\n try {\n await setTimeout(RefetchDebounceMs, undefined, { signal: this.abortController.signal });\n } catch {\n return; // aborted\n }\n\n const generation = this.projectGeneration();\n if (generation === seen) continue;\n\n try {\n await this.reseed();\n // Only once the look succeeded, so a failed one is retried on the next tick rather than\n // waiting for the project to change again.\n seen = generation;\n } catch (err: unknown) {\n if (this.abortController.signal.aborted) return;\n // The current tree stays in place: the surface keeps showing what it has rather than\n // going blank, and the next tick tries again.\n this.env.logger.warn(new Error(\"block status reseed failed\", { cause: err }));\n }\n }\n }\n\n /** Points the summary at the current render's context, replacing any earlier one. */\n private async reseed(): Promise<void> {\n const seed = ++this.seedSequence;\n\n const root = await readBlockActionContextRoot(\n this.env.pl,\n this.projectRid,\n this.blockId,\n this.mode,\n );\n if (this.abortController.signal.aborted) return;\n if (seed < this.installedSeed) return;\n if (root === this.current?.root) return;\n\n const tree =\n root === undefined\n ? undefined\n : await SynchronizedTreeState.init(\n this.env.pl,\n root,\n {\n ...this.env.ops.defaultTreeOptions,\n pollingInterval: StatusTreePollingIntervalMs,\n initialTreeLoadingTimeout: StatusTreeInitialLoadTimeoutMs,\n fieldFilter: statusTreeFieldFilter,\n // A context never becomes final: the backend keeps reporting into it for as long as\n // its render lives, so every poll has to seed it again.\n rootsNeverFinal: true,\n },\n this.env.logger,\n );\n\n // Opening the tree took time, and a later reseed may have installed a newer root meanwhile.\n // Terminating the tree just opened is the whole cost of losing that race.\n if (this.abortController.signal.aborted || seed < this.installedSeed) {\n await this.terminateTree(tree);\n return;\n }\n\n const previous = this.current;\n this.installedSeed = seed;\n this.current = root !== undefined && tree !== undefined ? { root, tree } : undefined;\n\n // Swapped before the old tree is terminated. A computable body runs to completion\n // synchronously, so after this returns no reader is inside the old tree.\n this.source.setValue(tree?.entry(), \"block status root changed\");\n await this.terminateTree(previous?.tree);\n }\n\n private async terminateTree(tree: SynchronizedTreeState | undefined): Promise<void> {\n if (tree === undefined) return;\n try {\n await tree.terminate();\n } catch (err: unknown) {\n // terminate() can throw when the sync loop had already failed; nothing is left to clean up.\n this.env.logger.warn(new Error(\"block status tree termination failed\", { cause: err }));\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqCA,MAAM,oBAAoB;;AAG1B,MAAM,8BAA8B;;;;;;;;AASpC,MAAM,iCAAiC;;AAGvC,MAAM,wBAAwBA,0BAAAA,WAAW,eAAeC,0BAAAA,iBAAiB,aAAa;;;;;;;AAQtF,eAAsB,2BACpB,IACA,YACA,SACA,MACuC;CACvC,OAAO,MAAM,GAAG,WAAW,8BAA8B,OAAO,OAAO;EACrE,MAAM,UAAU,MAAM,GAAG,gBAAgB,YAAY,IAAI;EACzD,MAAM,YAAYC,sBAAAA,iBAChB,SACA,SAAS,SAAS,sBAAsB,sBAC1C;EACA,MAAM,cAAc,QAAQ,OAAO,MAAM,MAAM,EAAE,SAAS,SAAS;EACnE,IAAI,gBAAgB,KAAA,MAAA,GAAaC,0BAAAA,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AE,OAAO,IAAI,CAAC,CAAC;GAC9E;EACF;CACF;;CAGA,MAAc,SAAwB;EACpC,MAAM,OAAO,EAAE,KAAK;EAEpB,MAAM,OAAO,MAAM,2BACjB,KAAK,IAAI,IACT,KAAK,YACL,KAAK,SACL,KAAK,IACP;EACA,IAAI,KAAK,gBAAgB,OAAO,SAAS;EACzC,IAAI,OAAO,KAAK,eAAe;EAC/B,IAAI,SAAS,KAAK,SAAS,MAAM;EAEjC,MAAM,OACJ,SAAS,KAAA,IACL,KAAA,IACA,MAAMC,wBAAAA,sBAAsB,KAC1B,KAAK,IAAI,IACT,MACA;GACE,GAAG,KAAK,IAAI,IAAI;GAChB,iBAAiB;GACjB,2BAA2B;GAC3B,aAAa;GAGb,iBAAiB;EACnB,GACA,KAAK,IAAI,MACX;EAIN,IAAI,KAAK,gBAAgB,OAAO,WAAW,OAAO,KAAK,eAAe;GACpE,MAAM,KAAK,cAAc,IAAI;GAC7B;EACF;EAEA,MAAM,WAAW,KAAK;EACtB,KAAK,gBAAgB;EACrB,KAAK,UAAU,SAAS,KAAA,KAAa,SAAS,KAAA,IAAY;GAAE;GAAM;EAAK,IAAI,KAAA;EAI3E,KAAK,OAAO,SAAS,MAAM,MAAM,GAAG,2BAA2B;EAC/D,MAAM,KAAK,cAAc,UAAU,IAAI;CACzC;CAEA,MAAc,cAAc,MAAwD;EAClF,IAAI,SAAS,KAAA,GAAW;EACxB,IAAI;GACF,MAAM,KAAK,UAAU;EACvB,SAAS,KAAc;GAErB,KAAK,IAAI,OAAO,KAAK,IAAI,MAAM,wCAAwC,EAAE,OAAO,IAAI,CAAC,CAAC;EACxF;CACF;AACF"}
@@ -0,0 +1,283 @@
1
+ import { projectFieldName } from "../model/project_model.js";
2
+ import { ActionContextLinkCapability } from "../mutator/template/render_block.js";
3
+ import { childContexts, foldContext, mergeSubtree, summarize } from "./block_status_fold.js";
4
+ import { EmptyBlockStatusSummary, UnreadableBlockStatusSummary, UnsupportedBlockStatusSummary } from "@milaboratories/pl-model-middle-layer";
5
+ import { Computable, WatchableValue } from "@milaboratories/computable";
6
+ import { setTimeout } from "node:timers/promises";
7
+ import { ResourceTypeName, isNullSignedResourceId, treeFilter } from "@milaboratories/pl-client";
8
+ import { SynchronizedTreeState } from "@milaboratories/pl-tree";
9
+ // src/middle_layer/block_status_tree.ts
10
+ /**
11
+ * How long the refetch loop waits between looks at the project's change generation.
12
+ *
13
+ * The tick itself reads an in-memory counter. It opens a read transaction only when the project
14
+ * has changed since the last look, which while a block runs is most ticks: one read transaction
15
+ * per second per watched block, which is the cost of noticing a re-run promptly.
16
+ */
17
+ const RefetchDebounceMs = 1e3;
18
+ /** The poll floor of a status tree, as the spec sets it. */
19
+ const StatusTreePollingIntervalMs = 5e3;
20
+ /**
21
+ * Deadline for the first load of a status tree.
22
+ *
23
+ * Deliberately NOT the project tree's, which disables the timeout outright: a status tree is
24
+ * opened and closed while the app runs, and {@link BlockStatusWatch.terminate} awaits the loop, so
25
+ * an init that never returns would hang a project close and with it the app's shutdown.
26
+ */
27
+ const StatusTreeInitialLoadTimeoutMs = 3e4;
28
+ /** The status tree walks action contexts and nothing else. */
29
+ const statusTreeFieldFilter = treeFilter.resourceTypeEq(ResourceTypeName.ActionContext);
30
+ /**
31
+ * The root action context of a block render, read once from the project.
32
+ *
33
+ * Undefined when the block has no context: it was never rendered, or it ran against a backend or a
34
+ * middle layer that did not create one.
35
+ */
36
+ async function readBlockActionContextRoot(pl, projectRid, blockId, mode) {
37
+ return await pl.withReadTx("readBlockActionContextRoot", async (tx) => {
38
+ const project = await tx.getResourceData(projectRid, true);
39
+ const fieldName = projectFieldName(blockId, mode === "prod" ? "prodActionContext" : "stagingActionContext");
40
+ const statusField = project.fields.find((f) => f.name === fieldName);
41
+ if (statusField === void 0 || isNullSignedResourceId(statusField.value)) return void 0;
42
+ return statusField.value;
43
+ });
44
+ }
45
+ /** Adapts a tree node accessor to what the fold reads. */
46
+ function actionContextNode(acc) {
47
+ return {
48
+ id: String(acc.id),
49
+ getData: () => acc.getDataAsJson(),
50
+ listKeyValuesAsString: (prefix) => acc.listKeyValuesAsString(prefix),
51
+ listFields: () => acc.listFields(),
52
+ traverse: (field) => {
53
+ const child = acc.traverse({
54
+ field,
55
+ ignoreError: true
56
+ });
57
+ return child === void 0 ? void 0 : actionContextNode(child);
58
+ }
59
+ };
60
+ }
61
+ /**
62
+ * The fold of the context an entry points at and everything under it, one computable per context.
63
+ *
64
+ * A report is a KV write into one context, and only that context's computable reads its KV, so a
65
+ * report re-reads that one context. Each computable above it re-merges its direct children, which
66
+ * are cached, and nothing else in the tree is read again.
67
+ *
68
+ * Undefined when the context cannot be read. A context that is gone is the ordinary case, not a
69
+ * fault: an ephemeral context is dropped as soon as the project stops holding it, which happens the
70
+ * moment the block is run again, and the watch is briefly pointed at it until the next look for a
71
+ * new render. A child that cannot be read is left out rather than breaking the whole run's status.
72
+ * The cause is logged, so a genuine fault is not silent.
73
+ */
74
+ function subtreeFold(entry, path, onError) {
75
+ return Computable.make((ctx) => {
76
+ try {
77
+ const acc = ctx.accessor(entry).node({ ignoreError: true });
78
+ if (acc === void 0) return void 0;
79
+ const node = actionContextNode(acc);
80
+ const below = new Set(path).add(node.id);
81
+ const children = childContexts(acc.listFields(), (field) => acc.traverse({
82
+ field,
83
+ ignoreError: true
84
+ }), below).map((child) => subtreeFold(child.persist(), below, onError));
85
+ return {
86
+ own: foldContext(node),
87
+ children
88
+ };
89
+ } catch (err) {
90
+ onError(err);
91
+ return;
92
+ }
93
+ }, {
94
+ key: `block-status-context/${entry.id}`,
95
+ postprocessValue: (value) => {
96
+ if (value === void 0) return void 0;
97
+ const children = [];
98
+ for (const child of value.children) if (child !== void 0) children.push(child);
99
+ return mergeSubtree(value.own, children);
100
+ }
101
+ });
102
+ }
103
+ /** The summary of the run whose root context an entry points at. */
104
+ function entrySummary(entry, reportsSupported, onError) {
105
+ return Computable.make(() => ({ fold: subtreeFold(entry, /* @__PURE__ */ new Set(), onError) }), {
106
+ key: `block-status-summary/${entry.id}`,
107
+ postprocessValue: ({ fold }) => {
108
+ if (fold === void 0) return UnreadableBlockStatusSummary;
109
+ const summary = summarize(fold);
110
+ if (reportsSupported || summary.totalContexts === 0) return summary;
111
+ return {
112
+ ...summary,
113
+ availability: "unsupported"
114
+ };
115
+ }
116
+ });
117
+ }
118
+ /**
119
+ * The live status of one block render.
120
+ *
121
+ * The summary is stable across runs of the block: clicking Run creates a new render with a new
122
+ * status context, and the watch re-seeds itself onto it rather than handing the caller a new
123
+ * computable. The watch is shared between callers and reference counted; the tree lives until the
124
+ * last holder releases it.
125
+ */
126
+ var BlockStatusWatch = class BlockStatusWatch {
127
+ /** The entry of the tree currently seeded, swapped when the block is run again. */
128
+ source = new WatchableValue(void 0);
129
+ current;
130
+ abortController = new AbortController();
131
+ loop;
132
+ /**
133
+ * Orders the seeds. A reseed that started before the one that last installed a root is stale by
134
+ * the time it finishes, however long its tree took to open, and must not displace it.
135
+ */
136
+ seedSequence = 0;
137
+ installedSeed = -1;
138
+ /** How many callers hold this watch. The tree is terminated when it reaches zero. */
139
+ holders = 0;
140
+ summary;
141
+ env;
142
+ projectRid;
143
+ blockId;
144
+ mode;
145
+ projectGeneration;
146
+ constructor({ env, projectRid, blockId, mode, projectGeneration }) {
147
+ this.env = env;
148
+ this.projectRid = projectRid;
149
+ this.blockId = blockId;
150
+ this.mode = mode;
151
+ this.projectGeneration = projectGeneration;
152
+ const reportsSupported = env.pl.hasCapability(ActionContextLinkCapability);
153
+ this.summary = Computable.make((ctx) => {
154
+ const entry = this.source.getValue(ctx);
155
+ if (entry === void 0) return reportsSupported ? EmptyBlockStatusSummary : UnsupportedBlockStatusSummary;
156
+ return entrySummary(entry, reportsSupported, (err) => this.env.logger.warn(new Error("block status fold failed", { cause: err })));
157
+ });
158
+ }
159
+ /**
160
+ * Starts watching the status of a block render.
161
+ *
162
+ * The first seed is awaited, so the caller gets a handle that already reports whatever the
163
+ * current render has reported. A block with no status context yet still gets a handle: it
164
+ * reports an empty summary and seeds itself when a render that has one appears.
165
+ *
166
+ * The refetch loop is started only once that first seed has settled. Starting it in the
167
+ * constructor would leave it running with nobody holding a reference to stop it if this throws.
168
+ */
169
+ static async start(params) {
170
+ const watch = new BlockStatusWatch(params);
171
+ try {
172
+ await watch.reseed();
173
+ } catch (err) {
174
+ await watch.terminateNow();
175
+ throw err;
176
+ }
177
+ watch.begin();
178
+ return watch;
179
+ }
180
+ /** Takes the first holder and starts looking for new renders, once the first seed settled. */
181
+ begin() {
182
+ this.holders = 1;
183
+ this.loop = this.refetchLoop().catch((err) => {
184
+ this.env.logger.warn(new Error("block status refetch loop failed", { cause: err }));
185
+ });
186
+ }
187
+ /** Records one more caller holding this watch. */
188
+ retain() {
189
+ this.holders++;
190
+ }
191
+ /**
192
+ * Releases one caller's hold. The tree is terminated, and the watch is finished, only when the
193
+ * last holder lets go; returns true when that happened.
194
+ */
195
+ async release() {
196
+ if (this.holders > 0) this.holders--;
197
+ if (this.holders > 0) return false;
198
+ await this.terminateNow();
199
+ return true;
200
+ }
201
+ /**
202
+ * Stops the watch whatever the holder count, for a project being torn down. An ordinary caller
203
+ * uses {@link release}.
204
+ */
205
+ async terminate() {
206
+ this.holders = 0;
207
+ await this.terminateNow();
208
+ }
209
+ /** Stops the loop, terminates the tree and releases the computable's holders. */
210
+ async terminateNow() {
211
+ this.abortController.abort();
212
+ await this.loop;
213
+ const held = this.current;
214
+ this.current = void 0;
215
+ this.source.setValue(void 0, "block status watch terminated");
216
+ this.summary.resetState();
217
+ await this.terminateTree(held?.tree);
218
+ }
219
+ /**
220
+ * Looks for a new render while the caller watches.
221
+ *
222
+ * The project field holding the root context is pruned from the project tree, so the re-point is
223
+ * not visible there; what is visible is that the project changed at all. A tick that finds the
224
+ * same root installs nothing.
225
+ */
226
+ async refetchLoop() {
227
+ let seen = this.projectGeneration();
228
+ while (!this.abortController.signal.aborted) {
229
+ try {
230
+ await setTimeout(RefetchDebounceMs, void 0, { signal: this.abortController.signal });
231
+ } catch {
232
+ return;
233
+ }
234
+ const generation = this.projectGeneration();
235
+ if (generation === seen) continue;
236
+ try {
237
+ await this.reseed();
238
+ seen = generation;
239
+ } catch (err) {
240
+ if (this.abortController.signal.aborted) return;
241
+ this.env.logger.warn(new Error("block status reseed failed", { cause: err }));
242
+ }
243
+ }
244
+ }
245
+ /** Points the summary at the current render's context, replacing any earlier one. */
246
+ async reseed() {
247
+ const seed = ++this.seedSequence;
248
+ const root = await readBlockActionContextRoot(this.env.pl, this.projectRid, this.blockId, this.mode);
249
+ if (this.abortController.signal.aborted) return;
250
+ if (seed < this.installedSeed) return;
251
+ if (root === this.current?.root) return;
252
+ const tree = root === void 0 ? void 0 : await SynchronizedTreeState.init(this.env.pl, root, {
253
+ ...this.env.ops.defaultTreeOptions,
254
+ pollingInterval: StatusTreePollingIntervalMs,
255
+ initialTreeLoadingTimeout: StatusTreeInitialLoadTimeoutMs,
256
+ fieldFilter: statusTreeFieldFilter,
257
+ rootsNeverFinal: true
258
+ }, this.env.logger);
259
+ if (this.abortController.signal.aborted || seed < this.installedSeed) {
260
+ await this.terminateTree(tree);
261
+ return;
262
+ }
263
+ const previous = this.current;
264
+ this.installedSeed = seed;
265
+ this.current = root !== void 0 && tree !== void 0 ? {
266
+ root,
267
+ tree
268
+ } : void 0;
269
+ this.source.setValue(tree?.entry(), "block status root changed");
270
+ await this.terminateTree(previous?.tree);
271
+ }
272
+ async terminateTree(tree) {
273
+ if (tree === void 0) return;
274
+ try {
275
+ await tree.terminate();
276
+ } catch (err) {
277
+ this.env.logger.warn(new Error("block status tree termination failed", { cause: err }));
278
+ }
279
+ }
280
+ };
281
+ export { BlockStatusWatch, actionContextNode, entrySummary, readBlockActionContextRoot, subtreeFold };
282
+
283
+ //# sourceMappingURL=block_status_tree.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"block_status_tree.js","names":[],"sources":["../../src/middle_layer/block_status_tree.ts"],"sourcesContent":["/**\n * The live action-context tree of one block render, and the computable that folds it.\n *\n * A status tree is its own {@link SynchronizedTreeState}, seeded at the root action context of the\n * render rather than at the project. It has to be separate: the project tree prunes the context\n * fields (see `ProjectStatusFieldPattern`), because a context holds the whole subtree of its render\n * and every report into it is a KV write.\n *\n * One tree per watched block, held while anyone watches, terminated when the last holder lets go.\n */\n\nimport type { PlClient, SignedResourceId } from \"@milaboratories/pl-client\";\nimport { isNullSignedResourceId, ResourceTypeName, treeFilter } from \"@milaboratories/pl-client\";\nimport { Computable, WatchableValue } from \"@milaboratories/computable\";\nimport type { PlTreeEntry, PlTreeNodeAccessor } from \"@milaboratories/pl-tree\";\nimport { SynchronizedTreeState } from \"@milaboratories/pl-tree\";\nimport type { BlockStatusSummary } from \"@milaboratories/pl-model-middle-layer\";\nimport {\n EmptyBlockStatusSummary,\n UnreadableBlockStatusSummary,\n UnsupportedBlockStatusSummary,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport { setTimeout } from \"node:timers/promises\";\nimport type { ActionContextNode, SubtreeFold } from \"./block_status_fold\";\nimport { childContexts, foldContext, mergeSubtree, summarize } from \"./block_status_fold\";\nimport type { BlockActionContextMode } from \"./block_action_context\";\nimport { ActionContextLinkCapability } from \"../mutator/template/render_block\";\nimport { projectFieldName } from \"../model/project_model\";\nimport type { MiddleLayerEnvironment } from \"./middle_layer\";\n\n/**\n * How long the refetch loop waits between looks at the project's change generation.\n *\n * The tick itself reads an in-memory counter. It opens a read transaction only when the project\n * has changed since the last look, which while a block runs is most ticks: one read transaction\n * per second per watched block, which is the cost of noticing a re-run promptly.\n */\nconst RefetchDebounceMs = 1_000;\n\n/** The poll floor of a status tree, as the spec sets it. */\nconst StatusTreePollingIntervalMs = 5_000;\n\n/**\n * Deadline for the first load of a status tree.\n *\n * Deliberately NOT the project tree's, which disables the timeout outright: a status tree is\n * opened and closed while the app runs, and {@link BlockStatusWatch.terminate} awaits the loop, so\n * an init that never returns would hang a project close and with it the app's shutdown.\n */\nconst StatusTreeInitialLoadTimeoutMs = 30_000;\n\n/** The status tree walks action contexts and nothing else. */\nconst statusTreeFieldFilter = treeFilter.resourceTypeEq(ResourceTypeName.ActionContext);\n\n/**\n * The root action context of a block render, read once from the project.\n *\n * Undefined when the block has no context: it was never rendered, or it ran against a backend or a\n * middle layer that did not create one.\n */\nexport async function readBlockActionContextRoot(\n pl: PlClient,\n projectRid: SignedResourceId,\n blockId: string,\n mode: BlockActionContextMode,\n): Promise<SignedResourceId | undefined> {\n return await pl.withReadTx(\"readBlockActionContextRoot\", async (tx) => {\n const project = await tx.getResourceData(projectRid, true);\n const fieldName = projectFieldName(\n blockId,\n mode === \"prod\" ? \"prodActionContext\" : \"stagingActionContext\",\n );\n const statusField = project.fields.find((f) => f.name === fieldName);\n if (statusField === undefined || isNullSignedResourceId(statusField.value)) return undefined;\n return statusField.value;\n });\n}\n\n/** Adapts a tree node accessor to what the fold reads. */\nexport function actionContextNode(acc: PlTreeNodeAccessor): ActionContextNode {\n return {\n id: String(acc.id),\n getData: () => acc.getDataAsJson<Record<string, unknown>>(),\n listKeyValuesAsString: (prefix: string) => acc.listKeyValuesAsString(prefix),\n listFields: () => acc.listFields(),\n traverse: (field: string) => {\n // A child that carries an error is skipped rather than thrown: the status surface is\n // diagnostic, and one broken branch must not take the whole line down with it.\n const child = acc.traverse({ field, ignoreError: true });\n return child === undefined ? undefined : actionContextNode(child);\n },\n };\n}\n\n/**\n * The fold of the context an entry points at and everything under it, one computable per context.\n *\n * A report is a KV write into one context, and only that context's computable reads its KV, so a\n * report re-reads that one context. Each computable above it re-merges its direct children, which\n * are cached, and nothing else in the tree is read again.\n *\n * Undefined when the context cannot be read. A context that is gone is the ordinary case, not a\n * fault: an ephemeral context is dropped as soon as the project stops holding it, which happens the\n * moment the block is run again, and the watch is briefly pointed at it until the next look for a\n * new render. A child that cannot be read is left out rather than breaking the whole run's status.\n * The cause is logged, so a genuine fault is not silent.\n */\nexport function subtreeFold(\n entry: PlTreeEntry,\n path: ReadonlySet<string>,\n onError: (err: unknown) => void,\n): Computable<SubtreeFold | undefined> {\n return Computable.make(\n (ctx) => {\n try {\n const acc = ctx.accessor(entry).node({ ignoreError: true });\n if (acc === undefined) return undefined;\n const node = actionContextNode(acc);\n const below = new Set(path).add(node.id);\n const children = childContexts(\n acc.listFields(),\n // A child that carries an error is skipped rather than thrown, as in actionContextNode.\n (field) => acc.traverse({ field, ignoreError: true }),\n below,\n ).map((child) => subtreeFold(child.persist(), below, onError));\n return { own: foldContext(node), children };\n } catch (err: unknown) {\n onError(err);\n return undefined;\n }\n },\n {\n key: `block-status-context/${entry.id}`,\n postprocessValue: (value) => {\n if (value === undefined) return undefined;\n const children: SubtreeFold[] = [];\n for (const child of value.children) if (child !== undefined) children.push(child);\n return mergeSubtree(value.own, children);\n },\n },\n );\n}\n\n/** The summary of the run whose root context an entry points at. */\nexport function entrySummary(\n entry: PlTreeEntry,\n reportsSupported: boolean,\n onError: (err: unknown) => void,\n): Computable<BlockStatusSummary> {\n return Computable.make(() => ({ fold: subtreeFold(entry, new Set(), onError) }), {\n key: `block-status-summary/${entry.id}`,\n postprocessValue: ({ fold }) => {\n // The counters of a context that could not be read are unknown, not zero.\n if (fold === undefined) return UnreadableBlockStatusSummary;\n const summary = summarize(fold);\n if (reportsSupported || summary.totalContexts === 0) return summary;\n // The context exists and carries its data, but no transition can ever arrive.\n return { ...summary, availability: \"unsupported\" as const };\n },\n });\n}\n\n/** What {@link BlockStatusWatch.start} watches. */\nexport type BlockStatusWatchParams = {\n readonly env: MiddleLayerEnvironment;\n readonly projectRid: SignedResourceId;\n readonly blockId: string;\n readonly mode: BlockActionContextMode;\n /** The project tree's change generation, the trigger for looking for a new render. */\n readonly projectGeneration: () => number;\n};\n\n/**\n * The live status of one block render.\n *\n * The summary is stable across runs of the block: clicking Run creates a new render with a new\n * status context, and the watch re-seeds itself onto it rather than handing the caller a new\n * computable. The watch is shared between callers and reference counted; the tree lives until the\n * last holder releases it.\n */\nexport class BlockStatusWatch {\n /** The entry of the tree currently seeded, swapped when the block is run again. */\n private readonly source = new WatchableValue<PlTreeEntry | undefined>(undefined);\n private current?: { readonly root: SignedResourceId; readonly tree: SynchronizedTreeState };\n private readonly abortController = new AbortController();\n private loop?: Promise<void>;\n\n /**\n * Orders the seeds. A reseed that started before the one that last installed a root is stale by\n * the time it finishes, however long its tree took to open, and must not displace it.\n */\n private seedSequence = 0;\n private installedSeed = -1;\n\n /** How many callers hold this watch. The tree is terminated when it reaches zero. */\n private holders = 0;\n\n public readonly summary: Computable<BlockStatusSummary>;\n\n private readonly env: MiddleLayerEnvironment;\n private readonly projectRid: SignedResourceId;\n private readonly blockId: string;\n private readonly mode: BlockActionContextMode;\n private readonly projectGeneration: () => number;\n\n private constructor({\n env,\n projectRid,\n blockId,\n mode,\n projectGeneration,\n }: BlockStatusWatchParams) {\n this.env = env;\n this.projectRid = projectRid;\n this.blockId = blockId;\n this.mode = mode;\n this.projectGeneration = projectGeneration;\n // Without the `actionContext` link a block has no context and nothing is ever reported.\n const reportsSupported = env.pl.hasCapability(ActionContextLinkCapability);\n // One computable for the life of the watch, reading whichever tree is seeded now, so a caller\n // keeps its handle across a re-run of the block.\n this.summary = Computable.make((ctx) => {\n const entry = this.source.getValue(ctx);\n if (entry === undefined)\n return reportsSupported ? EmptyBlockStatusSummary : UnsupportedBlockStatusSummary;\n return entrySummary(entry, reportsSupported, (err) =>\n this.env.logger.warn(new Error(\"block status fold failed\", { cause: err })),\n );\n });\n }\n\n /**\n * Starts watching the status of a block render.\n *\n * The first seed is awaited, so the caller gets a handle that already reports whatever the\n * current render has reported. A block with no status context yet still gets a handle: it\n * reports an empty summary and seeds itself when a render that has one appears.\n *\n * The refetch loop is started only once that first seed has settled. Starting it in the\n * constructor would leave it running with nobody holding a reference to stop it if this throws.\n */\n public static async start(params: BlockStatusWatchParams): Promise<BlockStatusWatch> {\n const watch = new BlockStatusWatch(params);\n try {\n await watch.reseed();\n } catch (err: unknown) {\n await watch.terminateNow();\n throw err;\n }\n watch.begin();\n return watch;\n }\n\n /** Takes the first holder and starts looking for new renders, once the first seed settled. */\n private begin(): void {\n this.holders = 1;\n // The loop handles its own errors; this catch is only a backstop, so the promise kept here\n // never rejects and can be awaited as is.\n this.loop = this.refetchLoop().catch((err: unknown) => {\n this.env.logger.warn(new Error(\"block status refetch loop failed\", { cause: err }));\n });\n }\n\n /** Records one more caller holding this watch. */\n public retain(): void {\n this.holders++;\n }\n\n /**\n * Releases one caller's hold. The tree is terminated, and the watch is finished, only when the\n * last holder lets go; returns true when that happened.\n */\n public async release(): Promise<boolean> {\n if (this.holders > 0) this.holders--;\n if (this.holders > 0) return false;\n await this.terminateNow();\n return true;\n }\n\n /**\n * Stops the watch whatever the holder count, for a project being torn down. An ordinary caller\n * uses {@link release}.\n */\n public async terminate(): Promise<void> {\n this.holders = 0;\n await this.terminateNow();\n }\n\n /** Stops the loop, terminates the tree and releases the computable's holders. */\n private async terminateNow(): Promise<void> {\n this.abortController.abort();\n await this.loop;\n const held = this.current;\n this.current = undefined;\n this.source.setValue(undefined, \"block status watch terminated\");\n this.summary.resetState();\n await this.terminateTree(held?.tree);\n }\n\n /**\n * Looks for a new render while the caller watches.\n *\n * The project field holding the root context is pruned from the project tree, so the re-point is\n * not visible there; what is visible is that the project changed at all. A tick that finds the\n * same root installs nothing.\n */\n private async refetchLoop(): Promise<void> {\n let seen = this.projectGeneration();\n while (!this.abortController.signal.aborted) {\n try {\n await setTimeout(RefetchDebounceMs, undefined, { signal: this.abortController.signal });\n } catch {\n return; // aborted\n }\n\n const generation = this.projectGeneration();\n if (generation === seen) continue;\n\n try {\n await this.reseed();\n // Only once the look succeeded, so a failed one is retried on the next tick rather than\n // waiting for the project to change again.\n seen = generation;\n } catch (err: unknown) {\n if (this.abortController.signal.aborted) return;\n // The current tree stays in place: the surface keeps showing what it has rather than\n // going blank, and the next tick tries again.\n this.env.logger.warn(new Error(\"block status reseed failed\", { cause: err }));\n }\n }\n }\n\n /** Points the summary at the current render's context, replacing any earlier one. */\n private async reseed(): Promise<void> {\n const seed = ++this.seedSequence;\n\n const root = await readBlockActionContextRoot(\n this.env.pl,\n this.projectRid,\n this.blockId,\n this.mode,\n );\n if (this.abortController.signal.aborted) return;\n if (seed < this.installedSeed) return;\n if (root === this.current?.root) return;\n\n const tree =\n root === undefined\n ? undefined\n : await SynchronizedTreeState.init(\n this.env.pl,\n root,\n {\n ...this.env.ops.defaultTreeOptions,\n pollingInterval: StatusTreePollingIntervalMs,\n initialTreeLoadingTimeout: StatusTreeInitialLoadTimeoutMs,\n fieldFilter: statusTreeFieldFilter,\n // A context never becomes final: the backend keeps reporting into it for as long as\n // its render lives, so every poll has to seed it again.\n rootsNeverFinal: true,\n },\n this.env.logger,\n );\n\n // Opening the tree took time, and a later reseed may have installed a newer root meanwhile.\n // Terminating the tree just opened is the whole cost of losing that race.\n if (this.abortController.signal.aborted || seed < this.installedSeed) {\n await this.terminateTree(tree);\n return;\n }\n\n const previous = this.current;\n this.installedSeed = seed;\n this.current = root !== undefined && tree !== undefined ? { root, tree } : undefined;\n\n // Swapped before the old tree is terminated. A computable body runs to completion\n // synchronously, so after this returns no reader is inside the old tree.\n this.source.setValue(tree?.entry(), \"block status root changed\");\n await this.terminateTree(previous?.tree);\n }\n\n private async terminateTree(tree: SynchronizedTreeState | undefined): Promise<void> {\n if (tree === undefined) return;\n try {\n await tree.terminate();\n } catch (err: unknown) {\n // terminate() can throw when the sync loop had already failed; nothing is left to clean up.\n this.env.logger.warn(new Error(\"block status tree termination failed\", { cause: err }));\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqCA,MAAM,oBAAoB;;AAG1B,MAAM,8BAA8B;;;;;;;;AASpC,MAAM,iCAAiC;;AAGvC,MAAM,wBAAwB,WAAW,eAAe,iBAAiB,aAAa;;;;;;;AAQtF,eAAsB,2BACpB,IACA,YACA,SACA,MACuC;CACvC,OAAO,MAAM,GAAG,WAAW,8BAA8B,OAAO,OAAO;EACrE,MAAM,UAAU,MAAM,GAAG,gBAAgB,YAAY,IAAI;EACzD,MAAM,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