@milaboratories/pl-middle-layer 1.76.5 → 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 (50) 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 +2 -2
  29. package/dist/middle_layer/project.d.ts +1 -1
  30. package/dist/middle_layer/project.js +2 -2
  31. package/dist/middle_layer/project_list.cjs +1 -1
  32. package/dist/middle_layer/project_list.d.ts +1 -1
  33. package/dist/middle_layer/project_list.js +1 -1
  34. package/dist/middle_layer/project_overview.cjs +1 -1
  35. package/dist/middle_layer/project_overview.js +1 -1
  36. package/dist/middle_layer/sharing_list.cjs +1 -1
  37. package/dist/middle_layer/sharing_list.d.ts +1 -1
  38. package/dist/middle_layer/sharing_list.js +1 -1
  39. package/dist/middle_layer/template_list.cjs +1 -1
  40. package/dist/middle_layer/template_list.js +1 -1
  41. package/dist/middle_layer/types.d.ts +1 -1
  42. package/dist/network_check/pings.cjs +1 -1
  43. package/dist/network_check/pings.js +1 -1
  44. package/dist/pool/result_pool.d.ts +1 -1
  45. package/package.json +25 -24
  46. package/src/middle_layer/index.ts +1 -0
  47. package/src/middle_layer/instance_stats.test.ts +135 -0
  48. package/src/middle_layer/instance_stats.ts +173 -0
  49. package/src/middle_layer/middle_layer.ts +16 -0
  50. package/src/middle_layer/render.test.ts +11 -2
@@ -7,9 +7,9 @@ import { MiddleLayerEnvironment } from "./middle_layer.js";
7
7
  import { AuthorMarker, BlockSettings, BlockStateInternalV3, ProjectOverview } from "@milaboratories/pl-model-middle-layer";
8
8
  import { MiLogger } from "@milaboratories/ts-helpers";
9
9
  import { NavigationState } from "@milaboratories/pl-model-common";
10
+ import { Computable, ComputableStableDefined } from "@milaboratories/computable";
10
11
  import { PlClient, SignedResourceId } from "@milaboratories/pl-client";
11
12
  import { ExtendedResourceData, SynchronizedTreeState } from "@milaboratories/pl-tree";
12
- import { Computable, ComputableStableDefined } from "@milaboratories/computable";
13
13
  /** Data access object, to manipulate and read single opened (!) project data. */
