@milaboratories/pl-middle-layer 2.9.1 → 2.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/index.cjs +5 -1
  2. package/dist/index.d.ts +3 -2
  3. package/dist/index.js +3 -2
  4. package/dist/middle_layer/build_stamp.cjs +1 -1
  5. package/dist/middle_layer/build_stamp.js +1 -1
  6. package/dist/middle_layer/index.cjs +4 -0
  7. package/dist/middle_layer/index.d.ts +2 -1
  8. package/dist/middle_layer/index.js +2 -1
  9. package/dist/middle_layer/middle_layer.cjs +100 -31
  10. package/dist/middle_layer/middle_layer.cjs.map +1 -1
  11. package/dist/middle_layer/middle_layer.d.ts +54 -8
  12. package/dist/middle_layer/middle_layer.d.ts.map +1 -1
  13. package/dist/middle_layer/middle_layer.js +99 -30
  14. package/dist/middle_layer/middle_layer.js.map +1 -1
  15. package/dist/middle_layer/project.cjs +45 -38
  16. package/dist/middle_layer/project.cjs.map +1 -1
  17. package/dist/middle_layer/project.d.ts +18 -3
  18. package/dist/middle_layer/project.d.ts.map +1 -1
  19. package/dist/middle_layer/project.js +44 -36
  20. package/dist/middle_layer/project.js.map +1 -1
  21. package/dist/middle_layer/project_holds.cjs +266 -0
  22. package/dist/middle_layer/project_holds.cjs.map +1 -0
  23. package/dist/middle_layer/project_holds.d.ts +50 -0
  24. package/dist/middle_layer/project_holds.d.ts.map +1 -0
  25. package/dist/middle_layer/project_holds.js +262 -0
  26. package/dist/middle_layer/project_holds.js.map +1 -0
  27. package/dist/model/block_pack_spec.cjs.map +1 -1
  28. package/dist/model/block_pack_spec.d.ts +3 -3
  29. package/dist/model/block_pack_spec.d.ts.map +1 -1
  30. package/dist/model/block_pack_spec.js.map +1 -1
  31. package/dist/model/template_spec.d.ts +18 -0
  32. package/dist/model/template_spec.d.ts.map +1 -1
  33. package/dist/mutator/block-pack/block_pack.cjs +89 -2
  34. package/dist/mutator/block-pack/block_pack.cjs.map +1 -1
  35. package/dist/mutator/block-pack/block_pack.d.ts +16 -0
  36. package/dist/mutator/block-pack/block_pack.d.ts.map +1 -1
  37. package/dist/mutator/block-pack/block_pack.js +90 -4
  38. package/dist/mutator/block-pack/block_pack.js.map +1 -1
  39. package/dist/mutator/block-pack/required_capabilities.cjs +16 -0
  40. package/dist/mutator/block-pack/required_capabilities.cjs.map +1 -1
  41. package/dist/mutator/block-pack/required_capabilities.js +16 -1
  42. package/dist/mutator/block-pack/required_capabilities.js.map +1 -1
  43. package/dist/mutator/template/template_cache.cjs +8 -1
  44. package/dist/mutator/template/template_cache.cjs.map +1 -1
  45. package/dist/mutator/template/template_cache.d.ts +7 -3
  46. package/dist/mutator/template/template_cache.d.ts.map +1 -1
  47. package/dist/mutator/template/template_cache.js +8 -1
  48. package/dist/mutator/template/template_cache.js.map +1 -1
  49. package/package.json +6 -6
  50. package/src/middle_layer/index.ts +2 -0
  51. package/src/middle_layer/middle_layer.ts +121 -40
  52. package/src/middle_layer/project.ts +47 -42
  53. package/src/middle_layer/project_close_during_write.test.ts +142 -0
  54. package/src/middle_layer/project_handles.test.ts +168 -0
  55. package/src/middle_layer/project_holds.ts +359 -0
  56. package/src/middle_layer/project_slots.test.ts +331 -0
  57. package/src/model/block_pack_spec.ts +3 -2
  58. package/src/model/template_spec.ts +21 -0
  59. package/src/mutator/block-pack/block_pack.test.ts +10 -1
  60. package/src/mutator/block-pack/block_pack.ts +102 -2
  61. package/src/mutator/block-pack/block_pack_load.test.ts +52 -0
  62. package/src/mutator/block-pack/required_capabilities.ts +25 -0
  63. package/src/mutator/project-v3.test.ts +27 -16
  64. package/src/mutator/template/template_cache.ts +26 -3
  65. package/src/test/block_packs.ts +12 -0
  66. package/src/test/write_tx_hooks.ts +75 -0
