@milaboratories/pl-middle-layer 2.2.0 → 2.4.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 (48) hide show
  1. package/dist/middle_layer/block_status_fold.cjs +427 -0
  2. package/dist/middle_layer/block_status_fold.cjs.map +1 -0
  3. package/dist/middle_layer/block_status_fold.js +416 -0
  4. package/dist/middle_layer/block_status_fold.js.map +1 -0
  5. package/dist/middle_layer/block_status_tree.cjs +317 -0
  6. package/dist/middle_layer/block_status_tree.cjs.map +1 -0
  7. package/dist/middle_layer/block_status_tree.js +313 -0
  8. package/dist/middle_layer/block_status_tree.js.map +1 -0
  9. package/dist/middle_layer/block_status_tree_fold.cjs +96 -0
  10. package/dist/middle_layer/block_status_tree_fold.cjs.map +1 -0
  11. package/dist/middle_layer/block_status_tree_fold.js +95 -0
  12. package/dist/middle_layer/block_status_tree_fold.js.map +1 -0
  13. package/dist/middle_layer/build_stamp.cjs +1 -1
  14. package/dist/middle_layer/build_stamp.js +1 -1
  15. package/dist/middle_layer/project.cjs +93 -2
  16. package/dist/middle_layer/project.cjs.map +1 -1
  17. package/dist/middle_layer/project.d.ts +34 -1
  18. package/dist/middle_layer/project.d.ts.map +1 -1
  19. package/dist/middle_layer/project.js +94 -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 +15 -15
  35. package/src/middle_layer/block_status_bench.test.ts +288 -0
  36. package/src/middle_layer/block_status_fold.test.ts +635 -0
  37. package/src/middle_layer/block_status_fold.ts +625 -0
  38. package/src/middle_layer/block_status_test_utils.ts +62 -0
  39. package/src/middle_layer/block_status_tree.test.ts +276 -0
  40. package/src/middle_layer/block_status_tree.ts +443 -0
  41. package/src/middle_layer/block_status_tree_fold.test.ts +198 -0
  42. package/src/middle_layer/block_status_tree_fold.ts +150 -0
  43. package/src/middle_layer/project.ts +144 -2
  44. package/src/middle_layer/project_pruning.test.ts +59 -0
  45. package/src/model/project_model.ts +30 -0
  46. package/src/mutator/project.ts +7 -1
  47. package/src/mutator/project_action_context.test.ts +13 -3
  48. package/src/mutator/template/render_block.ts +32 -2
