Route desktop telemetry control and stale power handling
- Add fd5 control channel for desktop telemetry demand - Stop gating background work on stale host power - Update telemetry sampling and receiver tests Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
1732212b43
commit
041f875ae5
28 files changed
+1786
-434
No files matched your search
@@ -275,6 +275,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
const config = yield* configuration.resolve;
|
||||
assert.equal(config.bootstrap.resourceMonitorPath, monitorPath);
|
||||
assert.equal(config.bootstrap.desktopTelemetryFd, 4);
|
||||
assert.equal(config.bootstrap.desktopTelemetryControlFd, 5);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
|
||||
@@ -168,6 +168,7 @@ const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolv
|
||||
tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
|
||||
tailscaleServePort: backendExposure.tailscaleServePort,
|
||||
desktopTelemetryFd: 4,
|
||||
desktopTelemetryControlFd: 5,
|
||||
...Option.match(input.resourceMonitorPath, {
|
||||
onNone: () => ({}),
|
||||
onSome: (resourceMonitorPath) => ({ resourceMonitorPath }),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
DesktopBackendBootstrap,
|
||||
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
|
||||
DesktopTelemetryControlMessage,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
@@ -33,6 +34,9 @@ const decodeDesktopBackendBootstrap = Schema.decodeEffect(
|
||||
Schema.fromJsonString(DesktopBackendBootstrap),
|
||||
);
|
||||
const isBackendProcessError = Schema.is(DesktopBackendManager.BackendProcessError);
|
||||
const encodeDesktopTelemetryControl = Schema.encodeSync(
|
||||
Schema.fromJsonString(DesktopTelemetryControlMessage),
|
||||
);
|
||||
|
||||
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
executablePath: "/electron",
|
||||
@@ -48,6 +52,8 @@ const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
desktopBootstrapToken: "token",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
desktopTelemetryFd: 4,
|
||||
desktopTelemetryControlFd: 5,
|
||||
},
|
||||
httpBaseUrl: new URL("http://127.0.0.1:3773"),
|
||||
captureOutput: true,
|
||||
@@ -64,6 +70,7 @@ function makeProcess(options?: {
|
||||
readonly stderr?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
|
||||
readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
|
||||
readonly getOutputFd?: ChildProcessSpawner.ChildProcessHandle["getOutputFd"];
|
||||
}): ChildProcessSpawner.ChildProcessHandle {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(123),
|
||||
@@ -75,7 +82,7 @@ function makeProcess(options?: {
|
||||
kill: options?.kill ?? (() => Effect.void),
|
||||
stdin: Sink.drain,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
getOutputFd: options?.getOutputFd ?? (() => Stream.empty),
|
||||
unref: Effect.succeed(Effect.void),
|
||||
});
|
||||
}
|
||||
@@ -112,6 +119,9 @@ function makeManagerLayer(input: {
|
||||
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLog["Service"]>;
|
||||
readonly desktopState?: DesktopState.DesktopState["Service"];
|
||||
readonly desktopWindow?: Partial<DesktopWindow.DesktopWindow["Service"]>;
|
||||
readonly desktopTelemetryPublisher?: Partial<
|
||||
DesktopTelemetryPublisher.DesktopTelemetryPublisher["Service"]
|
||||
>;
|
||||
readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
|
||||
}) {
|
||||
return DesktopBackendManager.layer.pipe(
|
||||
@@ -129,6 +139,8 @@ function makeManagerLayer(input: {
|
||||
latest: Effect.succeed(Option.none()),
|
||||
changes: Stream.empty,
|
||||
encoded: Stream.empty,
|
||||
handleControl: () => Effect.void,
|
||||
...input.desktopTelemetryPublisher,
|
||||
}),
|
||||
input.desktopState
|
||||
? Layer.succeed(DesktopState.DesktopState, input.desktopState)
|
||||
@@ -235,6 +247,8 @@ describe("DesktopBackendManager", () => {
|
||||
assert.equal(spawnedCommand.options.stderr, "pipe");
|
||||
assert.equal(spawnedCommand.options.killSignal, "SIGTERM");
|
||||
assert.isDefined(spawnedCommand.options.forceKillAfter);
|
||||
assert.equal(spawnedCommand.options.additionalFds?.fd4?.type, "input");
|
||||
assert.equal(spawnedCommand.options.additionalFds?.fd5?.type, "output");
|
||||
assert.equal(
|
||||
Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),
|
||||
2_000,
|
||||
@@ -482,6 +496,42 @@ describe("DesktopBackendManager", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes desktop telemetry control messages from fd5 to the publisher", () =>
|
||||
Effect.gen(function* () {
|
||||
const handled = yield* Deferred.make<boolean>();
|
||||
const controlMessage = encodeDesktopTelemetryControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: true,
|
||||
});
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
getOutputFd: (fd) =>
|
||||
fd === 5 ? Stream.encodeText(Stream.make(`${controlMessage}\n`)) : Stream.empty,
|
||||
exitCode: Deferred.await(handled).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const managerLayer = makeManagerLayer({
|
||||
spawnerLayer,
|
||||
desktopTelemetryPublisher: {
|
||||
handleControl: (message) =>
|
||||
Deferred.succeed(handled, message.enabled).pipe(Effect.asVoid),
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const manager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
yield* manager.start;
|
||||
assert.isTrue(yield* Deferred.await(handled));
|
||||
}).pipe(Effect.provide(managerLayer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("retries HTTP readiness before reporting the backend ready", () =>
|
||||
Effect.gen(function* () {
|
||||
const requestUrls: Array<string> = [];
|
||||
|
||||
@@ -14,6 +14,7 @@ import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Ndjson from "effect/unstable/encoding/Ndjson";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
@@ -21,6 +22,8 @@ import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawne
|
||||
import {
|
||||
DesktopBackendBootstrap,
|
||||
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
|
||||
DesktopTelemetryControlMessage,
|
||||
type DesktopTelemetryControlMessage as DesktopTelemetryControlMessageValue,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
@@ -174,6 +177,9 @@ export type BackendProcessError = typeof BackendProcessError.Type;
|
||||
|
||||
interface RunBackendProcessOptions extends DesktopBackendStartConfig {
|
||||
readonly desktopTelemetryStream: Stream.Stream<Uint8Array>;
|
||||
readonly onDesktopTelemetryControl?: (
|
||||
message: DesktopTelemetryControlMessageValue,
|
||||
) => Effect.Effect<void>;
|
||||
readonly readinessTimeout?: Duration.Duration;
|
||||
readonly onStarted?: (pid: number) => Effect.Effect<void>;
|
||||
readonly onReady?: () => Effect.Effect<void>;
|
||||
@@ -329,6 +335,7 @@ function drainBackendOutput(
|
||||
}
|
||||
|
||||
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
|
||||
const decodeDesktopTelemetryControl = Schema.decodeUnknownEffect(DesktopTelemetryControlMessage);
|
||||
|
||||
export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
options: RunBackendProcessOptions,
|
||||
@@ -347,6 +354,23 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
),
|
||||
);
|
||||
const onOutput = options.onOutput ?? (() => Effect.void);
|
||||
const additionalFds: Record<`fd${number}`, ChildProcess.AdditionalFdConfig> = {
|
||||
fd3: {
|
||||
type: "input",
|
||||
stream: Stream.encodeText(Stream.make(`${bootstrapJson}\n`)),
|
||||
},
|
||||
};
|
||||
if (options.bootstrap.desktopTelemetryFd !== undefined) {
|
||||
additionalFds[`fd${options.bootstrap.desktopTelemetryFd}`] = {
|
||||
type: "input",
|
||||
stream: options.desktopTelemetryStream,
|
||||
};
|
||||
}
|
||||
if (options.bootstrap.desktopTelemetryControlFd !== undefined) {
|
||||
additionalFds[`fd${options.bootstrap.desktopTelemetryControlFd}`] = {
|
||||
type: "output",
|
||||
};
|
||||
}
|
||||
const command = ChildProcess.make(
|
||||
options.executablePath,
|
||||
[options.entryPath, "--bootstrap-fd", "3"],
|
||||
@@ -361,16 +385,7 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
stderr: options.captureOutput ? "pipe" : "inherit",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
|
||||
additionalFds: {
|
||||
fd3: {
|
||||
type: "input",
|
||||
stream: Stream.encodeText(Stream.make(`${bootstrapJson}\n`)),
|
||||
},
|
||||
fd4: {
|
||||
type: "input",
|
||||
stream: options.desktopTelemetryStream,
|
||||
},
|
||||
},
|
||||
additionalFds,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -388,6 +403,32 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
);
|
||||
|
||||
yield* options.onStarted?.(handle.pid) ?? Effect.void;
|
||||
if (
|
||||
options.bootstrap.desktopTelemetryControlFd !== undefined &&
|
||||
options.onDesktopTelemetryControl !== undefined
|
||||
) {
|
||||
const controlFd = options.bootstrap.desktopTelemetryControlFd;
|
||||
const handleControl = options.onDesktopTelemetryControl;
|
||||
yield* handle.getOutputFd(controlFd).pipe(
|
||||
Stream.pipeThroughChannel(Ndjson.decode({ ignoreEmptyLines: true })),
|
||||
Stream.mapEffect((message) => decodeDesktopTelemetryControl(message)),
|
||||
Stream.runForEach(handleControl),
|
||||
Effect.catchCause((cause) =>
|
||||
logBackendManagerWarning("desktop telemetry control stream stopped", {
|
||||
fd: controlFd,
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
Effect.ensuring(
|
||||
handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: false,
|
||||
}),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
}
|
||||
if (options.captureOutput) {
|
||||
const outputContext = {
|
||||
executablePath: options.executablePath,
|
||||
@@ -606,6 +647,7 @@ export const make = Effect.gen(function* () {
|
||||
const program = runBackendProcess({
|
||||
...config.value,
|
||||
desktopTelemetryStream: desktopTelemetryPublisher.encoded,
|
||||
onDesktopTelemetryControl: desktopTelemetryPublisher.handleControl,
|
||||
onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) {
|
||||
yield* updateActiveRun(runId, (run) => ({
|
||||
...run,
|
||||
|
||||
@@ -14,7 +14,10 @@ import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
|
||||
import * as DesktopTelemetryPublisher from "./DesktopTelemetryPublisher.ts";
|
||||
|
||||
function makeElectronAppLayer(metrics: ReadonlyArray<Electron.ProcessMetric>) {
|
||||
function makeElectronAppLayer(
|
||||
metrics: ReadonlyArray<Electron.ProcessMetric>,
|
||||
onMetricsRead: () => void = () => undefined,
|
||||
) {
|
||||
return Layer.succeed(ElectronApp.ElectronApp, {
|
||||
metadata: Effect.die("unexpected metadata read"),
|
||||
name: Effect.succeed("T3 Code"),
|
||||
@@ -27,7 +30,10 @@ function makeElectronAppLayer(metrics: ReadonlyArray<Electron.ProcessMetric>) {
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed(metrics),
|
||||
getAppMetrics: Effect.sync(() => {
|
||||
onMetricsRead();
|
||||
return metrics;
|
||||
}),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
@@ -41,6 +47,7 @@ describe("DesktopTelemetryPublisher", () => {
|
||||
it.effect("publishes Electron metrics and event-driven power state over NDJSON", () =>
|
||||
Effect.gen(function* () {
|
||||
const onBattery = yield* Ref.make(false);
|
||||
let metricsReadCount = 0;
|
||||
const simpleListeners = new Map<string, () => void>();
|
||||
let thermalListener: ((state: ElectronPowerMonitor.ElectronThermalState) => void) | null =
|
||||
null;
|
||||
@@ -84,7 +91,14 @@ describe("DesktopTelemetryPublisher", () => {
|
||||
}),
|
||||
);
|
||||
const layer = DesktopTelemetryPublisher.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(makeElectronAppLayer(metrics), powerLayer)),
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
makeElectronAppLayer(metrics, () => {
|
||||
metricsReadCount += 1;
|
||||
}),
|
||||
powerLayer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
@@ -96,26 +110,86 @@ describe("DesktopTelemetryPublisher", () => {
|
||||
assert.equal(messages[0]?.type, "desktopTelemetryHello");
|
||||
assert.equal(messages[0]?.electronPid, process.pid);
|
||||
assert.equal(messages[1]?.type, "desktopTelemetry");
|
||||
assert.equal(messages[1]?.electronProcesses[0]?.pid, 4_242);
|
||||
assert.equal(messages[1]?.electronProcesses[0]?.cpuPercent, 12.5);
|
||||
assert.equal(messages[1]?.electronProcesses[0]?.workingSetBytes, 2_048 * 1_024);
|
||||
assert.deepEqual(messages[1]?.electronProcesses, []);
|
||||
assert.equal(messages[1]?.electronPid, process.pid);
|
||||
assert.equal(metricsReadCount, 0);
|
||||
|
||||
const nextSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
yield* Ref.set(onBattery, true);
|
||||
simpleListeners.get("lock-screen")?.();
|
||||
simpleListeners.get("suspend")?.();
|
||||
thermalListener?.("serious");
|
||||
speedLimitListener?.(65);
|
||||
yield* Effect.yieldNow;
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
yield* publisher.handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: true,
|
||||
});
|
||||
const demandedSnapshot = Option.getOrThrow(yield* Fiber.join(nextSnapshotFiber));
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.pid, 4_242);
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.cpuPercent, 12.5);
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.workingSetBytes, 2_048 * 1_024);
|
||||
assert.equal(metricsReadCount, 1);
|
||||
|
||||
const nextSnapshot = Option.getOrThrow(yield* Fiber.join(nextSnapshotFiber));
|
||||
assert.equal(nextSnapshot.power.locked, "true");
|
||||
assert.equal(nextSnapshot.power.suspended, true);
|
||||
assert.equal(nextSnapshot.power.onBattery, "true");
|
||||
assert.equal(nextSnapshot.power.thermalState, "serious");
|
||||
assert.equal(Option.getOrNull(nextSnapshot.speedLimitPercent), 65);
|
||||
const batterySnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
yield* Ref.set(onBattery, true);
|
||||
simpleListeners.get("on-battery")?.();
|
||||
const batterySnapshot = Option.getOrThrow(yield* Fiber.join(batterySnapshotFiber));
|
||||
assert.equal(batterySnapshot.power.onBattery, "true");
|
||||
|
||||
const metricsAfterBatteryEvent = metricsReadCount;
|
||||
yield* TestClock.adjust(Duration.millis(4_999));
|
||||
assert.equal(metricsReadCount, metricsAfterBatteryEvent);
|
||||
yield* TestClock.adjust(Duration.millis(1));
|
||||
assert.equal(metricsReadCount, metricsAfterBatteryEvent + 1);
|
||||
|
||||
const constrainedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
thermalListener?.("serious");
|
||||
const constrainedSnapshot = Option.getOrThrow(yield* Fiber.join(constrainedSnapshotFiber));
|
||||
assert.equal(constrainedSnapshot.power.thermalState, "serious");
|
||||
|
||||
const metricsAfterThermalEvent = metricsReadCount;
|
||||
yield* TestClock.adjust(Duration.millis(14_999));
|
||||
assert.equal(metricsReadCount, metricsAfterThermalEvent);
|
||||
yield* TestClock.adjust(Duration.millis(1));
|
||||
assert.equal(metricsReadCount, metricsAfterThermalEvent + 1);
|
||||
|
||||
const speedLimitSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
speedLimitListener?.(65);
|
||||
const speedLimitSnapshot = Option.getOrThrow(yield* Fiber.join(speedLimitSnapshotFiber));
|
||||
assert.equal(Option.getOrNull(speedLimitSnapshot.speedLimitPercent), 65);
|
||||
|
||||
const stoppedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
yield* publisher.handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: false,
|
||||
});
|
||||
const stoppedSnapshot = Option.getOrThrow(yield* Fiber.join(stoppedSnapshotFiber));
|
||||
assert.deepEqual(stoppedSnapshot.electronProcesses, []);
|
||||
const backgroundSequence = stoppedSnapshot.sequence;
|
||||
const metricsAfterStopping = metricsReadCount;
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(29));
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
|
||||
backgroundSequence,
|
||||
);
|
||||
assert.equal(metricsReadCount, metricsAfterStopping);
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
|
||||
backgroundSequence + 1,
|
||||
);
|
||||
assert.equal(metricsReadCount, metricsAfterStopping);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
DesktopHostTelemetryMessage,
|
||||
type DesktopHostTelemetrySnapshot,
|
||||
type DesktopTelemetryControlMessage,
|
||||
type HostPowerSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
@@ -18,7 +19,10 @@ import * as Stream from "effect/Stream";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
|
||||
|
||||
const SAMPLE_INTERVAL = Duration.seconds(1);
|
||||
const LIVE_SAMPLE_INTERVAL = Duration.seconds(1);
|
||||
const BATTERY_SAMPLE_INTERVAL = Duration.seconds(5);
|
||||
const CONSTRAINED_SAMPLE_INTERVAL = Duration.seconds(15);
|
||||
const BACKGROUND_HEARTBEAT_INTERVAL = Duration.seconds(30);
|
||||
const IDLE_THRESHOLD_SECONDS = 60;
|
||||
const encodeMessage = Schema.encodeSync(Schema.fromJsonString(DesktopHostTelemetryMessage));
|
||||
const textEncoder = new TextEncoder();
|
||||
@@ -42,6 +46,7 @@ export interface DesktopTelemetryPublisherShape {
|
||||
readonly latest: Effect.Effect<Option.Option<DesktopHostTelemetrySnapshot>>;
|
||||
readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;
|
||||
readonly encoded: Stream.Stream<Uint8Array>;
|
||||
readonly handleControl: (message: DesktopTelemetryControlMessage) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopTelemetryPublisher extends Context.Service<
|
||||
@@ -80,6 +85,20 @@ function updatePowerState(state: PowerState, event: PowerEvent): PowerState {
|
||||
}
|
||||
}
|
||||
|
||||
function sampleInterval(power: PowerState, diagnosticsDemand: boolean): Duration.Duration {
|
||||
if (!diagnosticsDemand) return BACKGROUND_HEARTBEAT_INTERVAL;
|
||||
if (
|
||||
power.suspended ||
|
||||
power.locked === "true" ||
|
||||
power.thermalState === "serious" ||
|
||||
power.thermalState === "critical"
|
||||
) {
|
||||
return CONSTRAINED_SAMPLE_INTERVAL;
|
||||
}
|
||||
if (power.onBattery === "true") return BATTERY_SAMPLE_INTERVAL;
|
||||
return LIVE_SAMPLE_INTERVAL;
|
||||
}
|
||||
|
||||
export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const powerMonitor = yield* ElectronPowerMonitor.ElectronPowerMonitor;
|
||||
@@ -94,6 +113,8 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
};
|
||||
const powerState = yield* Ref.make(initialPowerState);
|
||||
const powerEvents = yield* Queue.unbounded<PowerEvent>();
|
||||
const sampleTriggers = yield* Queue.sliding<void>(1);
|
||||
const diagnosticsDemand = yield* Ref.make(false);
|
||||
const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
|
||||
const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);
|
||||
const sequence = yield* Ref.make(0);
|
||||
@@ -117,19 +138,21 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
yield* Effect.forever(
|
||||
Queue.take(powerEvents).pipe(
|
||||
Effect.flatMap((event) => Ref.update(powerState, (state) => updatePowerState(state, event))),
|
||||
Effect.andThen(Queue.offer(sampleTriggers, undefined)),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
const sampleOnce = Effect.gen(function* () {
|
||||
const sampledAt = yield* DateTime.now;
|
||||
const sampledAtUnixMs = DateTime.toEpochMillis(sampledAt);
|
||||
const demand = yield* Ref.get(diagnosticsDemand);
|
||||
const [currentPower, idleSeconds, systemIdleState, onBattery, metrics] = yield* Effect.all(
|
||||
[
|
||||
Ref.get(powerState),
|
||||
powerMonitor.getSystemIdleTime,
|
||||
powerMonitor.getSystemIdleState(IDLE_THRESHOLD_SECONDS),
|
||||
powerMonitor.isOnBatteryPower,
|
||||
electronApp.getAppMetrics,
|
||||
demand ? electronApp.getAppMetrics : Effect.succeed([]),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
@@ -140,6 +163,7 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
type: "desktopTelemetry",
|
||||
sequence: nextSequence,
|
||||
sampledAtUnixMs,
|
||||
electronPid: process.pid,
|
||||
power: {
|
||||
source: "electron-main",
|
||||
idle: idleState(systemIdleState),
|
||||
@@ -179,9 +203,33 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.forever(sampleOnce.pipe(Effect.andThen(Effect.sleep(SAMPLE_INTERVAL)))).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* Effect.gen(function* () {
|
||||
yield* sampleOnce;
|
||||
while (true) {
|
||||
const [currentPower, demand] = yield* Effect.all([
|
||||
Ref.get(powerState),
|
||||
Ref.get(diagnosticsDemand),
|
||||
]);
|
||||
yield* Effect.raceFirst(
|
||||
Queue.take(sampleTriggers),
|
||||
Effect.sleep(sampleInterval(currentPower, demand)),
|
||||
);
|
||||
yield* sampleOnce;
|
||||
}
|
||||
}).pipe(Effect.forkScoped);
|
||||
|
||||
const handleControl: DesktopTelemetryPublisherShape["handleControl"] = (message) => {
|
||||
switch (message.type) {
|
||||
case "setDiagnosticsDemand":
|
||||
return Ref.getAndSet(diagnosticsDemand, message.enabled).pipe(
|
||||
Effect.flatMap((previous) =>
|
||||
previous === message.enabled
|
||||
? Effect.void
|
||||
: Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const snapshots = Stream.concat(
|
||||
Stream.unwrap(
|
||||
@@ -209,6 +257,7 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
latest: Ref.get(latest),
|
||||
changes: Stream.fromPubSub(changes),
|
||||
encoded,
|
||||
handleControl,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -65,7 +65,6 @@ function makeLayer(
|
||||
Effect.sync(() => {
|
||||
snapshot = next;
|
||||
}).pipe(Effect.andThen(PubSub.publish(changes, next)), Effect.asVoid),
|
||||
setDemandActive: () => Effect.void,
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
});
|
||||
}),
|
||||
@@ -188,4 +187,31 @@ describe("BackgroundPolicy", () => {
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not gate work on stale host power values", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport(),
|
||||
);
|
||||
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer(
|
||||
{
|
||||
...nominalHostPower,
|
||||
locked: "true",
|
||||
onBattery: "true",
|
||||
lowPowerMode: "true",
|
||||
thermalState: "critical",
|
||||
stale: true,
|
||||
},
|
||||
{ backgroundActivityProfile: "battery-saver" },
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -81,6 +81,7 @@ function isHostConstrained(
|
||||
hostPower: HostPowerSnapshot,
|
||||
settings: ResolvedBackgroundActivitySettings,
|
||||
): boolean {
|
||||
if (hostPower.stale) return false;
|
||||
if (
|
||||
(settings.pauseWhenHostLocked && hostPower.locked === "true") ||
|
||||
hasThermalPressure(hostPower)
|
||||
@@ -153,7 +154,7 @@ export const make = Effect.fn("background.policy.make")(function* () {
|
||||
|
||||
const backgroundActivitySettings = serverSettings.getSettings.pipe(
|
||||
Effect.map(resolveServerBackgroundActivitySettings),
|
||||
Effect.catch(() => Effect.succeed(getBackgroundActivityPresetSettings("balanced"))),
|
||||
Effect.orElseSucceed(() => getBackgroundActivityPresetSettings("balanced")),
|
||||
);
|
||||
|
||||
const snapshot = Effect.gen(function* () {
|
||||
@@ -166,10 +167,7 @@ export const make = Effect.fn("background.policy.make")(function* () {
|
||||
return computeSnapshot({ hostPower, leases, now, settings, updatedAt: now });
|
||||
});
|
||||
|
||||
const publishSnapshot = snapshot.pipe(
|
||||
Effect.tap((next) => hostPowerMonitor.setDemandActive(next.activeForegroundLeaseCount > 0)),
|
||||
Effect.flatMap((next) => PubSub.publish(changes, next)),
|
||||
);
|
||||
const publishSnapshot = snapshot.pipe(Effect.flatMap((next) => PubSub.publish(changes, next)));
|
||||
|
||||
const reportClientActivity: BackgroundPolicyShape["reportClientActivity"] = (
|
||||
sessionId,
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import type { DesktopHostTelemetrySnapshot } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as DesktopTelemetryReceiver from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
|
||||
import * as HostPowerMonitor from "./HostPowerMonitor.ts";
|
||||
|
||||
describe("HostPowerMonitor", () => {
|
||||
@@ -41,4 +46,47 @@ describe("HostPowerMonitor", () => {
|
||||
expect(Option.getOrThrow(yield* Fiber.join(nextChange)).locked).toBe("true");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("consumes desktop power directly without retaining diagnostics telemetry", () =>
|
||||
Effect.gen(function* () {
|
||||
const sampledAt = DateTime.makeUnsafe("2026-06-17T12:00:00.000Z");
|
||||
const desktopChanges = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(1);
|
||||
const diagnosticsDemandWrites = yield* Ref.make(0);
|
||||
const receiverLayer = DesktopTelemetryReceiver.layerTest({
|
||||
changes: Stream.fromPubSub(desktopChanges),
|
||||
setDiagnosticsDemand: () => Ref.update(diagnosticsDemandWrites, (count) => count + 1),
|
||||
});
|
||||
const layer = HostPowerMonitor.layer.pipe(Layer.provide(receiverLayer));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const monitor = yield* HostPowerMonitor.HostPowerMonitor;
|
||||
const nextPower = yield* Stream.runHead(monitor.streamChanges).pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
yield* PubSub.publish(desktopChanges, {
|
||||
version: 1,
|
||||
type: "desktopTelemetry",
|
||||
sequence: 1,
|
||||
sampledAtUnixMs: DateTime.toEpochMillis(sampledAt),
|
||||
electronPid: 100,
|
||||
power: {
|
||||
source: "electron-main",
|
||||
idle: "false",
|
||||
idleSeconds: 0,
|
||||
locked: "false",
|
||||
suspended: false,
|
||||
onBattery: "true",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "nominal",
|
||||
stale: false,
|
||||
updatedAt: sampledAt,
|
||||
},
|
||||
speedLimitPercent: Option.none(),
|
||||
electronProcesses: [],
|
||||
});
|
||||
|
||||
expect(Option.getOrThrow(yield* Fiber.join(nextPower)).onBattery).toBe("true");
|
||||
expect(yield* Ref.get(diagnosticsDemandWrites)).toBe(0);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -3,16 +3,16 @@ import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
|
||||
import * as DesktopTelemetryReceiver from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
|
||||
|
||||
export interface HostPowerMonitorShape {
|
||||
readonly snapshot: Effect.Effect<HostPowerSnapshot>;
|
||||
readonly report: (snapshot: HostPowerSnapshot) => Effect.Effect<void>;
|
||||
readonly setDemandActive: (active: boolean) => Effect.Effect<void>;
|
||||
readonly streamChanges: Stream.Stream<HostPowerSnapshot>;
|
||||
}
|
||||
|
||||
@@ -65,7 +65,6 @@ export const make = Effect.fn("background.hostPower.make")(function* (
|
||||
return HostPowerMonitor.of({
|
||||
snapshot: Ref.get(latestRef),
|
||||
report,
|
||||
setDemandActive: () => Effect.void,
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
});
|
||||
});
|
||||
@@ -73,11 +72,18 @@ export const make = Effect.fn("background.hostPower.make")(function* (
|
||||
export const layer = Layer.effect(
|
||||
HostPowerMonitor,
|
||||
Effect.gen(function* () {
|
||||
const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
|
||||
const initial = yield* telemetry.latest;
|
||||
const monitor = yield* make(initial.power.source);
|
||||
yield* monitor.report(initial.power);
|
||||
yield* telemetry.changes.pipe(
|
||||
const desktopTelemetry = yield* DesktopTelemetryReceiver.DesktopTelemetryReceiver;
|
||||
const initial = yield* desktopTelemetry.latest;
|
||||
const monitor = yield* make(
|
||||
Option.match(initial, {
|
||||
onNone: () => "unknown" as const,
|
||||
onSome: (snapshot) => snapshot.power.source,
|
||||
}),
|
||||
);
|
||||
if (Option.isSome(initial)) {
|
||||
yield* monitor.report(initial.value.power);
|
||||
}
|
||||
yield* desktopTelemetry.changes.pipe(
|
||||
Stream.map((snapshot) => snapshot.power),
|
||||
Stream.runForEach(monitor.report),
|
||||
Effect.forkScoped,
|
||||
|
||||
@@ -268,6 +268,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
t3Home: baseDir,
|
||||
noBrowser: true,
|
||||
desktopBootstrapToken: "desktop-token",
|
||||
desktopTelemetryFd: 4,
|
||||
desktopTelemetryControlFd: 5,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
||||
@@ -323,12 +325,17 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: "desktop-token",
|
||||
desktopTelemetryFd: 4,
|
||||
desktopTelemetryControlFd: 5,
|
||||
resourceMonitorPath: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
assert.equal(join(baseDir, "userdata"), resolved.stateDir);
|
||||
assert.equal(resolved.desktopTelemetryFd, 4);
|
||||
assert.equal(resolved.desktopTelemetryControlFd, 5);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -291,6 +291,7 @@ export const resolveServerConfig = (
|
||||
);
|
||||
const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
|
||||
const desktopTelemetryFd = bootstrap?.desktopTelemetryFd;
|
||||
const desktopTelemetryControlFd = bootstrap?.desktopTelemetryControlFd;
|
||||
const resourceMonitorPath = bootstrap?.resourceMonitorPath;
|
||||
const autoBootstrapProjectFromCwd = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
@@ -365,6 +366,7 @@ export const resolveServerConfig = (
|
||||
startupPresentation,
|
||||
desktopBootstrapToken,
|
||||
desktopTelemetryFd,
|
||||
desktopTelemetryControlFd,
|
||||
resourceMonitorPath,
|
||||
autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents,
|
||||
|
||||
@@ -18,7 +18,7 @@ function makeNativeSnapshot(
|
||||
processes: ResourceMonitorSnapshotEvent["processes"],
|
||||
): ResourceMonitorSnapshotEvent {
|
||||
return {
|
||||
version: 1,
|
||||
version: 2,
|
||||
type: "snapshot",
|
||||
sequence: 1,
|
||||
sampledAtUnixMs: DateTime.toEpochMillis(DateTime.makeUnsafe("2026-05-05T10:00:00.000Z")),
|
||||
@@ -42,6 +42,7 @@ function makeTelemetryLayer(
|
||||
lastSampleAt: Option.some(DateTime.makeUnsafe(snapshot.sampledAtUnixMs)),
|
||||
lastError: Option.none(),
|
||||
restartCount: 0,
|
||||
sampleIntervalMs: 1_000,
|
||||
}),
|
||||
});
|
||||
const desktopLayer = desktopSnapshot
|
||||
@@ -168,6 +169,7 @@ describe("ProcessDiagnostics", () => {
|
||||
type: "desktopTelemetry",
|
||||
sequence: 1,
|
||||
sampledAtUnixMs,
|
||||
electronPid: 4_242,
|
||||
power: {
|
||||
source: "electron-main",
|
||||
idle: "false",
|
||||
|
||||
@@ -6,21 +6,27 @@ import {
|
||||
DesktopHostTelemetryMessage,
|
||||
type DesktopHostTelemetryMessage as DesktopHostTelemetryMessageValue,
|
||||
type DesktopHostTelemetrySnapshot,
|
||||
DesktopTelemetryControlMessage,
|
||||
type ResourceTelemetrySourceStatus,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Ndjson from "effect/unstable/encoding/Ndjson";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
|
||||
const STALE_AFTER_MS = 90_000;
|
||||
const STALE_CHECK_INTERVAL = Duration.seconds(30);
|
||||
|
||||
export class DesktopTelemetryDescriptorUnavailable extends Schema.TaggedErrorClass<DesktopTelemetryDescriptorUnavailable>()(
|
||||
"DesktopTelemetryDescriptorUnavailable",
|
||||
{
|
||||
@@ -78,6 +84,18 @@ export class DesktopTelemetryStreamClosed extends Schema.TaggedErrorClass<Deskto
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopTelemetryStale extends Schema.TaggedErrorClass<DesktopTelemetryStale>()(
|
||||
"DesktopTelemetryStale",
|
||||
{
|
||||
fd: Schema.Number,
|
||||
staleAfterMs: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop telemetry on fd ${this.fd} has not updated for ${this.staleAfterMs}ms.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type DesktopTelemetryReceiverError =
|
||||
| DesktopTelemetryDescriptorUnavailable
|
||||
| DesktopTelemetryProtocolMismatch
|
||||
@@ -85,6 +103,19 @@ export type DesktopTelemetryReceiverError =
|
||||
| DesktopTelemetryStreamFailed
|
||||
| DesktopTelemetryStreamClosed;
|
||||
|
||||
export class DesktopTelemetryControlFailed extends Schema.TaggedErrorClass<DesktopTelemetryControlFailed>()(
|
||||
"DesktopTelemetryControlFailed",
|
||||
{
|
||||
fd: Schema.Number,
|
||||
operation: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop telemetry control '${this.operation}' failed on fd ${this.fd}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface DesktopTelemetryReceiverHealth {
|
||||
readonly status: ResourceTelemetrySourceStatus;
|
||||
readonly lastSampleAt: Option.Option<DateTime.Utc>;
|
||||
@@ -96,6 +127,9 @@ export interface DesktopTelemetryReceiverShape {
|
||||
readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;
|
||||
readonly health: Effect.Effect<DesktopTelemetryReceiverHealth>;
|
||||
readonly healthChanges: Stream.Stream<DesktopTelemetryReceiverHealth>;
|
||||
readonly setDiagnosticsDemand: (
|
||||
enabled: boolean,
|
||||
) => Effect.Effect<void, DesktopTelemetryControlFailed>;
|
||||
}
|
||||
|
||||
export class DesktopTelemetryReceiver extends Context.Service<
|
||||
@@ -104,6 +138,9 @@ export class DesktopTelemetryReceiver extends Context.Service<
|
||||
>()("t3/resourceTelemetry/DesktopTelemetryReceiver") {}
|
||||
|
||||
const decodeMessage = Schema.decodeUnknownEffect(DesktopHostTelemetryMessage);
|
||||
const encodeControlMessage = Schema.encodeEffect(
|
||||
Schema.fromJsonString(DesktopTelemetryControlMessage),
|
||||
);
|
||||
const isDescriptorUnavailable = Schema.is(DesktopTelemetryDescriptorUnavailable);
|
||||
const isProtocolMismatch = Schema.is(DesktopTelemetryProtocolMismatch);
|
||||
const isDecodeFailed = Schema.is(DesktopTelemetryDecodeFailed);
|
||||
@@ -132,6 +169,7 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")
|
||||
const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
|
||||
const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);
|
||||
const healthChanges = yield* PubSub.sliding<DesktopTelemetryReceiverHealth>(4);
|
||||
const controlMutex = yield* Semaphore.make(1);
|
||||
const health = yield* Ref.make<DesktopTelemetryReceiverHealth>({
|
||||
status: config.desktopTelemetryFd === undefined ? "unavailable" : "starting",
|
||||
lastSampleAt: Option.none(),
|
||||
@@ -154,6 +192,75 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")
|
||||
Effect.flatMap((next) => PubSub.publish(healthChanges, next)),
|
||||
Effect.asVoid,
|
||||
);
|
||||
const updateSampleHealth = (sampledAt: DateTime.Utc) =>
|
||||
Ref.modify(health, (current) => {
|
||||
const next: DesktopTelemetryReceiverHealth = {
|
||||
status: "healthy",
|
||||
lastSampleAt: Option.some(sampledAt),
|
||||
lastError: Option.none(),
|
||||
};
|
||||
return [
|
||||
current.status !== "healthy" || Option.isSome(current.lastError)
|
||||
? Option.some(next)
|
||||
: Option.none(),
|
||||
next,
|
||||
] as const;
|
||||
}).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () => Effect.void,
|
||||
onSome: (next) => PubSub.publish(healthChanges, next),
|
||||
}),
|
||||
),
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
const setDiagnosticsDemand: DesktopTelemetryReceiverShape["setDiagnosticsDemand"] = (enabled) =>
|
||||
controlMutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const fd = config.desktopTelemetryControlFd;
|
||||
if (fd === undefined) return;
|
||||
const encoded = yield* encodeControlMessage({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopTelemetryControlFailed({
|
||||
fd,
|
||||
operation: "encode",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
const payload = Buffer.from(`${encoded}\n`);
|
||||
let offset = 0;
|
||||
while (offset < payload.byteLength) {
|
||||
const written = NodeFileSystem.writeSync(fd, payload, offset);
|
||||
if (written <= 0) throw new Error("desktop telemetry control pipe accepted no bytes");
|
||||
offset += written;
|
||||
}
|
||||
},
|
||||
catch: (cause) =>
|
||||
new DesktopTelemetryControlFailed({
|
||||
fd,
|
||||
operation: "write",
|
||||
cause,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.tapError((error) =>
|
||||
updateHealth((current) => ({
|
||||
...current,
|
||||
status: "degraded",
|
||||
lastError: Option.some(error.message),
|
||||
})),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
if (config.desktopTelemetryFd !== undefined) {
|
||||
const fd = config.desktopTelemetryFd;
|
||||
@@ -217,13 +324,7 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")
|
||||
|
||||
const sampledAt = DateTime.makeUnsafe(message.sampledAtUnixMs);
|
||||
return Ref.set(latest, Option.some(message)).pipe(
|
||||
Effect.andThen(
|
||||
Ref.set(health, {
|
||||
status: "healthy",
|
||||
lastSampleAt: Option.some(sampledAt),
|
||||
lastError: Option.none(),
|
||||
}),
|
||||
),
|
||||
Effect.andThen(updateSampleHealth(sampledAt)),
|
||||
Effect.andThen(PubSub.publish(changes, message)),
|
||||
Effect.asVoid,
|
||||
);
|
||||
@@ -248,6 +349,36 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
yield* Effect.forever(
|
||||
Effect.sleep(STALE_CHECK_INTERVAL).pipe(
|
||||
Effect.andThen(
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.get(latest);
|
||||
if (Option.isNone(current) || current.value.power.stale) return;
|
||||
const now = yield* DateTime.now;
|
||||
if (DateTime.toEpochMillis(now) - current.value.sampledAtUnixMs < STALE_AFTER_MS)
|
||||
return;
|
||||
const staleSnapshot: DesktopHostTelemetrySnapshot = {
|
||||
...current.value,
|
||||
power: { ...current.value.power, stale: true },
|
||||
};
|
||||
yield* Ref.set(latest, Option.some(staleSnapshot));
|
||||
yield* updateHealth((currentHealth) => ({
|
||||
...currentHealth,
|
||||
status: currentHealth.status === "stopped" ? "stopped" : "degraded",
|
||||
lastError:
|
||||
currentHealth.status === "stopped"
|
||||
? currentHealth.lastError
|
||||
: Option.some(
|
||||
new DesktopTelemetryStale({ fd, staleAfterMs: STALE_AFTER_MS }).message,
|
||||
),
|
||||
}));
|
||||
yield* PubSub.publish(changes, staleSnapshot);
|
||||
}),
|
||||
),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
}
|
||||
|
||||
return DesktopTelemetryReceiver.of({
|
||||
@@ -255,6 +386,7 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")
|
||||
changes: Stream.fromPubSub(changes),
|
||||
health: Ref.get(health),
|
||||
healthChanges: Stream.fromPubSub(healthChanges),
|
||||
setDiagnosticsDemand,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -274,6 +406,7 @@ export const layerTest = (
|
||||
lastError: Option.some("Desktop telemetry test implementation is unavailable."),
|
||||
}),
|
||||
healthChanges: Stream.empty,
|
||||
setDiagnosticsDemand: () => Effect.void,
|
||||
...overrides,
|
||||
}),
|
||||
);
|
||||
@@ -39,7 +39,7 @@ function nativeSnapshot(
|
||||
sequence = 1,
|
||||
): ResourceMonitorSnapshotEvent {
|
||||
return {
|
||||
version: 1,
|
||||
version: 2,
|
||||
type: "snapshot",
|
||||
sequence,
|
||||
sampledAtUnixMs,
|
||||
@@ -74,6 +74,7 @@ function desktopSnapshot(
|
||||
type: "desktopTelemetry",
|
||||
sequence: 1,
|
||||
sampledAtUnixMs,
|
||||
electronPid: electronProcesses[0]?.pid ?? 10_000,
|
||||
power: {
|
||||
source: "electron-main",
|
||||
idle: "false",
|
||||
@@ -237,6 +238,45 @@ describe("resource telemetry process model", () => {
|
||||
expect(second.groups.backend.ioWriteBytes).toBe(3_000);
|
||||
});
|
||||
|
||||
it("derives deltas at the constrained 15-second sampling cadence", () => {
|
||||
const first = merge({
|
||||
native: nativeSnapshot(BASE_TIME_MS, [
|
||||
processSample({
|
||||
pid: SERVER_PID,
|
||||
ppid: 1,
|
||||
startTimeMs: 1_000,
|
||||
cpuTimeMs: 1_000,
|
||||
ioReadBytes: 10_000,
|
||||
ioWriteBytes: 20_000,
|
||||
}),
|
||||
]),
|
||||
});
|
||||
const second = merge({
|
||||
previous: first,
|
||||
native: nativeSnapshot(
|
||||
BASE_TIME_MS + 15_000,
|
||||
[
|
||||
processSample({
|
||||
pid: SERVER_PID,
|
||||
ppid: 1,
|
||||
startTimeMs: 1_000,
|
||||
cpuTimeMs: 2_500,
|
||||
ioReadBytes: 25_000,
|
||||
ioWriteBytes: 50_000,
|
||||
}),
|
||||
],
|
||||
2,
|
||||
),
|
||||
});
|
||||
|
||||
expect(second.processes[0]?.cpuPercent).toBe(10);
|
||||
expect(second.processes[0]?.ioReadBytesPerSecond).toBe(1_000);
|
||||
expect(second.processes[0]?.ioWriteBytesPerSecond).toBe(2_000);
|
||||
expect(second.groups.backend.cpuTimeMs).toBe(1_500);
|
||||
expect(second.groups.backend.ioReadBytes).toBe(15_000);
|
||||
expect(second.groups.backend.ioWriteBytes).toBe(30_000);
|
||||
});
|
||||
|
||||
it("preserves native rates while applying a desktop-only update", () => {
|
||||
const first = merge({
|
||||
native: nativeSnapshot(BASE_TIME_MS, [
|
||||
@@ -331,7 +371,7 @@ describe("resource telemetry process model", () => {
|
||||
const delayed = merge({
|
||||
previous: decreased,
|
||||
native: nativeSnapshot(
|
||||
BASE_TIME_MS + 20_000,
|
||||
BASE_TIME_MS + 90_000,
|
||||
[
|
||||
processSample({
|
||||
pid: SERVER_PID,
|
||||
|
||||
@@ -10,7 +10,7 @@ import type {
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
const MAX_DELTA_INTERVAL_MS = 10_000;
|
||||
const MAX_DELTA_INTERVAL_MS = 30_000;
|
||||
const ELECTRON_IDENTITY_TOLERANCE_MS = 2_000;
|
||||
|
||||
export interface ProcessState {
|
||||
@@ -47,6 +47,7 @@ export interface MergeProcessesInput {
|
||||
readonly fallbackSampledAtMs: number;
|
||||
readonly nativeSnapshot: Option.Option<ResourceMonitorSnapshotEvent>;
|
||||
readonly desktopSnapshot: Option.Option<DesktopHostTelemetrySnapshot>;
|
||||
readonly electronRootPids?: ReadonlySet<number>;
|
||||
readonly previous: ReadonlyMap<string, ProcessState>;
|
||||
readonly counters: TelemetryCounters;
|
||||
readonly updatePrevious: boolean;
|
||||
@@ -110,6 +111,15 @@ function electronCategory(metric: DesktopElectronProcessMetric): ResourceTelemet
|
||||
}
|
||||
}
|
||||
|
||||
function inferredElectronCategory(
|
||||
process: ResourceMonitorProcessSample,
|
||||
): ResourceTelemetryProcessCategory {
|
||||
const command = process.command.toLowerCase();
|
||||
if (command.includes("--type=renderer")) return "electron-renderer";
|
||||
if (command.includes("--type=gpu-process")) return "electron-gpu";
|
||||
return "electron-utility";
|
||||
}
|
||||
|
||||
function matchElectronMetric(
|
||||
process: ResourceMonitorProcessSample,
|
||||
metricsByPid: ReadonlyMap<number, DesktopElectronProcessMetric>,
|
||||
@@ -386,15 +396,20 @@ export function mergeProcesses(input: MergeProcessesInput): MergeProcessesResult
|
||||
}
|
||||
const processes = [...nativeByPid.values()];
|
||||
const processesByPid = new Map(processes.map((process) => [process.pid, process]));
|
||||
const electronPids = new Set(metricsByPid.keys());
|
||||
const electronRootPids = [...electronPids]
|
||||
.filter((pid) => {
|
||||
const process = processesByPid.get(pid);
|
||||
return process === undefined
|
||||
? true
|
||||
: !hasElectronAncestor(process, processesByPid, electronPids);
|
||||
})
|
||||
.toSorted((left, right) => left - right);
|
||||
const explicitElectronRootPids = input.electronRootPids ?? new Set<number>();
|
||||
const electronPids = new Set([...metricsByPid.keys(), ...explicitElectronRootPids]);
|
||||
const electronRootPids = [
|
||||
...explicitElectronRootPids,
|
||||
...[...electronPids]
|
||||
.filter((pid) => {
|
||||
if (explicitElectronRootPids.has(pid)) return false;
|
||||
const process = processesByPid.get(pid);
|
||||
return process === undefined
|
||||
? true
|
||||
: !hasElectronAncestor(process, processesByPid, electronPids);
|
||||
})
|
||||
.toSorted((left, right) => left - right),
|
||||
].filter((pid, index, values) => values.indexOf(pid) === index);
|
||||
const rootPids = [input.serverPid, ...electronRootPids];
|
||||
const roots = new Set(rootPids);
|
||||
const depths = processDepths(processes, roots);
|
||||
@@ -438,11 +453,13 @@ export function mergeProcesses(input: MergeProcessesInput): MergeProcessesResult
|
||||
? "server"
|
||||
: Option.contains(input.sidecarPid, process.pid)
|
||||
? "resource-monitor"
|
||||
: electronMetric
|
||||
? electronCategory(electronMetric)
|
||||
: isElectronDescendant(process.pid, processesByPid, electronPids)
|
||||
? "electron-utility"
|
||||
: "server-child";
|
||||
: explicitElectronRootPids.has(process.pid)
|
||||
? "electron-main"
|
||||
: electronMetric
|
||||
? electronCategory(electronMetric)
|
||||
: isElectronDescendant(process.pid, processesByPid, electronPids)
|
||||
? inferredElectronCategory(process)
|
||||
: "server-child";
|
||||
const firstSeenAt = previous?.process.firstSeenAt ?? DateTime.makeUnsafe(sampledAtMs);
|
||||
const preservePreviousRates = !input.updatePrevious && previous !== undefined;
|
||||
const cpuPercent = preservePreviousRates
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { HostPowerSnapshot } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
|
||||
import { resolveNativeSampleIntervalMs } from "./NativeTelemetryClient.ts";
|
||||
|
||||
const basePower: HostPowerSnapshot = {
|
||||
source: "electron-main",
|
||||
idle: "false",
|
||||
idleSeconds: 0,
|
||||
locked: "false",
|
||||
suspended: false,
|
||||
onBattery: "false",
|
||||
lowPowerMode: "false",
|
||||
thermalState: "nominal",
|
||||
stale: false,
|
||||
updatedAt: DateTime.makeUnsafe("2026-06-17T12:00:00.000Z"),
|
||||
};
|
||||
|
||||
describe("resolveNativeSampleIntervalMs", () => {
|
||||
it("pauses while suspended and backs off under host constraints", () => {
|
||||
expect(resolveNativeSampleIntervalMs({ ...basePower, suspended: true }, 1)).toBe(0);
|
||||
expect(resolveNativeSampleIntervalMs({ ...basePower, locked: "true" }, 1)).toBe(15_000);
|
||||
expect(resolveNativeSampleIntervalMs({ ...basePower, lowPowerMode: "true" }, 1)).toBe(15_000);
|
||||
expect(resolveNativeSampleIntervalMs({ ...basePower, thermalState: "critical" }, 1)).toBe(
|
||||
15_000,
|
||||
);
|
||||
expect(resolveNativeSampleIntervalMs({ ...basePower, onBattery: "true" }, 1)).toBe(5_000);
|
||||
});
|
||||
|
||||
it("keeps unknown background telemetry cheap but serves live diagnostics at 1Hz", () => {
|
||||
const unknown: HostPowerSnapshot = {
|
||||
...basePower,
|
||||
source: "unknown",
|
||||
stale: true,
|
||||
};
|
||||
expect(resolveNativeSampleIntervalMs(unknown, 0)).toBe(5_000);
|
||||
expect(resolveNativeSampleIntervalMs(unknown, 1)).toBe(1_000);
|
||||
expect(
|
||||
resolveNativeSampleIntervalMs(
|
||||
{ ...basePower, stale: true, locked: "true", suspended: true },
|
||||
0,
|
||||
),
|
||||
).toBe(5_000);
|
||||
expect(resolveNativeSampleIntervalMs(basePower, 0)).toBe(1_000);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import type {
|
||||
HostPowerSnapshot,
|
||||
ResourceMonitorCapabilities,
|
||||
ResourceMonitorCommand,
|
||||
ResourceMonitorEvent,
|
||||
@@ -36,8 +37,12 @@ import * as ResourceMonitorBinary from "./ResourceMonitorBinary.ts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
|
||||
const SAMPLE_INTERVAL_MS = 1_000;
|
||||
const UNKNOWN_BACKGROUND_SAMPLE_INTERVAL_MS = 5_000;
|
||||
const BATTERY_SAMPLE_INTERVAL_MS = 5_000;
|
||||
const CONSTRAINED_SAMPLE_INTERVAL_MS = 15_000;
|
||||
const HANDSHAKE_TIMEOUT = Duration.seconds(5);
|
||||
const SAMPLE_REQUEST_TIMEOUT = Duration.seconds(5);
|
||||
const HISTORY_REQUEST_TIMEOUT = Duration.seconds(15);
|
||||
const INITIAL_RESTART_DELAY = Duration.millis(500);
|
||||
const MAX_RESTART_DELAY = Duration.seconds(10);
|
||||
const FAILURE_WINDOW_MS = 60_000;
|
||||
@@ -138,14 +143,21 @@ export interface NativeTelemetryClientHealth {
|
||||
readonly lastSampleAt: Option.Option<DateTime.Utc>;
|
||||
readonly lastError: Option.Option<string>;
|
||||
readonly restartCount: number;
|
||||
readonly sampleIntervalMs: number;
|
||||
}
|
||||
|
||||
export interface NativeTelemetryClientShape {
|
||||
readonly capabilities: Effect.Effect<ResourceMonitorCapabilities, NativeTelemetryClientError>;
|
||||
readonly snapshots: Stream.Stream<ResourceMonitorSnapshotEvent, NativeTelemetryClientError>;
|
||||
readonly readHistory: (
|
||||
windowMs: number,
|
||||
) => Effect.Effect<ReadonlyArray<ResourceMonitorSnapshotEvent>, NativeTelemetryClientError>;
|
||||
readonly setExternalProcesses: (
|
||||
processes: ReadonlyArray<ResourceMonitorExternalProcess>,
|
||||
) => Effect.Effect<void, NativeTelemetryClientError>;
|
||||
readonly setHostPowerState: (
|
||||
snapshot: HostPowerSnapshot,
|
||||
) => Effect.Effect<void, NativeTelemetryClientError>;
|
||||
readonly sampleNow: Effect.Effect<ResourceMonitorSnapshotEvent, NativeTelemetryClientError>;
|
||||
readonly retry: Effect.Effect<boolean>;
|
||||
readonly health: Effect.Effect<NativeTelemetryClientHealth>;
|
||||
@@ -166,6 +178,20 @@ interface ClientState {
|
||||
readonly restartCount: number;
|
||||
}
|
||||
|
||||
interface CollectionControl {
|
||||
readonly hostPower: HostPowerSnapshot;
|
||||
readonly liveSubscriberCount: number;
|
||||
readonly sampleIntervalMs: number;
|
||||
}
|
||||
|
||||
interface PendingHistoryRequest {
|
||||
readonly deferred: Deferred.Deferred<
|
||||
ReadonlyArray<ResourceMonitorSnapshotEvent>,
|
||||
NativeTelemetryClientError
|
||||
>;
|
||||
readonly snapshots: ReadonlyArray<ResourceMonitorSnapshotEvent>;
|
||||
}
|
||||
|
||||
const initialState: ClientState = {
|
||||
status: "starting",
|
||||
handle: Option.none(),
|
||||
@@ -175,16 +201,40 @@ const initialState: ClientState = {
|
||||
restartCount: 0,
|
||||
};
|
||||
|
||||
function toHealth(state: ClientState): NativeTelemetryClientHealth {
|
||||
function toHealth(state: ClientState, sampleIntervalMs: number): NativeTelemetryClientHealth {
|
||||
return {
|
||||
status: state.status,
|
||||
hello: state.hello,
|
||||
lastSampleAt: state.lastSampleAt,
|
||||
lastError: state.lastError,
|
||||
restartCount: state.restartCount,
|
||||
sampleIntervalMs,
|
||||
};
|
||||
}
|
||||
|
||||
function isThermallyConstrained(snapshot: HostPowerSnapshot): boolean {
|
||||
return snapshot.thermalState === "serious" || snapshot.thermalState === "critical";
|
||||
}
|
||||
|
||||
export function resolveNativeSampleIntervalMs(
|
||||
snapshot: HostPowerSnapshot,
|
||||
liveSubscriberCount: number,
|
||||
): number {
|
||||
if (snapshot.stale || snapshot.source === "unknown") {
|
||||
return liveSubscriberCount > 0 ? SAMPLE_INTERVAL_MS : UNKNOWN_BACKGROUND_SAMPLE_INTERVAL_MS;
|
||||
}
|
||||
if (snapshot.suspended) return 0;
|
||||
if (
|
||||
snapshot.locked === "true" ||
|
||||
snapshot.lowPowerMode === "true" ||
|
||||
isThermallyConstrained(snapshot)
|
||||
) {
|
||||
return CONSTRAINED_SAMPLE_INTERVAL_MS;
|
||||
}
|
||||
if (snapshot.onBattery === "true") return BATTERY_SAMPLE_INTERVAL_MS;
|
||||
return SAMPLE_INTERVAL_MS;
|
||||
}
|
||||
|
||||
const decodeMonitorEvent: (
|
||||
value: unknown,
|
||||
) => Effect.Effect<ResourceMonitorEvent, Schema.SchemaError> = Schema.decodeUnknownEffect(
|
||||
@@ -216,29 +266,54 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const config = yield* ServerConfig;
|
||||
const initializedAt = yield* DateTime.now;
|
||||
const state = yield* Ref.make(initialState);
|
||||
const collectionControl = yield* Ref.make<CollectionControl>({
|
||||
hostPower: {
|
||||
source: "unknown",
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt: initializedAt,
|
||||
},
|
||||
liveSubscriberCount: 0,
|
||||
sampleIntervalMs: UNKNOWN_BACKGROUND_SAMPLE_INTERVAL_MS,
|
||||
});
|
||||
const externalProcesses = yield* Ref.make<ReadonlyArray<ResourceMonitorExternalProcess>>([]);
|
||||
const pendingSamples = yield* Ref.make(
|
||||
new Map<string, Deferred.Deferred<ResourceMonitorSnapshotEvent, NativeTelemetryClientError>>(),
|
||||
);
|
||||
const pendingHistories = yield* Ref.make(new Map<string, PendingHistoryRequest>());
|
||||
const snapshots = yield* PubSub.sliding<ResourceMonitorSnapshotEvent>(8);
|
||||
const healthChanges = yield* PubSub.sliding<NativeTelemetryClientHealth>(4);
|
||||
const retryQueue = yield* Queue.sliding<void>(1);
|
||||
const commandMutex = yield* Semaphore.make(1);
|
||||
const publishHealth = Ref.get(state).pipe(
|
||||
Effect.map(toHealth),
|
||||
const currentHealth = Effect.all([Ref.get(state), Ref.get(collectionControl)]).pipe(
|
||||
Effect.map(([current, control]) => toHealth(current, control.sampleIntervalMs)),
|
||||
);
|
||||
const publishHealth = currentHealth.pipe(
|
||||
Effect.flatMap((health) => PubSub.publish(healthChanges, health)),
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
const failPending = (error: NativeTelemetryClientError) =>
|
||||
Ref.getAndSet(pendingSamples, new Map()).pipe(
|
||||
Effect.flatMap((pending) =>
|
||||
Effect.forEach(pending.values(), (deferred) => Deferred.fail(deferred, error), {
|
||||
discard: true,
|
||||
}),
|
||||
),
|
||||
);
|
||||
Effect.gen(function* () {
|
||||
const samples = yield* Ref.getAndSet(pendingSamples, new Map());
|
||||
const histories = yield* Ref.getAndSet(pendingHistories, new Map());
|
||||
yield* Effect.forEach(samples.values(), (deferred) => Deferred.fail(deferred, error), {
|
||||
discard: true,
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
histories.values(),
|
||||
(request) => Deferred.fail(request.deferred, error),
|
||||
{ discard: true },
|
||||
);
|
||||
});
|
||||
|
||||
const writeCommand = (
|
||||
handle: ChildProcessSpawner.ChildProcessHandle,
|
||||
@@ -275,7 +350,7 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu
|
||||
case "hello":
|
||||
return Ref.update(state, (current) => ({
|
||||
...current,
|
||||
status: "healthy" as const,
|
||||
status: "starting" as const,
|
||||
hello: Option.some(event),
|
||||
lastError: Option.none(),
|
||||
})).pipe(
|
||||
@@ -305,6 +380,33 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu
|
||||
}
|
||||
}
|
||||
});
|
||||
case "historyChunk":
|
||||
return Effect.gen(function* () {
|
||||
const latestSnapshot = event.snapshots.at(-1);
|
||||
if (latestSnapshot) {
|
||||
yield* Ref.update(state, (current) => ({
|
||||
...current,
|
||||
status: "healthy" as const,
|
||||
lastSampleAt: Option.some(DateTime.makeUnsafe(latestSnapshot.sampledAtUnixMs)),
|
||||
lastError: Option.none(),
|
||||
}));
|
||||
}
|
||||
const completed = yield* Ref.modify(pendingHistories, (pending) => {
|
||||
const request = pending.get(event.requestId);
|
||||
if (!request) return [Option.none(), pending] as const;
|
||||
const snapshots = [...request.snapshots, ...event.snapshots];
|
||||
const next = new Map(pending);
|
||||
if (event.done) {
|
||||
next.delete(event.requestId);
|
||||
return [Option.some({ deferred: request.deferred, snapshots }), next] as const;
|
||||
}
|
||||
next.set(event.requestId, { deferred: request.deferred, snapshots });
|
||||
return [Option.none(), next] as const;
|
||||
});
|
||||
if (Option.isSome(completed)) {
|
||||
yield* Deferred.succeed(completed.value.deferred, completed.value.snapshots);
|
||||
}
|
||||
});
|
||||
case "error":
|
||||
return Ref.update(state, (current) => ({
|
||||
...current,
|
||||
@@ -413,18 +515,48 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu
|
||||
}),
|
||||
),
|
||||
);
|
||||
const control = yield* Ref.get(collectionControl);
|
||||
yield* writeCommand(handle, {
|
||||
version: RESOURCE_MONITOR_PROTOCOL_VERSION,
|
||||
type: "configure",
|
||||
rootPid: process.pid,
|
||||
sampleIntervalMs: SAMPLE_INTERVAL_MS,
|
||||
sampleIntervalMs: control.sampleIntervalMs,
|
||||
externalProcesses: [...(yield* Ref.get(externalProcesses))],
|
||||
});
|
||||
if (control.liveSubscriberCount > 0) {
|
||||
yield* writeCommand(handle, {
|
||||
version: RESOURCE_MONITOR_PROTOCOL_VERSION,
|
||||
type: "setStreaming",
|
||||
enabled: true,
|
||||
});
|
||||
}
|
||||
yield* Ref.update(state, (current) => ({
|
||||
...current,
|
||||
status: "healthy" as const,
|
||||
hello: Option.some(hello),
|
||||
}));
|
||||
yield* publishHealth;
|
||||
|
||||
yield* writeCommand(handle, {
|
||||
version: RESOURCE_MONITOR_PROTOCOL_VERSION,
|
||||
type: "setExternalProcesses",
|
||||
processes: [...(yield* Ref.get(externalProcesses))],
|
||||
});
|
||||
const latestControl = yield* Ref.get(collectionControl);
|
||||
if (latestControl.sampleIntervalMs !== control.sampleIntervalMs) {
|
||||
yield* writeCommand(handle, {
|
||||
version: RESOURCE_MONITOR_PROTOCOL_VERSION,
|
||||
type: "setSampleInterval",
|
||||
sampleIntervalMs: latestControl.sampleIntervalMs,
|
||||
});
|
||||
}
|
||||
if (latestControl.liveSubscriberCount > 0 !== control.liveSubscriberCount > 0) {
|
||||
yield* writeCommand(handle, {
|
||||
version: RESOURCE_MONITOR_PROTOCOL_VERSION,
|
||||
type: "setStreaming",
|
||||
enabled: latestControl.liveSubscriberCount > 0,
|
||||
});
|
||||
}
|
||||
|
||||
const exitEffect = handle.exitCode.pipe(
|
||||
Effect.mapError(
|
||||
@@ -517,11 +649,76 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const applyCollectionControl = Effect.fn(
|
||||
"resourceTelemetry.nativeTelemetryClient.applyCollectionControl",
|
||||
)(function* (previous: CollectionControl, next: CollectionControl) {
|
||||
const current = yield* Ref.get(state);
|
||||
if (Option.isSome(current.handle) && current.status === "healthy") {
|
||||
if (previous.sampleIntervalMs !== next.sampleIntervalMs) {
|
||||
yield* writeCommand(current.handle.value, {
|
||||
version: RESOURCE_MONITOR_PROTOCOL_VERSION,
|
||||
type: "setSampleInterval",
|
||||
sampleIntervalMs: next.sampleIntervalMs,
|
||||
});
|
||||
}
|
||||
const wasStreaming = previous.liveSubscriberCount > 0;
|
||||
const isStreaming = next.liveSubscriberCount > 0;
|
||||
if (wasStreaming !== isStreaming) {
|
||||
yield* writeCommand(current.handle.value, {
|
||||
version: RESOURCE_MONITOR_PROTOCOL_VERSION,
|
||||
type: "setStreaming",
|
||||
enabled: isStreaming,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (previous.sampleIntervalMs !== next.sampleIntervalMs) {
|
||||
yield* publishHealth;
|
||||
}
|
||||
});
|
||||
|
||||
const setHostPowerState: NativeTelemetryClientShape["setHostPowerState"] = (hostPower) =>
|
||||
Effect.gen(function* () {
|
||||
const [previous, next] = yield* Ref.modify(collectionControl, (current) => {
|
||||
const updated: CollectionControl = {
|
||||
...current,
|
||||
hostPower,
|
||||
sampleIntervalMs: resolveNativeSampleIntervalMs(hostPower, current.liveSubscriberCount),
|
||||
};
|
||||
return [[current, updated] as const, updated];
|
||||
});
|
||||
yield* applyCollectionControl(previous, next);
|
||||
});
|
||||
|
||||
const changeLiveSubscriberCount = Effect.fn(
|
||||
"resourceTelemetry.nativeTelemetryClient.changeLiveSubscriberCount",
|
||||
)(function* (delta: 1 | -1) {
|
||||
const [previous, next] = yield* Ref.modify(collectionControl, (current) => {
|
||||
const liveSubscriberCount = Math.max(0, current.liveSubscriberCount + delta);
|
||||
const updated: CollectionControl = {
|
||||
...current,
|
||||
liveSubscriberCount,
|
||||
sampleIntervalMs: resolveNativeSampleIntervalMs(current.hostPower, liveSubscriberCount),
|
||||
};
|
||||
return [[current, updated] as const, updated];
|
||||
});
|
||||
yield* applyCollectionControl(previous, next);
|
||||
});
|
||||
|
||||
const liveSnapshots = Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const subscription = yield* PubSub.subscribe(snapshots);
|
||||
yield* Effect.acquireRelease(changeLiveSubscriberCount(1), () =>
|
||||
changeLiveSubscriberCount(-1).pipe(Effect.ignore),
|
||||
);
|
||||
return Stream.fromSubscription(subscription);
|
||||
}),
|
||||
);
|
||||
|
||||
const setExternalProcesses: NativeTelemetryClientShape["setExternalProcesses"] = (processes) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Ref.set(externalProcesses, [...processes]);
|
||||
const current = yield* Ref.get(state);
|
||||
if (Option.isNone(current.handle)) return;
|
||||
if (Option.isNone(current.handle) || current.status !== "healthy") return;
|
||||
yield* writeCommand(current.handle.value, {
|
||||
version: RESOURCE_MONITOR_PROTOCOL_VERSION,
|
||||
type: "setExternalProcesses",
|
||||
@@ -529,9 +726,68 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu
|
||||
});
|
||||
});
|
||||
|
||||
const readHistory: NativeTelemetryClientShape["readHistory"] = (windowMs) =>
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.get(state);
|
||||
if (Option.isNone(current.handle) || current.status !== "healthy") {
|
||||
return yield* new NativeTelemetryUnavailable({
|
||||
reason: Option.getOrElse(current.lastError, () => "sidecar is not running"),
|
||||
});
|
||||
}
|
||||
const requestId = yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new NativeTelemetryCommandFailed({
|
||||
operation: "createHistoryRequestId",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const deferred = yield* Deferred.make<
|
||||
ReadonlyArray<ResourceMonitorSnapshotEvent>,
|
||||
NativeTelemetryClientError
|
||||
>();
|
||||
yield* Ref.update(pendingHistories, (pending) => {
|
||||
const next = new Map(pending);
|
||||
next.set(requestId, { deferred, snapshots: [] });
|
||||
return next;
|
||||
});
|
||||
return yield* writeCommand(current.handle.value, {
|
||||
version: RESOURCE_MONITOR_PROTOCOL_VERSION,
|
||||
type: "readHistory",
|
||||
requestId,
|
||||
windowMs: Math.max(0, Math.round(windowMs)),
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
Deferred.await(deferred).pipe(
|
||||
Effect.timeoutOption(HISTORY_REQUEST_TIMEOUT),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new NativeTelemetryCommandFailed({
|
||||
operation: "readHistory",
|
||||
cause: "history request timed out",
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.ensuring(
|
||||
Ref.update(pendingHistories, (pending) => {
|
||||
const next = new Map(pending);
|
||||
next.delete(requestId);
|
||||
return next;
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const sampleNow: NativeTelemetryClientShape["sampleNow"] = Effect.gen(function* () {
|
||||
const current = yield* Ref.get(state);
|
||||
if (Option.isNone(current.handle)) {
|
||||
if (Option.isNone(current.handle) || current.status !== "healthy") {
|
||||
return yield* new NativeTelemetryUnavailable({
|
||||
reason: Option.getOrElse(current.lastError, () => "sidecar is not running"),
|
||||
});
|
||||
@@ -587,7 +843,7 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu
|
||||
);
|
||||
});
|
||||
|
||||
const health = Ref.get(state).pipe(Effect.map(toHealth));
|
||||
const health = currentHealth;
|
||||
|
||||
return NativeTelemetryClient.of({
|
||||
capabilities: Ref.get(state).pipe(
|
||||
@@ -603,8 +859,10 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu
|
||||
}),
|
||||
),
|
||||
),
|
||||
snapshots: Stream.fromPubSub(snapshots),
|
||||
snapshots: liveSnapshots,
|
||||
readHistory,
|
||||
setExternalProcesses,
|
||||
setHostPowerState,
|
||||
sampleNow,
|
||||
retry: Ref.get(state).pipe(
|
||||
Effect.flatMap((current) =>
|
||||
@@ -636,7 +894,14 @@ export const layerTest = (
|
||||
processTree: true,
|
||||
}),
|
||||
snapshots: Stream.empty,
|
||||
readHistory: () =>
|
||||
Effect.fail(
|
||||
new NativeTelemetryUnavailable({
|
||||
reason: "No resource monitor history was configured for this test.",
|
||||
}),
|
||||
),
|
||||
setExternalProcesses: () => Effect.void,
|
||||
setHostPowerState: () => Effect.void,
|
||||
sampleNow: Effect.fail(
|
||||
new NativeTelemetryUnavailable({
|
||||
reason: "No resource monitor sample was configured for this test.",
|
||||
@@ -649,6 +914,7 @@ export const layerTest = (
|
||||
lastSampleAt: Option.none(),
|
||||
lastError: Option.some("Resource monitor test implementation is unavailable."),
|
||||
restartCount: 0,
|
||||
sampleIntervalMs: UNKNOWN_BACKGROUND_SAMPLE_INTERVAL_MS,
|
||||
}),
|
||||
healthChanges: Stream.empty,
|
||||
...overrides,
|
||||
|
||||
@@ -7,7 +7,6 @@ import { describe, expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
@@ -80,7 +79,7 @@ function nativeSnapshot(input: {
|
||||
}),
|
||||
];
|
||||
return {
|
||||
version: 1,
|
||||
version: 2,
|
||||
type: "snapshot",
|
||||
sequence: input.sequence,
|
||||
sampledAtUnixMs: input.sampledAtUnixMs,
|
||||
@@ -99,6 +98,7 @@ function desktopSnapshot(sampledAtUnixMs: number): DesktopHostTelemetrySnapshot
|
||||
type: "desktopTelemetry",
|
||||
sequence: 1,
|
||||
sampledAtUnixMs,
|
||||
electronPid: 5_000,
|
||||
power: {
|
||||
source: "electron-main",
|
||||
idle: "false",
|
||||
@@ -129,6 +129,48 @@ function desktopSnapshot(sampledAtUnixMs: number): DesktopHostTelemetrySnapshot
|
||||
}
|
||||
|
||||
describe("ResourceTelemetry", () => {
|
||||
it.effect("enables live native and Electron collection only while changes are retained", () =>
|
||||
Effect.gen(function* () {
|
||||
const sampledAtUnixMs = DateTime.toEpochMillis(yield* DateTime.now);
|
||||
const sample = nativeSnapshot({
|
||||
sequence: 1,
|
||||
sampledAtUnixMs,
|
||||
childCpuTimeMs: 100,
|
||||
childWriteBytes: 1_000,
|
||||
});
|
||||
const demandChanges = yield* Ref.make<ReadonlyArray<boolean>>([]);
|
||||
const nativeLayer = NativeTelemetryClient.layerTest({
|
||||
sampleNow: Effect.succeed(sample),
|
||||
health: Effect.succeed({
|
||||
status: "healthy",
|
||||
hello: Option.none(),
|
||||
lastSampleAt: Option.none(),
|
||||
lastError: Option.none(),
|
||||
restartCount: 0,
|
||||
sampleIntervalMs: 1_000,
|
||||
}),
|
||||
});
|
||||
const desktopLayer = DesktopTelemetryReceiver.layerTest({
|
||||
latest: Effect.succeedSome(desktopSnapshot(sampledAtUnixMs)),
|
||||
setDiagnosticsDemand: (enabled) =>
|
||||
Ref.update(demandChanges, (changes) => [...changes, enabled]),
|
||||
});
|
||||
const telemetryLayer = ResourceTelemetry.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(nativeLayer, desktopLayer, ResourceAttribution.layer)),
|
||||
);
|
||||
|
||||
const live = yield* Stream.runHead(
|
||||
Effect.gen(function* () {
|
||||
const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
|
||||
return telemetry.changes;
|
||||
}).pipe(Stream.unwrap),
|
||||
).pipe(Effect.provide(telemetryLayer));
|
||||
|
||||
expect(Option.isSome(live)).toBe(true);
|
||||
expect(yield* Ref.get(demandChanges)).toEqual([true, false]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("combines native, Electron, attribution, retry, and history data", () =>
|
||||
Effect.gen(function* () {
|
||||
const startedAt = DateTime.toEpochMillis(yield* DateTime.now);
|
||||
@@ -160,7 +202,7 @@ describe("ResourceTelemetry", () => {
|
||||
const nativeHealth = yield* Ref.make<NativeTelemetryClient.NativeTelemetryClientHealth>({
|
||||
status: "healthy",
|
||||
hello: Option.some({
|
||||
version: 1,
|
||||
version: 2,
|
||||
type: "hello",
|
||||
sidecarVersion: "0.1.0",
|
||||
sidecarPid: 9_000,
|
||||
@@ -179,11 +221,13 @@ describe("ResourceTelemetry", () => {
|
||||
lastSampleAt: Option.some(DateTime.makeUnsafe(startedAt)),
|
||||
lastError: Option.none(),
|
||||
restartCount: 2,
|
||||
sampleIntervalMs: 1_000,
|
||||
});
|
||||
const nativeHealthChanges =
|
||||
yield* PubSub.sliding<NativeTelemetryClient.NativeTelemetryClientHealth>(4);
|
||||
const nativeLayer = NativeTelemetryClient.layerTest({
|
||||
setExternalProcesses: (processes) => Ref.set(externalProcesses, processes),
|
||||
readHistory: () => Effect.succeed(samples.slice(0, 2)),
|
||||
sampleNow: Ref.modify(sampleIndex, (index) => [
|
||||
samples[Math.min(index, samples.length - 1)]!,
|
||||
index + 1,
|
||||
@@ -209,7 +253,7 @@ describe("ResourceTelemetry", () => {
|
||||
const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
|
||||
const attribution = yield* ResourceAttribution.ResourceAttribution;
|
||||
|
||||
expect(yield* Ref.get(externalProcesses)).toEqual([{ pid: 5_000, startTimeMs: 300 }]);
|
||||
expect(yield* Ref.get(externalProcesses)).toEqual([{ pid: 5_000 }]);
|
||||
|
||||
yield* attribution.record({
|
||||
component: "provider-event-log",
|
||||
@@ -280,15 +324,14 @@ describe("ResourceTelemetry", () => {
|
||||
expect(DateTime.toEpochMillis(restarted.readAt)).toBe(startedAt + 2_000);
|
||||
expect(Option.getOrNull(restarted.health.sidecarPid)).toBe(9_001);
|
||||
|
||||
const healthUpdateFiber = yield* Stream.runHead(telemetry.changes).pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
yield* Ref.update(nativeHealth, (current) => ({
|
||||
...current,
|
||||
status: "degraded" as const,
|
||||
lastError: Option.some("collector exited"),
|
||||
}));
|
||||
yield* PubSub.publish(nativeHealthChanges, yield* Ref.get(nativeHealth));
|
||||
const healthUpdate = Option.getOrThrow(yield* Fiber.join(healthUpdateFiber));
|
||||
yield* Effect.yieldNow;
|
||||
const healthUpdate = yield* telemetry.latest;
|
||||
expect(healthUpdate.health.native.status).toBe("degraded");
|
||||
expect(Option.getOrNull(healthUpdate.health.native.lastError)).toBe("collector exited");
|
||||
const degradedHistory = yield* telemetry.readHistory({
|
||||
|
||||
@@ -12,11 +12,14 @@ import type {
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
@@ -29,9 +32,10 @@ import {
|
||||
} from "./Model.ts";
|
||||
import * as NativeTelemetryClient from "./NativeTelemetryClient.ts";
|
||||
import * as ResourceAttribution from "./ResourceAttribution.ts";
|
||||
import * as ResourceTelemetryStore from "./ResourceTelemetryStore.ts";
|
||||
|
||||
const SAMPLE_INTERVAL_MS = 1_000;
|
||||
import {
|
||||
buildResourceTelemetryHistory,
|
||||
normalizeResourceTelemetryHistoryInput,
|
||||
} from "./ResourceTelemetryHistory.ts";
|
||||
|
||||
export class ResourceTelemetryRefreshFailed extends Schema.TaggedErrorClass<ResourceTelemetryRefreshFailed>()(
|
||||
"ResourceTelemetryRefreshFailed",
|
||||
@@ -72,6 +76,11 @@ interface TelemetryState {
|
||||
readonly lastNativeRestartCount: number;
|
||||
}
|
||||
|
||||
interface LiveTelemetryState {
|
||||
readonly retainCount: number;
|
||||
readonly scope: Option.Option<Scope.Closeable>;
|
||||
}
|
||||
|
||||
function unknownPower(updatedAt: DateTime.Utc): HostPowerSnapshot {
|
||||
return {
|
||||
source: "unknown",
|
||||
@@ -135,13 +144,9 @@ export const make = Effect.fn("resourceTelemetry.resourceTelemetry.make")(functi
|
||||
const initialDesktop = yield* desktopReceiver.latest;
|
||||
if (Option.isSome(initialDesktop)) {
|
||||
yield* nativeClient
|
||||
.setExternalProcesses(
|
||||
initialDesktop.value.electronProcesses.map((process) => ({
|
||||
pid: process.pid,
|
||||
startTimeMs: process.creationTimeMs,
|
||||
})),
|
||||
)
|
||||
.setExternalProcesses([{ pid: initialDesktop.value.electronPid }])
|
||||
.pipe(Effect.ignore);
|
||||
yield* nativeClient.setHostPowerState(initialDesktop.value.power).pipe(Effect.ignore);
|
||||
}
|
||||
const [initialNativeHealth, initialDesktopHealth, initialAttribution] = yield* Effect.all([
|
||||
nativeClient.health,
|
||||
@@ -160,7 +165,7 @@ export const make = Effect.fn("resourceTelemetry.resourceTelemetry.make")(functi
|
||||
});
|
||||
const initialSnapshot: ResourceTelemetrySnapshot = {
|
||||
readAt: initialReadAt,
|
||||
sampleIntervalMs: SAMPLE_INTERVAL_MS,
|
||||
sampleIntervalMs: initialNativeHealth.sampleIntervalMs,
|
||||
processes: initialMerge.processes,
|
||||
groups: initialMerge.groups,
|
||||
power: Option.match(initialDesktop, {
|
||||
@@ -184,7 +189,11 @@ export const make = Effect.fn("resourceTelemetry.resourceTelemetry.make")(functi
|
||||
lastNativeSequence: 0,
|
||||
lastNativeRestartCount: initialNativeHealth.restartCount,
|
||||
});
|
||||
const store = yield* ResourceTelemetryStore.make(initialSnapshot);
|
||||
const liveState = yield* Ref.make<LiveTelemetryState>({
|
||||
retainCount: 0,
|
||||
scope: Option.none(),
|
||||
});
|
||||
const liveMutex = yield* Semaphore.make(1);
|
||||
const refreshHealth = mutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.get(state);
|
||||
@@ -204,8 +213,9 @@ export const make = Effect.fn("resourceTelemetry.resourceTelemetry.make")(functi
|
||||
...current,
|
||||
latest: snapshot,
|
||||
});
|
||||
yield* store.updateLatest(snapshot);
|
||||
yield* PubSub.publish(changes, snapshot);
|
||||
if ((yield* Ref.get(liveState)).retainCount > 0) {
|
||||
yield* PubSub.publish(changes, snapshot);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -213,6 +223,7 @@ export const make = Effect.fn("resourceTelemetry.resourceTelemetry.make")(functi
|
||||
readonly nativeSnapshot?: ResourceMonitorSnapshotEvent;
|
||||
readonly desktopSnapshot?: DesktopHostTelemetrySnapshot;
|
||||
readonly updatePrevious: boolean;
|
||||
readonly publish?: boolean;
|
||||
}): Effect.Effect<ResourceTelemetrySnapshot> =>
|
||||
mutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
@@ -243,6 +254,10 @@ export const make = Effect.fn("resourceTelemetry.resourceTelemetry.make")(functi
|
||||
fallbackSampledAtMs: DateTime.toEpochMillis(current.latest.readAt),
|
||||
nativeSnapshot,
|
||||
desktopSnapshot,
|
||||
electronRootPids: Option.match(desktopSnapshot, {
|
||||
onNone: () => new Set<number>(),
|
||||
onSome: (desktop) => new Set([desktop.electronPid]),
|
||||
}),
|
||||
previous: current.previous,
|
||||
counters: current.counters,
|
||||
updatePrevious: input.updatePrevious,
|
||||
@@ -250,7 +265,7 @@ export const make = Effect.fn("resourceTelemetry.resourceTelemetry.make")(functi
|
||||
const readAt = DateTime.makeUnsafe(merged.sampledAtMs);
|
||||
const snapshot: ResourceTelemetrySnapshot = {
|
||||
readAt,
|
||||
sampleIntervalMs: SAMPLE_INTERVAL_MS,
|
||||
sampleIntervalMs: nativeHealth.sampleIntervalMs,
|
||||
processes: merged.processes,
|
||||
groups: merged.groups,
|
||||
power: Option.match(desktopSnapshot, {
|
||||
@@ -279,10 +294,9 @@ export const make = Effect.fn("resourceTelemetry.resourceTelemetry.make")(functi
|
||||
? nativeHealth.restartCount
|
||||
: current.lastNativeRestartCount,
|
||||
});
|
||||
if (input.updatePrevious) {
|
||||
yield* store.record(snapshot, merged.deltas);
|
||||
if (input.publish !== false) {
|
||||
yield* PubSub.publish(changes, snapshot);
|
||||
}
|
||||
yield* PubSub.publish(changes, snapshot);
|
||||
return snapshot;
|
||||
}),
|
||||
);
|
||||
@@ -291,30 +305,97 @@ export const make = Effect.fn("resourceTelemetry.resourceTelemetry.make")(functi
|
||||
rebuild({ nativeSnapshot: snapshot, updatePrevious: true });
|
||||
const ingestDesktop = (snapshot: DesktopHostTelemetrySnapshot) =>
|
||||
Effect.gen(function* () {
|
||||
yield* nativeClient
|
||||
.setExternalProcesses(
|
||||
snapshot.electronProcesses.map((process) => ({
|
||||
pid: process.pid,
|
||||
startTimeMs: process.creationTimeMs,
|
||||
})),
|
||||
)
|
||||
.pipe(Effect.ignore);
|
||||
return yield* rebuild({ desktopSnapshot: snapshot, updatePrevious: false });
|
||||
yield* nativeClient.setExternalProcesses([{ pid: snapshot.electronPid }]).pipe(Effect.ignore);
|
||||
yield* nativeClient.setHostPowerState(snapshot.power).pipe(Effect.ignore);
|
||||
const live = (yield* Ref.get(liveState)).retainCount > 0;
|
||||
return yield* rebuild({ desktopSnapshot: snapshot, updatePrevious: false, publish: live });
|
||||
});
|
||||
|
||||
yield* nativeClient.snapshots.pipe(
|
||||
Stream.runForEach((snapshot) => ingestNative(snapshot)),
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Native resource telemetry stream stopped", {
|
||||
cause: error.message,
|
||||
}),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* desktopReceiver.changes.pipe(
|
||||
Stream.runForEach((snapshot) => ingestDesktop(snapshot)),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const acquireLive = liveMutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.get(liveState);
|
||||
if (current.retainCount > 0) {
|
||||
yield* Ref.set(liveState, { ...current, retainCount: current.retainCount + 1 });
|
||||
return;
|
||||
}
|
||||
|
||||
const scope = yield* Scope.make();
|
||||
yield* Ref.set(liveState, { retainCount: 1, scope: Option.some(scope) });
|
||||
yield* desktopReceiver.setDiagnosticsDemand(true).pipe(Effect.ignore);
|
||||
yield* nativeClient.snapshots.pipe(
|
||||
Stream.runForEach(ingestNative),
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Native resource telemetry stream stopped", {
|
||||
cause: error.message,
|
||||
}),
|
||||
),
|
||||
Effect.forkIn(scope),
|
||||
);
|
||||
yield* nativeClient.sampleNow.pipe(Effect.flatMap(ingestNative), Effect.ignore);
|
||||
}),
|
||||
);
|
||||
|
||||
const releaseLive = liveMutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.get(liveState);
|
||||
if (current.retainCount <= 1) {
|
||||
yield* Ref.set(liveState, { retainCount: 0, scope: Option.none() });
|
||||
if (Option.isSome(current.scope)) {
|
||||
yield* Scope.close(current.scope.value, Exit.void).pipe(Effect.ignore);
|
||||
}
|
||||
yield* desktopReceiver.setDiagnosticsDemand(false).pipe(Effect.ignore);
|
||||
return;
|
||||
}
|
||||
yield* Ref.set(liveState, { ...current, retainCount: current.retainCount - 1 });
|
||||
}),
|
||||
);
|
||||
|
||||
const liveChanges = Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const subscription = yield* PubSub.subscribe(changes);
|
||||
yield* Effect.acquireRelease(acquireLive, () => releaseLive);
|
||||
return Stream.fromSubscription(subscription);
|
||||
}),
|
||||
);
|
||||
|
||||
const readHistory: ResourceTelemetryShape["readHistory"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const readAt = yield* DateTime.now;
|
||||
const normalizedInput = normalizeResourceTelemetryHistoryInput(input);
|
||||
const historyResult = yield* Effect.result(
|
||||
nativeClient.readHistory(normalizedInput.windowMs),
|
||||
);
|
||||
if (Result.isFailure(historyResult)) {
|
||||
yield* Effect.logWarning("Failed to read native resource telemetry history", {
|
||||
cause: historyResult.failure.message,
|
||||
});
|
||||
}
|
||||
const [nativeHealth, desktopHealth] = yield* Effect.all([
|
||||
nativeClient.health,
|
||||
desktopReceiver.health,
|
||||
]);
|
||||
const current = yield* Ref.get(state);
|
||||
return buildResourceTelemetryHistory({
|
||||
readAt,
|
||||
windowMs: normalizedInput.windowMs,
|
||||
bucketMs: normalizedInput.bucketMs,
|
||||
sampleIntervalMs: nativeHealth.sampleIntervalMs,
|
||||
serverPid: process.pid,
|
||||
sidecarPid: Option.map(nativeHealth.hello, (hello) => hello.sidecarPid),
|
||||
desktopSnapshot: current.desktopSnapshot,
|
||||
snapshots: Result.isSuccess(historyResult) ? historyResult.success : [],
|
||||
health: buildHealth({
|
||||
native: nativeHealth,
|
||||
desktop: desktopHealth,
|
||||
nativeSnapshot: current.nativeSnapshot,
|
||||
}),
|
||||
});
|
||||
});
|
||||
yield* nativeClient.healthChanges.pipe(
|
||||
Stream.runForEach(() => refreshHealth),
|
||||
Effect.forkScoped,
|
||||
@@ -353,8 +434,8 @@ export const make = Effect.fn("resourceTelemetry.resourceTelemetry.make")(functi
|
||||
|
||||
return ResourceTelemetry.of({
|
||||
latest: Ref.get(state).pipe(Effect.map((current) => current.latest)),
|
||||
changes: Stream.fromPubSub(changes),
|
||||
readHistory: store.readHistory,
|
||||
changes: liveChanges,
|
||||
readHistory,
|
||||
refresh,
|
||||
validateProcessIdentity,
|
||||
retry: nativeClient.retry.pipe(
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
import type {
|
||||
DesktopHostTelemetrySnapshot,
|
||||
ResourceMonitorProcessSample,
|
||||
ResourceMonitorSnapshotEvent,
|
||||
ResourceTelemetryHealth,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import {
|
||||
buildResourceTelemetryHistory,
|
||||
normalizeResourceTelemetryHistoryInput,
|
||||
} from "./ResourceTelemetryHistory.ts";
|
||||
|
||||
const SERVER_PID = 100;
|
||||
const ELECTRON_PID = 200;
|
||||
const CHILD_PID = 300;
|
||||
const STARTED_AT_MS = DateTime.toEpochMillis(DateTime.makeUnsafe("2026-06-17T12:00:00.000Z"));
|
||||
|
||||
function processSample(
|
||||
input: Partial<ResourceMonitorProcessSample> &
|
||||
Pick<ResourceMonitorProcessSample, "pid" | "ppid" | "startTimeMs">,
|
||||
): ResourceMonitorProcessSample {
|
||||
return {
|
||||
runTimeMs: 1_000,
|
||||
name: `process-${input.pid}`,
|
||||
command: `process-${input.pid}`,
|
||||
status: "Running",
|
||||
cpuPercent: 0,
|
||||
cpuTimeMs: 0,
|
||||
residentBytes: 1_024,
|
||||
virtualBytes: 2_048,
|
||||
ioReadBytes: 0,
|
||||
ioWriteBytes: 0,
|
||||
ioSemantics: "storage",
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
function snapshot(
|
||||
sequence: number,
|
||||
sampledAtUnixMs: number,
|
||||
childCpuTimeMs: number,
|
||||
childWriteBytes: number,
|
||||
): ResourceMonitorSnapshotEvent {
|
||||
const processes = [
|
||||
processSample({ pid: SERVER_PID, ppid: 1, startTimeMs: 10 }),
|
||||
processSample({
|
||||
pid: ELECTRON_PID,
|
||||
ppid: 1,
|
||||
startTimeMs: 20,
|
||||
name: "electron",
|
||||
command: "electron",
|
||||
}),
|
||||
processSample({
|
||||
pid: CHILD_PID,
|
||||
ppid: SERVER_PID,
|
||||
startTimeMs: 30,
|
||||
name: "codex",
|
||||
command: "codex app-server",
|
||||
cpuTimeMs: childCpuTimeMs,
|
||||
ioWriteBytes: childWriteBytes,
|
||||
}),
|
||||
];
|
||||
return {
|
||||
version: 2,
|
||||
type: "snapshot",
|
||||
sequence,
|
||||
sampledAtUnixMs,
|
||||
collectionDurationMicros: 100,
|
||||
scannedProcessCount: processes.length,
|
||||
retainedProcessCount: processes.length,
|
||||
inaccessibleProcessCount: 0,
|
||||
processes,
|
||||
};
|
||||
}
|
||||
|
||||
const health: ResourceTelemetryHealth = {
|
||||
native: {
|
||||
status: "healthy",
|
||||
lastSampleAt: Option.none(),
|
||||
lastError: Option.none(),
|
||||
},
|
||||
desktop: {
|
||||
status: "healthy",
|
||||
lastSampleAt: Option.none(),
|
||||
lastError: Option.none(),
|
||||
},
|
||||
sidecarVersion: Option.some("0.1.0"),
|
||||
sidecarPid: Option.some(400),
|
||||
restartCount: 0,
|
||||
collectionDurationMicros: 100,
|
||||
scannedProcessCount: 3,
|
||||
retainedProcessCount: 3,
|
||||
inaccessibleProcessCount: 0,
|
||||
};
|
||||
|
||||
function desktopSnapshot(): DesktopHostTelemetrySnapshot {
|
||||
const sampledAt = DateTime.makeUnsafe(STARTED_AT_MS + 1_000);
|
||||
return {
|
||||
version: 1,
|
||||
type: "desktopTelemetry",
|
||||
sequence: 1,
|
||||
sampledAtUnixMs: STARTED_AT_MS + 1_000,
|
||||
electronPid: ELECTRON_PID,
|
||||
power: {
|
||||
source: "electron-main",
|
||||
idle: "false",
|
||||
idleSeconds: 0,
|
||||
locked: "false",
|
||||
suspended: false,
|
||||
onBattery: "false",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "nominal",
|
||||
stale: false,
|
||||
updatedAt: sampledAt,
|
||||
},
|
||||
speedLimitPercent: Option.none(),
|
||||
electronProcesses: [
|
||||
{
|
||||
pid: ELECTRON_PID,
|
||||
creationTimeMs: 20,
|
||||
type: "Browser",
|
||||
cpuPercent: 999,
|
||||
idleWakeupsPerSecond: 999,
|
||||
workingSetBytes: 999_999,
|
||||
peakWorkingSetBytes: 999_999,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildResourceTelemetryHistory", () => {
|
||||
it("normalizes query bounds before requesting native history", () => {
|
||||
expect(normalizeResourceTelemetryHistoryInput({ windowMs: 0, bucketMs: 0 })).toEqual({
|
||||
windowMs: 1_000,
|
||||
bucketMs: 1_000,
|
||||
});
|
||||
});
|
||||
|
||||
it("replays native snapshots on demand without applying current Electron metrics", () => {
|
||||
const history = buildResourceTelemetryHistory({
|
||||
readAt: DateTime.makeUnsafe(STARTED_AT_MS + 2_000),
|
||||
windowMs: 10_000,
|
||||
bucketMs: 10_000,
|
||||
sampleIntervalMs: 1_000,
|
||||
serverPid: SERVER_PID,
|
||||
sidecarPid: Option.some(400),
|
||||
desktopSnapshot: Option.some(desktopSnapshot()),
|
||||
snapshots: [
|
||||
snapshot(1, STARTED_AT_MS, 100, 1_000),
|
||||
snapshot(2, STARTED_AT_MS + 1_000, 350, 5_000),
|
||||
],
|
||||
health,
|
||||
});
|
||||
|
||||
const child = history.topProcesses.find((process) => process.identity.pid === CHILD_PID);
|
||||
const electron = history.topProcesses.find((process) => process.identity.pid === ELECTRON_PID);
|
||||
expect(child?.sampleCount).toBe(2);
|
||||
expect(child?.cpuTimeMs).toBe(250);
|
||||
expect(child?.ioWriteBytes).toBe(4_000);
|
||||
expect(electron?.category).toBe("electron-main");
|
||||
expect(electron?.currentRssBytes).toBe(1_024);
|
||||
expect(history.buckets.reduce((total, bucket) => total + bucket.ioWriteBytes, 0)).toBe(4_000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,214 @@
|
||||
import type {
|
||||
DesktopHostTelemetrySnapshot,
|
||||
ResourceMonitorSnapshotEvent,
|
||||
ResourceTelemetryHealth,
|
||||
ResourceTelemetryHistory,
|
||||
ResourceTelemetryHistoryBucket,
|
||||
ResourceTelemetryProcess,
|
||||
ResourceTelemetryProcessSummary,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import {
|
||||
emptyTelemetryCounters,
|
||||
mergeProcesses,
|
||||
processIdentityKey,
|
||||
type ProcessState,
|
||||
type TelemetryCounters,
|
||||
} from "./Model.ts";
|
||||
|
||||
const MAX_HISTORY_WINDOW_MS = 60 * 60_000;
|
||||
|
||||
export function normalizeResourceTelemetryHistoryInput(input: {
|
||||
readonly windowMs: number;
|
||||
readonly bucketMs: number;
|
||||
}): { readonly windowMs: number; readonly bucketMs: number } {
|
||||
const windowMs = Math.max(1_000, Math.min(MAX_HISTORY_WINDOW_MS, input.windowMs));
|
||||
return {
|
||||
windowMs,
|
||||
bucketMs: Math.max(1_000, Math.min(windowMs, input.bucketMs)),
|
||||
};
|
||||
}
|
||||
|
||||
interface AggregateSample {
|
||||
readonly sampledAtMs: number;
|
||||
readonly cpuPercent: number;
|
||||
readonly rssBytes: number;
|
||||
readonly processCount: number;
|
||||
readonly ioReadBytes: number;
|
||||
readonly ioWriteBytes: number;
|
||||
}
|
||||
|
||||
interface ProcessSample {
|
||||
readonly sampledAtMs: number;
|
||||
readonly process: ResourceTelemetryProcess;
|
||||
readonly cpuTimeMs: number;
|
||||
readonly ioReadBytes: number;
|
||||
readonly ioWriteBytes: number;
|
||||
}
|
||||
|
||||
export interface BuildResourceTelemetryHistoryInput {
|
||||
readonly readAt: DateTime.Utc;
|
||||
readonly windowMs: number;
|
||||
readonly bucketMs: number;
|
||||
readonly sampleIntervalMs: number;
|
||||
readonly serverPid: number;
|
||||
readonly sidecarPid: Option.Option<number>;
|
||||
readonly desktopSnapshot: Option.Option<DesktopHostTelemetrySnapshot>;
|
||||
readonly snapshots: ReadonlyArray<ResourceMonitorSnapshotEvent>;
|
||||
readonly health: ResourceTelemetryHealth;
|
||||
}
|
||||
|
||||
function summarizeProcesses(
|
||||
samples: ReadonlyArray<ProcessSample>,
|
||||
): ReadonlyArray<ResourceTelemetryProcessSummary> {
|
||||
const groups = new Map<string, ProcessSample[]>();
|
||||
for (const sample of samples) {
|
||||
const identityKey = processIdentityKey(
|
||||
sample.process.identity.pid,
|
||||
sample.process.identity.startTimeMs,
|
||||
);
|
||||
const current = groups.get(identityKey) ?? [];
|
||||
current.push(sample);
|
||||
groups.set(identityKey, current);
|
||||
}
|
||||
|
||||
return [...groups.values()]
|
||||
.map((processSamples): ResourceTelemetryProcessSummary => {
|
||||
const sorted = processSamples.toSorted((left, right) => left.sampledAtMs - right.sampledAtMs);
|
||||
const first = sorted[0]!;
|
||||
const latest = sorted[sorted.length - 1]!;
|
||||
const cpuTotal = sorted.reduce((total, sample) => total + sample.process.cpuPercent, 0);
|
||||
return {
|
||||
identity: latest.process.identity,
|
||||
ppid: latest.process.ppid,
|
||||
depth: latest.process.depth,
|
||||
name: latest.process.name,
|
||||
command: latest.process.command,
|
||||
category: latest.process.category,
|
||||
firstSeenAt: first.process.firstSeenAt,
|
||||
lastSeenAt: latest.process.lastSeenAt,
|
||||
currentCpuPercent: latest.process.cpuPercent,
|
||||
avgCpuPercent: cpuTotal / sorted.length,
|
||||
maxCpuPercent: Math.max(...sorted.map((sample) => sample.process.cpuPercent)),
|
||||
cpuTimeMs: sorted.reduce((total, sample) => total + sample.cpuTimeMs, 0),
|
||||
currentRssBytes: latest.process.residentBytes,
|
||||
peakRssBytes: Math.max(...sorted.map((sample) => sample.process.peakResidentBytes)),
|
||||
ioReadBytes: sorted.reduce((total, sample) => total + sample.ioReadBytes, 0),
|
||||
ioWriteBytes: sorted.reduce((total, sample) => total + sample.ioWriteBytes, 0),
|
||||
ioSemantics: latest.process.ioSemantics,
|
||||
sampleCount: sorted.length,
|
||||
};
|
||||
})
|
||||
.toSorted(
|
||||
(left, right) => right.cpuTimeMs - left.cpuTimeMs || right.peakRssBytes - left.peakRssBytes,
|
||||
);
|
||||
}
|
||||
|
||||
function buildBuckets(input: {
|
||||
readonly samples: ReadonlyArray<AggregateSample>;
|
||||
readonly nowMs: number;
|
||||
readonly windowMs: number;
|
||||
readonly bucketMs: number;
|
||||
}): ReadonlyArray<ResourceTelemetryHistoryBucket> {
|
||||
const windowStartMs = input.nowMs - input.windowMs;
|
||||
const buckets: ResourceTelemetryHistoryBucket[] = [];
|
||||
for (let startedAtMs = windowStartMs; startedAtMs < input.nowMs; startedAtMs += input.bucketMs) {
|
||||
const endedAtMs = Math.min(input.nowMs, startedAtMs + input.bucketMs);
|
||||
const samples = input.samples.filter(
|
||||
(sample) =>
|
||||
sample.sampledAtMs >= startedAtMs &&
|
||||
(endedAtMs === input.nowMs
|
||||
? sample.sampledAtMs <= endedAtMs
|
||||
: sample.sampledAtMs < endedAtMs),
|
||||
);
|
||||
const cpuTotal = samples.reduce((total, sample) => total + sample.cpuPercent, 0);
|
||||
buckets.push({
|
||||
startedAt: DateTime.makeUnsafe(startedAtMs),
|
||||
endedAt: DateTime.makeUnsafe(endedAtMs),
|
||||
avgCpuPercent: samples.length === 0 ? 0 : cpuTotal / samples.length,
|
||||
maxCpuPercent:
|
||||
samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.cpuPercent)),
|
||||
maxRssBytes: samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.rssBytes)),
|
||||
ioReadBytes: samples.reduce((total, sample) => total + sample.ioReadBytes, 0),
|
||||
ioWriteBytes: samples.reduce((total, sample) => total + sample.ioWriteBytes, 0),
|
||||
maxProcessCount:
|
||||
samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.processCount)),
|
||||
});
|
||||
}
|
||||
return buckets;
|
||||
}
|
||||
|
||||
export function buildResourceTelemetryHistory(
|
||||
input: BuildResourceTelemetryHistoryInput,
|
||||
): ResourceTelemetryHistory {
|
||||
const readAtMs = DateTime.toEpochMillis(input.readAt);
|
||||
const { windowMs, bucketMs } = normalizeResourceTelemetryHistoryInput(input);
|
||||
const windowStartMs = readAtMs - windowMs;
|
||||
const snapshots = input.snapshots
|
||||
.filter((snapshot) => snapshot.sampledAtUnixMs >= windowStartMs)
|
||||
.toSorted((left, right) => left.sampledAtUnixMs - right.sampledAtUnixMs);
|
||||
const electronRootPids = Option.match(input.desktopSnapshot, {
|
||||
onNone: () => new Set<number>(),
|
||||
onSome: (snapshot) => new Set([snapshot.electronPid]),
|
||||
});
|
||||
const desktopIdentity = Option.map(input.desktopSnapshot, (snapshot) => ({
|
||||
...snapshot,
|
||||
electronProcesses: [],
|
||||
}));
|
||||
const aggregateSamples: AggregateSample[] = [];
|
||||
const processSamples: ProcessSample[] = [];
|
||||
let previous: ReadonlyMap<string, ProcessState> = new Map();
|
||||
let counters: TelemetryCounters = emptyTelemetryCounters();
|
||||
|
||||
for (const snapshot of snapshots) {
|
||||
const merged = mergeProcesses({
|
||||
serverPid: input.serverPid,
|
||||
sidecarPid: input.sidecarPid,
|
||||
fallbackSampledAtMs: snapshot.sampledAtUnixMs,
|
||||
nativeSnapshot: Option.some(snapshot),
|
||||
desktopSnapshot: desktopIdentity,
|
||||
electronRootPids,
|
||||
previous,
|
||||
counters,
|
||||
updatePrevious: true,
|
||||
});
|
||||
previous = merged.previous;
|
||||
counters = merged.counters;
|
||||
const deltasByIdentity = new Map(
|
||||
merged.deltas.map((processDelta) => [processDelta.identityKey, processDelta]),
|
||||
);
|
||||
aggregateSamples.push({
|
||||
sampledAtMs: snapshot.sampledAtUnixMs,
|
||||
cpuPercent: merged.groups.allT3.currentCpuPercent,
|
||||
rssBytes: merged.groups.allT3.currentRssBytes,
|
||||
processCount: merged.groups.allT3.processCount,
|
||||
ioReadBytes: merged.deltas.reduce((total, process) => total + process.ioReadBytes, 0),
|
||||
ioWriteBytes: merged.deltas.reduce((total, process) => total + process.ioWriteBytes, 0),
|
||||
});
|
||||
for (const process of merged.processes) {
|
||||
const processDelta = deltasByIdentity.get(
|
||||
processIdentityKey(process.identity.pid, process.identity.startTimeMs),
|
||||
);
|
||||
processSamples.push({
|
||||
sampledAtMs: snapshot.sampledAtUnixMs,
|
||||
process,
|
||||
cpuTimeMs: processDelta?.cpuTimeMs ?? 0,
|
||||
ioReadBytes: processDelta?.ioReadBytes ?? 0,
|
||||
ioWriteBytes: processDelta?.ioWriteBytes ?? 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
readAt: input.readAt,
|
||||
windowMs,
|
||||
bucketMs,
|
||||
sampleIntervalMs: input.sampleIntervalMs,
|
||||
retainedSampleCount: aggregateSamples.length + processSamples.length,
|
||||
buckets: buildBuckets({ samples: aggregateSamples, nowMs: readAtMs, windowMs, bucketMs }),
|
||||
topProcesses: summarizeProcesses(processSamples),
|
||||
health: input.health,
|
||||
};
|
||||
}
|
||||
@@ -1,253 +0,0 @@
|
||||
import type {
|
||||
ResourceTelemetryHistory,
|
||||
ResourceTelemetryHistoryBucket,
|
||||
ResourceTelemetryHistoryInput,
|
||||
ResourceTelemetryProcess,
|
||||
ResourceTelemetryProcessSummary,
|
||||
ResourceTelemetrySnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import type { ProcessDelta } from "./Model.ts";
|
||||
import { processIdentityKey } from "./Model.ts";
|
||||
|
||||
const RETENTION_MS = 60 * 60_000;
|
||||
const MAX_AGGREGATE_SAMPLES = 3_600;
|
||||
const MAX_PROCESS_SAMPLES = 20_000;
|
||||
|
||||
interface AggregateSample {
|
||||
readonly sampledAtMs: number;
|
||||
readonly cpuPercent: number;
|
||||
readonly rssBytes: number;
|
||||
readonly processCount: number;
|
||||
readonly ioReadBytes: number;
|
||||
readonly ioWriteBytes: number;
|
||||
}
|
||||
|
||||
interface ProcessSample {
|
||||
readonly sampledAtMs: number;
|
||||
readonly process: ResourceTelemetryProcess;
|
||||
readonly cpuTimeMs: number;
|
||||
readonly ioReadBytes: number;
|
||||
readonly ioWriteBytes: number;
|
||||
}
|
||||
|
||||
interface StoreState {
|
||||
readonly aggregateSamples: ReadonlyArray<AggregateSample>;
|
||||
readonly processSamples: ReadonlyArray<ProcessSample>;
|
||||
readonly latest: ResourceTelemetrySnapshot;
|
||||
}
|
||||
|
||||
export interface ResourceTelemetryStoreShape {
|
||||
readonly updateLatest: (snapshot: ResourceTelemetrySnapshot) => Effect.Effect<void>;
|
||||
readonly record: (
|
||||
snapshot: ResourceTelemetrySnapshot,
|
||||
deltas: ReadonlyArray<ProcessDelta>,
|
||||
) => Effect.Effect<void>;
|
||||
readonly readHistory: (
|
||||
input: ResourceTelemetryHistoryInput,
|
||||
) => Effect.Effect<ResourceTelemetryHistory>;
|
||||
}
|
||||
|
||||
export class ResourceTelemetryStore extends Context.Service<
|
||||
ResourceTelemetryStore,
|
||||
ResourceTelemetryStoreShape
|
||||
>()("t3/resourceTelemetry/ResourceTelemetryStore") {}
|
||||
|
||||
function trimByTime<A extends { readonly sampledAtMs: number }>(
|
||||
values: ReadonlyArray<A>,
|
||||
nowMs: number,
|
||||
max: number,
|
||||
): ReadonlyArray<A> {
|
||||
const retained = values.filter((value) => value.sampledAtMs >= nowMs - RETENTION_MS);
|
||||
return retained.length <= max ? retained : retained.slice(retained.length - max);
|
||||
}
|
||||
|
||||
function summarizeProcesses(
|
||||
samples: ReadonlyArray<ProcessSample>,
|
||||
): ReadonlyArray<ResourceTelemetryProcessSummary> {
|
||||
const groups = new Map<string, ProcessSample[]>();
|
||||
for (const sample of samples) {
|
||||
const identityKey = processIdentityKey(
|
||||
sample.process.identity.pid,
|
||||
sample.process.identity.startTimeMs,
|
||||
);
|
||||
const current = groups.get(identityKey) ?? [];
|
||||
current.push(sample);
|
||||
groups.set(identityKey, current);
|
||||
}
|
||||
|
||||
return [...groups.values()]
|
||||
.map((processSamples): ResourceTelemetryProcessSummary => {
|
||||
const sorted = processSamples.toSorted((left, right) => left.sampledAtMs - right.sampledAtMs);
|
||||
const first = sorted[0]!;
|
||||
const latest = sorted[sorted.length - 1]!;
|
||||
const cpuTotal = sorted.reduce((total, sample) => total + sample.process.cpuPercent, 0);
|
||||
return {
|
||||
identity: latest.process.identity,
|
||||
ppid: latest.process.ppid,
|
||||
depth: latest.process.depth,
|
||||
name: latest.process.name,
|
||||
command: latest.process.command,
|
||||
category: latest.process.category,
|
||||
firstSeenAt: first.process.firstSeenAt,
|
||||
lastSeenAt: latest.process.lastSeenAt,
|
||||
currentCpuPercent: latest.process.cpuPercent,
|
||||
avgCpuPercent: cpuTotal / sorted.length,
|
||||
maxCpuPercent: Math.max(...sorted.map((sample) => sample.process.cpuPercent)),
|
||||
cpuTimeMs: sorted.reduce((total, sample) => total + sample.cpuTimeMs, 0),
|
||||
currentRssBytes: latest.process.residentBytes,
|
||||
peakRssBytes: Math.max(...sorted.map((sample) => sample.process.peakResidentBytes)),
|
||||
ioReadBytes: sorted.reduce((total, sample) => total + sample.ioReadBytes, 0),
|
||||
ioWriteBytes: sorted.reduce((total, sample) => total + sample.ioWriteBytes, 0),
|
||||
ioSemantics: latest.process.ioSemantics,
|
||||
sampleCount: sorted.length,
|
||||
};
|
||||
})
|
||||
.toSorted(
|
||||
(left, right) => right.cpuTimeMs - left.cpuTimeMs || right.peakRssBytes - left.peakRssBytes,
|
||||
);
|
||||
}
|
||||
|
||||
function buildBuckets(input: {
|
||||
readonly samples: ReadonlyArray<AggregateSample>;
|
||||
readonly nowMs: number;
|
||||
readonly windowMs: number;
|
||||
readonly bucketMs: number;
|
||||
}): ReadonlyArray<ResourceTelemetryHistoryBucket> {
|
||||
const windowStartMs = input.nowMs - input.windowMs;
|
||||
const buckets: ResourceTelemetryHistoryBucket[] = [];
|
||||
for (let startedAtMs = windowStartMs; startedAtMs < input.nowMs; startedAtMs += input.bucketMs) {
|
||||
const endedAtMs = Math.min(input.nowMs, startedAtMs + input.bucketMs);
|
||||
const samples = input.samples.filter(
|
||||
(sample) =>
|
||||
sample.sampledAtMs >= startedAtMs &&
|
||||
(endedAtMs === input.nowMs
|
||||
? sample.sampledAtMs <= endedAtMs
|
||||
: sample.sampledAtMs < endedAtMs),
|
||||
);
|
||||
const cpuTotal = samples.reduce((total, sample) => total + sample.cpuPercent, 0);
|
||||
buckets.push({
|
||||
startedAt: DateTime.makeUnsafe(startedAtMs),
|
||||
endedAt: DateTime.makeUnsafe(endedAtMs),
|
||||
avgCpuPercent: samples.length === 0 ? 0 : cpuTotal / samples.length,
|
||||
maxCpuPercent:
|
||||
samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.cpuPercent)),
|
||||
maxRssBytes: samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.rssBytes)),
|
||||
ioReadBytes: samples.reduce((total, sample) => total + sample.ioReadBytes, 0),
|
||||
ioWriteBytes: samples.reduce((total, sample) => total + sample.ioWriteBytes, 0),
|
||||
maxProcessCount:
|
||||
samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.processCount)),
|
||||
});
|
||||
}
|
||||
return buckets;
|
||||
}
|
||||
|
||||
export const make = Effect.fn("resourceTelemetry.resourceTelemetryStore.make")(function* (
|
||||
initial: ResourceTelemetrySnapshot,
|
||||
) {
|
||||
const state = yield* Ref.make<StoreState>({
|
||||
aggregateSamples: [],
|
||||
processSamples: [],
|
||||
latest: initial,
|
||||
});
|
||||
|
||||
const record: ResourceTelemetryStoreShape["record"] = (snapshot, deltas) =>
|
||||
Ref.update(state, (current) => {
|
||||
const sampledAtMs = DateTime.toEpochMillis(snapshot.readAt);
|
||||
const deltasByIdentity = new Map(
|
||||
deltas.map((processDelta) => [processDelta.identityKey, processDelta]),
|
||||
);
|
||||
const aggregateDelta = deltas.reduce(
|
||||
(total, process) => ({
|
||||
ioReadBytes: total.ioReadBytes + process.ioReadBytes,
|
||||
ioWriteBytes: total.ioWriteBytes + process.ioWriteBytes,
|
||||
}),
|
||||
{ ioReadBytes: 0, ioWriteBytes: 0 },
|
||||
);
|
||||
return {
|
||||
latest: snapshot,
|
||||
aggregateSamples: trimByTime(
|
||||
[
|
||||
...current.aggregateSamples,
|
||||
{
|
||||
sampledAtMs,
|
||||
cpuPercent: snapshot.groups.allT3.currentCpuPercent,
|
||||
rssBytes: snapshot.groups.allT3.currentRssBytes,
|
||||
processCount: snapshot.groups.allT3.processCount,
|
||||
ioReadBytes: aggregateDelta.ioReadBytes,
|
||||
ioWriteBytes: aggregateDelta.ioWriteBytes,
|
||||
},
|
||||
],
|
||||
sampledAtMs,
|
||||
MAX_AGGREGATE_SAMPLES,
|
||||
),
|
||||
processSamples: trimByTime(
|
||||
[
|
||||
...current.processSamples,
|
||||
...snapshot.processes.map((process) => {
|
||||
const processDelta = deltasByIdentity.get(
|
||||
processIdentityKey(process.identity.pid, process.identity.startTimeMs),
|
||||
);
|
||||
return {
|
||||
sampledAtMs,
|
||||
process,
|
||||
cpuTimeMs: processDelta?.cpuTimeMs ?? 0,
|
||||
ioReadBytes: processDelta?.ioReadBytes ?? 0,
|
||||
ioWriteBytes: processDelta?.ioWriteBytes ?? 0,
|
||||
};
|
||||
}),
|
||||
],
|
||||
sampledAtMs,
|
||||
MAX_PROCESS_SAMPLES,
|
||||
),
|
||||
};
|
||||
});
|
||||
|
||||
const updateLatest: ResourceTelemetryStoreShape["updateLatest"] = (snapshot) =>
|
||||
Ref.update(state, (current) => ({
|
||||
...current,
|
||||
latest: snapshot,
|
||||
}));
|
||||
|
||||
const readHistory: ResourceTelemetryStoreShape["readHistory"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const readAt = yield* DateTime.now;
|
||||
const readAtMs = DateTime.toEpochMillis(readAt);
|
||||
const windowMs = Math.max(1_000, Math.min(RETENTION_MS, input.windowMs));
|
||||
const bucketMs = Math.max(1_000, Math.min(windowMs, input.bucketMs));
|
||||
const current = yield* Ref.get(state);
|
||||
const minSampledAtMs = readAtMs - windowMs;
|
||||
const aggregateSamples = current.aggregateSamples.filter(
|
||||
(sample) => sample.sampledAtMs >= minSampledAtMs,
|
||||
);
|
||||
const processSamples = current.processSamples.filter(
|
||||
(sample) => sample.sampledAtMs >= minSampledAtMs,
|
||||
);
|
||||
|
||||
return {
|
||||
readAt,
|
||||
windowMs,
|
||||
bucketMs,
|
||||
sampleIntervalMs: current.latest.sampleIntervalMs,
|
||||
retainedSampleCount: current.aggregateSamples.length + current.processSamples.length,
|
||||
buckets: buildBuckets({
|
||||
samples: aggregateSamples,
|
||||
nowMs: readAtMs,
|
||||
windowMs,
|
||||
bucketMs,
|
||||
}),
|
||||
topProcesses: summarizeProcesses(processSamples),
|
||||
health: current.latest.health,
|
||||
};
|
||||
});
|
||||
|
||||
return ResourceTelemetryStore.of({ updateLatest, record, readHistory });
|
||||
});
|
||||
|
||||
export const layer = (initial: ResourceTelemetrySnapshot) =>
|
||||
Layer.effect(ResourceTelemetryStore, make(initial));
|
||||
@@ -128,14 +128,15 @@ const ServerSettingsLayerLive = ServerSettings.layer.pipe(
|
||||
const NativeTelemetryLayerLive = NativeTelemetryClient.layer.pipe(
|
||||
Layer.provide(ResourceMonitorBinary.layer),
|
||||
);
|
||||
const DesktopTelemetryReceiverLayerLive = DesktopTelemetryReceiver.layer;
|
||||
|
||||
const ResourceTelemetryLayerLive = ResourceTelemetry.layer.pipe(
|
||||
Layer.provideMerge(NativeTelemetryLayerLive),
|
||||
Layer.provideMerge(DesktopTelemetryReceiver.layer),
|
||||
Layer.provideMerge(DesktopTelemetryReceiverLayerLive),
|
||||
);
|
||||
|
||||
const HostPowerMonitorLayerLive = HostPowerMonitor.layer.pipe(
|
||||
Layer.provide(ResourceTelemetryLayerLive),
|
||||
Layer.provide(DesktopTelemetryReceiverLayerLive),
|
||||
);
|
||||
|
||||
const BackgroundLayerLive = BackgroundPolicy.layer.pipe(
|
||||
|
||||
@@ -11,9 +11,9 @@ subprocess probes with two persistent, direct data sources:
|
||||
through operating-system APIs via `sysinfo`;
|
||||
2. Electron main-process APIs for Electron process metrics and host power state.
|
||||
|
||||
The server merges both sources, computes rates from cumulative counters, keeps
|
||||
bounded in-memory history, exposes typed RPCs, and drives the diagnostics page.
|
||||
Telemetry history is not persisted to disk.
|
||||
The native monitor owns bounded in-memory history. The server only merges and
|
||||
summarizes that history when diagnostics requests it. Telemetry history is not
|
||||
persisted to disk or continuously copied into Node.
|
||||
|
||||
## Why a standalone executable
|
||||
|
||||
@@ -38,14 +38,13 @@ native code into Node.
|
||||
```text
|
||||
Electron main
|
||||
├─ powerMonitor
|
||||
├─ app.getAppMetrics()
|
||||
└─ inherited fd 4, NDJSON
|
||||
│
|
||||
▼
|
||||
├─ app.getAppMetrics() while diagnostics is open
|
||||
├─ inherited fd 4, telemetry NDJSON ─────────────┐
|
||||
└─ inherited fd 5, demand-control NDJSON ◀──────┤
|
||||
▼
|
||||
Node server ── stdin/stdout NDJSON ── Rust resource monitor
|
||||
│
|
||||
├─ ResourceTelemetry Effect service
|
||||
├─ bounded in-memory history
|
||||
├─ background power policy projection
|
||||
└─ WebSocket RPC/subscription ── diagnostics UI
|
||||
```
|
||||
@@ -65,10 +64,14 @@ line on stdout:
|
||||
|
||||
- `configure`
|
||||
- `setExternalProcesses`
|
||||
- `setSampleInterval`
|
||||
- `setStreaming`
|
||||
- `sampleNow`
|
||||
- `readHistory`
|
||||
- `shutdown`
|
||||
- `hello`
|
||||
- `snapshot`
|
||||
- `historyChunk`
|
||||
- `error`
|
||||
|
||||
The protocol version is defined by
|
||||
@@ -77,8 +80,8 @@ The protocol version is defined by
|
||||
|
||||
### Collection
|
||||
|
||||
The monitor keeps one `sysinfo::System` instance and refreshes it on a one-second
|
||||
interval. It collects:
|
||||
The monitor keeps one `sysinfo::System` instance and refreshes it at the
|
||||
power-adaptive interval selected by the server. It collects:
|
||||
|
||||
- PID and parent PID;
|
||||
- process start time and run time;
|
||||
@@ -110,6 +113,26 @@ can have coarser platform resolution.
|
||||
The process list is emitted in depth-first tree order so renderer collapse and
|
||||
expansion preserves complete subtrees.
|
||||
|
||||
### Native history and streaming
|
||||
|
||||
Every native sample is appended to a one-hour in-memory ring bounded to 3,600
|
||||
snapshots and 20,000 retained process rows. History stays in the sidecar until a
|
||||
`readHistory` request and is returned in bounded chunks. The first bound reached
|
||||
wins, so high process counts shorten the effective history window.
|
||||
|
||||
Periodic snapshot streaming is disabled by default. The server enables it only
|
||||
while at least one diagnostics subscription is retained. `sampleNow` remains
|
||||
available for explicit refreshes and identity validation.
|
||||
|
||||
The server adjusts native sampling without restarting the sidecar:
|
||||
|
||||
- suspended: paused;
|
||||
- locked, low-power, or serious/critical thermal state: 15 seconds;
|
||||
- battery: 5 seconds;
|
||||
- normal AC: 1 second;
|
||||
- unknown or stale power: 5 seconds in the background and 1 second while live
|
||||
diagnostics is open.
|
||||
|
||||
### Sampling limits
|
||||
|
||||
This is counter sampling, not syscall tracing.
|
||||
@@ -143,14 +166,19 @@ columns are the operating system's cumulative counters for that process.
|
||||
|
||||
Electron main owns `DesktopTelemetryPublisher`.
|
||||
|
||||
It samples once per second from:
|
||||
Power events trigger an immediate snapshot. A low-rate 30-second heartbeat keeps
|
||||
the server-side power state fresh while diagnostics is closed. During that
|
||||
heartbeat Electron reads:
|
||||
|
||||
- `app.getAppMetrics()`;
|
||||
- `powerMonitor.isOnBatteryPower()`;
|
||||
- `powerMonitor.getSystemIdleTime()`;
|
||||
- `powerMonitor.getSystemIdleState()`;
|
||||
- `powerMonitor.getCurrentThermalState()`.
|
||||
|
||||
`app.getAppMetrics()` is only called while diagnostics demand is active. Its
|
||||
live cadence is 1 second on AC, 5 seconds on battery, and 15 seconds while
|
||||
locked, suspended, or thermally constrained.
|
||||
|
||||
It also listens for:
|
||||
|
||||
- lock and unlock;
|
||||
@@ -165,10 +193,11 @@ remains `unknown`.
|
||||
The desktop backend is spawned with:
|
||||
|
||||
- fd 3 for the existing bootstrap payload;
|
||||
- fd 4 for desktop telemetry NDJSON.
|
||||
- fd 4 for Electron-to-server telemetry NDJSON;
|
||||
- fd 5 for server-to-Electron diagnostics-demand NDJSON.
|
||||
|
||||
This is a private Electron-main-to-server pipe. It does not use the renderer
|
||||
WebSocket and is recreated for every backend restart.
|
||||
These are private Electron-main/server pipes. They do not use the renderer
|
||||
WebSocket and are recreated for every backend restart.
|
||||
|
||||
## Server Effect services
|
||||
|
||||
@@ -192,7 +221,10 @@ Owns the resource-monitor process and protocol.
|
||||
|
||||
- validates the hello/version handshake;
|
||||
- sends configuration and external process roots;
|
||||
- exposes automatic snapshots and `sampleNow`;
|
||||
- adapts the native interval from host power state;
|
||||
- enables streaming only for scoped live subscribers;
|
||||
- reads chunked native history on demand;
|
||||
- exposes `sampleNow`;
|
||||
- serializes commands;
|
||||
- supervises process exit and protocol failure;
|
||||
- restarts with bounded exponential backoff;
|
||||
@@ -207,8 +239,10 @@ restart cannot freeze telemetry.
|
||||
### `DesktopTelemetryReceiver`
|
||||
|
||||
Reads fd 4, decodes schema-validated messages, stores the latest Electron
|
||||
snapshot, and publishes desktop health. Decode errors, protocol mismatch,
|
||||
stream failure, and normal stream closure are represented explicitly.
|
||||
snapshot, and publishes desktop health. It writes diagnostics demand to fd 5
|
||||
and marks the source stale after 90 seconds without a heartbeat. Decode errors,
|
||||
protocol mismatch, control-write failure, stream failure, stale input, and
|
||||
normal stream closure are represented explicitly.
|
||||
|
||||
### `ResourceTelemetry`
|
||||
|
||||
@@ -220,20 +254,21 @@ Merges native and Electron data and owns public telemetry semantics.
|
||||
- computes process depth and child relationships;
|
||||
- tracks starts, exits, CPU time, and observed I/O;
|
||||
- projects power data;
|
||||
- publishes live snapshots;
|
||||
- acquires native streaming and Electron process metrics only for scoped live
|
||||
subscribers;
|
||||
- queries and replays native history only when requested;
|
||||
- validates `(pid, startTimeMs)` before process signaling;
|
||||
- updates history health even when no further native sample arrives.
|
||||
|
||||
Electron and monitor processes are visible but are not valid targets for the
|
||||
existing process-signal RPC.
|
||||
|
||||
### `ResourceTelemetryStore`
|
||||
### History projection
|
||||
|
||||
Keeps aggregate and process samples in memory for at most one hour, subject to
|
||||
hard sample-count bounds. Aggregate history retains up to 3,600 samples.
|
||||
Detailed process history retains up to 20,000 process samples, so high process
|
||||
fan-out can shorten detailed per-process coverage while aggregate coverage
|
||||
remains available.
|
||||
`ResourceTelemetryHistory` is a pure on-demand projection. It replays raw native
|
||||
snapshots to derive rates, lifecycle counters, buckets, and process summaries.
|
||||
Current Electron process metrics are intentionally excluded from historical
|
||||
replay so they cannot overwrite older native CPU or memory samples.
|
||||
|
||||
### `ResourceAttribution`
|
||||
|
||||
@@ -249,8 +284,8 @@ adding diagnostics-specific counters.
|
||||
|
||||
## Background policy integration
|
||||
|
||||
`HostPowerMonitor` now projects power state from `ResourceTelemetry`; it does not
|
||||
spawn macOS shell probes.
|
||||
`HostPowerMonitor` consumes `DesktopTelemetryReceiver` directly; observing host
|
||||
power does not retain live resource diagnostics or invoke shell probes.
|
||||
|
||||
The monitor updates its latest timestamp on every Electron sample but only
|
||||
publishes semantic state changes. Increasing idle seconds alone does not cause a
|
||||
@@ -300,11 +335,12 @@ with the CLI. Missing platform artifacts degrade native telemetry to
|
||||
Steady state uses:
|
||||
|
||||
- one native process;
|
||||
- one native sample per second;
|
||||
- one Electron sample per second in desktop mode;
|
||||
- power-adaptive native counter sampling with no periodic Node snapshot stream;
|
||||
- event-driven Electron power updates plus a 30-second heartbeat;
|
||||
- no `app.getAppMetrics()` calls while diagnostics is closed;
|
||||
- no telemetry database;
|
||||
- no recurring shell probes;
|
||||
- bounded PubSub queues and bounded history.
|
||||
- bounded PubSub queues and native ring history.
|
||||
|
||||
The diagnostics page exposes the monitor's own process resource usage and
|
||||
collection duration so the observer's cost is measurable.
|
||||
|
||||
@@ -6,10 +6,14 @@ use std::thread;
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System, UpdateKind};
|
||||
|
||||
const PROTOCOL_VERSION: u32 = 1;
|
||||
const PROTOCOL_VERSION: u32 = 2;
|
||||
const MIN_SAMPLE_INTERVAL_MS: u64 = 250;
|
||||
const MAX_SAMPLE_INTERVAL_MS: u64 = 60_000;
|
||||
const EXTERNAL_PROCESS_START_TOLERANCE_MS: u64 = 2_000;
|
||||
const HISTORY_RETENTION_MS: u64 = 60 * 60_000;
|
||||
const MAX_HISTORY_SNAPSHOTS: usize = 3_600;
|
||||
const MAX_HISTORY_PROCESS_SAMPLES: usize = 20_000;
|
||||
const HISTORY_CHUNK_SNAPSHOTS: usize = 32;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -37,10 +41,23 @@ enum Command {
|
||||
version: u32,
|
||||
processes: Vec<ExternalProcess>,
|
||||
},
|
||||
SetSampleInterval {
|
||||
version: u32,
|
||||
sample_interval_ms: u64,
|
||||
},
|
||||
SetStreaming {
|
||||
version: u32,
|
||||
enabled: bool,
|
||||
},
|
||||
SampleNow {
|
||||
version: u32,
|
||||
request_id: String,
|
||||
},
|
||||
ReadHistory {
|
||||
version: u32,
|
||||
request_id: String,
|
||||
window_ms: u64,
|
||||
},
|
||||
Shutdown {
|
||||
version: u32,
|
||||
},
|
||||
@@ -51,7 +68,10 @@ impl Command {
|
||||
match self {
|
||||
Self::Configure { version, .. }
|
||||
| Self::SetExternalProcesses { version, .. }
|
||||
| Self::SetSampleInterval { version, .. }
|
||||
| Self::SetStreaming { version, .. }
|
||||
| Self::SampleNow { version, .. }
|
||||
| Self::ReadHistory { version, .. }
|
||||
| Self::Shutdown { version } => *version,
|
||||
}
|
||||
}
|
||||
@@ -94,7 +114,7 @@ enum IoSemantics {
|
||||
AllIo,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ProcessSample {
|
||||
pid: u32,
|
||||
@@ -113,7 +133,7 @@ struct ProcessSample {
|
||||
io_semantics: IoSemantics,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct SnapshotEvent {
|
||||
version: u32,
|
||||
@@ -130,6 +150,17 @@ struct SnapshotEvent {
|
||||
processes: Vec<ProcessSample>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct HistoryChunkEvent<'a> {
|
||||
version: u32,
|
||||
#[serde(rename = "type")]
|
||||
event_type: &'static str,
|
||||
request_id: &'a str,
|
||||
done: bool,
|
||||
snapshots: &'a [SnapshotEvent],
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ErrorEvent {
|
||||
@@ -144,10 +175,51 @@ struct ErrorEvent {
|
||||
#[derive(Debug, Clone)]
|
||||
struct CollectorConfig {
|
||||
root_pid: u32,
|
||||
sample_interval: Duration,
|
||||
sample_interval: Option<Duration>,
|
||||
external_processes: HashMap<u32, Option<u64>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct HistoryRecorder {
|
||||
snapshots: VecDeque<SnapshotEvent>,
|
||||
process_sample_count: usize,
|
||||
}
|
||||
|
||||
impl HistoryRecorder {
|
||||
fn record(&mut self, snapshot: &SnapshotEvent) {
|
||||
let mut retained = snapshot.clone();
|
||||
retained.request_id = None;
|
||||
self.process_sample_count = self
|
||||
.process_sample_count
|
||||
.saturating_add(retained.processes.len());
|
||||
self.snapshots.push_back(retained);
|
||||
self.trim(snapshot.sampled_at_unix_ms);
|
||||
}
|
||||
|
||||
fn trim(&mut self, now_ms: u64) {
|
||||
while self.snapshots.front().is_some_and(|snapshot| {
|
||||
snapshot.sampled_at_unix_ms < now_ms.saturating_sub(HISTORY_RETENTION_MS)
|
||||
|| self.snapshots.len() > MAX_HISTORY_SNAPSHOTS
|
||||
|| self.process_sample_count > MAX_HISTORY_PROCESS_SAMPLES
|
||||
}) {
|
||||
if let Some(removed) = self.snapshots.pop_front() {
|
||||
self.process_sample_count = self
|
||||
.process_sample_count
|
||||
.saturating_sub(removed.processes.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read(&self, window_ms: u64, now_ms: u64) -> Vec<SnapshotEvent> {
|
||||
let started_at_ms = now_ms.saturating_sub(window_ms.min(HISTORY_RETENTION_MS));
|
||||
self.snapshots
|
||||
.iter()
|
||||
.filter(|snapshot| snapshot.sampled_at_unix_ms >= started_at_ms)
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
struct Collector {
|
||||
system: System,
|
||||
sequence: u64,
|
||||
@@ -303,8 +375,12 @@ fn unix_time_ms() -> u64 {
|
||||
.as_millis() as u64
|
||||
}
|
||||
|
||||
fn clamp_sample_interval(sample_interval_ms: u64) -> Duration {
|
||||
Duration::from_millis(sample_interval_ms.clamp(MIN_SAMPLE_INTERVAL_MS, MAX_SAMPLE_INTERVAL_MS))
|
||||
fn clamp_sample_interval(sample_interval_ms: u64) -> Option<Duration> {
|
||||
(sample_interval_ms > 0).then(|| {
|
||||
Duration::from_millis(
|
||||
sample_interval_ms.clamp(MIN_SAMPLE_INTERVAL_MS, MAX_SAMPLE_INTERVAL_MS),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn spawn_input_reader() -> Receiver<Input> {
|
||||
@@ -368,6 +444,40 @@ fn write_error(
|
||||
)
|
||||
}
|
||||
|
||||
fn write_history(
|
||||
writer: &mut impl Write,
|
||||
request_id: &str,
|
||||
snapshots: &[SnapshotEvent],
|
||||
) -> io::Result<()> {
|
||||
if snapshots.is_empty() {
|
||||
return write_event(
|
||||
writer,
|
||||
&HistoryChunkEvent {
|
||||
version: PROTOCOL_VERSION,
|
||||
event_type: "historyChunk",
|
||||
request_id,
|
||||
done: true,
|
||||
snapshots,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let chunk_count = snapshots.len().div_ceil(HISTORY_CHUNK_SNAPSHOTS);
|
||||
for (index, chunk) in snapshots.chunks(HISTORY_CHUNK_SNAPSHOTS).enumerate() {
|
||||
write_event(
|
||||
writer,
|
||||
&HistoryChunkEvent {
|
||||
version: PROTOCOL_VERSION,
|
||||
event_type: "historyChunk",
|
||||
request_id,
|
||||
done: index + 1 == chunk_count,
|
||||
snapshots: chunk,
|
||||
},
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn main() -> io::Result<()> {
|
||||
let mut writer = BufWriter::new(io::stdout().lock());
|
||||
write_event(
|
||||
@@ -393,8 +503,10 @@ fn main() -> io::Result<()> {
|
||||
|
||||
let receiver = spawn_input_reader();
|
||||
let mut collector = Collector::new();
|
||||
let mut history = HistoryRecorder::default();
|
||||
let mut config: Option<CollectorConfig> = None;
|
||||
let mut next_sample_at: Option<Instant> = None;
|
||||
let mut streaming_enabled = false;
|
||||
|
||||
loop {
|
||||
let timeout = next_sample_at
|
||||
@@ -435,7 +547,7 @@ fn main() -> io::Result<()> {
|
||||
.map(|process| (process.pid, process.start_time_ms))
|
||||
.collect(),
|
||||
});
|
||||
next_sample_at = Some(Instant::now());
|
||||
next_sample_at = sample_interval.map(|_| Instant::now());
|
||||
}
|
||||
Command::SetExternalProcesses { processes, .. } => {
|
||||
if let Some(current) = config.as_mut() {
|
||||
@@ -452,11 +564,34 @@ fn main() -> io::Result<()> {
|
||||
)?;
|
||||
}
|
||||
}
|
||||
Command::SetSampleInterval {
|
||||
sample_interval_ms, ..
|
||||
} => {
|
||||
if let Some(current) = config.as_mut() {
|
||||
current.sample_interval = clamp_sample_interval(sample_interval_ms);
|
||||
next_sample_at = current
|
||||
.sample_interval
|
||||
.map(|interval| Instant::now() + interval);
|
||||
} else {
|
||||
write_error(
|
||||
&mut writer,
|
||||
"not-configured",
|
||||
"configure must be sent before changing the sample interval",
|
||||
true,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
Command::SetStreaming { enabled, .. } => {
|
||||
streaming_enabled = enabled;
|
||||
}
|
||||
Command::SampleNow { request_id, .. } => {
|
||||
if let Some(current) = config.as_ref() {
|
||||
let event = collector.sample(current, Some(request_id));
|
||||
history.record(&event);
|
||||
write_event(&mut writer, &event)?;
|
||||
next_sample_at = Some(Instant::now() + current.sample_interval);
|
||||
next_sample_at = current
|
||||
.sample_interval
|
||||
.map(|interval| Instant::now() + interval);
|
||||
} else {
|
||||
write_error(
|
||||
&mut writer,
|
||||
@@ -466,14 +601,38 @@ fn main() -> io::Result<()> {
|
||||
)?;
|
||||
}
|
||||
}
|
||||
Command::ReadHistory {
|
||||
request_id,
|
||||
window_ms,
|
||||
..
|
||||
} => {
|
||||
if config.is_some() {
|
||||
let snapshots = history.read(window_ms, unix_time_ms());
|
||||
write_history(&mut writer, &request_id, &snapshots)?;
|
||||
} else {
|
||||
write_error(
|
||||
&mut writer,
|
||||
"not-configured",
|
||||
"configure must be sent before reading history",
|
||||
true,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
Command::Shutdown { .. } => return Ok(()),
|
||||
}
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout) => {
|
||||
if let Some(current) = config.as_ref() {
|
||||
let event = collector.sample(current, None);
|
||||
write_event(&mut writer, &event)?;
|
||||
next_sample_at = Some(Instant::now() + current.sample_interval);
|
||||
if let Some(interval) = current.sample_interval {
|
||||
let event = collector.sample(current, None);
|
||||
history.record(&event);
|
||||
if streaming_enabled {
|
||||
write_event(&mut writer, &event)?;
|
||||
}
|
||||
next_sample_at = Some(Instant::now() + interval);
|
||||
} else {
|
||||
next_sample_at = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(RecvTimeoutError::Disconnected) => return Ok(()),
|
||||
@@ -518,7 +677,7 @@ mod tests {
|
||||
#[test]
|
||||
fn decodes_protocol_commands() {
|
||||
let configure = serde_json::from_str::<Command>(
|
||||
r#"{"version":1,"type":"configure","rootPid":42,"sampleIntervalMs":1000,"externalProcesses":[{"pid":7}]}"#,
|
||||
r#"{"version":2,"type":"configure","rootPid":42,"sampleIntervalMs":1000,"externalProcesses":[{"pid":7}]}"#,
|
||||
)
|
||||
.expect("configure command");
|
||||
|
||||
@@ -536,14 +695,61 @@ mod tests {
|
||||
}
|
||||
_ => panic!("unexpected command"),
|
||||
}
|
||||
|
||||
let read_history = serde_json::from_str::<Command>(
|
||||
r#"{"version":2,"type":"readHistory","requestId":"history-1","windowMs":60000}"#,
|
||||
)
|
||||
.expect("read history command");
|
||||
assert!(matches!(
|
||||
read_history,
|
||||
Command::ReadHistory {
|
||||
request_id,
|
||||
window_ms: 60_000,
|
||||
..
|
||||
} if request_id == "history-1"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clamps_sample_interval() {
|
||||
assert_eq!(clamp_sample_interval(1), Duration::from_millis(250));
|
||||
assert_eq!(clamp_sample_interval(0), None);
|
||||
assert_eq!(clamp_sample_interval(1), Some(Duration::from_millis(250)));
|
||||
assert_eq!(
|
||||
clamp_sample_interval(100_000),
|
||||
Duration::from_millis(60_000)
|
||||
Some(Duration::from_millis(60_000))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retains_bounded_history_without_request_ids() {
|
||||
let mut history = HistoryRecorder::default();
|
||||
for sequence in 0..=MAX_HISTORY_SNAPSHOTS {
|
||||
history.record(&SnapshotEvent {
|
||||
version: PROTOCOL_VERSION,
|
||||
event_type: "snapshot",
|
||||
sequence: sequence as u64,
|
||||
sampled_at_unix_ms: sequence as u64 * 1_000,
|
||||
collection_duration_micros: 1,
|
||||
scanned_process_count: 0,
|
||||
retained_process_count: 0,
|
||||
inaccessible_process_count: 0,
|
||||
request_id: Some("request".to_owned()),
|
||||
processes: Vec::new(),
|
||||
});
|
||||
}
|
||||
|
||||
assert_eq!(history.snapshots.len(), MAX_HISTORY_SNAPSHOTS);
|
||||
assert!(
|
||||
history
|
||||
.snapshots
|
||||
.iter()
|
||||
.all(|snapshot| snapshot.request_id.is_none())
|
||||
);
|
||||
assert_eq!(
|
||||
history
|
||||
.read(10_000, MAX_HISTORY_SNAPSHOTS as u64 * 1_000)
|
||||
.len(),
|
||||
11
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ export const DesktopBackendBootstrap = Schema.Struct({
|
||||
otlpTracesUrl: Schema.optional(Schema.String),
|
||||
otlpMetricsUrl: Schema.optional(Schema.String),
|
||||
desktopTelemetryFd: Schema.optionalKey(PositiveInt),
|
||||
desktopTelemetryControlFd: Schema.optionalKey(PositiveInt),
|
||||
resourceMonitorPath: Schema.optionalKey(TrimmedNonEmptyString),
|
||||
});
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import * as Schema from "effect/Schema";
|
||||
import { NonNegativeInt, PositiveInt, TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
import { HostPowerSnapshot } from "./background.ts";
|
||||
|
||||
export const RESOURCE_MONITOR_PROTOCOL_VERSION = 1 as const;
|
||||
export const RESOURCE_MONITOR_PROTOCOL_VERSION = 2 as const;
|
||||
|
||||
export const ResourceTelemetryIoSemantics = Schema.Literals([
|
||||
"storage",
|
||||
@@ -101,6 +101,29 @@ export const ResourceMonitorSampleNowCommand = Schema.Struct({
|
||||
});
|
||||
export type ResourceMonitorSampleNowCommand = typeof ResourceMonitorSampleNowCommand.Type;
|
||||
|
||||
export const ResourceMonitorSetSampleIntervalCommand = Schema.Struct({
|
||||
version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),
|
||||
type: Schema.Literal("setSampleInterval"),
|
||||
sampleIntervalMs: NonNegativeInt,
|
||||
});
|
||||
export type ResourceMonitorSetSampleIntervalCommand =
|
||||
typeof ResourceMonitorSetSampleIntervalCommand.Type;
|
||||
|
||||
export const ResourceMonitorSetStreamingCommand = Schema.Struct({
|
||||
version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),
|
||||
type: Schema.Literal("setStreaming"),
|
||||
enabled: Schema.Boolean,
|
||||
});
|
||||
export type ResourceMonitorSetStreamingCommand = typeof ResourceMonitorSetStreamingCommand.Type;
|
||||
|
||||
export const ResourceMonitorReadHistoryCommand = Schema.Struct({
|
||||
version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),
|
||||
type: Schema.Literal("readHistory"),
|
||||
requestId: TrimmedNonEmptyString,
|
||||
windowMs: NonNegativeInt,
|
||||
});
|
||||
export type ResourceMonitorReadHistoryCommand = typeof ResourceMonitorReadHistoryCommand.Type;
|
||||
|
||||
export const ResourceMonitorShutdownCommand = Schema.Struct({
|
||||
version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),
|
||||
type: Schema.Literal("shutdown"),
|
||||
@@ -110,7 +133,10 @@ export type ResourceMonitorShutdownCommand = typeof ResourceMonitorShutdownComma
|
||||
export const ResourceMonitorCommand = Schema.Union([
|
||||
ResourceMonitorConfigureCommand,
|
||||
ResourceMonitorSetExternalProcessesCommand,
|
||||
ResourceMonitorSetSampleIntervalCommand,
|
||||
ResourceMonitorSetStreamingCommand,
|
||||
ResourceMonitorSampleNowCommand,
|
||||
ResourceMonitorReadHistoryCommand,
|
||||
ResourceMonitorShutdownCommand,
|
||||
]);
|
||||
export type ResourceMonitorCommand = typeof ResourceMonitorCommand.Type;
|
||||
@@ -140,6 +166,15 @@ export const ResourceMonitorSnapshotEvent = Schema.Struct({
|
||||
});
|
||||
export type ResourceMonitorSnapshotEvent = typeof ResourceMonitorSnapshotEvent.Type;
|
||||
|
||||
export const ResourceMonitorHistoryChunkEvent = Schema.Struct({
|
||||
version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),
|
||||
type: Schema.Literal("historyChunk"),
|
||||
requestId: TrimmedNonEmptyString,
|
||||
done: Schema.Boolean,
|
||||
snapshots: Schema.Array(ResourceMonitorSnapshotEvent),
|
||||
});
|
||||
export type ResourceMonitorHistoryChunkEvent = typeof ResourceMonitorHistoryChunkEvent.Type;
|
||||
|
||||
export const ResourceMonitorErrorEvent = Schema.Struct({
|
||||
version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),
|
||||
type: Schema.Literal("error"),
|
||||
@@ -152,6 +187,7 @@ export type ResourceMonitorErrorEvent = typeof ResourceMonitorErrorEvent.Type;
|
||||
export const ResourceMonitorEvent = Schema.Union([
|
||||
ResourceMonitorHelloEvent,
|
||||
ResourceMonitorSnapshotEvent,
|
||||
ResourceMonitorHistoryChunkEvent,
|
||||
ResourceMonitorErrorEvent,
|
||||
]);
|
||||
export type ResourceMonitorEvent = typeof ResourceMonitorEvent.Type;
|
||||
@@ -188,6 +224,7 @@ export const DesktopHostTelemetrySnapshot = Schema.Struct({
|
||||
type: Schema.Literal("desktopTelemetry"),
|
||||
sequence: NonNegativeInt,
|
||||
sampledAtUnixMs: NonNegativeInt,
|
||||
electronPid: PositiveInt,
|
||||
power: HostPowerSnapshot,
|
||||
speedLimitPercent: Schema.Option(Schema.Number),
|
||||
electronProcesses: Schema.Array(DesktopElectronProcessMetric),
|
||||
@@ -207,6 +244,16 @@ export const DesktopHostTelemetryMessage = Schema.Union([
|
||||
]);
|
||||
export type DesktopHostTelemetryMessage = typeof DesktopHostTelemetryMessage.Type;
|
||||
|
||||
export const DesktopTelemetrySetDiagnosticsDemand = Schema.Struct({
|
||||
version: Schema.Literal(1),
|
||||
type: Schema.Literal("setDiagnosticsDemand"),
|
||||
enabled: Schema.Boolean,
|
||||
});
|
||||
export type DesktopTelemetrySetDiagnosticsDemand = typeof DesktopTelemetrySetDiagnosticsDemand.Type;
|
||||
|
||||
export const DesktopTelemetryControlMessage = Schema.Union([DesktopTelemetrySetDiagnosticsDemand]);
|
||||
export type DesktopTelemetryControlMessage = typeof DesktopTelemetryControlMessage.Type;
|
||||
|
||||
export const ResourceTelemetryProcess = Schema.Struct({
|
||||
identity: ResourceTelemetryProcessIdentity,
|
||||
ppid: NonNegativeInt,
|
||||
|
||||
Reference in new issue
Block a user