[codex] Structure analytics batch delivery failures (#3311)
Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
973d3c12ce
commit
ff76f76de1
2 files changed
+153
-14
No files matched your search
@@ -4,7 +4,11 @@ import { assert, it } from "@effect/vitest";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as References from "effect/References";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpServer from "effect/unstable/http/HttpServer";
|
||||
import * as HttpClientError from "effect/unstable/http/HttpClientError";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
|
||||
@@ -35,10 +39,25 @@ interface RecordedBatchBody {
|
||||
}>;
|
||||
}
|
||||
|
||||
interface CapturedLog {
|
||||
readonly message: unknown;
|
||||
readonly annotations: Readonly<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
const isAnalyticsBatchDeliveryError = Schema.is(AnalyticsService.AnalyticsBatchDeliveryError);
|
||||
|
||||
it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
|
||||
it.effect("flush drains all buffered events across multiple batches", () =>
|
||||
it.effect("flush drains buffered events and retries failed batches with structured context", () =>
|
||||
Effect.gen(function* () {
|
||||
const capturedRequests: Array<RecordedBatchRequest> = [];
|
||||
const capturedLogs: CapturedLog[] = [];
|
||||
let rejectNextBatch = false;
|
||||
const logger = Logger.make(({ fiber, message }) => {
|
||||
capturedLogs.push({
|
||||
message,
|
||||
annotations: fiber.getRef(References.CurrentLogAnnotations),
|
||||
});
|
||||
});
|
||||
const serverConfigLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-telemetry-base-",
|
||||
});
|
||||
@@ -66,12 +85,20 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
|
||||
|
||||
capturedRequests.push({ path: request.url, body: payload });
|
||||
|
||||
if (rejectNextBatch) {
|
||||
rejectNextBatch = false;
|
||||
return HttpServerResponse.empty({ status: 503 });
|
||||
}
|
||||
|
||||
return HttpServerResponse.jsonUnsafe({});
|
||||
}),
|
||||
);
|
||||
const runtimeLayer = telemetryLayer.pipe(
|
||||
Layer.provide(configLayer),
|
||||
Layer.provideMerge(NodeHttpServer.layerTest),
|
||||
const runtimeLayer = Layer.merge(
|
||||
telemetryLayer.pipe(
|
||||
Layer.provide(configLayer),
|
||||
Layer.provideMerge(NodeHttpServer.layerTest),
|
||||
),
|
||||
Logger.layer([logger], { mergeWithExisting: false }),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
@@ -85,12 +112,17 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
|
||||
}
|
||||
|
||||
yield* analytics.flush;
|
||||
yield* analytics.record("test.flush.retry", { index: 45 });
|
||||
rejectNextBatch = true;
|
||||
yield* analytics.flush;
|
||||
yield* analytics.flush;
|
||||
}).pipe(Effect.provide(runtimeLayer));
|
||||
|
||||
const batchRequests = capturedRequests.filter(
|
||||
(request): request is RecordedBatchRequest & { readonly body: RecordedBatchBody } =>
|
||||
const batchRequests = capturedRequests
|
||||
.slice(0, 3)
|
||||
.filter((request): request is RecordedBatchRequest & { readonly body: RecordedBatchBody } =>
|
||||
Array.isArray(request.body?.batch),
|
||||
);
|
||||
);
|
||||
assert.equal(batchRequests.length, 3);
|
||||
assert.equal(
|
||||
batchRequests.every((request) => request.path === "/batch/" || request.path === "/batch"),
|
||||
@@ -115,6 +147,53 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
|
||||
),
|
||||
true,
|
||||
);
|
||||
|
||||
const retryRequests = capturedRequests.slice(3);
|
||||
assert.equal(retryRequests.length, 2);
|
||||
assert.deepEqual(retryRequests[0]?.body, retryRequests[1]?.body);
|
||||
|
||||
const deliveryLog = capturedLogs.find((log) =>
|
||||
isAnalyticsBatchDeliveryError(log.annotations.cause),
|
||||
);
|
||||
assert.isDefined(deliveryLog);
|
||||
assert.equal(
|
||||
deliveryLog?.message,
|
||||
"Failed to deliver 1 analytics event to PostHog (endpoint input length 7).",
|
||||
);
|
||||
assert.equal("endpoint" in deliveryLog.annotations, false);
|
||||
assert.equal(deliveryLog.annotations.endpointInputLength, 7);
|
||||
|
||||
const error = deliveryLog?.annotations.cause;
|
||||
assert.instanceOf(error, AnalyticsService.AnalyticsBatchDeliveryError);
|
||||
if (isAnalyticsBatchDeliveryError(error)) {
|
||||
assert.equal(error.endpointInputLength, 7);
|
||||
assert.equal(error.endpointProtocol, undefined);
|
||||
assert.equal(error.endpointHostname, undefined);
|
||||
assert.equal(error.eventCount, 1);
|
||||
assert.instanceOf(error.cause, HttpClientError.HttpClientError);
|
||||
if (error.cause instanceof HttpClientError.HttpClientError) {
|
||||
assert.equal(error.cause.reason._tag, "StatusCodeError");
|
||||
assert.equal(error.cause.response?.status, 503);
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps configured PostHog endpoint secrets out of direct error and log context", () => {
|
||||
const endpoint =
|
||||
"https://user:[email protected]/private/project?api_key=secret#fragment";
|
||||
const cause = new Error("delivery failed");
|
||||
const error = AnalyticsService.AnalyticsBatchDeliveryError.fromEndpoint({
|
||||
endpoint,
|
||||
eventCount: 2,
|
||||
cause,
|
||||
});
|
||||
|
||||
assert.equal(error.endpointInputLength, endpoint.length);
|
||||
assert.equal(error.endpointProtocol, "https:");
|
||||
assert.equal(error.endpointHostname, "posthog.example.test");
|
||||
assert.equal(error.cause, cause);
|
||||
assert.equal("endpoint" in error, false);
|
||||
assert.equal(/user|password|private|project|api_key|secret|fragment/.test(error.message), false);
|
||||
});
|
||||
@@ -7,6 +7,7 @@
|
||||
* @module AnalyticsService
|
||||
*/
|
||||
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
|
||||
import * as Config from "effect/Config";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
@@ -14,6 +15,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
|
||||
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
|
||||
@@ -43,6 +45,38 @@ const TelemetryEnvConfig = Config.all({
|
||||
wslDistroName: Config.string("WSL_DISTRO_NAME").pipe(Config.option),
|
||||
});
|
||||
|
||||
export class AnalyticsBatchDeliveryError extends Schema.TaggedErrorClass<AnalyticsBatchDeliveryError>()(
|
||||
"AnalyticsBatchDeliveryError",
|
||||
{
|
||||
endpointInputLength: Schema.Number,
|
||||
endpointProtocol: Schema.optionalKey(Schema.String),
|
||||
endpointHostname: Schema.optionalKey(Schema.String),
|
||||
eventCount: Schema.Int.check(Schema.isGreaterThan(0)),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
static fromEndpoint(input: {
|
||||
readonly endpoint: string;
|
||||
readonly eventCount: number;
|
||||
readonly cause: unknown;
|
||||
}): AnalyticsBatchDeliveryError {
|
||||
const diagnostics = getUrlDiagnostics(input.endpoint);
|
||||
return new AnalyticsBatchDeliveryError({
|
||||
endpointInputLength: diagnostics.inputLength,
|
||||
...(diagnostics.protocol === undefined ? {} : { endpointProtocol: diagnostics.protocol }),
|
||||
...(diagnostics.hostname === undefined ? {} : { endpointHostname: diagnostics.hostname }),
|
||||
eventCount: input.eventCount,
|
||||
cause: input.cause,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
const eventLabel = this.eventCount === 1 ? "event" : "events";
|
||||
const destination = this.endpointHostname ? ` at ${this.endpointHostname}` : "";
|
||||
return `Failed to deliver ${this.eventCount} analytics ${eventLabel} to PostHog${destination} (endpoint input length ${this.endpointInputLength}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class AnalyticsService extends Context.Service<
|
||||
AnalyticsService,
|
||||
{
|
||||
@@ -75,6 +109,7 @@ export const make = Effect.gen(function* () {
|
||||
const clientType = serverConfig.mode === "desktop" ? "desktop-app" : "cli-web-client";
|
||||
const hostPlatform = yield* HostProcessPlatform;
|
||||
const hostArchitecture = yield* HostProcessArchitecture;
|
||||
const batchEndpoint = `${telemetryConfig.posthogHost}/batch/`;
|
||||
|
||||
const enqueueBufferedEvent = (event: string, properties?: Readonly<Record<string, unknown>>) =>
|
||||
Effect.flatMap(DateTime.now, (now) =>
|
||||
@@ -126,10 +161,17 @@ export const make = Effect.gen(function* () {
|
||||
})),
|
||||
};
|
||||
|
||||
yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe(
|
||||
yield* HttpClientRequest.post(batchEndpoint).pipe(
|
||||
HttpClientRequest.bodyJson(payload),
|
||||
Effect.flatMap(httpClient.execute),
|
||||
Effect.flatMap(HttpClientResponse.filterStatusOk),
|
||||
Effect.mapError((cause) =>
|
||||
AnalyticsBatchDeliveryError.fromEndpoint({
|
||||
endpoint: batchEndpoint,
|
||||
eventCount: events.length,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -149,14 +191,32 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
yield* sendBatch(batch).pipe(
|
||||
Effect.catch((error) =>
|
||||
Ref.update(bufferRef, (current) => [...batch, ...current]).pipe(
|
||||
Effect.flatMap(() => Effect.fail(error)),
|
||||
),
|
||||
),
|
||||
Effect.catchTags({
|
||||
AnalyticsBatchDeliveryError: (error) =>
|
||||
Ref.update(bufferRef, (current) => [...batch, ...current]).pipe(
|
||||
Effect.flatMap(() => Effect.fail(error)),
|
||||
),
|
||||
}),
|
||||
);
|
||||
}
|
||||
}).pipe(Effect.catch((cause) => Effect.logError("Failed to flush telemetry", { cause })));
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
AnalyticsBatchDeliveryError: (error) =>
|
||||
Effect.logError(error.message).pipe(
|
||||
Effect.annotateLogs({
|
||||
endpointInputLength: error.endpointInputLength,
|
||||
...(error.endpointProtocol === undefined
|
||||
? {}
|
||||
: { endpointProtocol: error.endpointProtocol }),
|
||||
...(error.endpointHostname === undefined
|
||||
? {}
|
||||
: { endpointHostname: error.endpointHostname }),
|
||||
eventCount: error.eventCount,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const record: AnalyticsService["Service"]["record"] = Effect.fn("AnalyticsService.record")(
|
||||
function* (event, properties) {
|
||||
|
||||
Reference in new issue
Block a user