feat(scripts): server metrics attach real clients and time a reconnect storm #41281
Mergedjuliusmarmingemerged 8 commits into
perf/server-metrics-busy fromrefs/pull/41281/headmerged by juliusmarminge View on GitHubtanstack-source added labelsfeature
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- @@ -1019,3 +1118,21 @@10191118 }),10201119 );10211120 }1121+ if (wanted("clients")) {1122+ yield* withServer("clients", (server) =>1123+ Effect.gen(function* () {1124+ const token = yield* server.issueToken;1125+ const most = Math.max(STORM_CLIENTS, ...options.threads);1126+ const threads = yield* openThreads(server, 0, most);1127+ const attached: Record<string, Window> = {};1128+ for (const count of options.threads) {1129+ yield* Effect.scoped(1130+ Effect.gen(function* () {1131+ yield* attachClient(server, token, threads.slice(0, count));1132+ yield* Effect.sleep(Duration.seconds(10));1133+ attached[`${count}`] = yield* server.measure(30);1134+ }),1135+ );1136+ }1137+ // Every client holds the shell, VCS status and one thread, then all drop and come back.1138+ const clients = yield* Effect.forEach(threads.slice(0, STORM_CLIENTS), () => Scope.make());
Pushed59ab82f
- @@ -1008,0 +1028,21 @@1028+) {1029+ const http = yield* HttpClient.HttpClient;1030+ const ticketResponse = yield* http.execute(1031+ HttpClientRequest.post(`${server.origin}/api/auth/websocket-ticket`).pipe(1032+ HttpClientRequest.bearerToken(token),1033+ ),1034+ );1035+ const { ticket } = yield* decodeJson(Schema.Struct({ ticket: Schema.String }))(1036+ yield* ticketResponse.text,1037+ );1038+ const protocol = yield* Layer.build(1039+ RpcClient.layerProtocolSocket().pipe(1040+ Layer.provide(1041+ Socket.layerWebSocket(1042+ `${server.origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`,1043+ ),1044+ ),1045+ Layer.provide(RpcSerialization.layerJson),1046+ ),1047+ );1048+ const client = yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));@@ -1008,0 +1039,21 @@1039+ RpcClient.layerProtocolSocket().pipe(1040+ Layer.provide(1041+ Socket.layerWebSocket(1042+ `${server.origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`,1043+ ),1044+ ),1045+ Layer.provide(RpcSerialization.layerJson),1046+ ),1047+ );1048+ const client = yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));1049+ const ready = Effect.fn("serverMetrics.subscription")(function* <A, E, R>(1050+ stream: Stream.Stream<A, E, R>,1051+ isReady: (item: A) => boolean,1052+ ) {1053+ const synchronized = yield* Deferred.make<void, MetricsError>();1054+ yield* stream.pipe(1055+ Stream.runForEach((item) =>1056+ isReady(item) ? Deferred.succeed(synchronized, undefined) : Effect.void,1057+ ),1058+ Effect.catchCause(() =>1059+ Deferred.fail(synchronized, new MetricsError({ message: "a subscription failed" })),
Pushed0cd4cf2
- @@ -1024,0 +1070,21 @@1070+ isReady: (item: A) => boolean,1071+ ) {1072+ const synchronized = yield* Deferred.make<void, MetricsError>();1073+ const lose = (message: string) =>1074+ Ref.update(lost, (first) => first ?? message).pipe(1075+ Effect.andThen(Deferred.fail(synchronized, new MetricsError({ message }))),1076+ );1077+ yield* stream.pipe(1078+ Stream.runForEach((item) =>1079+ isReady(item) ? Deferred.succeed(synchronized, undefined) : Effect.void,1080+ ),1081+ Effect.andThen(lose("a subscription ended")),1082+ Effect.catchCause(() => lose("a subscription failed")),1083+ Effect.forkScoped,1084+ );1085+ return Deferred.await(synchronized);1086+ });1087+ // Reports presence the way the web client does, so work held for an active client runs.1088+ const clientId = `bench-${yield* Random.nextIntBetween(0, 1_000_000_000)}`;1089+ const report = Effect.gen(function* () {1090+ yield* client["server.reportClientActivity"]({@@ -1135,0 +1281,21 @@1281+ attached[`${count}`] = yield* server.measure(30);1282+ yield* client.healthy;1283+ }),1284+ );1285+ }1286+ // Each client gets its own scope so the storm can drop them on cue; the server's scope1287+ // still closes any left open when a step fails or is interrupted.1288+ const clientScope = Effect.acquireRelease(Scope.make(), (scope, exit) =>1289+ Scope.close(scope, exit),1290+ );1291+ // Every client holds the shell, VCS status and one thread, then all drop and come back.1292+ const clients = yield* Effect.forEach(threads.slice(0, STORM_CLIENTS), () => clientScope);1293+ const first = yield* Effect.forEach(1294+ clients,1295+ (scope, index) =>1296+ attachClient(server, token, threads.slice(index, index + 1)).pipe(Scope.provide(scope)),1297+ { concurrency: "unbounded" },1298+ );1299+ yield* Effect.sleep(Duration.seconds(10));1300+ yield* Effect.forEach(first, (client) => client.healthy, { discard: true });1301+ yield* server.loopStart;
Pushedbd75fb4
- @@ -1044,2 +1055,20 @@104410551045-const SCENARIOS = ["startup", "rest", "firstWord", "quiet", "streaming", "busy"] as const;1056+/**1057+ * One client over the real WebSocket RPC, signed in like a paired device, holding the1058+ * subscriptions a web client opens: the shell, VCS status of the project, and the given threads.1059+ * Succeeds once every subscription has delivered its snapshot.1060+ */1061+const attachClient = Effect.fn("serverMetrics.attachClient")(function* (1062+ server: Server,1063+ token: string,1064+ threadIds: ReadonlyArray<string>,1065+) {1066+ const http = yield* HttpClient.HttpClient;1067+ const ticketResponse = yield* http.execute(1068+ HttpClientRequest.post(`${server.origin}/api/auth/websocket-ticket`).pipe(1069+ HttpClientRequest.bearerToken(token),1070+ ),1071+ );1072+ const { ticket } = yield* decodeJson(Schema.Struct({ ticket: Schema.String }))(1073+ yield* ticketResponse.text,1074+ );@@ -1045,0 +1113,21 @@1113+ clientKind: "web",1114+ visible: true,1115+ focused: true,1116+ recentlyInteracted: true,1117+ appState: "active",1118+ scopes: [{ type: "provider-status" }, { type: "vcs-status", cwd: server.project }],1119+ ttlMs: 45_000,1120+ observedAt: yield* DateTime.now,1121+ });1122+ }).pipe(1123+ // A server that keeps the socket open but never answers would otherwise hang the scenario.1124+ Effect.timeoutOrElse({1125+ duration: Duration.seconds(15),1126+ orElse: () => new MetricsError({ message: "an activity report got no answer" }),1127+ }),1128+ );1129+ yield* report;1130+ yield* report.pipe(1131+ Effect.delay(Duration.seconds(25)),1132+ Effect.forever,1133+ Effect.catchCause(() => Ref.update(lost, (first) => first ?? "an activity report failed")),
Sign in to join this conversation.
Note
Reviews paused#
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review.
Walkthrough
The benchmark adds measurements for quiet windows with attached clients and for 20 clients disconnecting and reconnecting. The report schema records client counts, resubscription time, and event-loop delay measurements.
Changes: Client connection measurements
scripts/server-metrics-report.ts,scripts/server-metrics.tsscripts/server-metrics.ts,scripts/server-metrics-report.tsclientsscenario measures quiet windows at different client counts and reconnect behavior for 20 clients. Metric comparison skipsclients.storm.clients.Estimated code review effort: 3 (Moderate) | ~20 minutes
Change: Feature
Sequence Diagram(s)#
Possibly related PRs
Suggested reviewers:
macroscopeappMerge Risk:
Low · previous review
3cc35This adds a client-attach and reconnect-storm scenario to the server metrics benchmark. It is maintainer tooling only and has no production impact. One minor weakness remains: if the server is very slow to answer the first activity report, the first renewal can come after the lease expires. An attached-client window could then slightly under-report policy-gated work. This is a narrow edge case and is safe to merge, with a possible follow-up to schedule the first renewal from the initial send.
Pre-merge checks:
4
Full details: Title check
Explanation
The title names the two main changes: the server metrics script now attaches real clients, and it times a reconnect storm. It follows the conventional commit format and matches the changeset, which adds the attached-client scenario and the 20-client storm measurement to scripts/server-metrics.ts and scripts/server-metrics-report.ts.
Full details: Description check
Explanation
The description follows the template well. It has Problem, Change, Scope, and Verification sections. The Problem section states the expected behavior. The Change section lists the client flow and both scenarios. The Scope section explains why no issue is linked and names the requesting maintainer. Verification gives the check command, the untested platforms, and measured results in tables. Two template items are weak. The Scope section does not link an issue. The Problem section does not include reproduction steps. The agent attribution at the end is present, as the template requests.
Finishing Touches
Generate unit tests (beta)
a391fc95-1d4f-480c-a074-bcbc128a94c6Reviewing files that changed from the base of the PR and between bd75fb40249baa03aec1474845ce56dca205242a and 3cc35c5fa46f8b35aa641ce8f23b593e0320df81.
scripts/server-metrics.tsIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.