@@ -0,0 +1,331 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import type { ProjectId } from "../model/project_model";
3
+ import type { SlotProject } from "./project_holds";
4
+ import {
5
+ asProjectHolder,
6
+ isProjectInUseError,
7
+ ProjectInUseError,
8
+ ProjectSlots,
9
+ } from "./project_holds";
10
+
11
+ /**
12
+ * The hold bookkeeping of {@link ProjectSlots} on projects that are plain objects, so every
13
+ * interleaving is set up exactly. What a real project does under it is covered against a backend
14
+ * in `project_handles.test.ts`.
15
+ */
16
+
17
+ const ID = "p1" as ProjectId;
18
+
19
+ class FakeProject implements SlotProject {
20
+ destroyed = false;
21
+ snapshots = 0;
22
+ constructor(readonly serial: number) {}
23
+ async destroy(): Promise<void> {
24
+ await Promise.resolve();
25
+ this.destroyed = true;
26
+ }
27
+ snapshotOnClose(): Promise<void> {
28
+ this.snapshots++;
29
+ return Promise.resolve();
30
+ }
31
+ }
32
+
33
+ type Deferred<T> = { promise: Promise<T>; resolve: (v: T) => void; reject: (e: Error) => void };
34
+
35
+ function deferred<T>(): Deferred<T> {
36
+ let resolve: (v: T) => void = () => {};
37
+ let reject: (e: Error) => void = () => {};
38
+ const promise = new Promise<T>((res, rej) => {
39
+ resolve = res;
40
+ reject = rej;
41
+ });
42
+ return { promise, resolve, reject };
43
+ }
44
+
45
+ /** Slots whose loads finish when the test says so. */
46
+ function setup(
47
+ options: {
48
+ /** Runs at the end of a load, before it returns the project. */
49
+ beforeLoaded?: (project: FakeProject, onGone: (p: FakeProject) => void) => void;
50
+ } = {},
51
+ ) {
52
+ const loads: Deferred<void>[] = [];
53
+ const projects: FakeProject[] = [];
54
+ const goneCallbacks: ((p: FakeProject) => void)[] = [];
55
+ const published: ProjectId[][] = [];
56
+ const slots = new ProjectSlots<FakeProject>({
57
+ load: async (_id, onGone) => {
58
+ const gate = deferred<void>();
59
+ loads.push(gate);
60
+ await gate.promise;
61
+ const project = new FakeProject(projects.length);
62
+ projects.push(project);
63
+ goneCallbacks.push(onGone);
64
+ options.beforeLoaded?.(project, onGone);
65
+ return project;
66
+ },
67
+ trackSnapshotWrite: () => {},
68
+ publish: (open) => published.push(open),
69
+ logger: { info: () => {}, warn: () => {} },
70
+ });
71
+ return { slots, loads, projects, goneCallbacks, published };
72
+ }
73
+
74
+ /** Opens the project with one hold per label. */
75
+ async function opened(s: ReturnType<typeof setup>, ...holders: string[]) {
76
+ const acquiring = Promise.all(holders.map((h) => s.slots.acquire(ID, asProjectHolder(h))));
77
+ await settle();
78
+ s.loads.at(-1)?.resolve();
79
+ return await acquiring;
80
+ }
81
+
82
+ /** Lets every pending callback run. */
83
+ async function settle(): Promise<void> {
84
+ for (let i = 0; i < 10; i++) await Promise.resolve();
85
+ }
86
+
87
+ describe("ProjectSlots", () => {
88
+ test("concurrent acquires share one load and one project", async () => {
89
+ const { slots, loads, projects } = setup();
90
+ const acquires = [
91
+ slots.acquire(ID, asProjectHolder("a")),
92
+ slots.acquire(ID, asProjectHolder("b")),
93
+ slots.acquire(ID, asProjectHolder("c")),
94
+ ];
95
+ await settle();
96
+ expect(loads).toHaveLength(1);
97
+ loads[0].resolve();
98
+ const handles = await Promise.all(acquires);
99
+ expect(projects).toHaveLength(1);
100
+ expect(new Set(handles.map((h) => h.project)).size).toBe(1);
101
+ expect(slots.holders(ID).sort()).toEqual(["a", "b", "c"]);
102
+ });
103
+
104
+ test("the project is destroyed only when the last hold is released", async () => {
105
+ const { slots, loads, projects, published } = setup();
106
+ const acquiring = Promise.all([
107
+ slots.acquire(ID, asProjectHolder("a")),
108
+ slots.acquire(ID, asProjectHolder("b")),
109
+ ]);
110
+ await settle();
111
+ loads[0].resolve();
112
+ const [a, b] = await acquiring;
113
+ expect(published.at(-1)).toEqual([ID]);
114
+
115
+ await a.release();
116
+ expect(projects[0].destroyed).toBe(false);
117
+ expect(slots.get(ID)).toBe(projects[0]);
118
+
119
+ await b.release();
120
+ expect(projects[0].destroyed).toBe(true);
121
+ expect(projects[0].snapshots).toBe(1);
122
+ expect(slots.get(ID)).toBeUndefined();
123
+ expect(published.at(-1)).toEqual([]);
124
+ });
125
+
126
+ test("a second release does nothing, and an ended handle has no project", async () => {
127
+ const { slots, loads } = setup();
128
+ const acquiring = Promise.all([
129
+ slots.acquire(ID, asProjectHolder("a")),
130
+ slots.acquire(ID, asProjectHolder("b")),
131
+ ]);
132
+ await settle();
133
+ loads[0].resolve();
134
+ const [a] = await acquiring;
135
+ await a.release();
136
+ await a.release();
137
+ expect(slots.holders(ID)).toEqual(["b"]);
138
+ expect(a.ended).toBe(true);
139
+ expect(a.signal.reason).toBe("released");
140
+ expect(() => a.project).toThrow(/has ended/);
141
+ });
142
+
143
+ test("an acquire right after the last release waits for the destroy and loads anew", async () => {
144
+ const { slots, loads, projects } = setup();
145
+ const first = slots.acquire(ID, asProjectHolder("a"));
146
+ await settle();
147
+ loads[0].resolve();
148
+ const a = await first;
149
+ const destroyed = a.release();
150
+ expect(slots.get(ID)).toBeUndefined();
151
+ const second = slots.acquire(ID, asProjectHolder("b"));
152
+ await destroyed;
153
+ await settle();
154
+ expect(projects[0].destroyed).toBe(true);
155
+ expect(loads).toHaveLength(2);
156
+ loads[1].resolve();
157
+ const b = await second;
158
+ expect(b.project).toBe(projects[1]);
159
+ });
160
+
161
+ test("a failed load rejects every waiter and leaves nothing behind", async () => {
162
+ const { slots, loads } = setup();
163
+ const acquires = [
164
+ slots.acquire(ID, asProjectHolder("a")),
165
+ slots.acquire(ID, asProjectHolder("b")),
166
+ ];
167
+ await settle();
168
+ loads[0].reject(new Error("load failed"));
169
+ for (const acquire of acquires) await expect(acquire).rejects.toThrow("load failed");
170
+ expect(slots.holders(ID)).toEqual([]);
171
+ const again = slots.acquire(ID, asProjectHolder("c"));
172
+ await settle();
173
+ expect(loads).toHaveLength(2);
174
+ loads[1].resolve();
175
+ await again;
176
+ });
177
+
178
+ test("eviction ends every hold with its reason and destroys the project", async () => {
179
+ const { slots, loads, projects } = setup();
180
+ const acquiring = Promise.all([
181
+ slots.acquire(ID, asProjectHolder("a")),
182
+ slots.acquire(ID, asProjectHolder("b")),
183
+ ]);
184
+ await settle();
185
+ loads[0].resolve();
186
+ const [a, b] = await acquiring;
187
+ await slots.evict(ID, "deleted");
188
+ expect(a.signal.reason).toBe("deleted");
189
+ expect(b.signal.reason).toBe("deleted");
190
+ expect(projects[0].destroyed).toBe(true);
191
+ // Nothing is written for a project that no longer exists.
192
+ expect(projects[0].snapshots).toBe(0);
193
+ await a.release();
194
+ });
195
+
196
+ test("eviction during the load rejects the waiters and destroys what the load produced", async () => {
197
+ const { slots, loads, projects } = setup();
198
+ const acquire = slots.acquire(ID, asProjectHolder("a"));
199
+ await settle();
200
+ const evicted = slots.evict(ID, "deleted");
201
+ loads[0].resolve();
202
+ await expect(acquire).rejects.toThrow(/not found/);
203
+ await evicted;
204
+ expect(projects[0].destroyed).toBe(true);
205
+ expect(slots.get(ID)).toBeUndefined();
206
+ });
207
+
208
+ test("the project's own report that it was deleted evicts it", async () => {
209
+ const { slots, loads, projects, goneCallbacks } = setup();
210
+ const acquire = slots.acquire(ID, asProjectHolder("a"));
211
+ await settle();
212
+ loads[0].resolve();
213
+ const a = await acquire;
214
+ goneCallbacks[0](projects[0]);
215
+ await settle();
216
+ expect(a.signal.reason).toBe("deleted");
217
+ expect(projects[0].destroyed).toBe(true);
218
+ });
219
+
220
+ test("a release while another acquire waits for the same load leaves the project loaded", async () => {
221
+ const { slots, loads, projects } = setup();
222
+ const first = slots.acquire(ID, asProjectHolder("a")).then(async (a) => {
223
+ await a.release();
224
+ return a;
225
+ });
226
+ const second = slots.acquire(ID, asProjectHolder("b"));
227
+ await settle();
228
+ loads[0].resolve();
229
+ const [a, b] = await Promise.all([first, second]);
230
+ expect(a.ended).toBe(true);
231
+ expect(b.ended).toBe(false);
232
+ expect(b.project).toBe(projects[0]);
233
+ expect(projects[0].destroyed).toBe(false);
234
+ expect(slots.holders(ID)).toEqual(["b"]);
235
+ await b.release();
236
+ expect(projects[0].destroyed).toBe(true);
237
+ });
238
+
239
+ test("the project's report that it was deleted, during its load, rejects the waiters", async () => {
240
+ const { slots, loads, projects } = setup({
241
+ beforeLoaded: (project, onGone) => onGone(project),
242
+ });
243
+ const acquires = [
244
+ slots.acquire(ID, asProjectHolder("a")),
245
+ slots.acquire(ID, asProjectHolder("b")),
246
+ ];
247
+ await settle();
248
+ loads[0].resolve();
249
+ for (const acquire of acquires) await expect(acquire).rejects.toThrow(/not found/);
250
+ await settle();
251
+ expect(projects[0].destroyed).toBe(true);
252
+ expect(projects[0].snapshots).toBe(0);
253
+ expect(slots.get(ID)).toBeUndefined();
254
+ expect(slots.holders(ID)).toEqual([]);
255
+ });
256
+
257
+ test("a refused delete removes nothing and leaves the holds alone", async () => {
258
+ const s = setup();
259
+ const [tab] = await opened(s, "desktop");
260
+ let removed = false;
261
+ const refused = s.slots.delete(
262
+ ID,
263
+ async () => {
264
+ removed = true;
265
+ },
266
+ (holder) => holder !== "mcp:me",
267
+ );
268
+ await expect(refused).rejects.toBeInstanceOf(ProjectInUseError);
269
+ await expect(refused).rejects.toMatchObject({ holders: ["desktop"] });
270
+ expect(isProjectInUseError(await refused.catch((e: unknown) => e))).toBe(true);
271
+ expect(removed).toBe(false);
272
+ expect(tab.ended).toBe(false);
273
+ });
274
+
275
+ test("a delete is not refused by the holds it allows, and ends them with deleted", async () => {
276
+ const s = setup();
277
+ const [mine] = await opened(s, "mcp:me");
278
+ await s.slots.delete(
279
+ ID,
280
+ async () => {},
281
+ (holder) => holder !== "mcp:me",
282
+ );
283
+ expect(mine.signal.reason).toBe("deleted");
284
+ expect(s.projects[0].destroyed).toBe(true);
285
+ expect(s.projects[0].snapshots).toBe(0);
286
+ });
287
+
288
+ test("a delete whose write fails leaves the project and its holds as they were", async () => {
289
+ const s = setup();
290
+ const [held] = await opened(s, "a");
291
+ await expect(
292
+ s.slots.delete(ID, async () => {
293
+ throw new Error("write failed");
294
+ }),
295
+ ).rejects.toThrow("write failed");
296
+ expect(held.ended).toBe(false);
297
+ expect(s.slots.get(ID)).toBe(s.projects[0]);
298
+ const second = await s.slots.acquire(ID, asProjectHolder("b"));
299
+ expect(second.project).toBe(s.projects[0]);
300
+ });
301
+
302
+ test("closeAll waits for a load in flight and destroys what it produced", async () => {
303
+ const { slots, loads, projects } = setup();
304
+ const acquire = slots.acquire(ID, asProjectHolder("a"));
305
+ acquire.catch(() => {});
306
+ await settle();
307
+ let closed = false;
308
+ const closing = slots.closeAll().then(() => {
309
+ closed = true;
310
+ });
311
+ await settle();
312
+ expect(closed).toBe(false);
313
+
314
+ loads[0].resolve();
315
+ await closing;
316
+ expect(projects[0].destroyed).toBe(true);
317
+ await expect(acquire).rejects.toThrow("Middle layer is closed");
318
+ });
319
+
320
+ test("after closeAll every hold has ended and acquires are refused", async () => {
321
+ const { slots, loads, projects } = setup();
322
+ const acquire = slots.acquire(ID, asProjectHolder("a"));
323
+ await settle();
324
+ loads[0].resolve();
325
+ const a = await acquire;
326
+ await slots.closeAll();
327
+ expect(a.signal.reason).toBe("closed");
328
+ expect(projects[0].destroyed).toBe(true);
329
+ await expect(slots.acquire(ID, asProjectHolder("b"))).rejects.toThrow("Middle layer is closed");
330
+ });
331
+ });
@@ -1,4 +1,5 @@
1
1
  import type { CachedTemplate, ExplicitTemplate, PreparedTemplate } from "./template_spec";
