Compare commits

...
Author SHA1 Message Date
Cursor AgentandJulius Marminge 039ce19871 Format telemetry test types
Co-authored-by: Julius Marminge <[email protected]>
2026-07-13 16:15:04 +00:00
Cursor AgentandJulius Marminge 149f72a121 Fix Effect test type assertions
Co-authored-by: Julius Marminge <[email protected]>
2026-07-13 16:13:40 +00:00
Cursor AgentandJulius Marminge 47f50256b5 Assert normalized filesystem platform errors
Co-authored-by: Julius Marminge <[email protected]>
2026-07-13 16:11:32 +00:00
Cursor AgentandJulius Marminge 6241e155fb Use idiomatic Effect APIs in filesystem and telemetry
Co-authored-by: Julius Marminge <[email protected]>
2026-07-13 16:10:09 +00:00
4 changed files with 210 additions and 106 deletions

No files matched your search

@@ -2,8 +2,13 @@ import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as TestClock from "effect/testing/TestClock";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
import * as HttpServer from "effect/unstable/http/HttpServer";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
@@ -16,25 +21,46 @@ interface RecordedBatchRequest {
readonly path: string;
readonly body: {
readonly batch?: ReadonlyArray<{
readonly event?: string;
readonly properties?: {
readonly index?: number;
readonly clientType?: string;
};
readonly event?: string | undefined;
readonly properties?:
| {
readonly index?: number | undefined;
readonly clientType?: string | undefined;
}
| undefined;
}>;
} | null;
}
interface RecordedBatchBody {
readonly batch: ReadonlyArray<{
readonly event?: string;
readonly properties?: {
readonly index?: number;
readonly clientType?: string;
};
readonly event?: string | undefined;
readonly properties?:
| {
readonly index?: number | undefined;
readonly clientType?: string | undefined;
}
| undefined;
}>;
}
const RecordedBatchBodySchema = Schema.Struct({
batch: Schema.Array(
Schema.Struct({
event: Schema.optional(Schema.String),
properties: Schema.optional(
Schema.Struct({
index: Schema.optional(Schema.Number),
clientType: Schema.optional(Schema.String),
}),
),
}),
),
});
const decodeRecordedBatchBody = Schema.decodeUnknownEffect(
Schema.fromJsonString(RecordedBatchBodySchema),
);
it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
it.effect("flush drains all buffered events across multiple batches", () =>
Effect.gen(function* () {
@@ -117,4 +143,74 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
);
}),
);
it.effect("background flush runs on the TestClock-adjustable interval", () =>
Effect.gen(function* () {
const capturedRequests: Array<RecordedBatchRequest> = [];
const serverConfigLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
prefix: "t3-telemetry-clock-",
});
const telemetryLayer = AnalyticsService.layer.pipe(Layer.provideMerge(serverConfigLayer));
const configLayer = ConfigProvider.layer(
ConfigProvider.fromUnknown({
T3CODE_TELEMETRY_ENABLED: true,
T3CODE_POSTHOG_KEY: "phc_test_key",
T3CODE_POSTHOG_HOST: "http://posthog.test",
T3CODE_TELEMETRY_FLUSH_BATCH_SIZE: 20,
}),
);
const httpClientLayer = Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request, url) =>
Effect.gen(function* () {
const body =
request.body._tag === "Uint8Array"
? yield* decodeRecordedBatchBody(new TextDecoder().decode(request.body.body)).pipe(
Effect.orDie,
)
: null;
capturedRequests.push({ path: url.pathname, body });
return HttpClientResponse.fromWeb(request, new Response("{}", { status: 200 }));
}),
),
);
const runtimeLayer = telemetryLayer.pipe(
Layer.provide(configLayer),
Layer.provide(httpClientLayer),
);
yield* Effect.gen(function* () {
const analytics = yield* AnalyticsService.AnalyticsService;
yield* analytics.record("test.flush.clock", { index: 1 });
yield* Effect.yieldNow;
yield* TestClock.adjust(Duration.millis(999));
assert.equal(capturedRequests.length, 0);
yield* TestClock.adjust(Duration.millis(1));
yield* Effect.yieldNow;
}).pipe(Effect.provide(Layer.merge(runtimeLayer, TestClock.layer())));
const batchRequests = capturedRequests.filter(
(request): request is RecordedBatchRequest & { readonly body: RecordedBatchBody } =>
Array.isArray(request.body?.batch),
);
assert.equal(batchRequests.length, 1);
assert.equal(batchRequests[0]?.path, "/batch/");
assert.deepEqual(
batchRequests[0]?.body.batch.map((event) => ({
event: event.event,
index: event.properties?.index,
clientType: event.properties?.clientType,
})),
[
{
event: "test.flush.clock",
index: 1,
clientType: "cli-web-client",
},
],
);
}),
);
});
@@ -10,6 +10,7 @@ import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/ho
import * as Config from "effect/Config";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -43,6 +44,8 @@ const TelemetryEnvConfig = Config.all({
wslDistroName: Config.string("WSL_DISTRO_NAME").pipe(Config.option),
});
const BACKGROUND_FLUSH_INTERVAL = Duration.seconds(1);
export class AnalyticsService extends Context.Service<
AnalyticsService,
{
@@ -172,7 +175,7 @@ export const make = Effect.gen(function* () {
},
);
yield* Effect.forever(Effect.sleep(1000).pipe(Effect.flatMap(() => flush)), {
yield* Effect.forever(Effect.sleep(BACKGROUND_FLUSH_INTERVAL).pipe(Effect.flatMap(() => flush)), {
disableYield: true,
}).pipe(Effect.forkScoped);
@@ -1,9 +1,10 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, describe, expect } from "@effect/vitest";
import { assert, it, describe, expect } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import type * as PlatformError from "effect/PlatformError";
import * as ServerConfig from "../config.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
@@ -186,7 +187,13 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
operation: "realpath-target",
});
expect(error.cause).toBeInstanceOf(Error);
expect((error.cause as NodeJS.ErrnoException).code).toBe("ENOENT");
const cause = error.cause as PlatformError.PlatformError;
assert.equal(cause._tag, "PlatformError");
if (cause.reason._tag === "BadArgument") {
assert.fail("expected filesystem system error");
}
assert.equal(cause.reason._tag, "NotFound");
assert.equal(cause.reason.pathOrDescriptor, resolvedPath);
}),
);
});
@@ -1,4 +1,3 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* WorkspaceFileSystem - Effect service contract for workspace file mutations.
*
@@ -7,8 +6,6 @@
*
* @module WorkspaceFileSystem
*/
import * as NodeFSP from "node:fs/promises";
import type {
ProjectReadFileInput,
ProjectReadFileResult,
@@ -19,6 +16,7 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
@@ -140,30 +138,32 @@ export const make = Effect.gen(function* () {
relativePath: input.relativePath,
});
const realWorkspaceRoot = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(input.cwd),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: input.cwd,
operation: "realpath-workspace-root",
cause,
}),
});
const realTargetPath = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(target.absolutePath),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: target.absolutePath,
operation: "realpath-target",
cause,
}),
});
const realWorkspaceRoot = yield* fileSystem.realPath(input.cwd).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: input.cwd,
operation: "realpath-workspace-root",
cause,
}),
),
);
const realTargetPath = yield* fileSystem.realPath(target.absolutePath).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: target.absolutePath,
operation: "realpath-target",
cause,
}),
),
);
const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
if (
relativeRealPath.startsWith(`..${path.sep}`) ||
@@ -178,24 +178,24 @@ export const make = Effect.gen(function* () {
});
}
return yield* Effect.acquireUseRelease(
Effect.tryPromise({
try: () => NodeFSP.open(realTargetPath, "r"),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "open",
cause,
}),
}),
(handle) =>
Effect.gen(function* () {
const stat = yield* Effect.tryPromise({
try: () => handle.stat(),
catch: (cause) =>
return yield* Effect.scoped(
Effect.gen(function* () {
const file = yield* fileSystem.open(realTargetPath, { flag: "r" }).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "open",
cause,
}),
),
);
const stat = yield* file.stat.pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
@@ -204,58 +204,56 @@ export const make = Effect.gen(function* () {
operation: "stat",
cause,
}),
),
);
if (stat.type !== "File") {
return yield* new WorkspacePathNotFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
if (!stat.isFile()) {
return yield* new WorkspacePathNotFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
}
const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
const buffer = Buffer.alloc(bytesToRead);
const { bytesRead } = yield* Effect.tryPromise({
try: () => handle.read(buffer, 0, bytesToRead, 0),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "read",
cause,
}),
const truncated = stat.size > FileSystem.Size(PROJECT_READ_FILE_MAX_BYTES);
const byteLength = Number(stat.size);
const bytesToRead = truncated ? PROJECT_READ_FILE_MAX_BYTES : byteLength;
const fileBytes =
bytesToRead === 0
? new Uint8Array()
: yield* file.readAlloc(bytesToRead).pipe(
Effect.map(
Option.match({
onNone: () => new Uint8Array(),
onSome: (bytes) => bytes,
}),
),
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "read",
cause,
}),
),
);
if (fileBytes.includes(0)) {
return yield* new WorkspaceBinaryFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
const fileBytes = buffer.subarray(0, bytesRead);
if (fileBytes.includes(0)) {
return yield* new WorkspaceBinaryFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
}
return {
relativePath: target.relativePath,
contents: new TextDecoder("utf-8").decode(fileBytes),
byteLength: stat.size,
truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
};
}),
(handle) =>
Effect.tryPromise({
try: () => handle.close(),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "close",
cause,
}),
}),
return {
relativePath: target.relativePath,
contents: new TextDecoder("utf-8").decode(fileBytes),
byteLength,
truncated,
};
}),
);
});