refactor(server): instrument WS RPCs in group middleware (#15548)

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Opus 5.5 authored and GitHub committed 2026-10-06 17:51:52 -07:00
1 parent 517188b3ca
commit d021f57bf3
5 files changed
+1455 -2026

No files matched your search

@@ -1,313 +1,336 @@
import { assert, describe, it } from "@effect/vitest";
import { WS_METHODS } from "@t3tools/contracts";
import {
AuthOrchestrationOperateScope,
AuthOrchestrationReadScope,
type AuthEnvironmentScope,
ScheduledTaskError,
ScheduledTaskId,
WS_METHODS,
WsRpcGroup,
} from "@t3tools/contracts";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Metric from "effect/Metric";
import * as Option from "effect/Option";
import * as Stream from "effect/Stream";
import * as Tracer from "effect/Tracer";
import * as RpcTest from "effect/rpc/RpcTest";
import * as TestClock from "effect/testing/TestClock";
import {
observeRpcEffect,
observeRpcStream,
observeRpcStreamEffect,
} from "./RpcInstrumentation.ts";
import { RPC_REQUIRED_SCOPES } from "../auth/RpcAuthorization.ts";
import * as RpcAuthorization from "../auth/RpcAuthorization.ts";
import { RpcInstrumentation, rpcInstrumentationLayer } from "./RpcInstrumentation.ts";
const hasMetricSnapshot = (
snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
id: string,
attributes: Readonly<Record<string, string>>,
) =>
snapshots.some(
(snapshot) =>
snapshot.id === id &&
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
type WsRpcMethod = keyof typeof RPC_REQUIRED_SCOPES;
/** The server group narrowed to `tags`, so a test only implements the handlers it calls. */
const groupOf = <const Tags extends ReadonlyArray<WsRpcMethod>>(...tags: Tags) =>
WsRpcGroup.omit(
...[...WsRpcGroup.requests.keys()].filter(
(tag): tag is Exclude<WsRpcMethod, Tags[number]> =>
!(tags as ReadonlyArray<string>).includes(tag),
),
).middleware(RpcInstrumentation);
/** The middleware ws.ts installs for a connection with `scopes`. */
const connectionMiddleware = (scopes: ReadonlyArray<AuthEnvironmentScope>) =>
Layer.merge(RpcAuthorization.layer(scopes), rpcInstrumentationLayer);
const readOnlyConnection = connectionMiddleware([AuthOrchestrationReadScope]);
const taskId = ScheduledTaskId.make("scheduled-task:instrumented");
const rpcSpanDefaults = { "rpc.transport": "websocket", "rpc.system": "effect-rpc" };
/** Runs a test with a fresh metric registry and a tracer that keeps every span it ends. */
const withTelemetry = <A, E, R>(
test: (ended: ReadonlyArray<Tracer.NativeSpan>) => Effect.Effect<A, E, R>,
) => {
const ended: Array<Tracer.NativeSpan> = [];
const tracer = Tracer.make({
span: (options) => {
const span = new Tracer.NativeSpan(options);
const end = span.end.bind(span);
span.end = (endTime, exit) => {
end(endTime, exit);
ended.push(span);
};
return span;
},
});
return test(ended).pipe(
Effect.scoped,
Effect.withTracer(tracer),
Effect.provideService(Metric.MetricRegistry, new Map()),
);
};
const findHistogramSnapshot = (
const rpcSpans = (ended: ReadonlyArray<Tracer.NativeSpan>) =>
ended.filter((span) => span.name.startsWith("ws.rpc."));
// RpcTest keeps Effect's own RpcServer/RpcClient spans, which ws.ts turns off with
// `disableTracing: true`. Everything else comes from the middleware or the handlers.
const appSpans = (ended: ReadonlyArray<Tracer.NativeSpan>) =>
ended.filter((span) => !/^Rpc(Server|Client)\./.test(span.name));
const exitTag = (span: Tracer.NativeSpan | undefined) =>
span?.status._tag === "Ended" ? span.status.exit._tag : undefined;
const parentSpanId = (span: Tracer.NativeSpan | undefined) =>
span?.parent._tag === "Some" ? span.parent.value.spanId : undefined;
const requestCount = (
snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
id: string,
attributes: Readonly<Record<string, string>>,
method: string,
outcome: string,
) =>
snapshots.find(
(snapshot): snapshot is Extract<Metric.Metric.Snapshot, { readonly type: "Counter" }> =>
snapshot.type === "Counter" &&
snapshot.id === "t3_rpc_requests_total" &&
snapshot.attributes?.["method"] === method &&
snapshot.attributes?.["outcome"] === outcome,
)?.state;
const requestDuration = (snapshots: ReadonlyArray<Metric.Metric.Snapshot>, method: string) =>
snapshots.find(
(snapshot): snapshot is Extract<Metric.Metric.Snapshot, { readonly type: "Histogram" }> =>
snapshot.type === "Histogram" &&
snapshot.id === id &&
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
);
snapshot.id === "t3_rpc_request_duration" &&
snapshot.attributes?.["method"] === method,
)?.state;
const collectSpanNames = <A, E, R>(
effect: Effect.Effect<A, E, R>,
): Effect.Effect<ReadonlyArray<string>, E, R> =>
Effect.gen(function* () {
const spanNames: Array<string> = [];
const tracer = Tracer.make({
span: (options) => {
const span = new Tracer.NativeSpan(options);
const end = span.end.bind(span);
span.end = (endTime, exit) => {
end(endTime, exit);
if (span.sampled) {
spanNames.push(span.name);
}
};
return span;
},
});
yield* effect.pipe(Effect.withTracer(tracer));
return spanNames;
});
describe("RpcInstrumentation", () => {
it.effect("records success metrics for unary RPC handlers", () =>
Effect.gen(function* () {
yield* observeRpcEffect("rpc.instrumentation.success", Effect.succeed("ok"), {
"rpc.aggregate": "test",
}).pipe(Effect.withSpan("rpc.instrumentation.success.span"));
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
method: "rpc.instrumentation.success",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
method: "rpc.instrumentation.success",
}),
true,
);
}),
);
it.effect("records failure outcomes for unary RPC handlers", () =>
Effect.gen(function* () {
yield* Effect.exit(
observeRpcEffect("rpc.instrumentation.failure", Effect.fail("boom"), {
"rpc.aggregate": "test",
}).pipe(Effect.withSpan("rpc.instrumentation.failure.span")),
);
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
method: "rpc.instrumentation.failure",
outcome: "failure",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
method: "rpc.instrumentation.failure",
}),
true,
);
}),
);
it.effect("records subscription activation metrics for stream RPC handlers", () =>
Effect.gen(function* () {
const events = yield* Stream.runCollect(
observeRpcStreamEffect(
"rpc.instrumentation.stream",
Effect.succeed(Stream.make("a", "b")),
{ "rpc.aggregate": "test" },
).pipe(Stream.withSpan("rpc.instrumentation.stream.span")),
);
assert.deepStrictEqual(Array.from(events), ["a", "b"]);
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
method: "rpc.instrumentation.stream",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
method: "rpc.instrumentation.stream",
}),
true,
);
}),
);
it.effect("records failure outcomes for direct stream RPC handlers during consumption", () =>
Effect.gen(function* () {
const exit = yield* Stream.runCollect(
observeRpcStream(
"rpc.instrumentation.stream.failure",
Stream.make("a").pipe(Stream.concat(Stream.fail("boom"))),
{ "rpc.aggregate": "test" },
).pipe(Stream.withSpan("rpc.instrumentation.stream.failure.span")),
).pipe(Effect.exit);
assert.equal(Exit.isFailure(exit), true);
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
method: "rpc.instrumentation.stream.failure",
outcome: "failure",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
method: "rpc.instrumentation.stream.failure",
}),
true,
);
}),
);
it.effect("records direct stream durations from nanosecond clock readings", () =>
Effect.gen(function* () {
const duration = Duration.nanos(1_500_000n);
const events = yield* Effect.gen(function* () {
const fiber = yield* Stream.runCollect(
observeRpcStream(
WS_METHODS.serverGetProcessDiagnostics,
Stream.fromEffect(Effect.sleep(duration).pipe(Effect.as("ok"))),
{
"rpc.aggregate": "test",
},
),
).pipe(Effect.forkChild);
yield* Effect.yieldNow;
yield* TestClock.adjust(duration);
return yield* Fiber.join(fiber);
}).pipe(Effect.provide(TestClock.layer()));
assert.deepStrictEqual(Array.from(events), ["ok"]);
const snapshots = yield* Metric.snapshot;
const snapshot = findHistogramSnapshot(snapshots, "t3_rpc_request_duration", {
method: WS_METHODS.serverGetProcessDiagnostics,
});
assert.equal(snapshot?.state.count, 1);
assert.equal(snapshot?.state.sum, 1.5);
}),
);
it.effect("records failure outcomes when a stream RPC effect produces a failing stream", () =>
Effect.gen(function* () {
const exit = yield* Stream.runCollect(
observeRpcStreamEffect(
"rpc.instrumentation.stream.effect.failure",
Effect.succeed(Stream.fail("boom")),
{ "rpc.aggregate": "test" },
).pipe(Stream.withSpan("rpc.instrumentation.stream.effect.failure.span")),
).pipe(Effect.exit);
assert.equal(Exit.isFailure(exit), true);
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
method: "rpc.instrumentation.stream.effect.failure",
outcome: "failure",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
method: "rpc.instrumentation.stream.effect.failure",
}),
true,
);
}),
);
it.effect("records spans for traced stream RPC handlers", () =>
Effect.gen(function* () {
const spanNames = yield* collectSpanNames(
Stream.runCollect(
observeRpcStream(
"rpc.instrumentation.traced.stream",
Stream.fromEffect(
Effect.succeed("ok").pipe(Effect.withSpan("rpc.instrumentation.traced.stream.child")),
),
{ "rpc.aggregate": "test" },
),
),
);
assert.equal(spanNames.includes("ws.rpc.rpc.instrumentation.traced.stream"), true);
assert.equal(spanNames.includes("rpc.instrumentation.traced.stream.child"), true);
}),
);
it.effect("does not create spans for disabled unary RPC handlers", () =>
Effect.gen(function* () {
const spanNames = yield* collectSpanNames(
observeRpcEffect(
WS_METHODS.serverGetTraceDiagnostics,
Effect.succeed("ok").pipe(Effect.withSpan("rpc.instrumentation.disabled.unary.child")),
{ "rpc.aggregate": "test" },
),
);
assert.deepStrictEqual(spanNames, []);
}),
);
it.effect("does not create spans for disabled direct stream RPC handlers", () =>
Effect.gen(function* () {
const spanNames = yield* collectSpanNames(
Stream.runCollect(
observeRpcStream(
WS_METHODS.serverGetTraceDiagnostics,
Stream.fromEffect(
Effect.succeed("ok").pipe(
Effect.withSpan("rpc.instrumentation.disabled.stream.child"),
describe("WS RPC instrumentation middleware", () => {
it.effect("records one span and request metric per call, including rejected calls", () =>
withTelemetry((ended) =>
Effect.gen(function* () {
const group = groupOf(
WS_METHODS.serverProbe,
WS_METHODS.scheduledTasksList,
WS_METHODS.serverRetryResourceTelemetry,
WS_METHODS.pullRequestsSubscribeRefreshes,
WS_METHODS.scheduledTasksSubscribe,
WS_METHODS.serverGetSettings,
);
const client = yield* RpcTest.makeClient(group).pipe(
Effect.provide(
Layer.mergeAll(
group.toLayerHandler(WS_METHODS.serverProbe, () =>
Effect.succeed({}).pipe(Effect.withSpan("serverProbe.child")),
),
),
{ "rpc.aggregate": "test" },
),
),
);
assert.deepStrictEqual(spanNames, []);
}),
);
it.effect("does not create spans for disabled stream effect RPC handlers", () =>
Effect.gen(function* () {
const spanNames = yield* collectSpanNames(
Stream.runCollect(
observeRpcStreamEffect(
WS_METHODS.serverGetTraceDiagnostics,
Effect.succeed(
Stream.fromEffect(
Effect.succeed("ok").pipe(
Effect.withSpan("rpc.instrumentation.disabled.stream.effect.consume"),
group.toLayerHandler(WS_METHODS.scheduledTasksList, () =>
Effect.annotateCurrentSpan({ "scheduled_task.id": taskId }).pipe(
Effect.andThen(new ScheduledTaskError({ message: "List failed." })),
),
),
).pipe(Effect.withSpan("rpc.instrumentation.disabled.stream.effect.create")),
{ "rpc.aggregate": "test" },
group.toLayerHandler(WS_METHODS.serverRetryResourceTelemetry, () =>
Effect.die("authorization let a rejected call through"),
),
group.toLayerHandler(WS_METHODS.pullRequestsSubscribeRefreshes, () =>
Stream.make(1, 2),
),
group.toLayerHandler(WS_METHODS.scheduledTasksSubscribe, () =>
Stream.concat(
Stream.make({ tasks: [] }),
Stream.fail(new ScheduledTaskError({ message: "Subscription failed." })),
),
),
group.toLayerHandler(WS_METHODS.serverGetSettings, () => Effect.die("broken")),
readOnlyConnection,
),
),
),
);
);
assert.deepStrictEqual(spanNames, []);
}),
assert.deepStrictEqual(yield* client[WS_METHODS.serverProbe]({}), {});
const listError = yield* client[WS_METHODS.scheduledTasksList]({}).pipe(Effect.flip);
assert.equal(listError._tag, "ScheduledTaskError");
// Retrying telemetry needs operate scope, so the handler must not run.
const rejection = yield* client[WS_METHODS.serverRetryResourceTelemetry]({}).pipe(
Effect.flip,
);
assert.equal(rejection._tag, "EnvironmentAuthorizationError");
const refreshes = yield* Stream.runCollect(
client[WS_METHODS.pullRequestsSubscribeRefreshes]({}),
);
assert.deepStrictEqual(Array.from(refreshes), [1, 2]);
const subscribeError = yield* Stream.runDrain(
client[WS_METHODS.scheduledTasksSubscribe]({}),
).pipe(Effect.flip);
assert.equal(subscribeError._tag, "ScheduledTaskError");
const settingsExit = yield* Effect.exit(client[WS_METHODS.serverGetSettings]({}));
assert.isTrue(Exit.hasDies(settingsExit));
assert.deepStrictEqual(
rpcSpans(ended).map((span) => [span.name, Object.fromEntries(span.attributes)]),
[
[
"ws.rpc.server.probe",
{
...rpcSpanDefaults,
"rpc.method": WS_METHODS.serverProbe,
"rpc.aggregate": "server",
},
],
[
"ws.rpc.scheduledTasks.list",
{
...rpcSpanDefaults,
"rpc.method": WS_METHODS.scheduledTasksList,
"rpc.aggregate": "scheduledTasks",
"scheduled_task.id": taskId,
},
],
[
"ws.rpc.server.retryResourceTelemetry",
{
...rpcSpanDefaults,
"rpc.method": WS_METHODS.serverRetryResourceTelemetry,
"rpc.aggregate": "server",
},
],
[
"ws.rpc.pullRequests.subscribeRefreshes",
{
...rpcSpanDefaults,
"rpc.method": WS_METHODS.pullRequestsSubscribeRefreshes,
"rpc.aggregate": "pull-requests",
},
],
[
"ws.rpc.scheduledTasks.subscribe",
{
...rpcSpanDefaults,
"rpc.method": WS_METHODS.scheduledTasksSubscribe,
"rpc.aggregate": "scheduledTasks",
},
],
[
"ws.rpc.server.getSettings",
{
...rpcSpanDefaults,
"rpc.method": WS_METHODS.serverGetSettings,
"rpc.aggregate": "server",
},
],
],
);
assert.deepStrictEqual(rpcSpans(ended).map(exitTag), [
"Success",
"Failure",
"Failure",
"Success",
"Failure",
"Failure",
]);
const probeSpan = rpcSpans(ended)[0];
const child = ended.find((span) => span.name === "serverProbe.child");
assert.equal(parentSpanId(child), probeSpan?.spanId);
const snapshots = yield* Metric.snapshot;
assert.deepStrictEqual(
[
requestCount(snapshots, WS_METHODS.serverProbe, "success"),
requestCount(snapshots, WS_METHODS.scheduledTasksList, "failure"),
requestCount(snapshots, WS_METHODS.serverRetryResourceTelemetry, "failure"),
requestCount(snapshots, WS_METHODS.pullRequestsSubscribeRefreshes, "success"),
requestCount(snapshots, WS_METHODS.scheduledTasksSubscribe, "failure"),
requestCount(snapshots, WS_METHODS.serverGetSettings, "failure"),
].map((state) => state?.count),
[1, 1, 1, 1, 1, 1],
);
for (const method of group.requests.keys()) {
assert.equal(requestDuration(snapshots, method)?.count, 1);
}
}),
),
);
it.effect("keeps a stream's span and duration open until the subscription is interrupted", () =>
withTelemetry((ended) =>
Effect.gen(function* () {
const waiting = yield* Deferred.make<void>();
const group = groupOf(WS_METHODS.pullRequestsSubscribeRefreshes);
const client = yield* RpcTest.makeClient(group).pipe(
Effect.provide(
Layer.mergeAll(
group.toLayerHandler(WS_METHODS.pullRequestsSubscribeRefreshes, () =>
Stream.concat(
Stream.make(1),
Stream.fromEffect(
Deferred.succeed(waiting, undefined).pipe(
Effect.andThen(Effect.never),
Effect.withSpan("refreshes.wait"),
),
),
),
),
readOnlyConnection,
),
),
);
// Wall and monotonic time disagree before the call starts, so a duration that mixes
// the two clocks is caught.
yield* TestClock.adjust(Duration.seconds(1));
yield* TestClock.setTime(0);
const consumer = yield* Stream.runDrain(
client[WS_METHODS.pullRequestsSubscribeRefreshes]({}),
).pipe(Effect.forkChild);
yield* Deferred.await(waiting);
yield* TestClock.adjust(Duration.millis(250));
// A backward wall-clock correction must not shorten the measured duration.
yield* TestClock.setTime(0);
assert.deepStrictEqual(appSpans(ended), []);
// The client waits for the server to stop the call, which ends the RPC span.
yield* Fiber.interrupt(consumer);
const [rpcSpan] = rpcSpans(ended);
assert.equal(rpcSpan?.name, "ws.rpc.pullRequests.subscribeRefreshes");
assert.equal(exitTag(rpcSpan), "Failure");
const waitSpan = ended.find((span) => span.name === "refreshes.wait");
assert.equal(parentSpanId(waitSpan), rpcSpan?.spanId);
const snapshots = yield* Metric.snapshot;
assert.equal(
requestCount(snapshots, WS_METHODS.pullRequestsSubscribeRefreshes, "interrupt")?.count,
1,
);
const duration = requestDuration(snapshots, WS_METHODS.pullRequestsSubscribeRefreshes);
assert.equal(duration?.count, 1);
assert.equal(duration?.sum, 250);
}),
),
);
it.effect("records metrics but no spans for methods with tracing disabled", () =>
withTelemetry((ended) =>
Effect.gen(function* () {
const group = groupOf(WS_METHODS.serverSignalProcess);
const client = yield* RpcTest.makeClient(group).pipe(
Effect.provide(
Layer.mergeAll(
group.toLayerHandler(WS_METHODS.serverSignalProcess, (input) =>
Effect.succeed({
pid: input.pid,
signal: input.signal,
signaled: true,
message: Option.none(),
}).pipe(Effect.withSpan("signalProcess.child")),
),
connectionMiddleware([AuthOrchestrationReadScope, AuthOrchestrationOperateScope]),
),
),
);
const input = { pid: 4242, startTimeMs: 0, signal: "SIGINT" } as const;
assert.equal((yield* client[WS_METHODS.serverSignalProcess](input)).signaled, true);
assert.deepStrictEqual(appSpans(ended), []);
const snapshots = yield* Metric.snapshot;
assert.equal(requestCount(snapshots, WS_METHODS.serverSignalProcess, "success")?.count, 1);
}),
),
);
});
@@ -1,14 +1,198 @@
import { WS_METHODS } from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Duration from "effect/Duration";
import { ORCHESTRATION_V2_WS_METHODS, WS_METHODS, type WsRpcGroup } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Metric from "effect/Metric";
import * as Layer from "effect/Layer";
import * as References from "effect/References";
import * as Stream from "effect/Stream";
import type * as RpcGroup from "effect/rpc/RpcGroup";
import * as RpcMiddleware from "effect/rpc/RpcMiddleware";
import { outcomeFromExit } from "./Attributes.ts";
import { metricAttributes, rpcRequestDuration, rpcRequestsTotal, withMetrics } from "./Metrics.ts";
import { rpcRequestDuration, rpcRequestsTotal, withMetrics } from "./Metrics.ts";
type WsRpcMethod = RpcGroup.Rpcs<typeof WsRpcGroup>["_tag"];
/**
* The `rpc.aggregate` span attribute of every WebSocket RPC. Trace queries and dashboards group by
* these labels, so they keep their historical values even where they differ from the method
* prefix. Adding an RPC to `WsRpcGroup` without a label is a type error.
*/
const RPC_AGGREGATES = {
[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: "orchestrationV2",
[ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: "orchestration",
[ORCHESTRATION_V2_WS_METHODS.getTurnItem]: "orchestration",
[ORCHESTRATION_V2_WS_METHODS.getTurnDiff]: "orchestration",
[ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff]: "orchestration",
[ORCHESTRATION_V2_WS_METHODS.searchThreads]: "orchestration",
[ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: "orchestration",
[ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: "orchestrationV2",
[ORCHESTRATION_V2_WS_METHODS.launchThread]: "orchestration",
[ORCHESTRATION_V2_WS_METHODS.subscribeArchivedShell]: "orchestration",
[ORCHESTRATION_V2_WS_METHODS.subscribeShell]: "orchestrationV2",
[ORCHESTRATION_V2_WS_METHODS.subscribeThread]: "orchestrationV2",
[WS_METHODS.projectsMutate]: "orchestration",
[WS_METHODS.serverProbe]: "server",
[WS_METHODS.serverGetConfig]: "server",
[WS_METHODS.serverRefreshProviders]: "server",
[WS_METHODS.serverUpdateProvider]: "server",
[WS_METHODS.providerAuthStart]: "provider",
[WS_METHODS.providerConsumeResetCredit]: "provider",
[WS_METHODS.providerAuthComplete]: "provider",
[WS_METHODS.chatGptReconnectProfile]: "provider",
[WS_METHODS.chatGptImportProfile]: "provider",
[WS_METHODS.chatGptHandoffSubscribe]: "provider",
[WS_METHODS.codexAuthCallbackSubscribe]: "provider",
[WS_METHODS.providerAuthRespond]: "provider",
[WS_METHODS.providerAuthCancel]: "provider",
[WS_METHODS.providerAuthLogout]: "provider",
[WS_METHODS.providerAuthSubscribe]: "provider",
[WS_METHODS.providerInstallStart]: "provider",
[WS_METHODS.providerInstallCancel]: "provider",
[WS_METHODS.providerInstallSubscribe]: "provider",
[WS_METHODS.providerInstallRemove]: "provider",
[WS_METHODS.serverUpdateServer]: "server",
[WS_METHODS.serverUpdateServerWithProgress]: "server",
[WS_METHODS.serverCommitDesktopUpdate]: "server",
[WS_METHODS.serverUpsertKeybinding]: "server",
[WS_METHODS.serverRemoveKeybinding]: "server",
[WS_METHODS.serverGetSettings]: "server",
[WS_METHODS.serverUpdateSettings]: "server",
[WS_METHODS.serverSearchAcpRegistry]: "server",
[WS_METHODS.serverPrepareAcpRegistryAgent]: "server",
[WS_METHODS.serverUninstallAcpRegistryManagedBinary]: "server",
[WS_METHODS.serverAcceptAcpRegistryUrlAuth]: "server",
[WS_METHODS.serverListAcpRegistrySessions]: "server",
[WS_METHODS.serverImportAcpRegistrySession]: "server",
[WS_METHODS.serverDeleteAcpRegistrySession]: "server",
[WS_METHODS.serverListAcpRegistryProviders]: "server",
[WS_METHODS.serverSetAcpRegistryProvider]: "server",
[WS_METHODS.serverDisableAcpRegistryProvider]: "server",
[WS_METHODS.serverLogoutAcpRegistry]: "server",
[WS_METHODS.serverDiscoverSourceControl]: "server",
[WS_METHODS.serverGetTraceDiagnostics]: "server",
[WS_METHODS.serverGetProcessDiagnostics]: "server",
[WS_METHODS.serverGetHostResources]: "server",
[WS_METHODS.serverGetProcessResourceHistory]: "server",
[WS_METHODS.serverGetResourceTelemetryHistory]: "server",
[WS_METHODS.serverRetryResourceTelemetry]: "server",
[WS_METHODS.serverGetUsageSummary]: "server",
[WS_METHODS.serverRefreshUsageRates]: "server",
[WS_METHODS.serverSignalProcess]: "server",
[WS_METHODS.serverReportClientActivity]: "server",
[WS_METHODS.serverReportHostPowerState]: "server",
[WS_METHODS.serverGetBackgroundPolicy]: "server",
[WS_METHODS.scheduledTasksList]: "scheduledTasks",
[WS_METHODS.scheduledTasksSubscribe]: "scheduledTasks",
[WS_METHODS.scheduledTasksUpsert]: "scheduledTasks",
[WS_METHODS.scheduledTasksSetEnabled]: "scheduledTasks",
[WS_METHODS.scheduledTasksDelete]: "scheduledTasks",
[WS_METHODS.scheduledTasksRunNow]: "scheduledTasks",
[WS_METHODS.scheduledTasksRotateWebhookToken]: "scheduledTasks",
[WS_METHODS.scheduledTasksListWebhookDeliveries]: "scheduledTasks",
[WS_METHODS.scheduledTasksGetWebhookDelivery]: "scheduledTasks",
[WS_METHODS.secretsAnswerRequest]: "secrets",
[WS_METHODS.cloudGetRelayClientStatus]: "cloud",
[WS_METHODS.cloudInstallRelayClient]: "cloud",
[WS_METHODS.pullRequestsList]: "pull-requests",
[WS_METHODS.pullRequestsListStats]: "pull-requests",
[WS_METHODS.pullRequestsSummary]: "pull-requests",
[WS_METHODS.pullRequestsRouting]: "pull-requests",
[WS_METHODS.pullRequestsRoutingIdentity]: "pull-requests",
[WS_METHODS.pullRequestsStack]: "pull-requests",
[WS_METHODS.pullRequestsLinkedThreads]: "pull-requests",
[WS_METHODS.pullRequestsDetail]: "pull-requests",
[WS_METHODS.pullRequestsPreview]: "pull-requests",
[WS_METHODS.pullRequestsChecks]: "pull-requests",
[WS_METHODS.pullRequestsActivity]: "pull-requests",
[WS_METHODS.pullRequestsThreadComments]: "pull-requests",
[WS_METHODS.pullRequestsDiffFileContents]: "pull-requests",
[WS_METHODS.pullRequestsFilesViewed]: "pull-requests",
[WS_METHODS.pullRequestsRunAction]: "pull-requests",
[WS_METHODS.pullRequestsUpdate]: "pull-requests",
[WS_METHODS.pullRequestsComment]: "pull-requests",
[WS_METHODS.pullRequestsUpdateComment]: "pull-requests",
[WS_METHODS.pullRequestsSubmitReview]: "pull-requests",
[WS_METHODS.pullRequestsReplyToThread]: "pull-requests",
[WS_METHODS.pullRequestsSetThreadResolution]: "pull-requests",
[WS_METHODS.pullRequestsSetReaction]: "pull-requests",
[WS_METHODS.pullRequestsSetFilesViewed]: "pull-requests",
[WS_METHODS.pullRequestsInvalidate]: "pull-requests",
[WS_METHODS.pullRequestsSubscribeRefreshes]: "pull-requests",
[WS_METHODS.pullRequestsReviewerCandidates]: "pull-requests",
[WS_METHODS.pullRequestsRequestReviewers]: "pull-requests",
[WS_METHODS.pullRequestsLabelCandidates]: "pull-requests",
[WS_METHODS.pullRequestsSetLabels]: "pull-requests",
[WS_METHODS.sourceControlLookupRepository]: "source-control",
[WS_METHODS.sourceControlCloneRepository]: "source-control",
[WS_METHODS.sourceControlPublishRepository]: "source-control",
[WS_METHODS.projectCloneStart]: "source-control",
[WS_METHODS.projectCloneCancel]: "source-control",
[WS_METHODS.projectCloneRetry]: "source-control",
[WS_METHODS.subscribeProjectClones]: "source-control",
[WS_METHODS.projectsListEntries]: "workspace",
[WS_METHODS.projectsReadFile]: "workspace",
[WS_METHODS.projectsSearchContents]: "workspace",
[WS_METHODS.projectsSearchEntries]: "workspace",
[WS_METHODS.projectsWriteFile]: "workspace",
[WS_METHODS.projectsEnsureScratch]: "orchestration",
[WS_METHODS.projectsCreateNew]: "orchestration",
[WS_METHODS.shellOpenInEditor]: "workspace",
[WS_METHODS.filesystemBrowse]: "workspace",
[WS_METHODS.agentSessionsScan]: "workspace",
[WS_METHODS.agentSessionsImport]: "workspace",
[WS_METHODS.assetsCreateUrl]: "workspace",
[WS_METHODS.assetsPersistChatAttachments]: "orchestration",
[WS_METHODS.attachmentsCreateUploadUrl]: "workspace",
[WS_METHODS.attachmentsDelete]: "workspace",
[WS_METHODS.providerUploadFeedback]: "provider",
[WS_METHODS.subscribeVcsStatus]: "vcs",
[WS_METHODS.subscribeWorktreeSetup]: "vcs",
[WS_METHODS.worktreeSetupCancel]: "vcs",
[WS_METHODS.subscribeResourceTelemetry]: "server",
[WS_METHODS.vcsRefreshStatus]: "vcs",
[WS_METHODS.vcsPull]: "git",
[WS_METHODS.gitRunStackedAction]: "vcs",
[WS_METHODS.gitResolvePullRequest]: "git",
[WS_METHODS.gitPreparePullRequestThread]: "git",
[WS_METHODS.vcsListRefs]: "vcs",
[WS_METHODS.vcsCreateWorktree]: "vcs",
[WS_METHODS.vcsRemoveWorktree]: "vcs",
[WS_METHODS.vcsCreateRef]: "vcs",
[WS_METHODS.vcsSwitchRef]: "vcs",
[WS_METHODS.vcsInit]: "vcs",
[WS_METHODS.reviewGetDiffPreview]: "review",
[WS_METHODS.reviewGetDiffFileContents]: "review",
[WS_METHODS.terminalOpen]: "terminal",
[WS_METHODS.terminalAttach]: "terminal",
[WS_METHODS.terminalWrite]: "terminal",
[WS_METHODS.terminalResize]: "terminal",
[WS_METHODS.terminalClear]: "terminal",
[WS_METHODS.terminalRestart]: "terminal",
[WS_METHODS.terminalClose]: "terminal",
[WS_METHODS.subscribeTerminalEvents]: "terminal",
[WS_METHODS.subscribeTerminalMetadata]: "terminal",
[WS_METHODS.previewOpen]: "preview",
[WS_METHODS.previewNavigate]: "preview",
[WS_METHODS.previewResize]: "preview",
[WS_METHODS.previewAdjust]: "preview",
[WS_METHODS.previewRefresh]: "preview",
[WS_METHODS.previewClose]: "preview",
[WS_METHODS.previewList]: "preview",
[WS_METHODS.previewClearProfile]: "preview",
[WS_METHODS.previewReportStatus]: "preview",
[WS_METHODS.subscribePreviewEvents]: "preview",
[WS_METHODS.subscribeDiscoveredLocalServers]: "preview",
[WS_METHODS.deviceConfigure]: "device",
[WS_METHODS.deviceTestHost]: "device",
[WS_METHODS.deviceList]: "device",
[WS_METHODS.deviceOpen]: "device",
[WS_METHODS.deviceClose]: "device",
[WS_METHODS.deviceShutdown]: "device",
[WS_METHODS.deviceDetail]: "device",
[WS_METHODS.deviceAction]: "device",
[WS_METHODS.subscribeDeviceState]: "device",
[WS_METHODS.subscribeServerConfig]: "server",
[WS_METHODS.subscribeServerLifecycle]: "server",
[WS_METHODS.subscribeAuthAccess]: "auth",
[WS_METHODS.subscribeBackgroundPolicy]: "server",
} as const satisfies Readonly<Record<WsRpcMethod, string>>;
const RPC_SPAN_PREFIX = "ws.rpc";
const DEFAULT_RPC_SPAN_ATTRIBUTES = {
@@ -22,117 +206,36 @@ const RPC_METHODS_WITH_TRACING_DISABLED: ReadonlySet<string> = new Set([
WS_METHODS.serverSignalProcess,
]);
function shouldTraceRpc(method: string): boolean {
return !RPC_METHODS_WITH_TRACING_DISABLED.has(method);
}
/**
* Records each WebSocket RPC's span and request metrics. `ws.ts` adds it to the server's group
* after `RpcScopeAuthorization`, so it wraps authorization and also records rejected calls.
*/
export class RpcInstrumentation extends RpcMiddleware.Service<RpcInstrumentation>()(
"t3/server/RpcInstrumentation",
) {}
const rpcSpanAttributes = (
method: string,
traceAttributes?: Readonly<Record<string, unknown>>,
): Record<string, unknown> => ({
...DEFAULT_RPC_SPAN_ATTRIBUTES,
"rpc.method": method,
...traceAttributes,
});
/**
* Wraps each WebSocket RPC call in its `ws.rpc.<method>` span and records its request counter and
* duration. For a stream RPC, the middleware receives the whole stream run, so the span and the
* metrics cover the subscription until it ends, fails, or is interrupted. Methods in
* `RPC_METHODS_WITH_TRACING_DISABLED` record metrics but no spans, for the call or anything it runs.
*/
export const rpcInstrumentationLayer = Layer.succeed(RpcInstrumentation)((effect, { rpc }) => {
const method = rpc._tag;
const measured = effect.pipe(
withMetrics({ counter: rpcRequestsTotal, timer: rpcRequestDuration, attributes: { method } }),
);
const withRpcEffectTracing = <A, E, R>(
method: string,
effect: Effect.Effect<A, E, R>,
traceAttributes?: Readonly<Record<string, unknown>>,
): Effect.Effect<A, E, R> =>
shouldTraceRpc(method)
? effect.pipe(
Effect.withSpan(`${RPC_SPAN_PREFIX}.${method}`, {
attributes: rpcSpanAttributes(method, traceAttributes),
}),
)
: effect.pipe(Effect.provideService(References.TracerEnabled, false));
const withRpcStreamTracing = <A, E, R>(
method: string,
stream: Stream.Stream<A, E, R>,
traceAttributes?: Readonly<Record<string, unknown>>,
): Stream.Stream<A, E, R> =>
shouldTraceRpc(method)
? stream.pipe(
Stream.withSpan(`${RPC_SPAN_PREFIX}.${method}`, {
attributes: rpcSpanAttributes(method, traceAttributes),
}),
)
: stream.pipe(Stream.provideService(References.TracerEnabled, false));
const recordRpcStreamMetrics = <E>(
method: string,
startedAt: bigint,
exit: Exit.Exit<unknown, E>,
): Effect.Effect<void, never, never> =>
Effect.gen(function* () {
yield* Metric.update(
Metric.withAttributes(rpcRequestDuration, metricAttributes({ method })),
Duration.nanos((yield* Clock.monotonicTimeNanos) - startedAt),
);
yield* Metric.update(
Metric.withAttributes(
rpcRequestsTotal,
metricAttributes({
method,
outcome: outcomeFromExit(exit),
}),
),
1,
);
});
export const observeRpcEffect = <A, E, R>(
method: string,
effect: Effect.Effect<A, E, R>,
traceAttributes?: Readonly<Record<string, unknown>>,
): Effect.Effect<A, E, R> => {
const instrumented = effect.pipe(
withMetrics({
counter: rpcRequestsTotal,
timer: rpcRequestDuration,
if (RPC_METHODS_WITH_TRACING_DISABLED.has(method)) {
return measured.pipe(Effect.provideService(References.TracerEnabled, false));
}
return measured.pipe(
Effect.withSpan(`${RPC_SPAN_PREFIX}.${method}`, {
attributes: {
method,
...DEFAULT_RPC_SPAN_ATTRIBUTES,
"rpc.method": method,
"rpc.aggregate": RPC_AGGREGATES[method as WsRpcMethod],
},
}),
);
return withRpcEffectTracing(method, instrumented, traceAttributes);
};
export const observeRpcStream = <A, E, R>(
method: string,
stream: Stream.Stream<A, E, R>,
traceAttributes?: Readonly<Record<string, unknown>>,
): Stream.Stream<A, E, R> => {
const instrumented = Stream.unwrap(
Effect.gen(function* () {
const startedAt = yield* Clock.monotonicTimeNanos;
return stream.pipe(Stream.onExit((exit) => recordRpcStreamMetrics(method, startedAt, exit)));
}),
);
return withRpcStreamTracing(method, instrumented, traceAttributes);
};
export const observeRpcStreamEffect = <A, StreamError, StreamContext, EffectError, EffectContext>(
method: string,
effect: Effect.Effect<Stream.Stream<A, StreamError, StreamContext>, EffectError, EffectContext>,
traceAttributes?: Readonly<Record<string, unknown>>,
): Stream.Stream<A, StreamError | EffectError, StreamContext | EffectContext> => {
const instrumented = Stream.unwrap(
Effect.gen(function* () {
const startedAt = yield* Clock.monotonicTimeNanos;
// onError also runs when the stream is interrupted before it is produced.
const stream = yield* effect.pipe(
Effect.onError((cause) => recordRpcStreamMetrics(method, startedAt, Exit.failCause(cause))),
);
return stream.pipe(
Stream.onExit((streamExit) => recordRpcStreamMetrics(method, startedAt, streamExit)),
);
}),
);
return withRpcStreamTracing(method, instrumented, traceAttributes);
};
});
+915 -1614
View File
File diff suppressed because it is too large. Load diff
+9 -7
View File
@@ -24,15 +24,17 @@ message) are fine next to the service; the capability itself is the method.
```ts
// ws.ts: a thin handler
[WS_METHODS.projectsCreateNew]: (input) =>
observeRpcEffect(
WS_METHODS.projectsCreateNew,
projectFolders.createNamedProject(input).pipe(
Effect.mapError((cause) => new ProjectCreateNewError({ cause })),
),
{ "rpc.aggregate": "orchestration" },
),
projectFolders
.createNamedProject(input)
.pipe(Effect.mapError((cause) => new ProjectCreateNewError({ cause }))),
```
Handlers don't add their own spans or request metrics. Group middleware authorizes every call
([`RpcAuthorization.ts`](../../apps/server/src/auth/RpcAuthorization.ts)), and the server's group
also instruments it
([`RpcInstrumentation.ts`](../../apps/server/src/observability/RpcInstrumentation.ts)). A handler
with per-call context, such as a thread id, adds it with `Effect.annotateCurrentSpan`.
## Shape of a service module
One module per service, in this order: imports, errors and schemas, the `Context.Service` tag with
+2 -2
View File
@@ -635,8 +635,8 @@ wins for its signal. `otlp` is the default, and any other exporter name, such as
Current high-value span and metric boundaries include:
- Effect RPC websocket request spans from `effect/rpc`
- RPC request metrics in `apps/server/src/observability/RpcInstrumentation.ts`
- WebSocket RPC request spans (`ws.rpc.<method>`) and metrics in
`apps/server/src/observability/RpcInstrumentation.ts`
- startup phases
- orchestration command processing
- provider session and turn operations