Skip to content
TypeScript

fix(client-runtime): connection attempts record their outcome and failure reason (#22081)

Julius Marmingee45ddea067e8
diff --git a/packages/client-runtime/src/connection/supervisor.test.ts b/packages/client-runtime/src/connection/supervisor.test.ts
index e5556ab8473..8b51e10c0f4 100644
--- a/packages/client-runtime/src/connection/supervisor.test.ts
+++ b/packages/client-runtime/src/connection/supervisor.test.ts
@@ -1,8 +1,10 @@
import { AuthStandardClientScopes, EnvironmentId, type ServerConfig } from "@t3tools/contracts";
import { RelayClientTracer } from "@t3tools/shared/relayTracing";
import { describe, expect, it } from "@effect/vitest";
+import * as Cause from "effect/Cause";
import * as Deferred from "effect/Deferred";
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 Random from "effect/Random";
@@ -294,7 +296,7 @@ describe("retryDelayMs", () => {
});
describe("EnvironmentSupervisor", () => {
- it.effect("exports each relay setup as a standalone linked trace that ends at readiness", () =>
+ it.effect("exports each relay setup as a standalone linked trace with its outcome", () =>
Effect.gen(function* () {
const spans: Array<Tracer.NativeSpan> = [];
const tracer = Tracer.make({
@@ -308,9 +310,10 @@ describe("EnvironmentSupervisor", () => {
return span;
},
});
+ const firstFailure = transient();
const harness = yield* makeHarness({
- prepare: (attempt) =>
- attempt === 1 ? Effect.fail(transient()) : Effect.succeed(PREPARED_CONNECTION),
+ prepare: (attempt, target) =>
+ attempt === 1 ? Effect.fail(firstFailure) : Effect.succeed(preparedFor(target)),
});
const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
initiallyDesired: true,
@@ -334,6 +337,23 @@ describe("EnvironmentSupervisor", () => {
expect(attempts[0]?.traceId).not.toBe(attempts[1]?.traceId);
expect(attempts[1]?.links.map((link) => link.span.spanId)).toContain(attempts[0]?.spanId);
expect(yield* Ref.get(harness.releaseCount)).toBe(0);
+
+ const [failed, connected] = attempts;
+ // The exporter derives the status message from the failure, so it must
+ // be the connection error rather than a wrapper object.
+ const failedExit = failed?.status._tag === "Ended" ? failed.status.exit : undefined;
+ expect(failedExit && Exit.isFailure(failedExit) ? Cause.squash(failedExit.cause) : null).toBe(
+ firstFailure,
+ );
+ expect(Object.fromEntries(failed?.attributes ?? [])).toMatchObject({
+ "connection.outcome": "failed",
+ "connection.failure.tag": "ConnectionTransientError",
+ "connection.failure.reason": "transport",
+ });
+ expect(Object.fromEntries(connected?.attributes ?? [])).toMatchObject({
+ "connection.outcome": "connected",
+ "connection.route": "relay",
+ });
}).pipe(Effect.provide(TestClock.layer())),
);
diff --git a/packages/client-runtime/src/connection/supervisor.ts b/packages/client-runtime/src/connection/supervisor.ts
index 4d13ddf9f89..c8ec9dd2bd5 100644
--- a/packages/client-runtime/src/connection/supervisor.ts
+++ b/packages/client-runtime/src/connection/supervisor.ts
@@ -32,6 +32,7 @@ import { NETWORK_BLOCKING_HINT } from "../errors/network.ts";
import * as ConnectionWakeups from "./wakeups.ts";
import {
connectionRouteId,
+ connectionRouteKind,
connectionRoutes,
entryWithRoutes,
type ReportedEndpoint,
@@ -405,6 +406,34 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
);
});
+ // Low-cardinality dimensions for time-to-connected dashboards; the error
+ // detail stays in the span status, never in an attribute.
+ const annotateAttemptOutcome = Effect.fnUntraced(function* (
+ exit: Exit.Exit<ConnectionDriver.EnvironmentConnectionLease, ConnectionAttemptError>,
+ ) {
+ if (Exit.isSuccess(exit)) {
+ const leaseTarget = exit.value.prepared.target;
+ const route = (yield* currentRoutes).find(
+ (candidate) => connectionRouteId(candidate.target) === connectionRouteId(leaseTarget),
+ );
+ return yield* Effect.annotateCurrentSpan({
+ "connection.outcome": "connected",
+ "connection.route": connectionRouteKind(
+ route ?? { target: leaseTarget, profile: Option.none() },
+ ),
+ });
+ }
+ if (Cause.hasInterruptsOnly(exit.cause)) {
+ return yield* Effect.annotateCurrentSpan("connection.outcome", "interrupted");
+ }
+ const failure = exit.cause.reasons.find(Cause.isFailReason)?.error;
+ yield* Effect.annotateCurrentSpan({
+ "connection.outcome": "failed",
+ "connection.failure.tag": failure?._tag ?? "defect",
+ "connection.failure.reason": failure?.reason ?? "defect",
+ });
+ });
+
const traceRelayEstablishment = (
effect: Effect.Effect<
ConnectionDriver.EnvironmentConnectionLease,
@@ -415,8 +444,12 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
generation: number,
pendingRetry: Option.Option<PendingRetryTrace>,
) => {
+ // The span must end with the ConnectionAttemptError itself: the exporter
+ // can only describe an Error-like failure, and a TracedAttemptFailure
+ // wrapper reached it as "[object Object]". The wrapper is added outside.
+ let attemptSpan = Option.none<Tracer.Span>();
const traced = Effect.gen(function* () {
- const attemptSpan = yield* Effect.currentSpan.pipe(Effect.orDie);
+ attemptSpan = Option.some(yield* Effect.currentSpan.pipe(Effect.orDie));
yield* annotateTarget(target);
yield* Effect.annotateCurrentSpan({
"connection.attempt": attempt,
@@ -426,13 +459,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
onSome: (retry) => retry.failureCount,
}),
});
- const lease = yield* effect.pipe(
- Effect.mapError((error): TracedAttemptFailure => ({
- error,
- attemptSpan: Option.some(attemptSpan),
- })),
- );
- return { attemptSpan: Option.some(attemptSpan), lease };
+ return yield* effect.pipe(Effect.onExit(annotateAttemptOutcome));
}).pipe(Effect.withSpan("relay.connection.attempt", { root: true }));
return Option.match(pendingRetry, {
@@ -444,7 +471,11 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
"connection.retry.reason": retry.reason,
}),
),
- }).pipe(withRelayClientTracing);
+ }).pipe(
+ Effect.map((lease) => ({ attemptSpan, lease })),
+ Effect.mapError((error): TracedAttemptFailure => ({ error, attemptSpan })),
+ withRelayClientTracing,
+ );
};
const establishTracedConnection = Effect.fnUntraced(function* (
diff --git a/packages/client-runtime/src/rpc/session.ts b/packages/client-runtime/src/rpc/session.ts
index d6368980ac8..2bf48cdde05 100644
--- a/packages/client-runtime/src/rpc/session.ts
+++ b/packages/client-runtime/src/rpc/session.ts
@@ -214,6 +214,14 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* (
const protocolContext = yield* Layer.build(layerProtocol).pipe(
Effect.withSpan("environment.websocket.connect"),
);
+ // Building the protocol only starts the socket; this span times the
+ // handshake up to the first open, without making `connect` wait for it.
+ yield* Deferred.await(connected).pipe(
+ Effect.raceFirst(Deferred.await(disconnected)),
+ Effect.withSpan("environment.websocket.open"),
+ Effect.ignore,
+ Effect.forkScoped,
+ );
const protocolClient = yield* makeWsRpcProtocolClient.pipe(Effect.provide(protocolContext));
const initialConfigDeferred = yield* Deferred.make<ServerConfig>();
const serverConfigExit = yield* Deferred.make<void, ServerConfigSubscriptionError>();