From 6241e155fb4bd53b475ab27c953f0d0f443f2131 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 13 Jul 2026 16:10:09 +0000 Subject: [PATCH] Use idiomatic Effect APIs in filesystem and telemetry Co-authored-by: Julius Marminge --- .../src/telemetry/AnalyticsService.test.ts | 92 +++++++++ apps/server/src/telemetry/AnalyticsService.ts | 5 +- .../src/workspace/WorkspaceFileSystem.ts | 184 +++++++++--------- 3 files changed, 187 insertions(+), 94 deletions(-) diff --git a/apps/server/src/telemetry/AnalyticsService.test.ts b/apps/server/src/telemetry/AnalyticsService.test.ts index d69bab32fe..2aec6fdb2b 100644 --- a/apps/server/src/telemetry/AnalyticsService.test.ts +++ b/apps/server/src/telemetry/AnalyticsService.test.ts @@ -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"; @@ -35,6 +40,23 @@ interface RecordedBatchBody { }>; } +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 +139,74 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => { ); }), ); + + it.effect("background flush runs on the TestClock-adjustable interval", () => + Effect.gen(function* () { + const capturedRequests: Array = []; + 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", + }, + ], + ); + }), + ); }); diff --git a/apps/server/src/telemetry/AnalyticsService.ts b/apps/server/src/telemetry/AnalyticsService.ts index 5fdc7bdeb1..5bec4bcc39 100644 --- a/apps/server/src/telemetry/AnalyticsService.ts +++ b/apps/server/src/telemetry/AnalyticsService.ts @@ -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); diff --git a/apps/server/src/workspace/WorkspaceFileSystem.ts b/apps/server/src/workspace/WorkspaceFileSystem.ts index e2dc9cbbb3..c7afcd6e79 100644 --- a/apps/server/src/workspace/WorkspaceFileSystem.ts +++ b/apps/server/src/workspace/WorkspaceFileSystem.ts @@ -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, + }; + }), ); });