Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
[codex] Structure server runtime-state failures (#3319)
Julius Marminge90f1936fade3
diff --git a/apps/server/src/serverRuntimeState.test.ts b/apps/server/src/serverRuntimeState.test.tsnew file mode 100644index 000000000..749fd3062--- /dev/null+++ b/apps/server/src/serverRuntimeState.test.ts@@ -0,0 +1,167 @@+import { assert, describe, it } from "@effect/vitest";+import * as NodeServices from "@effect/platform-node/NodeServices";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Layer from "effect/Layer";+import * as Logger from "effect/Logger";+import * as Option from "effect/Option";+import * as Path from "effect/Path";+import * as References from "effect/References";+import * as Schema from "effect/Schema";++import * as ServerRuntimeState from "./serverRuntimeState.ts";++const isServerRuntimeStateError = Schema.is(ServerRuntimeState.ServerRuntimeStateError);++interface CapturedLog {+ readonly message: unknown;+ readonly annotations: Readonly<Record<string, unknown>>;+}++describe("serverRuntimeState", () => {+ it.effect("persists and reads the runtime state", () =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const root = yield* fileSystem.makeTempDirectoryScoped({+ prefix: "t3-server-runtime-state-test-",+ });+ const statePath = path.join(root, "runtime", "server.json");+ const state: ServerRuntimeState.PersistedServerRuntimeState = {+ version: 1,+ pid: 123,+ host: "127.0.0.1",+ port: 4_971,+ origin: "http://127.0.0.1:4971",+ startedAt: "2026-06-20T00:00:00.000Z",+ };++ yield* ServerRuntimeState.persistServerRuntimeState({ path: statePath, state });+ const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath);++ assert.deepEqual(Option.getOrThrow(restored), state);+ }).pipe(Effect.provide(NodeServices.layer)),+ );++ it.effect("treats a missing runtime state file as absent", () =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const root = yield* fileSystem.makeTempDirectoryScoped({+ prefix: "t3-server-runtime-state-test-",+ });++ const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(+ path.join(root, "missing.json"),+ );++ assert.isTrue(Option.isNone(restored));+ }).pipe(Effect.provide(NodeServices.layer)),+ );++ it.effect("preserves malformed state decode failures", () => {+ const logs: CapturedLog[] = [];+ const logger = Logger.make(({ fiber, message }) => {+ logs.push({+ message,+ annotations: fiber.getRef(References.CurrentLogAnnotations),+ });+ });++ return Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const root = yield* fileSystem.makeTempDirectoryScoped({+ prefix: "t3-server-runtime-state-test-",+ });+ const statePath = path.join(root, "server.json");+ yield* fileSystem.writeFileString(statePath, "{not json");++ const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath);++ assert.isTrue(Option.isNone(restored));+ assert.equal(logs[0]?.message, `Failed to decode server runtime state at ${statePath}.`);+ const error = logs[0]?.annotations.cause;+ assert.isTrue(isServerRuntimeStateError(error));+ if (isServerRuntimeStateError(error)) {+ assert.equal(error.operation, "decode");+ assert.equal(error.statePath, statePath);+ assert.equal(error.message, `Failed to decode server runtime state at ${statePath}.`);+ assert.deepInclude(error.cause, { _tag: "SchemaError" });+ }+ }).pipe(+ Effect.provide(+ Layer.merge(NodeServices.layer, Logger.layer([logger], { mergeWithExisting: false })),+ ),+ );+ });++ it.effect("preserves runtime state read failures", () => {+ const logs: CapturedLog[] = [];+ const logger = Logger.make(({ fiber, message }) => {+ logs.push({+ message,+ annotations: fiber.getRef(References.CurrentLogAnnotations),+ });+ });++ return Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const root = yield* fileSystem.makeTempDirectoryScoped({+ prefix: "t3-server-runtime-state-test-",+ });+ const statePath = path.join(root, "server.json");+ yield* fileSystem.makeDirectory(statePath);++ const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath);++ assert.isTrue(Option.isNone(restored));+ assert.equal(logs[0]?.message, `Failed to read server runtime state at ${statePath}.`);+ const error = logs[0]?.annotations.cause;+ assert.isTrue(isServerRuntimeStateError(error));+ if (isServerRuntimeStateError(error)) {+ assert.equal(error.operation, "read");+ assert.equal(error.statePath, statePath);+ assert.equal(error.message, `Failed to read server runtime state at ${statePath}.`);+ assert.deepInclude(error.cause, { _tag: "PlatformError" });+ }+ }).pipe(+ Effect.provide(+ Layer.merge(NodeServices.layer, Logger.layer([logger], { mergeWithExisting: false })),+ ),+ );+ });++ it.effect("preserves runtime state persistence failures", () =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const root = yield* fileSystem.makeTempDirectoryScoped({+ prefix: "t3-server-runtime-state-test-",+ });+ const blockedDirectory = path.join(root, "not-a-directory");+ const statePath = path.join(blockedDirectory, "server.json");+ yield* fileSystem.writeFileString(blockedDirectory, "blocked");++ const error = yield* ServerRuntimeState.persistServerRuntimeState({+ path: statePath,+ state: {+ version: 1,+ pid: 123,+ port: 4_971,+ origin: "http://127.0.0.1:4971",+ startedAt: "2026-06-20T00:00:00.000Z",+ },+ }).pipe(Effect.flip);++ assert.isTrue(isServerRuntimeStateError(error));+ if (isServerRuntimeStateError(error)) {+ assert.equal(error.operation, "persist");+ assert.equal(error.statePath, statePath);+ assert.equal(error.message, `Failed to persist server runtime state at ${statePath}.`);+ assert.deepInclude(error.cause, { _tag: "PlatformError" });+ }+ }).pipe(Effect.provide(NodeServices.layer)),+ );+});diff --git a/apps/server/src/serverRuntimeState.ts b/apps/server/src/serverRuntimeState.tsindex 289bddcb8..329b00036 100644--- a/apps/server/src/serverRuntimeState.ts+++ b/apps/server/src/serverRuntimeState.ts@@ -18,6 +18,19 @@ export const PersistedServerRuntimeState = Schema.Struct({});export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type;+export class ServerRuntimeStateError extends Schema.TaggedErrorClass<ServerRuntimeStateError>()(+ "ServerRuntimeStateError",+ {+ operation: Schema.Literals(["persist", "read", "decode", "clear"]),+ statePath: Schema.String,+ cause: Schema.Defect(),+ },+) {+ override get message(): string {+ return `Failed to ${this.operation} server runtime state at ${this.statePath}.`;+ }+}+const decodePersistedServerRuntimeState = Schema.decodeUnknownEffect(Schema.fromJsonString(PersistedServerRuntimeState),);@@ -51,27 +64,90 @@ export const persistServerRuntimeState = (input: {writeFileStringAtomically({filePath: input.path,contents: `${JSON.stringify(input.state)}\n`,- });+ }).pipe(+ Effect.mapError(+ (cause) =>+ new ServerRuntimeStateError({+ operation: "persist",+ statePath: input.path,+ cause,+ }),+ ),+ );export const clearPersistedServerRuntimeState = (path: string) =>Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;- yield* fs.remove(path, { force: true }).pipe(Effect.ignore({ log: true }));+ yield* fs.remove(path, { force: true }).pipe(+ Effect.mapError(+ (cause) =>+ new ServerRuntimeStateError({+ operation: "clear",+ statePath: path,+ cause,+ }),+ ),+ Effect.catchTags({+ ServerRuntimeStateError: (error) =>+ Effect.logWarning(error.message).pipe(+ Effect.annotateLogs({+ operation: error.operation,+ statePath: error.statePath,+ cause: error,+ }),+ ),+ }),+ );});export const readPersistedServerRuntimeState = (path: string) =>Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;- const exists = yield* fs.exists(path).pipe(Effect.orElseSucceed(() => false));- if (!exists) {+ const raw = yield* fs.readFileString(path).pipe(+ Effect.matchEffect({+ onFailure: (cause) =>+ cause.reason._tag === "NotFound"+ ? Effect.succeed(Option.none<string>())+ : Effect.fail(+ new ServerRuntimeStateError({+ operation: "read",+ statePath: path,+ cause,+ }),+ ),+ onSuccess: (contents) => Effect.succeed(Option.some(contents)),+ }),+ );+ if (Option.isNone(raw)) {return Option.none<PersistedServerRuntimeState>();}- const raw = yield* fs.readFileString(path).pipe(Effect.orElseSucceed(() => ""));- const trimmed = raw.trim();+ const trimmed = raw.value.trim();if (trimmed.length === 0) {return Option.none<PersistedServerRuntimeState>();}- return yield* decodePersistedServerRuntimeState(trimmed).pipe(Effect.option);- });+ return yield* decodePersistedServerRuntimeState(trimmed).pipe(+ Effect.map(Option.some),+ Effect.mapError(+ (cause) =>+ new ServerRuntimeStateError({+ operation: "decode",+ statePath: path,+ cause,+ }),+ ),+ );+ }).pipe(+ Effect.catchTags({+ ServerRuntimeStateError: (error) =>+ Effect.logWarning(error.message).pipe(+ Effect.annotateLogs({+ operation: error.operation,+ statePath: error.statePath,+ cause: error,+ }),+ Effect.as(Option.none<PersistedServerRuntimeState>()),+ ),+ }),+ );