14
14
  export declare class Project {
15
15
  private readonly env;
@@ -15,12 +15,12 @@ import { cacheBlockPackTemplate } from "../mutator/template/template_cache.js";
15
15
  import { BLOCK_STORAGE_FACADE_VERSION, checkBlockFlag, extractConfig } from "@platforma-sdk/model";
16
16
  import { cachedDeserialize, createInfiniteRetryState, nextInfiniteRetryState, notEmpty } from "@milaboratories/ts-helpers";
17
17
  import fsp from "node:fs/promises";
18
+ import { Computable } from "@milaboratories/computable";
19
+ import { setTimeout } from "node:timers/promises";
18
20
  import { DefaultRetryOptions, Pl, TreeFinality, ensureSignedResourceIdNotNull, field, isNotFoundError, isPermissionDenied, isTimeoutOrCancelError, isUnauthenticated, parseSignedResourceId, resourceIdToString, treeFilter } from "@milaboratories/pl-client";
19
21
  import { SynchronizedTreeState, TreeStateUpdateError, treeDumpStats } from "@milaboratories/pl-tree";
20
- import { Computable } from "@milaboratories/computable";
21
22
  import { randomUUID } from "node:crypto";
22
23
  import canonicalize from "canonicalize";
23
- import { setTimeout } from "node:timers/promises";
24
24
  // src/middle_layer/project.ts
25
25
  function stringifyForDump(object) {
26
26
  return JSON.stringify(object, (key, value) => {
@@ -1,8 +1,8 @@
1
1
  const require_project_model = require("../model/project_model.cjs");
2
2
  let _milaboratories_pl_model_common = require("@milaboratories/pl-model-common");
3
+ let _milaboratories_computable = require("@milaboratories/computable");
3
4
  let _milaboratories_pl_client = require("@milaboratories/pl-client");
4
5
  let _milaboratories_pl_tree = require("@milaboratories/pl-tree");
5
- let _milaboratories_computable = require("@milaboratories/computable");
6
6
  // src/middle_layer/project_list.ts
7
7
  const ProjectsField = "projects";
8
8
  const ProjectsResourceType = {
@@ -1,9 +1,9 @@
1
1
  import "../model/project_model.js";
2
2
  import "./types.js";
3
3
  import "./middle_layer.js";
4
+ import { WatchableValue } from "@milaboratories/computable";
4
5
  import { PlClient, PlTransaction, ResourceType, SignedResourceId } from "@milaboratories/pl-client";
5
6
  import "@milaboratories/pl-tree";
6
- import { WatchableValue } from "@milaboratories/computable";
7
7
  export declare const ProjectsField = "projects";
8
8
  export declare const ProjectsResourceType: ResourceType;
9
9
  //# sourceMappingURL=project_list.d.ts.map
@@ -1,8 +1,8 @@
1
1
  import { ProjectCreatedTimestamp, ProjectLastModifiedTimestamp, ProjectMetaKey, ProjectResourceType } from "../model/project_model.js";
2
2
  import { asProjectId } from "@milaboratories/pl-model-common";
3
+ import { Computable } from "@milaboratories/computable";
3
4
  import { field, isNullSignedResourceId, resourceIdToString, resourceTypesEqual, treeFilter } from "@milaboratories/pl-client";
4
5
  import { SynchronizedTreeState } from "@milaboratories/pl-tree";
5
- import { Computable } from "@milaboratories/computable";
6
6
  // src/middle_layer/project_list.ts
7
7
  const ProjectsField = "projects";
8
8
  const ProjectsResourceType = {
@@ -8,8 +8,8 @@ const require_render = require("./render.cjs");
8
8
  const require_util$1 = require("./util.cjs");
9
9
  let _platforma_sdk_model = require("@platforma-sdk/model");
10
10
  let _milaboratories_ts_helpers = require("@milaboratories/ts-helpers");
11
- let _milaboratories_pl_client = require("@milaboratories/pl-client");
12
11
  let _milaboratories_computable = require("@milaboratories/computable");
12
+ let _milaboratories_pl_client = require("@milaboratories/pl-client");
13
13
  let es_toolkit = require("es-toolkit");
14
14
  // src/middle_layer/project_overview.ts
15
15
  function argsEquals(a, b) {
@@ -8,8 +8,8 @@ import { computableFromCfgOrRF } from "./render.js";
8
8
  import { getBlockPackInfo } from "./util.js";
9
9
  import { BLOCK_STORAGE_FACADE_VERSION, extractCodeWithInfo, wrapCallback } from "@platforma-sdk/model";
10
10
  import { notEmpty } from "@milaboratories/ts-helpers";
11
- import { resourceIdToString } from "@milaboratories/pl-client";
12
11
  import { Computable } from "@milaboratories/computable";
12
+ import { resourceIdToString } from "@milaboratories/pl-client";
13
13
  import { isEqual, omitBy } from "es-toolkit";
14
14
  // src/middle_layer/project_overview.ts
15
15
  function argsEquals(a, b) {
@@ -1,7 +1,7 @@
1
1
  const require_sharing_model = require("../model/sharing_model.cjs");
2
+ let _milaboratories_computable = require("@milaboratories/computable");
2
3
  let _milaboratories_pl_client = require("@milaboratories/pl-client");
3
4
  let _milaboratories_pl_tree = require("@milaboratories/pl-tree");
4
- let _milaboratories_computable = require("@milaboratories/computable");
5
5
  // src/middle_layer/sharing_list.ts
6
6
  /**
7
7
  * Reactive view of the donor's own outbox. Reads each live envelope's immutable
@@ -2,9 +2,9 @@ import { EnvelopeMode, EnvelopePayloadKind, ShareId } from "../model/sharing_mod
2
2
  import "./middle_layer.js";
3
3
  import { FolderId } from "@milaboratories/pl-model-middle-layer";
4
4
  import { ProjectId, TemplateId } from "@milaboratories/pl-model-common";
5
+ import { Computable } from "@milaboratories/computable";
5
6
  import { PlClient, SignedResourceId } from "@milaboratories/pl-client";
6
7
  import { SynchronizedTreeState } from "@milaboratories/pl-tree";
7
- import { Computable } from "@milaboratories/computable";
8
8
  /** What a folder share carries, as both share lists show it. */
9
9
  export interface EnvelopeFolderSummary {
10
10
  label: string;
@@ -1,7 +1,7 @@
1
1
  import { SharedEnvelopeResourceType, SharingOutboxResourceType, SharingStateResourceType, envelopeFolderRoot, envelopeProjectMap, hiddenFieldShareId, isHiddenField, normalizeEnvelopeData } from "../model/sharing_model.js";
2
+ import { Computable } from "@milaboratories/computable";
2
3
  import { isEveryoneUserLogin, resourceType, resourceTypesEqual, treeFilter } from "@milaboratories/pl-client";
3
4
  import { SynchronizedTreeState } from "@milaboratories/pl-tree";
4
- import { Computable } from "@milaboratories/computable";
5
5
  // src/middle_layer/sharing_list.ts
6
6
  /**
7
7
  * Reactive view of the donor's own outbox. Reads each live envelope's immutable
@@ -1,8 +1,8 @@
1
1
  let _milaboratories_pl_model_middle_layer = require("@milaboratories/pl-model-middle-layer");
2
2
  let _milaboratories_pl_model_common = require("@milaboratories/pl-model-common");
3
+ let _milaboratories_computable = require("@milaboratories/computable");
3
4
  let _milaboratories_pl_client = require("@milaboratories/pl-client");
4
5
  let _milaboratories_pl_tree = require("@milaboratories/pl-tree");
5
- let _milaboratories_computable = require("@milaboratories/computable");
6
6
  // src/middle_layer/template_list.ts
7
7
  const TemplatesField = "templates";
8
8
  const TemplatesResourceType = {
@@ -1,8 +1,8 @@
1
1
  import { normalizeDescription } from "@milaboratories/pl-model-middle-layer";
2
2
  import { asTemplateId } from "@milaboratories/pl-model-common";
3
+ import { Computable } from "@milaboratories/computable";
3
4
  import { resourceIdToString, resourceTypesEqual, treeFilter } from "@milaboratories/pl-client";
4
5
  import { SynchronizedTreeState } from "@milaboratories/pl-tree";
5
- import { Computable } from "@milaboratories/computable";
6
6
  // src/middle_layer/template_list.ts
7
7
  const TemplatesField = "templates";
8
8
  const TemplatesResourceType = {
@@ -1,4 +1,4 @@
1
- import { SynchronizedTreeOps, SynchronizedTreeState } from "@milaboratories/pl-tree";
2
1
  import { Computable } from "@milaboratories/computable";
2
+ import { SynchronizedTreeOps, SynchronizedTreeState } from "@milaboratories/pl-tree";
3
3
  export type TemporalSynchronizedTreeOps = Pick<SynchronizedTreeOps, "pollingInterval" | "stopPollingDelay" | "logStat" | "initialTreeLoadingTimeout" | "traversalMode">;
4
4
  //# sourceMappingURL=types.d.ts.map
@@ -1,6 +1,6 @@
1
1
  let undici = require("undici");
2
- let _milaboratories_pl_client = require("@milaboratories/pl-client");
3
2
  let node_timers_promises = require("node:timers/promises");
3
+ let _milaboratories_pl_client = require("@milaboratories/pl-client");
4
4
  // src/network_check/pings.ts
5
5
  async function backendPings(ops, plConfig) {
6
6
  return await recordPings(ops.pingCheckDurationMs, ops.maxPingsPerSecond, async () => {
@@ -1,6 +1,6 @@
1
1
  import { request } from "undici";
2
- import { UnauthenticatedPlClient } from "@milaboratories/pl-client";
3
2
  import { setTimeout } from "node:timers/promises";
3
+ import { UnauthenticatedPlClient } from "@milaboratories/pl-client";
4
4
  // src/network_check/pings.ts
5
5
  async function backendPings(ops, plConfig) {
6
6
  return await recordPings(ops.pingCheckDurationMs, ops.maxPingsPerSecond, async () => {
@@ -1,4 +1,4 @@
1
1
  import { PObject, PlRef } from "@platforma-sdk/model";
2
- import { PlTreeNodeAccessor } from "@milaboratories/pl-tree";
3
2
  import "@milaboratories/computable";
3
+ import { PlTreeNodeAccessor } from "@milaboratories/pl-tree";
4
4
  import "utility-types";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@milaboratories/pl-middle-layer",
3
- "version": "1.76.5",
3
+ "version": "1.77.0",
4
4
  "description": "Pl Middle Layer",
5
5
  "keywords": [],
6
6
  "license": "UNLICENSED",
@@ -19,27 +19,27 @@
19
19
  }
20
20
  },
21
21
  "dependencies": {
22
- "@milaboratories/columns-collection-driver": "0.2.13",
23
- "@milaboratories/computable": "2.9.9",
24
- "@milaboratories/helpers": "1.14.6",
25
- "@milaboratories/pf-driver": "1.9.13",
26
- "@milaboratories/pf-spec-driver": "1.5.13",
22
+ "@milaboratories/columns-collection-driver": "0.2.14",
23
+ "@milaboratories/computable": "2.9.10",
24
+ "@milaboratories/helpers": "1.14.7",
25
+ "@milaboratories/pf-driver": "1.9.14",
26
+ "@milaboratories/pf-spec-driver": "1.5.14",
27
27
  "@milaboratories/pframes-rs-node": "1.2.0",
28
- "@milaboratories/pl-client": "3.21.1",
29
- "@milaboratories/pl-crash-recorder": "0.3.9",
30
- "@milaboratories/pl-deployments": "3.0.25",
31
- "@milaboratories/pl-drivers": "1.16.42",
32
- "@milaboratories/pl-errors": "1.4.59",
33
- "@milaboratories/pl-http": "1.2.5",
34
- "@milaboratories/pl-model-backend": "1.4.44",
35
- "@milaboratories/pl-model-common": "1.55.0",
36
- "@milaboratories/pl-model-middle-layer": "1.35.0",
37
- "@milaboratories/pl-tree": "1.17.1",
28
+ "@milaboratories/pl-client": "3.22.0",
29
+ "@milaboratories/pl-crash-recorder": "0.3.10",
30
+ "@milaboratories/pl-deployments": "3.0.26",
31
+ "@milaboratories/pl-drivers": "1.16.43",
32
+ "@milaboratories/pl-errors": "1.4.60",
33
+ "@milaboratories/pl-http": "1.2.6",
34
+ "@milaboratories/pl-model-backend": "1.4.45",
35
+ "@milaboratories/pl-model-common": "1.55.1",
36
+ "@milaboratories/pl-model-middle-layer": "1.36.0",
37
+ "@milaboratories/pl-tree": "1.17.2",
38
38
  "@milaboratories/resolve-helper": "1.1.3",
39
- "@milaboratories/ts-helpers": "1.9.0",
40
- "@platforma-sdk/block-tools": "2.17.7",
41
- "@platforma-sdk/model": "1.88.0",
42
- "@platforma-sdk/workflow-tengo": "6.22.0",
39
+ "@milaboratories/ts-helpers": "1.9.1",
40
+ "@platforma-sdk/block-tools": "2.17.8",
41
+ "@platforma-sdk/model": "1.88.8",
42
+ "@platforma-sdk/workflow-tengo": "6.22.1",
43
43
  "canonicalize": "~2.1.0",
44
44
  "denque": "^2.1.0",
45
45
  "es-toolkit": "^1.39.10",
@@ -52,12 +52,13 @@
52
52
  "zod": "~3.25.76"
53
53
  },
54
54
  "devDependencies": {
55
- "@milaboratories/build-configs": "2.0.2",
56
- "@milaboratories/ts-builder": "1.7.3",
57
- "@milaboratories/ts-configs": "1.4.0",
55
+ "@milaboratories/build-configs": "2.0.3",
56
+ "@milaboratories/ts-builder": "1.7.4",
57
+ "@milaboratories/ts-configs": "1.4.1",
58
58
  "@types/node": "~24.19.2",
59
59
  "@types/semver": "^7.7.0",
60
60
  "@vitest/coverage-istanbul": "^4.1.12",
61
+ "shx": "^0.4.0",
61
62
  "typescript": "7.0.2",
62
63
  "vitest": "^4.1.12"
63
64
  },
@@ -77,7 +78,7 @@
77
78
  "linter:check": "ts-builder linter --check",
78
79
  "types:check": "ts-builder type-check --target node",
79
80
  "test": "vitest run --coverage",
80
- "do-pack": "rm -f *.tgz && pnpm pack && mv *.tgz package.tgz",
81
+ "do-pack": "shx rm -f *.tgz && pnpm pack && shx mv *.tgz package.tgz",
81
82
  "fmt": "ts-builder format"
82
83
  }
83
84
  }
@@ -21,3 +21,4 @@ export type {
21
21
  BlockActionContextNode,
22
22
  BlockActionTransition,
23
23
  } from "./block_action_context";
24
+ export { InstanceStatsContextTypeName, parseInstanceStats } from "./instance_stats";
@@ -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([
@@ -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
  }