GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(client-runtime): reconnects back off with jitter and keep healthy… · pingdotgg/t3code@9333509

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps/server/src/telemetry
    • AnalyticsService.test.ts
    • AnalyticsService.ts
  • docs/internals
    • connection-runtime.md
    • product-analytics.md
  • packages/client-runtime/src
    • connection
      • registry.test.ts
      • supervisor.test.ts
      • supervisor.ts
      • wakeups.ts
    • state
      • server.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

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

Copy file name to clipboardExpand all lines: apps/server/src/telemetry/AnalyticsService.test.ts
+83Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@ import { assert, it } from "@effect/vitest";
44
import * as ConfigProvider from "effect/ConfigProvider";
55
import * as Effect from "effect/Effect";
66
import * as Layer from "effect/Layer";
7+
import * as Schema from "effect/Schema";
8+
import * as TestClock from "effect/testing/TestClock";
9+
import * as HttpClient from "effect/unstable/http/HttpClient";
10+
import * as HttpClientError from "effect/unstable/http/HttpClientError";
711
import * as HttpServer from "effect/unstable/http/HttpServer";
812
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
913
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
@@ -46,7 +50,86 @@ interface RecordedBatchBody {
4650
}>;
4751
}
4852

53+
const SentBatch = Schema.fromJsonString(
54+
Schema.Struct({
55+
batch: Schema.Array(Schema.Struct({ uuid: Schema.String })),
56+
}),
57+
);
58+
59+
/**
60+
* HTTP client that reads each batch, then fails as if the connection dropped
61+
* before the response arrived. PostHog stores these batches, so the server
62+
* must not send them forever.
63+
*/
64+
const acceptThenFailClient = (batches: Array<ReadonlyArray<{ readonly uuid: string }>>) =>
65+
Layer.succeed(
66+
HttpClient.HttpClient,
67+
HttpClient.make((request) =>
68+
Effect.gen(function* () {
69+
if (request.body._tag === "Uint8Array") {
70+
const body = yield* Schema.decodeEffect(SentBatch)(
71+
new TextDecoder().decode(request.body.body),
72+
).pipe(Effect.orDie);
73+
batches.push(body.batch);
74+
}
75+
return yield* new HttpClientError.HttpClientError({
76+
reason: new HttpClientError.TransportError({ request, cause: "connection reset" }),
77+
});
78+
}),
79+
),
80+
);
81+
82+
it("retryDelayMs doubles from 2s and stays under the 5 minute cap", () => {
83+
assert.equal(AnalyticsService.retryDelayMs(1, 0), 1_000);
84+
assert.equal(AnalyticsService.retryDelayMs(2, 0.999_999), 4_000);
85+
assert.equal(AnalyticsService.retryDelayMs(30, 0), 150_000);
86+
assert.equal(AnalyticsService.retryDelayMs(30, 0.999_999), 300_000);
87+
});
88+
4989
it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
90+
it.effect("a batch that keeps failing is retried with backoff, then dropped", () =>
91+
Effect.gen(function* () {
92+
const batches: Array<ReadonlyArray<{ readonly uuid: string }>> = [];
93+
const runtimeLayer = AnalyticsService.layer.pipe(
94+
Layer.provideMerge(
95+
ServerConfig.ServerConfig.layerTest(process.cwd(), { prefix: "t3-telemetry-retry-" }),
96+
),
97+
Layer.provide(
98+
ConfigProvider.layer(
99+
ConfigProvider.fromUnknown({
100+
T3CODE_TELEMETRY_ENABLED: true,
101+
T3CODE_POSTHOG_KEY: "phc_test_key",
102+
T3CODE_POSTHOG_HOST: "http://localhost",
103+
}),
104+
),
105+
),
106+
Layer.provide(
107+
Layer.mergeAll(
108+
Layer.succeed(HostProcessPlatform, "win32"),
109+
Layer.succeed(HostProcessArchitecture, "x64"),
110+
acceptThenFailClient(batches),
111+
),
112+
),
113+
);
114+
115+
yield* Effect.gen(function* () {
116+
const analytics = yield* AnalyticsService.AnalyticsService;
117+
for (let index = 0; index < 20; index += 1) {
118+
yield* analytics.record("test.retry", { index });
119+
}
120+
// Before the fix this loop sent the batch about once a second.
121+
for (let second = 0; second < 600; second += 1) {
122+
yield* TestClock.adjust("1 second");
123+
}
124+
}).pipe(Effect.provide(runtimeLayer));
125+
126+
assert.equal(batches.length, 5);
127+
const uuids = batches.map((batch) => batch.map((event) => event.uuid).join(","));
128+
assert.equal(new Set(uuids).size, 1, "every retry carries the same uuids");
129+
assert.equal(new Set(batches[0]?.map((event) => event.uuid)).size, 20);
130+
}),
131+
);
132+
50133
it.effect("flush drains all buffered events across multiple batches", () =>
51134
Effect.gen(function* () {
52135
const capturedRequests: Array<RecordedBatchRequest> = [];
Collapse file

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

Copy file name to clipboardExpand all lines: apps/server/src/telemetry/AnalyticsService.ts
+103-21Lines changed: 103 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,27 @@
22
* Anonymous PostHog telemetry service.
33
*
44
* Persists an installation-scoped anonymous identifier, buffers events in
5-
* memory, and flushes batches over Effect's HTTP client.
5+
* memory, and flushes batches over Effect's HTTP client. A failed batch is
6+
* retried with backoff and dropped after a few tries. Each event carries a
7+
* uuid, so PostHog can tell a retried copy from a new event.
68
*
79
* @module AnalyticsService
810
*/
911
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
1012
import type { ClientOs } from "@t3tools/contracts";
13+
import * as Clock from "effect/Clock";
1114
import * as Config from "effect/Config";
1215
import * as Context from "effect/Context";
16+
import * as Crypto from "effect/Crypto";
1317
import * as DateTime from "effect/DateTime";
1418
import * as Effect from "effect/Effect";
19+
import * as Exit from "effect/Exit";
1520
import * as Layer from "effect/Layer";
1621
import * as Option from "effect/Option";
22+
import * as Random from "effect/Random";
1723
import * as Ref from "effect/Ref";
24+
import * as Result from "effect/Result";
25+
import * as Semaphore from "effect/Semaphore";
1826
import * as HttpClient from "effect/unstable/http/HttpClient";
1927
import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
2028
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
@@ -24,11 +32,40 @@ import * as ServerConfig from "../config.ts";
2432
import { getTelemetryIdentifier } from "./Identify.ts";
2533

2634
interface BufferedAnalyticsEvent {
35+
readonly uuid: string;
2736
readonly event: string;
2837
readonly properties?: Readonly<Record<string, unknown>>;
2938
readonly capturedAt: string;
3039
}
3140

41+
interface DeliveryState {
42+
/** Batch that failed last. It is sent again before newer events. */
43+
readonly failedBatch: ReadonlyArray<BufferedAnalyticsEvent>;
44+
/** Failed sends of `failedBatch`. */
45+
readonly batchAttempts: number;
46+
/** Failed sends since the last success. Sets the backoff delay. */
47+
readonly failures: number;
48+
/** The background flush does not send before this time (epoch ms). */
49+
readonly retryAt: number;
50+
}
51+
52+
const FLUSH_INTERVAL_MS = 1_000;
53+
// A hung send would hold the flush lock, and with it the shutdown flush.
54+
const SEND_TIMEOUT = "10 seconds";
55+
const MAX_BATCH_ATTEMPTS = 5;
56+
const RETRY_BASE_DELAY_MS = 2_000;
57+
const RETRY_MAX_DELAY_MS = 300_000;
58+
59+
/**
60+
* Delay before the next send after `failures` consecutive failed sends. The
61+
* ceiling doubles from 2s up to 5 minutes, and the delay is a random point in
62+
* its upper half. `random` is in [0, 1).
63+
*/
64+
export function retryDelayMs(failures: number, random: number): number {
65+
const ceiling = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** (failures - 1));
66+
return Math.round(ceiling / 2 + (ceiling / 2) * random);
67+
}
68+
3269
const TelemetryEnvConfig = Config.all({
3370
posthogKey: Config.String("T3CODE_POSTHOG_KEY").pipe(
3471
Config.withDefault("phc_XOWci4oZP4VvLiEyrFqkFjP4CZn55mjYYBMREK5Wd6m"),
@@ -88,17 +125,31 @@ export const make = Effect.gen(function* () {
88125
const httpClient = yield* HttpClient.HttpClient;
89126
const serverConfig = yield* ServerConfig.ServerConfig;
90127
const identifier = yield* getTelemetryIdentifier;
128+
const crypto = yield* Crypto.Crypto;
91129
const bufferRef = yield* Ref.make<ReadonlyArray<BufferedAnalyticsEvent>>([]);
130+
const deliveryRef = yield* Ref.make<DeliveryState>({
131+
failedBatch: [],
132+
batchAttempts: 0,
133+
failures: 0,
134+
retryAt: 0,
135+
});
136+
// The background flush and the shutdown flush must not send the same batch at once.
137+
const flushLock = yield* Semaphore.make(1);
92138
const clientType = serverConfig.mode === "desktop" ? "desktop-app" : "cli-web-client";
93139
const hostPlatform = yield* HostProcessPlatform;
94140
const hostArchitecture = yield* HostProcessArchitecture;
95141

96-
const enqueueBufferedEvent = (event: string, properties?: Readonly<Record<string, unknown>>) =>
142+
const enqueueBufferedEvent = (
143+
uuid: string,
144+
event: string,
145+
properties?: Readonly<Record<string, unknown>>,
146+
) =>
97147
Effect.flatMap(DateTime.now, (now) =>
98148
Ref.modify(bufferRef, (current) => {
99149
const appended = [
100150
...current,
101151
{
152+
uuid,
102153
event,
103154
...(properties ? { properties } : {}),
104155
capturedAt: DateTime.formatIso(now),
@@ -128,6 +179,7 @@ export const make = Effect.gen(function* () {
128179
const payload = {
129180
api_key: telemetryConfig.posthogKey,
130181
batch: events.map((event) => ({
182+
uuid: event.uuid,
131183
event: event.event,
132184
distinct_id: identifier,
133185
properties: {
@@ -152,39 +204,69 @@ export const make = Effect.gen(function* () {
152204
HttpClientRequest.bodyJson(payload),
153205
Effect.flatMap(httpClient.execute),
154206
Effect.flatMap(HttpClientResponse.filterStatusOk),
207+
Effect.timeout(SEND_TIMEOUT),
155208
);
156209
});
157210

211+
const takeBatch = Ref.modify(bufferRef, (current) => {
212+
const nextBatch = current.slice(0, telemetryConfig.flushBatchSize);
213+
return [nextBatch, current.slice(nextBatch.length)] as const;
214+
});
215+
216+
// Sends batches until the buffer is empty or a send fails. A failed batch is
217+
// kept for the next flush, and dropped after MAX_BATCH_ATTEMPTS failed sends.
158218
const flush: AnalyticsService["Service"]["flush"] = Effect.gen(function* () {
159219
while (true) {
160-
const batch = yield* Ref.modify(bufferRef, (current) => {
161-
if (current.length === 0) {
162-
return [[] as ReadonlyArray<BufferedAnalyticsEvent>, current] as const;
163-
}
164-
const nextBatch = current.slice(0, telemetryConfig.flushBatchSize);
165-
const remaining = current.slice(nextBatch.length);
166-
return [nextBatch, remaining] as const;
167-
});
168-
220+
const delivery = yield* Ref.get(deliveryRef);
221+
const batch = delivery.failedBatch.length > 0 ? delivery.failedBatch : yield* takeBatch;
169222
if (batch.length === 0) {
170223
return;
171224
}
172225

173-
yield* sendBatch(batch).pipe(
174-
Effect.catch((error) =>
175-
Ref.update(bufferRef, (current) => [...batch, ...current]).pipe(
176-
Effect.flatMap(() => Effect.fail(error)),
177-
),
178-
),
179-
);
226+
const sent = yield* Effect.result(sendBatch(batch));
227+
if (Result.isSuccess(sent)) {
228+
yield* Ref.set(deliveryRef, { failedBatch: [], batchAttempts: 0, failures: 0, retryAt: 0 });
229+
continue;
230+
}
231+
232+
const failures = delivery.failures + 1;
233+
const batchAttempts = delivery.batchAttempts + 1;
234+
const retryAt = (yield* Clock.currentTimeMillis) + retryDelayMs(failures, yield* Random.next);
235+
if (batchAttempts < MAX_BATCH_ATTEMPTS) {
236+
yield* Ref.set(deliveryRef, { failedBatch: batch, batchAttempts, failures, retryAt });
237+
yield* Effect.logDebug("Failed to send telemetry batch; will retry", {
238+
attempt: batchAttempts,
239+
cause: sent.failure,
240+
});
241+
return;
242+
}
243+
yield* Ref.set(deliveryRef, { failedBatch: [], batchAttempts: 0, failures, retryAt });
244+
yield* Effect.logWarning("Dropped telemetry batch after repeated send failures", {
245+
events: batch.length,
246+
attempts: batchAttempts,
247+
cause: sent.failure,
248+
});
249+
return;
180250
}
181-
}).pipe(Effect.catch((cause) => Effect.logError("Failed to flush telemetry", { cause })));
251+
}).pipe(flushLock.withPermit);
252+
253+
const flushWhenDue = Effect.gen(function* () {
254+
const { retryAt } = yield* Ref.get(deliveryRef);
255+
if ((yield* Clock.currentTimeMillis) >= retryAt) {
256+
yield* flush;
257+
}
258+
});
182259

183260
const record: AnalyticsService["Service"]["record"] = Effect.fn("AnalyticsService.record")(
184261
function* (event, properties) {
185262
if (!telemetryConfig.enabled || !identifier) return;
186263

187-
const enqueueResult = yield* enqueueBufferedEvent(event, properties);
264+
// Telemetry is best effort: an event without a uuid is not sent. The
265+
// Node implementation throws (a defect) rather than failing, so catch both.
266+
const uuid = yield* Effect.exit(crypto.randomUUIDv7);
267+
if (Exit.isFailure(uuid)) return;
268+
269+
const enqueueResult = yield* enqueueBufferedEvent(uuid.value, event, properties);
188270
if (enqueueResult.dropped) {
189271
yield* Effect.logDebug("analytics buffer full; dropping oldest event", {
190272
size: enqueueResult.size,
@@ -194,7 +276,7 @@ export const make = Effect.gen(function* () {
194276
},
195277
);
196278

197-
yield* Effect.forever(Effect.sleep(1000).pipe(Effect.flatMap(() => flush)), {
279+
yield* Effect.forever(Effect.sleep(FLUSH_INTERVAL_MS).pipe(Effect.flatMap(() => flushWhenDue)), {
198280
disableYield: true,
199281
}).pipe(Effect.forkScoped);
200282

Collapse file

‎docs/internals/connection-runtime.md‎

Copy file name to clipboardExpand all lines: docs/internals/connection-runtime.md
+13-9Lines changed: 13 additions & 9 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,20 @@ several views need the same environment.
1010

1111
The [supervisor](../../packages/client-runtime/src/connection/supervisor.ts) owns
1212
transport retry policy; resolving an endpoint and opening an RPC session are single
13-
attempts. Transient failures retry with capped backoff. Offline states and
14-
authentication failures wait for a wakeup instead of spending attempts on
15-
unchanged conditions.
13+
attempts. Transient failures retry with jittered exponential backoff, capped at
14+
five minutes, that resets only after a connection stays up. Without jitter, every
15+
client of a restarted server reconnects in the same second; with a short cap, a
16+
client that can never connect retries all day. Offline states and authentication
17+
failures wait for a wakeup instead of spending attempts on unchanged conditions.
1618

17-
Foregrounding needs different treatment depending on the connection's state.
18-
It wakes a retry immediately, leaves an ordinary in-flight attempt alone, and
19-
probes an established session before replacing it. A long mobile background
20-
suspension forces replacement because the OS can kill a socket without reporting
21-
closure. Treating every foreground event as a reconnect delays healthy attempts;
22-
treating every resume as harmless leaves suspended sockets stuck.
19+
Foregrounding, an explicit retry, and an offline report probe the established
20+
session, and only a failed probe reconnects. Offline reports are often wrong, for
21+
example for a loopback server. A long mobile background suspension is the one
22+
exception: it replaces the session at once, because the OS can kill a socket
23+
without reporting closure, and a probe would hold a dead socket in "Resuming"
24+
until it times out. That fresh attempt runs even while the network reports
25+
offline. Foregrounding also wakes a pending retry immediately and
26+
leaves an ordinary in-flight attempt alone.
2327

2428
The [registry](../../packages/client-runtime/src/connection/registry.ts) scopes
2529
connections by environment. An involuntary disconnect retains the registration
Collapse file

‎docs/internals/product-analytics.md‎

Copy file name to clipboardExpand all lines: docs/internals/product-analytics.md
+7Lines changed: 7 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,13 @@ Unknown counts stay absent. Partial usage contains valid observed counts but
4141
cannot establish a whole-turn total. Keep these distinctions when changing token
4242
normalization or building reports.
4343

44+
## Delivery
45+
46+
A send can fail after PostHog has stored the batch, so every retry is a copy.
47+
[Delivery](../../apps/server/src/telemetry/AnalyticsService.ts) gives each event a
48+
uuid when it is recorded, backs off after a failed send, and drops a batch after a
49+
few tries. Without these limits, one stuck batch was sent every second for days.
50+
4451
## Collection boundary
4552

4653
Keep analytics payloads to product metadata and normalized measurements. Do not
Collapse file

‎packages/client-runtime/src/connection/registry.test.ts‎

Copy file name to clipboardExpand all lines: packages/client-runtime/src/connection/registry.test.ts
+40Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1443,6 +1443,46 @@ describe("EnvironmentRegistry", () => {
14431443
}),
14441444
);
14451445

1446+
it.effect("keeps one session per environment across concurrent registrations and retries", () =>
1447+
Effect.gen(function* () {
1448+
const harness = yield* makeHarness([]);
1449+
1450+
yield* Effect.gen(function* () {
1451+
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
1452+
const registration = new PrimaryConnectionRegistration({ target: TARGET });
1453+
yield* Effect.all(
1454+
Array.from({ length: 5 }, () => registry.registerPlatform(registration)),
1455+
{ concurrency: "unbounded", discard: true },
1456+
);
1457+
yield* awaitConnectionState(
1458+
registry,
1459+
TARGET.environmentId,
1460+
(state) => state.phase === "connected",
1461+
);
1462+
1463+
// Platform polls and explicit retries reach a healthy connection at once.
1464+
yield* Effect.all(
1465+
[
1466+
...Array.from({ length: 5 }, () => registry.registerPlatform(registration)),
1467+
...Array.from({ length: 5 }, () => registry.retryNow(TARGET.environmentId)),
1468+
registry.reconcilePlatform([registration]),
1469+
],
1470+
{ concurrency: "unbounded", discard: true },
1471+
);
1472+
for (let attempt = 0; attempt < 100; attempt += 1) {
1473+
yield* Effect.yieldNow;
1474+
}
1475+
1476+
expect(yield* Ref.get(harness.sessions)).toHaveLength(1);
1477+
expect(yield* Ref.get(harness.releasedSessions)).toBe(0);
1478+
expect(yield* registry.state(TARGET.environmentId)).toMatchObject({
1479+
phase: "connected",
1480+
generation: 1,
1481+
});
1482+
}).pipe(Effect.provide(harness.layer), Effect.scoped);
1483+
}),
1484+
);
1485+
14461486
it.effect("retains a healthy runtime when the platform repeats an identical registration", () =>
14471487
Effect.gen(function* () {
14481488
const harness = yield* makeHarness([]);

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.