@milaboratories/pl-middle-layer 1.76.4 → 1.77.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 (55) hide show
  1. package/dist/index.cjs +3 -0
  2. package/dist/index.d.ts +2 -1
  3. package/dist/index.js +2 -1
  4. package/dist/middle_layer/block.cjs +1 -1
  5. package/dist/middle_layer/block.js +1 -1
  6. package/dist/middle_layer/build_stamp.cjs +1 -1
  7. package/dist/middle_layer/build_stamp.js +1 -1
  8. package/dist/middle_layer/folders.cjs +1 -1
  9. package/dist/middle_layer/folders.d.ts +1 -1
  10. package/dist/middle_layer/folders.js +1 -1
  11. package/dist/middle_layer/frontend_path.cjs +1 -1
  12. package/dist/middle_layer/frontend_path.js +1 -1
  13. package/dist/middle_layer/index.cjs +3 -0
  14. package/dist/middle_layer/index.d.ts +2 -1
  15. package/dist/middle_layer/index.js +2 -1
  16. package/dist/middle_layer/instance_stats.cjs +125 -0
  17. package/dist/middle_layer/instance_stats.cjs.map +1 -0
  18. package/dist/middle_layer/instance_stats.d.ts +16 -0
  19. package/dist/middle_layer/instance_stats.d.ts.map +1 -0
  20. package/dist/middle_layer/instance_stats.js +122 -0
  21. package/dist/middle_layer/instance_stats.js.map +1 -0
  22. package/dist/middle_layer/middle_layer.cjs +14 -1
  23. package/dist/middle_layer/middle_layer.cjs.map +1 -1
  24. package/dist/middle_layer/middle_layer.d.ts +10 -2
  25. package/dist/middle_layer/middle_layer.d.ts.map +1 -1
  26. package/dist/middle_layer/middle_layer.js +14 -1
  27. package/dist/middle_layer/middle_layer.js.map +1 -1
  28. package/dist/middle_layer/project.cjs +8 -7
  29. package/dist/middle_layer/project.cjs.map +1 -1
  30. package/dist/middle_layer/project.d.ts +1 -1
  31. package/dist/middle_layer/project.d.ts.map +1 -1
  32. package/dist/middle_layer/project.js +8 -7
  33. package/dist/middle_layer/project.js.map +1 -1
  34. package/dist/middle_layer/project_list.cjs +1 -1
  35. package/dist/middle_layer/project_list.d.ts +1 -1
  36. package/dist/middle_layer/project_list.js +1 -1
  37. package/dist/middle_layer/project_overview.cjs +1 -1
  38. package/dist/middle_layer/project_overview.js +1 -1
  39. package/dist/middle_layer/sharing_list.cjs +1 -1
  40. package/dist/middle_layer/sharing_list.d.ts +1 -1
  41. package/dist/middle_layer/sharing_list.js +1 -1
  42. package/dist/middle_layer/template_list.cjs +1 -1
  43. package/dist/middle_layer/template_list.js +1 -1
  44. package/dist/middle_layer/types.d.ts +1 -1
  45. package/dist/network_check/pings.cjs +1 -1
  46. package/dist/network_check/pings.js +1 -1
  47. package/dist/pool/result_pool.d.ts +1 -1
  48. package/package.json +25 -24
  49. package/src/middle_layer/close_dead_link.test.ts +49 -0
  50. package/src/middle_layer/index.ts +1 -0
  51. package/src/middle_layer/instance_stats.test.ts +135 -0
  52. package/src/middle_layer/instance_stats.ts +173 -0
  53. package/src/middle_layer/middle_layer.ts +16 -0
  54. package/src/middle_layer/project.ts +9 -5
  55. package/src/middle_layer/render.test.ts +11 -2
