Skip to content

Commit 701f5df

Browse files
server heartbeat
1 parent 3f3f3ca commit 701f5df

4 files changed

Lines changed: 80 additions & 1 deletion

File tree

‎apps/server/src/main.test.ts‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import * as Http from "node:http";
22
import * as NodeServices from "@effect/platform-node/NodeServices";
33
import { assert, it, vi } from "@effect/vitest";
4+
import type { OrchestrationReadModel } from "@t3tools/contracts";
45
import * as ConfigProvider from "effect/ConfigProvider";
56
import * as Effect from "effect/Effect";
67
import * as Layer from "effect/Layer";
@@ -9,9 +10,10 @@ import { FetchHttpClient } from "effect/unstable/http";
910
import { beforeEach } from "vitest";
1011
import { NetService } from "@t3tools/shared/Net";
1112

12-
import { CliConfig, t3Cli, type CliConfigShape } from "./main";
13+
import { CliConfig, recordStartupHeartbeat, t3Cli, type CliConfigShape } from "./main";
1314
import { ServerConfig, type ServerConfigShape } from "./config";
1415
import { Open, type OpenShape } from "./open";
16+
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
1517
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
1618
import { Server, type ServerShape } from "./wsServer";
1719

@@ -231,6 +233,43 @@ it.layer(testLayer)("server CLI command", (it) => {
231233
}),
232234
);
233235

236+
it.effect("records a startup heartbeat with thread/project counts", () =>
237+
Effect.gen(function* () {
238+
const recordTelemetry = vi.fn(
239+
(_event: string, _properties?: Readonly<Record<string, unknown>>) => Effect.void,
240+
);
241+
const getSnapshot = vi.fn(() =>
242+
Effect.succeed({
243+
snapshotSequence: 2,
244+
projects: [{} as OrchestrationReadModel["projects"][number]],
245+
threads: [
246+
{} as OrchestrationReadModel["threads"][number],
247+
{} as OrchestrationReadModel["threads"][number],
248+
],
249+
updatedAt: new Date(1).toISOString(),
250+
} satisfies OrchestrationReadModel),
251+
);
252+
253+
yield* recordStartupHeartbeat.pipe(
254+
Effect.provideService(ProjectionSnapshotQuery, {
255+
getSnapshot,
256+
}),
257+
Effect.provideService(AnalyticsService, {
258+
record: recordTelemetry,
259+
flush: Effect.void,
260+
}),
261+
);
262+
263+
assert.deepEqual(recordTelemetry.mock.calls[0], [
264+
"server.boot.heartbeat",
265+
{
266+
threadCount: 2,
267+
projectCount: 1,
268+
},
269+
]);
270+
}),
271+
);
272+
234273
it.effect("does not start server for invalid --mode values", () =>
235274
Effect.gen(function* () {
236275
yield* runCli(["--mode", "invalid"]);

‎apps/server/src/main.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,12 @@ import { fixPath, resolveStateDir } from "./os-jank";
2020
import { Open } from "./open";
2121
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
2222
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
23+
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
2324
import { ProviderHealthLive } from "./provider/Layers/ProviderHealth";
2425
import { Server } from "./wsServer";
2526
import { ServerLoggerLive } from "./serverLogger";
2627
import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
28+
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
2729

2830
export class StartupError extends Data.TaggedError("StartupError")<{
2931
readonly message: string;
@@ -208,6 +210,31 @@ const isWildcardHost = (host: string | undefined): boolean =>
208210
const formatHostForUrl = (host: string): string =>
209211
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
210212

213+
export const recordStartupHeartbeat = Effect.gen(function* () {
214+
const analytics = yield* AnalyticsService;
215+
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
216+
217+
const { threadCount, projectCount } = yield* projectionSnapshotQuery.getSnapshot().pipe(
218+
Effect.map((snapshot) => ({
219+
threadCount: snapshot.threads.length,
220+
projectCount: snapshot.projects.length,
221+
})),
222+
Effect.catch((cause) =>
223+
Effect.logWarning("failed to gather startup snapshot for telemetry", { cause }).pipe(
224+
Effect.as({
225+
threadCount: 0,
226+
projectCount: 0,
227+
}),
228+
),
229+
),
230+
);
231+
232+
yield* analytics.record("server.boot.heartbeat", {
233+
threadCount,
234+
projectCount,
235+
});
236+
});
237+
211238
const makeServerProgram = (input: CliInput) =>
212239
Effect.gen(function* () {
213240
const cliConfig = yield* CliConfig;
@@ -227,6 +254,7 @@ const makeServerProgram = (input: CliInput) =>
227254
}
228255

229256
yield* start;
257+
yield* Effect.forkChild(recordStartupHeartbeat);
230258

231259
const localUrl = `http://localhost:${config.port}`;
232260
const bindUrl =

‎apps/server/src/telemetry/Layers/AnalyticsService.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ interface RecordedBatchRequest {
1818
readonly event?: string;
1919
readonly properties?: {
2020
readonly index?: number;
21+
readonly clientType?: string;
2122
};
2223
}>;
2324
} | null;
@@ -28,6 +29,7 @@ interface RecordedBatchBody {
2829
readonly event?: string;
2930
readonly properties?: {
3031
readonly index?: number;
32+
readonly clientType?: string;
3133
};
3234
}>;
3335
}
@@ -109,6 +111,12 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
109111
sorted,
110112
Array.from({ length: 45 }, (_, index) => index),
111113
);
114+
assert.equal(
115+
batchRequests.every((request) =>
116+
request.body.batch.every((event) => event.properties?.clientType === "cli-web-client"),
117+
),
118+
true,
119+
);
112120
}),
113121
);
114122
});

‎apps/server/src/telemetry/Layers/AnalyticsService.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import { Config, DateTime, Effect, Layer, Ref } from "effect";
1111
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
1212

13+
import { ServerConfig } from "../../config.ts";
1314
import { AnalyticsService, type AnalyticsServiceShape } from "../Services/AnalyticsService.ts";
1415
import { getTelemetryIdentifier } from "../Identify.ts";
1516
import { version } from "../../../package.json" with { type: "json" };
@@ -37,8 +38,10 @@ const TelemetryEnvConfig = Config.all({
3738
const makeAnalyticsService = Effect.gen(function* () {
3839
const telemetryConfig = yield* TelemetryEnvConfig.asEffect();
3940
const httpClient = yield* HttpClient.HttpClient;
41+
const serverConfig = yield* ServerConfig;
4042
const identifier = yield* getTelemetryIdentifier;
4143
const bufferRef = yield* Ref.make<ReadonlyArray<BufferedAnalyticsEvent>>([]);
44+
const clientType = serverConfig.mode === "desktop" ? "desktop-app" : "cli-web-client";
4245

4346
const enqueueBufferedEvent = (event: string, properties?: Readonly<Record<string, unknown>>) =>
4447
Effect.flatMap(DateTime.now, (now) =>
@@ -83,6 +86,7 @@ const makeAnalyticsService = Effect.gen(function* () {
8386
wsl: process.env.WSL_DISTRO_NAME,
8487
arch: process.arch,
8588
t3CodeVersion: version,
89+
clientType,
8690
},
8791
timestamp: event.capturedAt,
8892
})),

0 commit comments

Comments
 (0)