2
+ import type { InstallablePackTemplate } from "./template_spec";
2
3
  import type { ResourceType } from "@milaboratories/pl-client";
3
4
  import type { BlockConfigContainer } from "@platforma-sdk/model";
4
5
  import type { BlockPackSpec } from "@milaboratories/pl-model-middle-layer";
@@ -71,13 +72,13 @@ export interface BlockPackExplicit {
71
72
  /** Block-pack spec that can be materialized in pl. */
72
73
  export type BlockPackSpecPrepared = {
73
74
  type: "prepared";
74
- template: PreparedTemplate | CachedTemplate;
75
+ template: PreparedTemplate | CachedTemplate | InstallablePackTemplate;
75
76
  config: BlockConfigContainer;
76
77
  frontend: FrontendSpec;
77
78
  source: BlockPackSpec;
78
79
  /** Backend-side runtime capabilities the block requires at install time.
79
80
  * Derived from the parsed workflow template by
80
- * `requiredCapabilitiesFromTemplate` during `BlockPackPreparer.prepare`.
81
+ * `requiredCapabilitiesFromTemplate` during `BlockPackPreparer.prepare`, or from the manifest.
81
82
  * `Project.addBlock` matches this list against `pl.serverInfo.capabilities`
82
83
  * and refuses to install when anything is missing. */
83
84
  requiredCapabilities?: string[];
@@ -10,6 +10,8 @@ export interface TemplateFromRegistry {
10
10
  export interface ExplicitTemplate {
11
11
  readonly type: "explicit";
12
12
  content: Uint8Array;
13
+ /** The pack file `content` was read from, for local dev blocks. */
14
+ localPath?: string;
13
15
  }
14
16
 
15
17
  export interface PreparedTemplate {
@@ -17,6 +19,25 @@ export interface PreparedTemplate {
17
19
  data: TemplateData | CompiledTemplateV3;
18
20
  }
19
21
 
22
+ /** A registry pack not yet downloaded: it is fetched from `url` when installed. */
23
+ export interface RegistryPackTemplate {
24
+ readonly type: "registry-pack";
25
+ url: string;
26
+ /** Lowercase hex sha256 of the gzipped pack, from the registry manifest. */
27
+ sha256: string;
28
+ }
29
+
30
+ /** A local dev pack: it is read from `path` when installed. */
31
+ export interface LocalPackTemplate {
32
+ readonly type: "local-pack";
33
+ path: string;
34
+ /** Lowercase hex sha256 of the gzipped pack file. */
35
+ sha256: string;
36
+ }
37
+
38
+ /** A pack not yet loaded: `cacheBlockPackTemplate` installs it. */
39
+ export type InstallablePackTemplate = RegistryPackTemplate | LocalPackTemplate;
40
+
20
41
  export interface CachedTemplate {
21
42
  readonly type: "cached";
22
43
  readonly resourceId: SignedResourceId;
@@ -10,6 +10,7 @@ import path from "node:path";
10
10
  import { expect, test } from "vitest";
11
11
  import { V2RegistryProvider } from "../../block_registry/registry-v2-provider";
12
12
  import { BlockPackSpecAny } from "../../model";
13
+ import { cacheBlockPackTemplate } from "../template/template_cache";
13
14
  import { BlockPackPreparer, createBlockPack } from "./block_pack";
14
15
 
15
16
  const preparation = new BlockPackPreparer(
@@ -29,6 +30,13 @@ test.each([
29
30
  },
30
31
  } as BlockPackSpecAny,
31
32
  },
33
+ {
34
+ spec: {
35
+ type: "from-registry-v2",
36
+ registryUrl: "https://blocks.pl-open.science",
37
+ id: { organization: "milaboratories", name: "gpu-test", version: "0.9.0" },
38
+ } as BlockPackSpecAny,
39
+ },
32
40
  {
33
41
  spec: {
34
42
  type: "dev-v1",
@@ -43,11 +51,12 @@ test.each([
43
51
  const specPrepared = await preparation.prepare(spec);
44
52
 
45
53
  await TestHelpers.withTempRoot(async (pl) => {
54
+ const cachedBp = await cacheBlockPackTemplate(pl, specPrepared, { preparer: preparation });
46
55
  const f0 = { resourceId: pl.clientRoot, fieldName: "test0" };
47
56
 
48
57
  const bp = await pl.withWriteTx("test", async (tx) => {
49
58
  tx.createField(f0, "Dynamic");
50
- const bp = createBlockPack(tx, specPrepared);
59
+ const bp = createBlockPack(tx, cachedBp);
51
60
  tx.setField(f0, bp);
52
61
  await tx.commit();
53
62
  return await toGlobalResourceId(bp);
@@ -3,9 +3,10 @@ import { field } from "@milaboratories/pl-client";
3
3
  import { loadTemplate } from "../template/template_loading";
4
4
  import type { BlockPackExplicit, BlockPackSpecAny, BlockPackSpecPrepared } from "../../model";
5
5
  import type { Signer } from "@milaboratories/ts-helpers";
6
- import { assertNever } from "@milaboratories/ts-helpers";
6
+ import { assertNever, notEmpty } from "@milaboratories/ts-helpers";
7
7
  import type { Branded } from "@milaboratories/pl-model-common";
8
8
  import fs from "node:fs";
9
+ import { createHash } from "node:crypto";
9
10
  import { fileURLToPath } from "node:url";
10
11
  import type { Dispatcher } from "undici";
11
12
  import { request } from "undici";
@@ -19,12 +20,13 @@ import {
19
20
  RegistryV1,
20
21
  } from "@platforma-sdk/block-tools";
21
22
  import type { BlockPackInfo } from "../../model/block_pack";
23
+ import type { InstallablePackTemplate, PreparedTemplate } from "../../model/template_spec";
22
24
  import { resolveDevPacket } from "../../dev_env";
23
25
  import { getDevV2PacketMtime, getFromPackV2Mtime } from "../../block_registry";
24
26
  import type { V2RegistryProvider } from "../../block_registry/registry-v2-provider";
25
27
  import { LRUCache } from "lru-cache";
26
28
  import canonicalize from "canonicalize";
27
- import type { BlockPackSpec } from "@milaboratories/pl-model-middle-layer";
29
+ import type { BlockPackFromRegistryV2, BlockPackSpec } from "@milaboratories/pl-model-middle-layer";
28
30
  import { WorkerManager } from "../../worker/WorkerManager";
29
31
  import { z } from "zod";
30
32
 
@@ -75,6 +77,9 @@ export class BlockPackPreparer {
75
77
  sizeCalculation: (value) => value.byteLength,
76
78
  });
77
79
 
80
+ /** Parsed packs by sha256, so adding a block again does not parse its workflow again. */
81
+ private readonly loadedPackCache = new LRUCache<string, LoadedPack>({ max: 50 });
82
+
78
83
  /** Cache of prepared block packs for registry specs (immutable by version). */
79
84
  private readonly preparedCache = new LRUCache<PreparedCacheKey, BlockPackSpecPrepared>({
80
85
  max: 50,
@@ -156,8 +161,24 @@ export class BlockPackPreparer {
156
161
  if (cached) return cached;
157
162
  }
158
163
 
164
+ const registryPack =
165
+ spec.type === "from-registry-v2" ? await this.prepareRegistryPack(spec) : undefined;
166
+ if (registryPack !== undefined) {
167
+ if (key) this.preparedCache.set(key, registryPack);
168
+ return registryPack;
169
+ }
170
+
159
171
  const explicit = await this.prepareWithoutUnpacking(spec);
160
172
 
173
+ // Local dev packs are parsed when installed, which also checks their required capabilities.
174
+ const { localPath, content } = explicit.template;
175
+ if (localPath !== undefined)
176
+ return {
177
+ ...explicit,
178
+ type: "prepared",
179
+ template: { type: "local-pack", path: localPath, sha256: packSha256(content) },
180
+ };
181
+
161
182
  await using workerManager = new WorkerManager();
162
183
 
163
184
  const parsed = await workerManager.process("parseTemplate", explicit.template.content);
@@ -179,6 +200,73 @@ export class BlockPackPreparer {
179
200
  return result;
180
201
  }
181
202
 
203
+ /**
204
+ * Prepares a v2 registry block from its manifest alone, without downloading the workflow.
205
+ * Undefined when the manifest does not list the workflow pack's sha256.
206
+ */
207
+ private async prepareRegistryPack(
208
+ spec: BlockPackFromRegistryV2,
209
+ ): Promise<BlockPackSpecPrepared | undefined> {
210
+ const registry = this.v2RegistryProvider.getRegistry(spec.registryUrl);
211
+ const [manifest, components] = await Promise.all([
212
+ registry.getManifest(spec.id),
213
+ registry.getComponents(spec.id),
214
+ ]);
215
+ const workflowPath = manifest.description.components.workflow.main.path;
216
+ const workflowFile = manifest.files.find((f) => f.name === workflowPath);
217
+ if (workflowFile === undefined) return undefined;
218
+
219
+ return {
220
+ type: "prepared",
221
+ template: {
222
+ type: "registry-pack",
223
+ url: components.workflow.main.url,
224
+ sha256: workflowFile.sha256.toLowerCase(),
225
+ },
226
+ config: parseBufferConfig(await this.remoteContentCache.forceFetch(components.model.url)),
227
+ frontend: { type: "url", url: components.ui.url },
228
+ source: spec,
229
+ requiredCapabilities: manifest.description.meta.requiredCapabilities,
230
+ };
231
+ }
232
+
233
+ /** Downloads or reads a pack, checks its sha256 and parses it. */
234
+ public async loadPack(template: InstallablePackTemplate): Promise<LoadedPack> {
235
+ let content: Uint8Array | undefined;
236
+ if (template.type === "local-pack") {
237
+ // A rebuild after prepare would pair this config with another build's workflow.
238
+ content = await fs.promises.readFile(template.path);
239
+ if (packSha256(content) !== template.sha256)
240
+ throw new Error(
241
+ `workflow pack ${template.path} changed after the block was prepared; add the block again`,
242
+ );
243
+ }
244
+
245
+ const cached = this.loadedPackCache.get(template.sha256);
246
+ if (cached !== undefined) return cached;
247
+
248
+ if (content === undefined && template.type === "registry-pack") {
249
+ content = new Uint8Array(await this.remoteContentCache.forceFetch(template.url));
250
+ const sha256 = packSha256(content);
251
+ if (sha256 !== template.sha256) {
252
+ // Do not keep a broken download for the next attempt.
253
+ this.remoteContentCache.delete(template.url);
254
+ throw new Error(
255
+ `workflow pack ${template.url} has sha256 ${sha256}, expected ${template.sha256}`,
256
+ );
257
+ }
258
+ }
259
+
260
+ await using workerManager = new WorkerManager();
261
+ const parsed = await workerManager.process("parseTemplate", notEmpty(content));
262
+ const loaded: LoadedPack = {
263
+ template: { type: "prepared", data: parsed },
264
+ requiredCapabilities: requiredCapabilitiesFromTemplate(parsed),
265
+ };
266
+ this.loadedPackCache.set(template.sha256, loaded);
267
+ return loaded;
268
+ }
269
+
182
270
  private async prepareWithoutUnpacking(
183
271
  spec: BlockPackExplicit | BlockPackSpec,
184
272
  ): Promise<BlockPackExplicit> {
@@ -234,6 +322,7 @@ export class BlockPackPreparer {
234
322
  template: {
235
323
  type: "explicit",
236
324
  content: workflowContent,
325
+ localPath: description.components.workflow.main.file,
237
326
  },
238
327
  config,
239
328
  frontend: {
@@ -276,6 +365,7 @@ export class BlockPackPreparer {
276
365
  template: {
277
366
  type: "explicit",
278
367
  content: workflowContent,
368
+ localPath: description.components.workflow.main.file,
279
369
  },
280
370
  config,
281
371
  frontend: {
@@ -349,7 +439,17 @@ export class BlockPackPreparer {
349
439
  }
350
440
  }
351
441
 
442
+ /** A pack parsed on the client, with the capabilities it declares. */
443
+ type LoadedPack = { template: PreparedTemplate; requiredCapabilities?: string[] };
444
+
445
+ /** Lowercase hex sha256 of a gzipped workflow pack, the key the backend installs it by. */
446
+ export function packSha256(content: Uint8Array): string {
447
+ return createHash("sha256").update(content).digest("hex");
448
+ }
449
+
352
450
  function createCustomBlockPack(tx: PlTransaction, spec: BlockPackSpecPrepared): AnyResourceRef {
451
+ if (spec.template.type === "registry-pack" || spec.template.type === "local-pack")
452
+ throw new Error("BUG: a pack must be installed by cacheBlockPackTemplate first");
353
453
  const blockPackInfo: BlockPackInfo = { config: spec.config, source: spec.source };
354
454
  const bp = tx.createStruct(BlockPackCustomType, JSON.stringify(blockPackInfo));
355
455
  tx.createField(field(bp, BlockPackTemplateField), "Input", loadTemplate(tx, spec.template));
@@ -0,0 +1,52 @@
1
+ import { defaultHttpDispatcher } from "@milaboratories/pl-http";
2
+ import { HmacSha256Signer } from "@milaboratories/ts-helpers";
3
+ import fs from "node:fs/promises";
4
+ import http from "node:http";
5
+ import type { AddressInfo } from "node:net";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+ import { expect, test } from "vitest";
9
+ import { V2RegistryProvider } from "../../block_registry/registry-v2-provider";
10
+ import { BlockPackPreparer, packSha256 } from "./block_pack";
11
+
12
+ const newPreparer = () =>
13
+ new BlockPackPreparer(
14
+ new V2RegistryProvider(defaultHttpDispatcher()),
15
+ new HmacSha256Signer(HmacSha256Signer.generateSecret()),
16
+ );
17
+
18
+ test("loadPack drops a download with the wrong sha256, so the next attempt fetches again", async () => {
19
+ let requests = 0;
20
+ const server = http.createServer((_req, res) => {
21
+ requests++;
22
+ res.end("not the pack");
23
+ });
24
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
25
+ try {
26
+ const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/main.plj.gz`;
27
+ const preparer = newPreparer();
28
+ const template = { type: "registry-pack" as const, url, sha256: "0".repeat(64) };
29
+
30
+ await expect(preparer.loadPack(template)).rejects.toThrow(/expected 0{64}/);
31
+ await expect(preparer.loadPack(template)).rejects.toThrow(/expected 0{64}/);
32
+ expect(requests).toBe(2);
33
+ } finally {
34
+ server.close();
35
+ }
36
+ });
37
+
38
+ test("loadPack refuses a local pack rebuilt after prepare", async () => {
39
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), "pack-"));
40
+ try {
41
+ const packPath = path.join(dir, "main.plj.gz");
42
+ await fs.writeFile(packPath, "build 1");
43
+ const sha256 = packSha256(new TextEncoder().encode("build 1"));
44
+ await fs.writeFile(packPath, "build 2");
45
+
46
+ await expect(
47
+ newPreparer().loadPack({ type: "local-pack", path: packPath, sha256 }),
48
+ ).rejects.toThrow(/changed after the block was prepared/);
49
+ } finally {
50
+ await fs.rm(dir, { recursive: true, force: true });
51
+ }
52
+ });
@@ -1,5 +1,6 @@
1
1
  import { gunzipSync } from "node:zlib";
2
2
  import type { CompiledTemplateV3, TemplateData } from "@milaboratories/pl-model-backend";
3
+ import type { PlClient } from "@milaboratories/pl-client";
3
4
 
4
5
  /**
5
6
  * Reads the capability tokens a template declares it requires via
@@ -42,3 +43,27 @@ export function deriveRequiredCapabilities(
42
43
  }
43
44
  return requiredCapabilitiesFromTemplate(parsed as TemplateData | CompiledTemplateV3);
44
45
  }
46
+
47
+ /** Throws when the connected backend doesn't advertise every capability the
48
+ * block-pack requires (as declared in `meta.requiredCapabilities`).
49
+ *
50
+ * The matching set is the desktop's install gate moved server-side so both
51
+ * the UI (`AddBlockModal`) and direct middle-layer callers (the MCP server's
52
+ * `add_block` tool, programmatic block installs, tests) reject incompatible
53
+ * blocks consistently. */
54
+ export function throwIfMissingServerCapabilities(
55
+ pl: PlClient,
56
+ requiredCapabilities: readonly string[] | undefined,
57
+ ): void {
58
+ if (!requiredCapabilities || requiredCapabilities.length === 0) return;
59
+ const advertised = (pl.serverInfo.capabilities ?? []) as readonly string[];
60
+ const filterFn = (c: string) => !advertised.includes(c);
61
+ if (!requiredCapabilities.some(filterFn)) return;
62
+ const missing = requiredCapabilities.filter(filterFn);
63
+ throw new Error(
64
+ `Block cannot be added: connected backend does not advertise capabilities ` +
65
+ `${JSON.stringify(missing)}. ` +
66
+ `Backend advertises ${JSON.stringify(advertised)}. ` +
67
+ `Upgrade the backend or remove the requirement from the block manifest.`,
68
+ );
69
+ }