@@ -0,0 +1,276 @@
1
+ /**
2
+ * The status read path against a real backend: an action-context tree in the backend, a
3
+ * synchronized tree over it, and the fold, with the surface following reports as they land.
4
+ *
5
+ * The tests build the contexts themselves, the way the middle layer and the workflow SDK do: an
6
+ * ActionContext resource carrying baggage, children in Dynamic `child/...` fields, reports as KV
7
+ * entries under the reporters' key layout. That keeps them independent of whether this backend
8
+ * takes the render's `actionContext` link, which only decides whether the middle layer creates the
9
+ * root itself.
10
+ */
11
+
12
+ import type {
13
+ AnyResourceRef,
14
+ PlClient,
15
+ PlTransaction,
16
+ ResourceRef,
17
+ } from "@milaboratories/pl-client";
18
+ import {
19
+ ContinuePolling,
20
+ field,
21
+ poll,
22
+ TestHelpers,
23
+ toGlobalResourceId,
24
+ } from "@milaboratories/pl-client";
25
+ import { SynchronizedTreeState } from "@milaboratories/pl-tree";
26
+ import { randomUUID } from "node:crypto";
27
+ import path from "node:path";
28
+ import { expect, test } from "vitest";
29
+ import { projectFieldName } from "../model/project_model";
30
+ import { ActionContextType } from "../mutator/template/render_block";
31
+ import { entrySummary, readBlockActionContextRoot } from "./block_status_tree";
32
+ import { MiddleLayer } from "./middle_layer";
33
+ import type { Project } from "./project";
34
+
35
+ // ── Building a tree ──────────────────────────────────────────────────────────
36
+
37
+ /** Creates an action context, linked under `parent` when given. */
38
+ function createContext(tx: PlTransaction, name: string, parent?: AnyResourceRef): ResourceRef {
39
+ const ctx = tx.createEphemeral(
40
+ ActionContextType,
41
+ JSON.stringify({ name, "block-id": "block1", "run-id": randomUUID() }),
42
+ );
43
+ if (parent !== undefined) {
44
+ const child = field(parent, `child/${name}`);
45
+ tx.createField(child, "Dynamic");
46
+ tx.setField(child, ctx);
47
+ }
48
+ return ctx;
49
+ }
50
+
51
+ /** Writes one transition the way a reporter writes it. */
52
+ function record(
53
+ tx: PlTransaction,
54
+ ctx: AnyResourceRef,
55
+ namespace: string,
56
+ reporter: string,
57
+ atMs: number,
58
+ state: string,
59
+ detail = "",
60
+ ): void {
61
+ const ns = String(BigInt(atMs) * 1_000_000n);
62
+ tx.setKValue(
63
+ ctx,
64
+ `transition/${namespace}/${reporter}/${ns}`,
65
+ JSON.stringify({ state, detail, reason: "" }),
66
+ );
67
+ }
68
+
69
+ // ── The fold over a real tree ────────────────────────────────────────────────
70
+
71
+ test("a real action-context tree folds into the summary and follows its reports", async () => {
72
+ await TestHelpers.withTempRoot(async (pl) => {
73
+ const ids = await pl.withWriteTx("BuildTree", async (tx) => {
74
+ const root = createContext(tx, "root");
75
+ const children = ["a", "b", "c"].map((n) => createContext(tx, n, root));
76
+ tx.createField(field(tx.clientRoot, "statusRoot"), "Dynamic", root);
77
+ await tx.commit();
78
+ return {
79
+ root: await toGlobalResourceId(root),
80
+ children: await Promise.all(children.map((c) => toGlobalResourceId(c))),
81
+ };
82
+ });
83
+
84
+ const tree = await SynchronizedTreeState.init(pl, ids.root, {
85
+ pollingInterval: 100,
86
+ stopPollingDelay: 2500,
87
+ rootsNeverFinal: true,
88
+ });
89
+ try {
90
+ const summary = entrySummary(tree.entry(), true, (err) => {
91
+ throw err;
92
+ });
93
+ const settled = async (until: (s: Awaited<ReturnType<typeof summary.getValue>>) => boolean) =>
94
+ await poll(pl, async () => {
95
+ await tree.refreshState();
96
+ const current = await summary.getValue();
97
+ if (!until(current)) throw new ContinuePolling();
98
+ return current;
99
+ });
100
+
101
+ // Four contexts, nothing reported yet: all live, no state named.
102
+ const initial = await settled((s) => s.totalContexts === 4);
103
+ expect(initial).toMatchObject({ activeContexts: 4, done: false });
104
+
105
+ // Two children wait for a machine, one stages files.
106
+ const at = Date.now();
107
+ await pl.withWriteTx("Report", async (tx) => {
108
+ record(tx, ids.children[0], "exec", "1", at, "WaitingForMachine");
109
+ record(tx, ids.children[1], "exec", "2", at + 1, "WaitingForMachine");
110
+ record(tx, ids.children[2], "workdir", "3", at + 2, "PopulatingWorkdir", "12 files");
111
+ await tx.commit();
112
+ });
113
+ const waiting = await settled((s) => s.jobs.total === 3);
114
+ expect(waiting.jobs.byState).toEqual([
115
+ expect.objectContaining({ namespace: "exec", state: "WaitingForMachine", count: 2 }),
116
+ expect.objectContaining({ namespace: "workdir", state: "PopulatingWorkdir", count: 1 }),
117
+ ]);
118
+
119
+ // Every render reports its own end: the run is done.
120
+ await pl.withWriteTx("Finish", async (tx) => {
121
+ for (const [i, ctx] of [ids.root, ...ids.children].entries())
122
+ record(tx, ctx, "render", String(10 + i), at + 1000, "Completed");
123
+ record(tx, ids.children[0], "exec", "1", at + 900, "Completed");
124
+ record(tx, ids.children[1], "exec", "2", at + 900, "Completed");
125
+ record(tx, ids.children[2], "workdir", "3", at + 900, "Completed");
126
+ await tx.commit();
127
+ });
128
+ const finished = await settled((s) => s.done);
129
+ expect(finished).toMatchObject({ activeContexts: 0, totalContexts: 4, done: true });
130
+ } finally {
131
+ await tree.terminate();
132
+ }
133
+ });
134
+ });
135
+
136
+ // ── The watch, through the Project API ───────────────────────────────────────
137
+
138
+ /** A middle layer over a temporary root, closed afterwards. */
139
+ async function withMl(cb: (ml: MiddleLayer) => Promise<void>): Promise<void> {
140
+ const workFolder = path.resolve(`work/${randomUUID()}`);
141
+ await TestHelpers.withTempRoot(async (pl) => {
142
+ const ml = await MiddleLayer.init(pl, workFolder, {
143
+ defaultTreeOptions: { pollingInterval: 250, stopPollingDelay: 500 },
144
+ devBlockUpdateRecheckInterval: 300,
145
+ localSecret: MiddleLayer.generateLocalSecret(),
146
+ openFileDialogCallback: () => {
147
+ throw new Error("Not implemented.");
148
+ },
149
+ });
150
+ try {
151
+ await cb(ml);
152
+ } finally {
153
+ await ml.close();
154
+ }
155
+ });
156
+ }
157
+
158
+ /** Waits until a block has finished its production render. */
159
+ async function awaitBlockDone(prj: Project, blockId: string, timeout: number): Promise<void> {
160
+ const abortSignal = AbortSignal.timeout(timeout);
161
+ while (true) {
162
+ const overview = (await prj.overview.getValue())!;
163
+ const block = overview.blocks.find((b) => b.id === blockId);
164
+ if (block === undefined) throw new Error(`block not found: ${blockId}`);
165
+ if (block.outputErrors || block.calculationStatus === "Done") return;
166
+ await prj.overview.awaitChange(abortSignal);
167
+ }
168
+ }
169
+
170
+ /** A project with one block run to completion. */
171
+ async function projectWithBlock(ml: MiddleLayer): Promise<{ prj: Project; blockId: string }> {
172
+ const projectId = await ml.createProject({ label: "Block status" });
173
+ await ml.openProject(projectId);
174
+ const prj = ml.getOpenedProject(projectId);
175
+ const blockId = await prj.addBlock("Block 1", {
176
+ type: "from-registry-v1",
177
+ registryUrl: "https://block.registry.platforma.bio/releases",
178
+ id: { organization: "milaboratory", name: "enter-numbers", version: "1.1.1" },
179
+ });
180
+ await prj.setBlockArgs(blockId, { numbers: [1, 2, 3] });
181
+ await prj.runBlock(blockId);
182
+ await awaitBlockDone(prj, blockId, 30_000);
183
+ return { prj, blockId };
184
+ }
185
+
186
+ /**
187
+ * Points the block's prodActionContext at a new context, as a render does, and touches the project
188
+ * so its tree's change generation moves: the field itself is pruned from that tree, and a real
189
+ * render changes other project fields in the same transaction.
190
+ */
191
+ async function plantRoot(pl: PlClient, prj: Project, blockId: string): Promise<string> {
192
+ const runId = randomUUID();
193
+ await pl.withWriteTx("PlantRoot", async (tx) => {
194
+ const ctx = tx.createEphemeral(
195
+ ActionContextType,
196
+ JSON.stringify({ name: "Block 1", "block-id": blockId, "run-id": runId }),
197
+ );
198
+ const f = field(prj.rid, projectFieldName(blockId, "prodActionContext"));
199
+ tx.createField(f, "Dynamic");
200
+ tx.setField(f, ctx);
201
+ tx.setKValue(prj.rid, "test/blockStatusBump", runId);
202
+ await tx.commit();
203
+ });
204
+ return runId;
205
+ }
206
+
207
+ /** The root the middle layer would seed at, read through the project. */
208
+ async function rootOf(pl: PlClient, prj: Project, blockId: string) {
209
+ return await readBlockActionContextRoot(pl, prj.rid, blockId, "prod");
210
+ }
211
+
212
+ test("a watch follows the block's context and is shared between holders", async () => {
213
+ await withMl(async (ml) => {
214
+ const { prj, blockId } = await projectWithBlock(ml);
215
+ const run1 = await plantRoot(ml.pl, prj, blockId);
216
+ expect(await rootOf(ml.pl, prj, blockId)).toBeDefined();
217
+
218
+ const first = await prj.watchBlockStatus(blockId);
219
+ const second = await prj.watchBlockStatus(blockId);
220
+ expect(second).toBe(first);
221
+ expect((await first.getValue()).runId).toBe(run1);
222
+
223
+ // A new context for the block: the watch re-seeds itself, the handle stays the same.
224
+ const run2 = await plantRoot(ml.pl, prj, blockId);
225
+ const reseeded = await poll(ml.pl, async () => {
226
+ const current = await first.getValue();
227
+ if (current.runId !== run2) throw new ContinuePolling();
228
+ return current;
229
+ });
230
+ expect(reseeded.runId).toBe(run2);
231
+
232
+ // One holder letting go keeps the tree for the other; the last one releases it.
233
+ await prj.unwatchBlockStatus(blockId);
234
+ expect((await second.getValue()).runId).toBe(run2);
235
+ await prj.unwatchBlockStatus(blockId);
236
+ expect((await second.getValue()).runId).toBeUndefined();
237
+ await prj.unwatchBlockStatus(blockId); // idempotent once nothing holds it
238
+ });
239
+ }, 120_000);
240
+
241
+ test("closing the project terminates its watches and refuses new ones", async () => {
242
+ await withMl(async (ml) => {
243
+ const { prj, blockId } = await projectWithBlock(ml);
244
+ const run = await plantRoot(ml.pl, prj, blockId);
245
+
246
+ const summary = await prj.watchBlockStatus(blockId);
247
+ expect((await summary.getValue()).runId).toBe(run);
248
+
249
+ await ml.closeProject(prj.id);
250
+ expect((await summary.getValue()).runId).toBeUndefined();
251
+ await expect(prj.watchBlockStatus(blockId)).rejects.toThrow(/project is closed/);
252
+ });
253
+ }, 120_000);
254
+
255
+ test("the tree shares the watch and follows the expansion", async () => {
256
+ await withMl(async (ml) => {
257
+ const { prj, blockId } = await projectWithBlock(ml);
258
+ const run = await plantRoot(ml.pl, prj, blockId);
259
+
260
+ const summary = await prj.watchBlockStatus(blockId);
261
+ const tree = await prj.watchBlockStatusTree(blockId);
262
+ const first = await tree.getValue();
263
+ expect(first.summary.runId).toBe(run);
264
+ expect(first.root?.children).toEqual([]);
265
+
266
+ // The expansion is the tree's own input: setting it recomputes the tree.
267
+ await prj.setBlockStatusTreeExpanded(blockId, [first.root!.contextId]);
268
+ await tree.getValue();
269
+
270
+ // The tree holds the watch on its own once the summary lets go.
271
+ await prj.unwatchBlockStatus(blockId);
272
+ expect((await summary.getValue()).runId).toBe(run);
273
+ await prj.unwatchBlockStatus(blockId);
274
+ expect((await tree.getValue()).summary.runId).toBeUndefined();
275
+ });
276
+ }, 120_000);