@@ -0,0 +1,135 @@
1
+ import { TestHelpers } from "@milaboratories/pl-client";
2
+ import { ConsoleLoggerAdapter } from "@milaboratories/ts-helpers";
3
+ import { describe, expect, it, test } from "vitest";
4
+ import type { BackendCapability, SignedResourceId } from "@milaboratories/pl-client";
5
+ import { createSignedResourceId } from "@milaboratories/pl-client";
6
+ import type { InstanceStatsClient } from "./instance_stats";
7
+ import { InstanceStatsCapability, InstanceStatsWatch, parseInstanceStats } from "./instance_stats";
8
+
9
+ const kv = (key: string, value: unknown) => ({ key, value: JSON.stringify(value) });
10
+
11
+ describe("parseInstanceStats", () => {
12
+ it("reads every reading of a sample", () => {
13
+ expect(
14
+ parseInstanceStats([
15
+ kv("reading/instance/cpu", { total: 24000, current: 18500 }),
16
+ kv("reading/instance/ram", { total: 64e9, current: 41e9 }),
17
+ kv("reading/instance/jobs", { running: 12, queued: 14 }),
18
+ kv("reading/instance/source", "scheduler"),
19
+ ]),
20
+ ).toEqual({
21
+ availability: "read",
22
+ cpu: { total: 24000, current: 18500 },
23
+ ram: { total: 64e9, current: 41e9 },
24
+ jobs: { running: 12, queued: 14 },
25
+ source: "scheduler",
26
+ });
27
+ });
28
+
29
+ it("reads the GPU devices and GPU memory, and no GPU count from a null reading", () => {
30
+ const stats = parseInstanceStats([
31
+ kv("reading/instance/gpu", { total: 8, current: 3 }),
32
+ kv("reading/instance/gpu-memory", null),
33
+ ]);
34
+ expect(stats.gpu).toEqual({ total: 8, current: 3 });
35
+ expect(stats.gpuMemory).toBeUndefined();
36
+ expect(
37
+ parseInstanceStats([kv("reading/instance/gpu-memory", { total: 24e9, current: 12e9 })])
38
+ .gpuMemory,
39
+ ).toEqual({ total: 24e9, current: 12e9 });
40
+ });
41
+
42
+ it("keeps a capacity whose total the source does not know", () => {
43
+ expect(parseInstanceStats([kv("reading/instance/cpu", { current: 4000 })]).cpu).toEqual({
44
+ current: 4000,
45
+ });
46
+ });
47
+
48
+ it("leaves out a reading that is not the expected JSON, and keys of other namespaces", () => {
49
+ const stats = parseInstanceStats([
50
+ { key: "reading/instance/cpu", value: "not json" },
51
+ kv("reading/instance/jobs", { running: "many" }),
52
+ kv("reading/other/cpu", { current: 1 }),
53
+ ]);
54
+ expect(stats).toEqual({ availability: "read" });
55
+ });
56
+ });
57
+
58
+ test("the watch reads a sample where the capability is advertised, and nothing elsewhere", async () => {
59
+ const pl = await TestHelpers.getTestClient();
60
+ const watch = new InstanceStatsWatch(pl, new ConsoleLoggerAdapter());
61
+ try {
62
+ let stats = await watch.stats.getValue();
63
+ for (let i = 0; i < 50 && stats === undefined; i++) {
64
+ await new Promise((r) => setTimeout(r, 100));
65
+ stats = await watch.stats.getValue();
66
+ }
67
+ expect(stats?.availability).toEqual(
68
+ pl.hasCapability(InstanceStatsCapability) ? "read" : "unsupported",
69
+ );
70
+ } finally {
71
+ await watch.terminate();
72
+ await pl.close();
73
+ }
74
+ }, 30_000);
75
+
76
+ /** A client that advertises `capabilities` and serves one context with `kvs`, or none. */
77
+ function fakeClient(opts: {
78
+ capabilities: BackendCapability[];
79
+ context?: { key: string; value: string }[];
80
+ }): InstanceStatsClient & { listed: number } {
81
+ const ref = createSignedResourceId(7n);
82
+ const client = {
83
+ listed: 0,
84
+ hasCapability: (c: BackendCapability) => opts.capabilities.includes(c),
85
+ listSharedResourcesByType: async (_name: string): Promise<SignedResourceId[]> => {
86
+ client.listed++;
87
+ return opts.context === undefined ? [] : [ref];
88
+ },
89
+ withReadTx: async <T>(
90
+ _name: string,
91
+ body: (tx: {
92
+ listKeyValuesString(rId: SignedResourceId): Promise<{ key: string; value: string }[]>;
93
+ }) => Promise<T>,
94
+ ) => await body({ listKeyValuesString: async () => opts.context ?? [] }),
95
+ };
96
+ return client;
97
+ }
98
+
99
+ async function firstSample(client: InstanceStatsClient) {
100
+ const watch = new InstanceStatsWatch(client, new ConsoleLoggerAdapter());
101
+ try {
102
+ for (let i = 0; i < 50; i++) {
103
+ const stats = await watch.stats.getValue();
104
+ if (stats !== undefined) return stats;
105
+ await new Promise((r) => setTimeout(r, 20));
106
+ }
107
+ return undefined;
108
+ } finally {
109
+ await watch.terminate();
110
+ }
111
+ }
112
+
113
+ describe("InstanceStatsWatch", () => {
114
+ it("does nothing on a backend that does not advertise the capability", async () => {
115
+ const client = fakeClient({ capabilities: [] });
116
+ expect(await firstSample(client)).toEqual({ availability: "unsupported" });
117
+ expect(client.listed).toBe(0);
118
+ });
119
+
120
+ it("reports unsupported when the capability is advertised but the context is missing", async () => {
121
+ const client = fakeClient({ capabilities: [InstanceStatsCapability] });
122
+ expect(await firstSample(client)).toEqual({ availability: "unsupported" });
123
+ expect(client.listed).toBe(1);
124
+ });
125
+
126
+ it("reads the context's readings, and nothing when its writer is off", async () => {
127
+ const sample = [kv("reading/instance/jobs", { running: 1, queued: 2 })];
128
+ expect(
129
+ await firstSample(fakeClient({ capabilities: [InstanceStatsCapability], context: sample })),
130
+ ).toEqual({ availability: "read", jobs: { running: 1, queued: 2 } });
131
+ expect(
132
+ await firstSample(fakeClient({ capabilities: [InstanceStatsCapability], context: [] })),
133
+ ).toEqual({ availability: "read" });
134
+ });
135
+ });
@@ -0,0 +1,173 @@
1
+ /**
2
+ * The load of the whole Platforma instance, read from the backend's instance statistics context.
3
+ *
4
+ * A backend that advertises `instanceStats:v1` keeps one such context; without it nothing is read.
5
+ * Core creates one context per instance and grants every user read access; the executor runner
6
+ * writes its readings as `reading/instance/<key>` every few seconds, all keys of a sample in one
7
+ * transaction. The middle layer finds the context once, then reads its key-values on the same
8
+ * cadence and publishes a sample only when it changed.
9
+ *
10
+ * Contract: pl `plapi/plapi/instance_stats_context.go` (MILAB-7312).
11
+ */
12
+
13
+ import type {
14
+ BackendCapability,
15
+ KeyValueString,
16
+ SignedResourceId,
17
+ } from "@milaboratories/pl-client";
18
+ import type { Computable } from "@milaboratories/computable";
19
+ import { Computable as ComputableFactory, WatchableValue } from "@milaboratories/computable";
20
+ import type { MiLogger } from "@milaboratories/ts-helpers";
21
+ import type { InstanceStats, InstanceStatsCapacity } from "@milaboratories/pl-model-middle-layer";
22
+ import { UnsupportedInstanceStats } from "@milaboratories/pl-model-middle-layer";
23
+ import { setTimeout } from "node:timers/promises";
24
+
25
+ /** The backend capability that says the instance statistics context exists. */
26
+ export const InstanceStatsCapability = "instanceStats:v1";
27
+
28
+ /** The resource type name of the instance statistics context. */
29
+ export const InstanceStatsContextTypeName = "InstanceStatsContext";
30
+
31
+ /** Prefix of the instance statistics readings. */
32
+ const ReadingPrefix = "reading/instance/";
33
+
34
+ /** How often the readings are read: the writer's default interval. */
35
+ const PollIntervalMs = 10_000;
36
+
37
+ function asCapacity(v: unknown): InstanceStatsCapacity | undefined {
38
+ if (typeof v !== "object" || v === null) return undefined;
39
+ const { total, current } = v as { total?: unknown; current?: unknown };
40
+ if (typeof current !== "number") return undefined;
41
+ return typeof total === "number" ? { total, current } : { current };
42
+ }
43
+
44
+ function asJobs(v: unknown): InstanceStats["jobs"] {
45
+ if (typeof v !== "object" || v === null) return undefined;
46
+ const { running, queued } = v as { running?: unknown; queued?: unknown };
47
+ if (typeof running !== "number" || typeof queued !== "number") return undefined;
48
+ return { running, queued };
49
+ }
50
+
51
+ /**
52
+ * The stats from the context's key-values. A reading that is missing or not the expected JSON is
53
+ * left out rather than failing the sample: the readings are diagnostic, and a newer writer may add
54
+ * or reshape keys.
55
+ */
56
+ export function parseInstanceStats(kvs: readonly { key: string; value: string }[]): InstanceStats {
57
+ const readings = new Map<string, unknown>();
58
+ for (const { key, value } of kvs) {
59
+ if (!key.startsWith(ReadingPrefix)) continue;
60
+ try {
61
+ readings.set(key.slice(ReadingPrefix.length), JSON.parse(value));
62
+ } catch {
63
+ // not JSON: left out
64
+ }
65
+ }
66
+
67
+ const source = readings.get("source");
68
+ return {
69
+ availability: "read",
70
+ cpu: asCapacity(readings.get("cpu")),
71
+ ram: asCapacity(readings.get("ram")),
72
+ gpu: asCapacity(readings.get("gpu")),
73
+ gpuMemory: asCapacity(readings.get("gpu-memory")),
74
+ jobs: asJobs(readings.get("jobs")),
75
+ source: typeof source === "string" ? source : undefined,
76
+ };
77
+ }
78
+
79
+ /**
80
+ * The part of a client the watch uses: a `PlClient` satisfies it, and a test can serve it without a
81
+ * backend.
82
+ */
83
+ export interface InstanceStatsClient {
84
+ hasCapability(capability: BackendCapability): boolean;
85
+ listSharedResourcesByType(resourceTypeName: string): Promise<SignedResourceId[]>;
86
+ withReadTx<T>(
87
+ name: string,
88
+ body: (tx: {
89
+ listKeyValuesString(rId: SignedResourceId): Promise<KeyValueString[]>;
90
+ }) => Promise<T>,
91
+ ): Promise<T>;
92
+ }
93
+
94
+ /**
95
+ * Reads the instance statistics while the middle layer lives.
96
+ *
97
+ * Reports `unsupported` without `instanceStats:v1`, and while the context cannot be found. A
98
+ * context whose writer is off yields a sample without readings.
99
+ */
100
+ export class InstanceStatsWatch {
101
+ private readonly value = new WatchableValue<InstanceStats | undefined>(undefined);
102
+ private readonly abortController = new AbortController();
103
+ private readonly loop: Promise<void>;
104
+
105
+ /** The latest sample; undefined until the first read. */
106
+ public readonly stats: Computable<InstanceStats | undefined>;
107
+
108
+ constructor(
109
+ private readonly pl: InstanceStatsClient,
110
+ private readonly logger: MiLogger,
111
+ ) {
112
+ this.stats = ComputableFactory.make((ctx) => this.value.getValue(ctx));
113
+ this.loop = this.run();
114
+ this.loop.catch((err: unknown) =>
115
+ this.logger.warn(new Error("instance stats loop failed", { cause: err })),
116
+ );
117
+ }
118
+
119
+ public async terminate(): Promise<void> {
120
+ this.abortController.abort();
121
+ try {
122
+ await this.loop;
123
+ } catch {
124
+ // logged where it was raised
125
+ }
126
+ this.stats.resetState();
127
+ }
128
+
129
+ /** The last published sample, serialized, to skip publishing one that did not change. */
130
+ private lastPublished?: string;
131
+
132
+ private publish(stats: InstanceStats): void {
133
+ const serialized = JSON.stringify(stats);
134
+ if (serialized === this.lastPublished) return;
135
+ this.lastPublished = serialized;
136
+ this.value.setValue(stats, "instance stats changed");
137
+ }
138
+
139
+ private async run(): Promise<void> {
140
+ // A backend that does not advertise the context has none to find: nothing is listed or read.
141
+ if (!this.pl.hasCapability(InstanceStatsCapability)) {
142
+ this.publish(UnsupportedInstanceStats);
143
+ return;
144
+ }
145
+
146
+ let context: SignedResourceId | undefined;
147
+ while (!this.abortController.signal.aborted) {
148
+ try {
149
+ context ??= (await this.pl.listSharedResourcesByType(InstanceStatsContextTypeName))[0];
150
+ if (context === undefined) this.publish(UnsupportedInstanceStats);
151
+ else {
152
+ const ref = context;
153
+ const kvs = await this.pl.withReadTx("instanceStats", (tx) =>
154
+ tx.listKeyValuesString(ref),
155
+ );
156
+ this.publish(parseInstanceStats(kvs));
157
+ }
158
+ } catch (err: unknown) {
159
+ if (this.abortController.signal.aborted) return;
160
+ // Retried on the next tick, with the context looked up again in case it was replaced.
161
+ this.logger.warn(new Error("instance stats read failed", { cause: err }));
162
+ context = undefined;
163
+ this.publish({ availability: "unreadable" });
164
+ }
165
+
166
+ try {
167
+ await setTimeout(PollIntervalMs, undefined, { signal: this.abortController.signal });
168
+ } catch {
169
+ return; // aborted
170
+ }
171
+ }
172
+ }
173
+ }
@@ -1,3 +1,5 @@
1
+ import { InstanceStatsWatch } from "./instance_stats";
2
+ import type { InstanceStats } from "@milaboratories/pl-model-middle-layer";
1
3
  import type {
2
4
  PlClient,
3
5
  PlTransaction,
@@ -1843,8 +1845,22 @@ export class MiddleLayer {
1843
1845
  * actual termination of event loops and other processes associated with
1844
1846
  * them.
1845
1847
  */
1848
+ private instanceStatsWatch?: InstanceStatsWatch;
1849
+
1850
+ /**
1851
+ * The load of the whole instance: allocated CPU and RAM out of its capacity, and running and
1852
+ * queued jobs. Read from the backend's instance statistics context every few seconds, starting on
1853
+ * first access; undefined until the first read, `unsupported` on a backend that does not advertise
1854
+ * `instanceStats:v1`.
1855
+ */
1856
+ public get instanceStats(): Computable<InstanceStats | undefined> {
1857
+ this.instanceStatsWatch ??= new InstanceStatsWatch(this.pl, this.env.logger);
1858
+ return this.instanceStatsWatch.stats;
1859
+ }
1860
+
1846
1861
  public async close() {
1847
1862
  if (this.envelopeCleanupTimer !== undefined) clearInterval(this.envelopeCleanupTimer);
1863
+ await this.instanceStatsWatch?.terminate();
1848
1864
  await Promise.all([...this.openedProjects.values()].map((prj) => prj.destroy()));
1849
1865
  // this.env.quickJs;
1850
1866
  await Promise.all([
@@ -296,7 +296,11 @@ export class Project {
296
296
  (prj) => {
297
297
  prj.doRefresh();
298
298
  },
299
- { name: "doRefresh", lockId: this.projectLockId },
299
+ {
300
+ name: "doRefresh",
301
+ lockId: this.projectLockId,
302
+ abortSignal: this.abortController.signal,
303
+ },
300
304
  );
301
305
  await this.activeConfigs.getValue();
302
306
  await setTimeout(this.env.ops.projectRefreshInterval, undefined, {
@@ -317,16 +321,16 @@ export class Project {
317
321
  }
318
322
  }
319
323
  retryState = undefined;
320
- } catch (e: unknown) {
324
+ } catch (error: unknown) {
321
325
  // If we're destroyed, exit gracefully regardless of error type
322
326
  if (this.destroyed) break;
323
327
 
324
- if (isNotFoundError(e)) {
328
+ if (isNotFoundError(error)) {
325
329
  this.env.logger.warn(
326
330
  "project refresh routine terminated, because project was externally deleted",
327
331
  );
328
332
  break;
329
- } else if (isTimeoutOrCancelError(e)) {
333
+ } else if (isTimeoutOrCancelError(error)) {
330
334
  // Timeout during normal operation, continue the loop
331
335
  } else {
332
336
  retryState = retryState
@@ -340,7 +344,7 @@ export class Project {
340
344
  });
341
345
  this.env.logger.error(
342
346
  new Error(`[refreshLoop] unexpected exception, retrying in ${retryState.nextDelay}ms`, {
343
- cause: e,
347
+ cause: error,
344
348
  }),
345
349
  );
346
350
  try {
@@ -34,7 +34,12 @@ export async function withMl(
34
34
  });
35
35
  }
36
36
 
37
- export async function awaitBlockDone(prj: Project, blockId: string, timeout: number = 2000) {
37
+ /**
38
+ * The timeout covers the whole wait, not one change notification: the block is
39
+ * fetched from the remote registry and then run, so the budget must fit a cold
40
+ * download on a CI runner.
41
+ */
42
+ export async function awaitBlockDone(prj: Project, blockId: string, timeout: number = 10_000) {
38
43
  const abortSignal = AbortSignal.timeout(timeout);
39
44
  const overview = prj.overview;
40
45
  const state = prj.getBlockState(blockId);
@@ -52,8 +57,12 @@ export async function awaitBlockDone(prj: Project, blockId: string, timeout: num
52
57
  try {
53
58
  await overview.awaitChange(abortSignal);
54
59
  } catch (e: any) {
60
+ console.dir(blockOverview, { depth: 5 });
55
61
  console.dir(await state.getValue(), { depth: 5 });
56
- throw new Error("Aborted.", { cause: e });
62
+ throw new Error(
63
+ `Block ${blockId} was still ${blockOverview.calculationStatus} after ${timeout}ms.`,
64
+ { cause: e },
65
+ );
57
66
  }
58
67
  }
59
68
  }