@milaboratories/pl-middle-layer 2.1.2 → 2.2.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.
- package/dist/middle_layer/build_stamp.cjs +1 -1
- package/dist/middle_layer/build_stamp.js +1 -1
- package/dist/middle_layer/instance_stats.cjs +2 -2
- package/dist/middle_layer/instance_stats.cjs.map +1 -1
- package/dist/middle_layer/instance_stats.js +2 -2
- package/dist/middle_layer/instance_stats.js.map +1 -1
- package/package.json +6 -6
- package/src/middle_layer/instance_stats.test.ts +7 -9
- package/src/middle_layer/instance_stats.ts +2 -2
|
@@ -43,7 +43,7 @@ function parseInstanceStats(kvs) {
|
|
|
43
43
|
}
|
|
44
44
|
const source = readings.get("source");
|
|
45
45
|
return {
|
|
46
|
-
|
|
46
|
+
status: "ok",
|
|
47
47
|
cpu: asCapacity(readings.get("cpu")),
|
|
48
48
|
ram: asCapacity(readings.get("ram")),
|
|
49
49
|
gpu: asCapacity(readings.get("gpu")),
|
|
@@ -107,7 +107,7 @@ var InstanceStatsWatch = class {
|
|
|
107
107
|
if (this.abortController.signal.aborted) return;
|
|
108
108
|
this.logger.warn(new Error("instance stats read failed", { cause: err }));
|
|
109
109
|
context = void 0;
|
|
110
|
-
this.publish({
|
|
110
|
+
this.publish({ status: "unreadable" });
|
|
111
111
|
}
|
|
112
112
|
try {
|
|
113
113
|
await (0, node_timers_promises.setTimeout)(PollIntervalMs, void 0, { signal: this.abortController.signal });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instance_stats.cjs","names":["WatchableValue","ComputableFactory","UnsupportedInstanceStats","setTimeout"],"sources":["../../src/middle_layer/instance_stats.ts"],"sourcesContent":["/**\n * The load of the whole Platforma instance, read from the backend's instance statistics context.\n *\n * A backend that advertises `instanceStats:v1` keeps one such context; without it nothing is read.\n * Core creates one context per instance and grants every user read access; the executor runner\n * writes its readings as `reading/instance/<key>` every few seconds, all keys of a sample in one\n * transaction. The middle layer finds the context once, then reads its key-values on the same\n * cadence and publishes a sample only when it changed.\n *\n * Contract: pl `plapi/plapi/instance_stats_context.go` (MILAB-7312).\n */\n\nimport type {\n BackendCapability,\n KeyValueString,\n SignedResourceId,\n} from \"@milaboratories/pl-client\";\nimport type { Computable } from \"@milaboratories/computable\";\nimport { Computable as ComputableFactory, WatchableValue } from \"@milaboratories/computable\";\nimport type { MiLogger } from \"@milaboratories/ts-helpers\";\nimport type { InstanceStats, InstanceStatsCapacity } from \"@milaboratories/pl-model-middle-layer\";\nimport { UnsupportedInstanceStats } from \"@milaboratories/pl-model-middle-layer\";\nimport { setTimeout } from \"node:timers/promises\";\n\n/** The backend capability that says the instance statistics context exists. */\nexport const InstanceStatsCapability = \"instanceStats:v1\";\n\n/** The resource type name of the instance statistics context. */\nexport const InstanceStatsContextTypeName = \"InstanceStatsContext\";\n\n/** Prefix of the instance statistics readings. */\nconst ReadingPrefix = \"reading/instance/\";\n\n/** How often the readings are read: the writer's default interval. */\nconst PollIntervalMs = 10_000;\n\nfunction asCapacity(v: unknown): InstanceStatsCapacity | undefined {\n if (typeof v !== \"object\" || v === null) return undefined;\n const { total, current } = v as { total?: unknown; current?: unknown };\n if (typeof current !== \"number\") return undefined;\n return typeof total === \"number\" ? { total, current } : { current };\n}\n\nfunction asJobs(v: unknown): InstanceStats[\"jobs\"] {\n if (typeof v !== \"object\" || v === null) return undefined;\n const { running, queued } = v as { running?: unknown; queued?: unknown };\n if (typeof running !== \"number\" || typeof queued !== \"number\") return undefined;\n return { running, queued };\n}\n\n/**\n * The stats from the context's key-values. A reading that is missing or not the expected JSON is\n * left out rather than failing the sample: the readings are diagnostic, and a newer writer may add\n * or reshape keys.\n */\nexport function parseInstanceStats(kvs: readonly { key: string; value: string }[]): InstanceStats {\n const readings = new Map<string, unknown>();\n for (const { key, value } of kvs) {\n if (!key.startsWith(ReadingPrefix)) continue;\n try {\n readings.set(key.slice(ReadingPrefix.length), JSON.parse(value));\n } catch {\n // not JSON: left out\n }\n }\n\n const source = readings.get(\"source\");\n return {\n
|
|
1
|
+
{"version":3,"file":"instance_stats.cjs","names":["WatchableValue","ComputableFactory","UnsupportedInstanceStats","setTimeout"],"sources":["../../src/middle_layer/instance_stats.ts"],"sourcesContent":["/**\n * The load of the whole Platforma instance, read from the backend's instance statistics context.\n *\n * A backend that advertises `instanceStats:v1` keeps one such context; without it nothing is read.\n * Core creates one context per instance and grants every user read access; the executor runner\n * writes its readings as `reading/instance/<key>` every few seconds, all keys of a sample in one\n * transaction. The middle layer finds the context once, then reads its key-values on the same\n * cadence and publishes a sample only when it changed.\n *\n * Contract: pl `plapi/plapi/instance_stats_context.go` (MILAB-7312).\n */\n\nimport type {\n BackendCapability,\n KeyValueString,\n SignedResourceId,\n} from \"@milaboratories/pl-client\";\nimport type { Computable } from \"@milaboratories/computable\";\nimport { Computable as ComputableFactory, WatchableValue } from \"@milaboratories/computable\";\nimport type { MiLogger } from \"@milaboratories/ts-helpers\";\nimport type { InstanceStats, InstanceStatsCapacity } from \"@milaboratories/pl-model-middle-layer\";\nimport { UnsupportedInstanceStats } from \"@milaboratories/pl-model-middle-layer\";\nimport { setTimeout } from \"node:timers/promises\";\n\n/** The backend capability that says the instance statistics context exists. */\nexport const InstanceStatsCapability = \"instanceStats:v1\";\n\n/** The resource type name of the instance statistics context. */\nexport const InstanceStatsContextTypeName = \"InstanceStatsContext\";\n\n/** Prefix of the instance statistics readings. */\nconst ReadingPrefix = \"reading/instance/\";\n\n/** How often the readings are read: the writer's default interval. */\nconst PollIntervalMs = 10_000;\n\nfunction asCapacity(v: unknown): InstanceStatsCapacity | undefined {\n if (typeof v !== \"object\" || v === null) return undefined;\n const { total, current } = v as { total?: unknown; current?: unknown };\n if (typeof current !== \"number\") return undefined;\n return typeof total === \"number\" ? { total, current } : { current };\n}\n\nfunction asJobs(v: unknown): InstanceStats[\"jobs\"] {\n if (typeof v !== \"object\" || v === null) return undefined;\n const { running, queued } = v as { running?: unknown; queued?: unknown };\n if (typeof running !== \"number\" || typeof queued !== \"number\") return undefined;\n return { running, queued };\n}\n\n/**\n * The stats from the context's key-values. A reading that is missing or not the expected JSON is\n * left out rather than failing the sample: the readings are diagnostic, and a newer writer may add\n * or reshape keys.\n */\nexport function parseInstanceStats(kvs: readonly { key: string; value: string }[]): InstanceStats {\n const readings = new Map<string, unknown>();\n for (const { key, value } of kvs) {\n if (!key.startsWith(ReadingPrefix)) continue;\n try {\n readings.set(key.slice(ReadingPrefix.length), JSON.parse(value));\n } catch {\n // not JSON: left out\n }\n }\n\n const source = readings.get(\"source\");\n return {\n status: \"ok\",\n cpu: asCapacity(readings.get(\"cpu\")),\n ram: asCapacity(readings.get(\"ram\")),\n gpu: asCapacity(readings.get(\"gpu\")),\n gpuMemory: asCapacity(readings.get(\"gpu-memory\")),\n jobs: asJobs(readings.get(\"jobs\")),\n source: typeof source === \"string\" ? source : undefined,\n };\n}\n\n/**\n * The part of a client the watch uses: a `PlClient` satisfies it, and a test can serve it without a\n * backend.\n */\nexport interface InstanceStatsClient {\n hasCapability(capability: BackendCapability): boolean;\n listSharedResourcesByType(resourceTypeName: string): Promise<SignedResourceId[]>;\n withReadTx<T>(\n name: string,\n body: (tx: {\n listKeyValuesString(rId: SignedResourceId): Promise<KeyValueString[]>;\n }) => Promise<T>,\n ): Promise<T>;\n}\n\n/**\n * Reads the instance statistics while the middle layer lives.\n *\n * Reports `unsupported` without `instanceStats:v1`, and while the context cannot be found. A\n * context whose writer is off yields a sample without readings.\n */\nexport class InstanceStatsWatch {\n private readonly value = new WatchableValue<InstanceStats | undefined>(undefined);\n private readonly abortController = new AbortController();\n private readonly loop: Promise<void>;\n\n /** The latest sample; undefined until the first read. */\n public readonly stats: Computable<InstanceStats | undefined>;\n\n constructor(\n private readonly pl: InstanceStatsClient,\n private readonly logger: MiLogger,\n ) {\n this.stats = ComputableFactory.make((ctx) => this.value.getValue(ctx));\n this.loop = this.run();\n this.loop.catch((err: unknown) =>\n this.logger.warn(new Error(\"instance stats loop failed\", { cause: err })),\n );\n }\n\n public async terminate(): Promise<void> {\n this.abortController.abort();\n try {\n await this.loop;\n } catch {\n // logged where it was raised\n }\n this.stats.resetState();\n }\n\n /** The last published sample, serialized, to skip publishing one that did not change. */\n private lastPublished?: string;\n\n private publish(stats: InstanceStats): void {\n const serialized = JSON.stringify(stats);\n if (serialized === this.lastPublished) return;\n this.lastPublished = serialized;\n this.value.setValue(stats, \"instance stats changed\");\n }\n\n private async run(): Promise<void> {\n // A backend that does not advertise the context has none to find: nothing is listed or read.\n if (!this.pl.hasCapability(InstanceStatsCapability)) {\n this.publish(UnsupportedInstanceStats);\n return;\n }\n\n let context: SignedResourceId | undefined;\n while (!this.abortController.signal.aborted) {\n try {\n context ??= (await this.pl.listSharedResourcesByType(InstanceStatsContextTypeName))[0];\n if (context === undefined) this.publish(UnsupportedInstanceStats);\n else {\n const ref = context;\n const kvs = await this.pl.withReadTx(\"instanceStats\", (tx) =>\n tx.listKeyValuesString(ref),\n );\n this.publish(parseInstanceStats(kvs));\n }\n } catch (err: unknown) {\n if (this.abortController.signal.aborted) return;\n // Retried on the next tick, with the context looked up again in case it was replaced.\n this.logger.warn(new Error(\"instance stats read failed\", { cause: err }));\n context = undefined;\n this.publish({ status: \"unreadable\" });\n }\n\n try {\n await setTimeout(PollIntervalMs, undefined, { signal: this.abortController.signal });\n } catch {\n return; // aborted\n }\n }\n }\n}\n"],"mappings":";;;;;AAyBA,MAAa,0BAA0B;;AAGvC,MAAa,+BAA+B;;AAG5C,MAAM,gBAAgB;;AAGtB,MAAM,iBAAiB;AAEvB,SAAS,WAAW,GAA+C;CACjE,IAAI,OAAO,MAAM,YAAY,MAAM,MAAM,OAAO,KAAA;CAChD,MAAM,EAAE,OAAO,YAAY;CAC3B,IAAI,OAAO,YAAY,UAAU,OAAO,KAAA;CACxC,OAAO,OAAO,UAAU,WAAW;EAAE;EAAO;CAAQ,IAAI,EAAE,QAAQ;AACpE;AAEA,SAAS,OAAO,GAAmC;CACjD,IAAI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AAK;EACb,QAAQ,CAER;EACA,KAAK,MAAM,WAAW;CACxB;;CAGA;CAEA,QAAgB,OAA4B;EAC1C,MAAM,aAAa,KAAK,UAAU,KAAK;EACvC,IAAI,eAAe,KAAK,eAAe;EACvC,KAAK,gBAAgB;EACrB,KAAK,MAAM,SAAS,OAAO,wBAAwB;CACrD;CAEA,MAAc,MAAqB;EAEjC,IAAI,CAAC,KAAK,GAAG,cAAA,kBAAqC,GAAG;GACnD,KAAK,QAAQC,sCAAAA,wBAAwB;GACrC;EACF;EAEA,IAAI;EACJ,OAAO,CAAC,KAAK,gBAAgB,OAAO,SAAS;GAC3C,IAAI;IACF,aAAa,MAAM,KAAK,GAAG,0BAA0B,4BAA4B,EAAA,CAAG;IACpF,IAAI,YAAY,KAAA,GAAW,KAAK,QAAQA,sCAAAA,wBAAwB;SAC3D;KACH,MAAM,MAAM;KACZ,MAAM,MAAM,MAAM,KAAK,GAAG,WAAW,kBAAkB,OACrD,GAAG,oBAAoB,GAAG,CAC5B;KACA,KAAK,QAAQ,mBAAmB,GAAG,CAAC;IACtC;GACF,SAAS,KAAc;IACrB,IAAI,KAAK,gBAAgB,OAAO,SAAS;IAEzC,KAAK,OAAO,KAAK,IAAI,MAAM,8BAA8B,EAAE,OAAO,IAAI,CAAC,CAAC;IACxE,UAAU,KAAA;IACV,KAAK,QAAQ,EAAE,QAAQ,aAAa,CAAC;GACvC;GAEA,IAAI;IACF,OAAA,GAAMC,qBAAAA,WAAAA,CAAW,gBAAgB,KAAA,GAAW,EAAE,QAAQ,KAAK,gBAAgB,OAAO,CAAC;GACrF,QAAQ;IACN;GACF;EACF;CACF;AACF"}
|
|
@@ -43,7 +43,7 @@ function parseInstanceStats(kvs) {
|
|
|
43
43
|
}
|
|
44
44
|
const source = readings.get("source");
|
|
45
45
|
return {
|
|
46
|
-
|
|
46
|
+
status: "ok",
|
|
47
47
|
cpu: asCapacity(readings.get("cpu")),
|
|
48
48
|
ram: asCapacity(readings.get("ram")),
|
|
49
49
|
gpu: asCapacity(readings.get("gpu")),
|
|
@@ -107,7 +107,7 @@ var InstanceStatsWatch = class {
|
|
|
107
107
|
if (this.abortController.signal.aborted) return;
|
|
108
108
|
this.logger.warn(new Error("instance stats read failed", { cause: err }));
|
|
109
109
|
context = void 0;
|
|
110
|
-
this.publish({
|
|
110
|
+
this.publish({ status: "unreadable" });
|
|
111
111
|
}
|
|
112
112
|
try {
|
|
113
113
|
await setTimeout(PollIntervalMs, void 0, { signal: this.abortController.signal });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instance_stats.js","names":["ComputableFactory"],"sources":["../../src/middle_layer/instance_stats.ts"],"sourcesContent":["/**\n * The load of the whole Platforma instance, read from the backend's instance statistics context.\n *\n * A backend that advertises `instanceStats:v1` keeps one such context; without it nothing is read.\n * Core creates one context per instance and grants every user read access; the executor runner\n * writes its readings as `reading/instance/<key>` every few seconds, all keys of a sample in one\n * transaction. The middle layer finds the context once, then reads its key-values on the same\n * cadence and publishes a sample only when it changed.\n *\n * Contract: pl `plapi/plapi/instance_stats_context.go` (MILAB-7312).\n */\n\nimport type {\n BackendCapability,\n KeyValueString,\n SignedResourceId,\n} from \"@milaboratories/pl-client\";\nimport type { Computable } from \"@milaboratories/computable\";\nimport { Computable as ComputableFactory, WatchableValue } from \"@milaboratories/computable\";\nimport type { MiLogger } from \"@milaboratories/ts-helpers\";\nimport type { InstanceStats, InstanceStatsCapacity } from \"@milaboratories/pl-model-middle-layer\";\nimport { UnsupportedInstanceStats } from \"@milaboratories/pl-model-middle-layer\";\nimport { setTimeout } from \"node:timers/promises\";\n\n/** The backend capability that says the instance statistics context exists. */\nexport const InstanceStatsCapability = \"instanceStats:v1\";\n\n/** The resource type name of the instance statistics context. */\nexport const InstanceStatsContextTypeName = \"InstanceStatsContext\";\n\n/** Prefix of the instance statistics readings. */\nconst ReadingPrefix = \"reading/instance/\";\n\n/** How often the readings are read: the writer's default interval. */\nconst PollIntervalMs = 10_000;\n\nfunction asCapacity(v: unknown): InstanceStatsCapacity | undefined {\n if (typeof v !== \"object\" || v === null) return undefined;\n const { total, current } = v as { total?: unknown; current?: unknown };\n if (typeof current !== \"number\") return undefined;\n return typeof total === \"number\" ? { total, current } : { current };\n}\n\nfunction asJobs(v: unknown): InstanceStats[\"jobs\"] {\n if (typeof v !== \"object\" || v === null) return undefined;\n const { running, queued } = v as { running?: unknown; queued?: unknown };\n if (typeof running !== \"number\" || typeof queued !== \"number\") return undefined;\n return { running, queued };\n}\n\n/**\n * The stats from the context's key-values. A reading that is missing or not the expected JSON is\n * left out rather than failing the sample: the readings are diagnostic, and a newer writer may add\n * or reshape keys.\n */\nexport function parseInstanceStats(kvs: readonly { key: string; value: string }[]): InstanceStats {\n const readings = new Map<string, unknown>();\n for (const { key, value } of kvs) {\n if (!key.startsWith(ReadingPrefix)) continue;\n try {\n readings.set(key.slice(ReadingPrefix.length), JSON.parse(value));\n } catch {\n // not JSON: left out\n }\n }\n\n const source = readings.get(\"source\");\n return {\n
|
|
1
|
+
{"version":3,"file":"instance_stats.js","names":["ComputableFactory"],"sources":["../../src/middle_layer/instance_stats.ts"],"sourcesContent":["/**\n * The load of the whole Platforma instance, read from the backend's instance statistics context.\n *\n * A backend that advertises `instanceStats:v1` keeps one such context; without it nothing is read.\n * Core creates one context per instance and grants every user read access; the executor runner\n * writes its readings as `reading/instance/<key>` every few seconds, all keys of a sample in one\n * transaction. The middle layer finds the context once, then reads its key-values on the same\n * cadence and publishes a sample only when it changed.\n *\n * Contract: pl `plapi/plapi/instance_stats_context.go` (MILAB-7312).\n */\n\nimport type {\n BackendCapability,\n KeyValueString,\n SignedResourceId,\n} from \"@milaboratories/pl-client\";\nimport type { Computable } from \"@milaboratories/computable\";\nimport { Computable as ComputableFactory, WatchableValue } from \"@milaboratories/computable\";\nimport type { MiLogger } from \"@milaboratories/ts-helpers\";\nimport type { InstanceStats, InstanceStatsCapacity } from \"@milaboratories/pl-model-middle-layer\";\nimport { UnsupportedInstanceStats } from \"@milaboratories/pl-model-middle-layer\";\nimport { setTimeout } from \"node:timers/promises\";\n\n/** The backend capability that says the instance statistics context exists. */\nexport const InstanceStatsCapability = \"instanceStats:v1\";\n\n/** The resource type name of the instance statistics context. */\nexport const InstanceStatsContextTypeName = \"InstanceStatsContext\";\n\n/** Prefix of the instance statistics readings. */\nconst ReadingPrefix = \"reading/instance/\";\n\n/** How often the readings are read: the writer's default interval. */\nconst PollIntervalMs = 10_000;\n\nfunction asCapacity(v: unknown): InstanceStatsCapacity | undefined {\n if (typeof v !== \"object\" || v === null) return undefined;\n const { total, current } = v as { total?: unknown; current?: unknown };\n if (typeof current !== \"number\") return undefined;\n return typeof total === \"number\" ? { total, current } : { current };\n}\n\nfunction asJobs(v: unknown): InstanceStats[\"jobs\"] {\n if (typeof v !== \"object\" || v === null) return undefined;\n const { running, queued } = v as { running?: unknown; queued?: unknown };\n if (typeof running !== \"number\" || typeof queued !== \"number\") return undefined;\n return { running, queued };\n}\n\n/**\n * The stats from the context's key-values. A reading that is missing or not the expected JSON is\n * left out rather than failing the sample: the readings are diagnostic, and a newer writer may add\n * or reshape keys.\n */\nexport function parseInstanceStats(kvs: readonly { key: string; value: string }[]): InstanceStats {\n const readings = new Map<string, unknown>();\n for (const { key, value } of kvs) {\n if (!key.startsWith(ReadingPrefix)) continue;\n try {\n readings.set(key.slice(ReadingPrefix.length), JSON.parse(value));\n } catch {\n // not JSON: left out\n }\n }\n\n const source = readings.get(\"source\");\n return {\n status: \"ok\",\n cpu: asCapacity(readings.get(\"cpu\")),\n ram: asCapacity(readings.get(\"ram\")),\n gpu: asCapacity(readings.get(\"gpu\")),\n gpuMemory: asCapacity(readings.get(\"gpu-memory\")),\n jobs: asJobs(readings.get(\"jobs\")),\n source: typeof source === \"string\" ? source : undefined,\n };\n}\n\n/**\n * The part of a client the watch uses: a `PlClient` satisfies it, and a test can serve it without a\n * backend.\n */\nexport interface InstanceStatsClient {\n hasCapability(capability: BackendCapability): boolean;\n listSharedResourcesByType(resourceTypeName: string): Promise<SignedResourceId[]>;\n withReadTx<T>(\n name: string,\n body: (tx: {\n listKeyValuesString(rId: SignedResourceId): Promise<KeyValueString[]>;\n }) => Promise<T>,\n ): Promise<T>;\n}\n\n/**\n * Reads the instance statistics while the middle layer lives.\n *\n * Reports `unsupported` without `instanceStats:v1`, and while the context cannot be found. A\n * context whose writer is off yields a sample without readings.\n */\nexport class InstanceStatsWatch {\n private readonly value = new WatchableValue<InstanceStats | undefined>(undefined);\n private readonly abortController = new AbortController();\n private readonly loop: Promise<void>;\n\n /** The latest sample; undefined until the first read. */\n public readonly stats: Computable<InstanceStats | undefined>;\n\n constructor(\n private readonly pl: InstanceStatsClient,\n private readonly logger: MiLogger,\n ) {\n this.stats = ComputableFactory.make((ctx) => this.value.getValue(ctx));\n this.loop = this.run();\n this.loop.catch((err: unknown) =>\n this.logger.warn(new Error(\"instance stats loop failed\", { cause: err })),\n );\n }\n\n public async terminate(): Promise<void> {\n this.abortController.abort();\n try {\n await this.loop;\n } catch {\n // logged where it was raised\n }\n this.stats.resetState();\n }\n\n /** The last published sample, serialized, to skip publishing one that did not change. */\n private lastPublished?: string;\n\n private publish(stats: InstanceStats): void {\n const serialized = JSON.stringify(stats);\n if (serialized === this.lastPublished) return;\n this.lastPublished = serialized;\n this.value.setValue(stats, \"instance stats changed\");\n }\n\n private async run(): Promise<void> {\n // A backend that does not advertise the context has none to find: nothing is listed or read.\n if (!this.pl.hasCapability(InstanceStatsCapability)) {\n this.publish(UnsupportedInstanceStats);\n return;\n }\n\n let context: SignedResourceId | undefined;\n while (!this.abortController.signal.aborted) {\n try {\n context ??= (await this.pl.listSharedResourcesByType(InstanceStatsContextTypeName))[0];\n if (context === undefined) this.publish(UnsupportedInstanceStats);\n else {\n const ref = context;\n const kvs = await this.pl.withReadTx(\"instanceStats\", (tx) =>\n tx.listKeyValuesString(ref),\n );\n this.publish(parseInstanceStats(kvs));\n }\n } catch (err: unknown) {\n if (this.abortController.signal.aborted) return;\n // Retried on the next tick, with the context looked up again in case it was replaced.\n this.logger.warn(new Error(\"instance stats read failed\", { cause: err }));\n context = undefined;\n this.publish({ status: \"unreadable\" });\n }\n\n try {\n await setTimeout(PollIntervalMs, undefined, { signal: this.abortController.signal });\n } catch {\n return; // aborted\n }\n }\n }\n}\n"],"mappings":";;;;;AAyBA,MAAa,0BAA0B;;AAGvC,MAAa,+BAA+B;;AAG5C,MAAM,gBAAgB;;AAGtB,MAAM,iBAAiB;AAEvB,SAAS,WAAW,GAA+C;CACjE,IAAI,OAAO,MAAM,YAAY,MAAM,MAAM,OAAO,KAAA;CAChD,MAAM,EAAE,OAAO,YAAY;CAC3B,IAAI,OAAO,YAAY,UAAU,OAAO,KAAA;CACxC,OAAO,OAAO,UAAU,WAAW;EAAE;EAAO;CAAQ,IAAI,EAAE,QAAQ;AACpE;AAEA,SAAS,OAAO,GAAmC;CACjD,IAAI,OAAO,MAAM,YAAY,MAAM,MAAM,OAAO,KAAA;CAChD,MAAM,EAAE,SAAS,WAAW;CAC5B,IAAI,OAAO,YAAY,YAAY,OAAO,WAAW,UAAU,OAAO,KAAA;CACtE,OAAO;EAAE;EAAS;CAAO;AAC3B;;;;;;AAOA,SAAgB,mBAAmB,KAA+D;CAChG,MAAM,2BAAW,IAAI,IAAqB;CAC1C,KAAK,MAAM,EAAE,KAAK,WAAW,KAAK;EAChC,IAAI,CAAC,IAAI,WAAW,aAAa,GAAG;EACpC,IAAI;GACF,SAAS,IAAI,IAAI,MAAM,EAAoB,GAAG,KAAK,MAAM,KAAK,CAAC;EACjE,QAAQ,CAER;CACF;CAEA,MAAM,SAAS,SAAS,IAAI,QAAQ;CACpC,OAAO;EACL,QAAQ;EACR,KAAK,WAAW,SAAS,IAAI,KAAK,CAAC;EACnC,KAAK,WAAW,SAAS,IAAI,KAAK,CAAC;EACnC,KAAK,WAAW,SAAS,IAAI,KAAK,CAAC;EACnC,WAAW,WAAW,SAAS,IAAI,YAAY,CAAC;EAChD,MAAM,OAAO,SAAS,IA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O,SAAS;IAEzC,KAAK,OAAO,KAAK,IAAI,MAAM,8BAA8B,EAAE,OAAO,IAAI,CAAC,CAAC;IACxE,UAAU,KAAA;IACV,KAAK,QAAQ,EAAE,QAAQ,aAAa,CAAC;GACvC;GAEA,IAAI;IACF,MAAM,WAAW,gBAAgB,KAAA,GAAW,EAAE,QAAQ,KAAK,gBAAgB,OAAO,CAAC;GACrF,QAAQ;IACN;GACF;EACF;CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@milaboratories/pl-middle-layer",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.0",
|
|
4
4
|
"description": "Pl Middle Layer",
|
|
5
5
|
"keywords": [],
|
|
6
6
|
"license": "UNLICENSED",
|
|
@@ -22,8 +22,8 @@
|
|
|
22
22
|
"@milaboratories/columns-collection-driver": "0.2.14",
|
|
23
23
|
"@milaboratories/computable": "2.9.10",
|
|
24
24
|
"@milaboratories/helpers": "1.14.7",
|
|
25
|
-
"@milaboratories/pf-driver": "1.9.
|
|
26
|
-
"@milaboratories/pf-spec-driver": "1.5.
|
|
25
|
+
"@milaboratories/pf-driver": "1.9.15",
|
|
26
|
+
"@milaboratories/pf-spec-driver": "1.5.15",
|
|
27
27
|
"@milaboratories/pframes-rs-node": "1.2.0",
|
|
28
28
|
"@milaboratories/pl-client": "3.22.0",
|
|
29
29
|
"@milaboratories/pl-crash-recorder": "0.3.10",
|
|
@@ -32,12 +32,12 @@
|
|
|
32
32
|
"@milaboratories/pl-http": "1.2.6",
|
|
33
33
|
"@milaboratories/pl-model-backend": "1.4.45",
|
|
34
34
|
"@milaboratories/pl-model-common": "1.55.1",
|
|
35
|
-
"@milaboratories/pl-model-middle-layer": "1.
|
|
35
|
+
"@milaboratories/pl-model-middle-layer": "1.37.0",
|
|
36
36
|
"@milaboratories/pl-tree": "1.17.2",
|
|
37
37
|
"@milaboratories/resolve-helper": "1.1.3",
|
|
38
38
|
"@milaboratories/ts-helpers": "1.9.1",
|
|
39
|
-
"@platforma-sdk/block-tools": "2.18.
|
|
40
|
-
"@platforma-sdk/model": "1.88.
|
|
39
|
+
"@platforma-sdk/block-tools": "2.18.1",
|
|
40
|
+
"@platforma-sdk/model": "1.88.13",
|
|
41
41
|
"@platforma-sdk/workflow-tengo": "6.22.1",
|
|
42
42
|
"canonicalize": "~2.1.0",
|
|
43
43
|
"denque": "^2.1.0",
|
|
@@ -18,7 +18,7 @@ describe("parseInstanceStats", () => {
|
|
|
18
18
|
kv("reading/instance/source", "scheduler"),
|
|
19
19
|
]),
|
|
20
20
|
).toEqual({
|
|
21
|
-
|
|
21
|
+
status: "ok",
|
|
22
22
|
cpu: { total: 24000, current: 18500 },
|
|
23
23
|
ram: { total: 64e9, current: 41e9 },
|
|
24
24
|
jobs: { running: 12, queued: 14 },
|
|
@@ -51,7 +51,7 @@ describe("parseInstanceStats", () => {
|
|
|
51
51
|
kv("reading/instance/jobs", { running: "many" }),
|
|
52
52
|
kv("reading/other/cpu", { current: 1 }),
|
|
53
53
|
]);
|
|
54
|
-
expect(stats).toEqual({
|
|
54
|
+
expect(stats).toEqual({ status: "ok" });
|
|
55
55
|
});
|
|
56
56
|
});
|
|
57
57
|
|
|
@@ -64,9 +64,7 @@ test("the watch reads a sample where the capability is advertised, and nothing e
|
|
|
64
64
|
await new Promise((r) => setTimeout(r, 100));
|
|
65
65
|
stats = await watch.stats.getValue();
|
|
66
66
|
}
|
|
67
|
-
expect(stats?.
|
|
68
|
-
pl.hasCapability(InstanceStatsCapability) ? "read" : "unsupported",
|
|
69
|
-
);
|
|
67
|
+
expect(stats?.status).toEqual(pl.hasCapability(InstanceStatsCapability) ? "ok" : "unsupported");
|
|
70
68
|
} finally {
|
|
71
69
|
await watch.terminate();
|
|
72
70
|
await pl.close();
|
|
@@ -113,13 +111,13 @@ async function firstSample(client: InstanceStatsClient) {
|
|
|
113
111
|
describe("InstanceStatsWatch", () => {
|
|
114
112
|
it("does nothing on a backend that does not advertise the capability", async () => {
|
|
115
113
|
const client = fakeClient({ capabilities: [] });
|
|
116
|
-
expect(await firstSample(client)).toEqual({
|
|
114
|
+
expect(await firstSample(client)).toEqual({ status: "unsupported" });
|
|
117
115
|
expect(client.listed).toBe(0);
|
|
118
116
|
});
|
|
119
117
|
|
|
120
118
|
it("reports unsupported when the capability is advertised but the context is missing", async () => {
|
|
121
119
|
const client = fakeClient({ capabilities: [InstanceStatsCapability] });
|
|
122
|
-
expect(await firstSample(client)).toEqual({
|
|
120
|
+
expect(await firstSample(client)).toEqual({ status: "unsupported" });
|
|
123
121
|
expect(client.listed).toBe(1);
|
|
124
122
|
});
|
|
125
123
|
|
|
@@ -127,9 +125,9 @@ describe("InstanceStatsWatch", () => {
|
|
|
127
125
|
const sample = [kv("reading/instance/jobs", { running: 1, queued: 2 })];
|
|
128
126
|
expect(
|
|
129
127
|
await firstSample(fakeClient({ capabilities: [InstanceStatsCapability], context: sample })),
|
|
130
|
-
).toEqual({
|
|
128
|
+
).toEqual({ status: "ok", jobs: { running: 1, queued: 2 } });
|
|
131
129
|
expect(
|
|
132
130
|
await firstSample(fakeClient({ capabilities: [InstanceStatsCapability], context: [] })),
|
|
133
|
-
).toEqual({
|
|
131
|
+
).toEqual({ status: "ok" });
|
|
134
132
|
});
|
|
135
133
|
});
|
|
@@ -66,7 +66,7 @@ export function parseInstanceStats(kvs: readonly { key: string; value: string }[
|
|
|
66
66
|
|
|
67
67
|
const source = readings.get("source");
|
|
68
68
|
return {
|
|
69
|
-
|
|
69
|
+
status: "ok",
|
|
70
70
|
cpu: asCapacity(readings.get("cpu")),
|
|
71
71
|
ram: asCapacity(readings.get("ram")),
|
|
72
72
|
gpu: asCapacity(readings.get("gpu")),
|
|
@@ -160,7 +160,7 @@ export class InstanceStatsWatch {
|
|
|
160
160
|
// Retried on the next tick, with the context looked up again in case it was replaced.
|
|
161
161
|
this.logger.warn(new Error("instance stats read failed", { cause: err }));
|
|
162
162
|
context = undefined;
|
|
163
|
-
this.publish({
|
|
163
|
+
this.publish({ status: "unreadable" });
|
|
164
164
|
}
|
|
165
165
|
|
|
166
166
|
try {
|