Compare commits

...
Author SHA1 Message Date
Cursor AgentandJulius Marminge 0f9d858efb Unwrap secret store options at call sites
Co-authored-by: Julius Marminge <[email protected]>
2026-06-02 16:09:19 +00:00
Cursor AgentandJulius Marminge 8e7cf43e19 Use supported Effect catch combinator
Co-authored-by: Julius Marminge <[email protected]>
2026-06-02 16:08:04 +00:00
Cursor AgentandJulius Marminge b44e0ca1e5 Fix Windows diagnostics schema union
Co-authored-by: Julius Marminge <[email protected]>
2026-06-02 16:07:46 +00:00
Cursor AgentandJulius Marminge 26ad4021b9 Use idiomatic Effect patterns in server internals
Co-authored-by: Julius Marminge <[email protected]>
2026-06-02 16:07:13 +00:00
6 changed files with 213 additions and 82 deletions

No files matched your search

@@ -1,10 +1,12 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { assert, expect, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as Deferred from "effect/Deferred";
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 Ref from "effect/Ref";
import * as PlatformError from "effect/PlatformError";
@@ -18,6 +20,21 @@ const makeServerConfigLayer = () =>
const makeServerSecretStoreLayer = () =>
Layer.provide(ServerSecretStoreLive, makeServerConfigLayer());
const makeDeterministicCryptoLayer = (fillByte: number) =>
Layer.succeed(
Crypto.Crypto,
Crypto.make({
randomBytes: (size) => new Uint8Array(size).fill(fillByte),
digest: (_algorithm, data) => Effect.succeed(data),
}),
);
const makeDeterministicSecretStoreLayer = (fillByte: number) =>
ServerSecretStoreLive.pipe(
Layer.provide(makeServerConfigLayer()),
Layer.provideMerge(makeDeterministicCryptoLayer(fillByte)),
);
const PermissionDeniedFileSystemLayer = Layer.effect(
FileSystem.FileSystem,
Effect.gen(function* () {
@@ -146,16 +163,26 @@ const makeConcurrentCreateSecretStoreLayer = () =>
);
it.layer(NodeServices.layer)("ServerSecretStoreLive", (it) => {
it.effect("returns null when a secret file does not exist", () =>
it.effect("returns none when a secret file does not exist", () =>
Effect.gen(function* () {
const secretStore = yield* ServerSecretStore;
const secret = yield* secretStore.get("missing-secret");
expect(secret).toBeNull();
assert.isTrue(Option.isNone(secret));
}).pipe(Effect.provide(makeServerSecretStoreLayer())),
);
it.effect("uses the provided Crypto service when generating a new secret", () =>
Effect.gen(function* () {
const secretStore = yield* ServerSecretStore;
const secret = yield* secretStore.getOrCreateRandom("session-signing-key", 4);
assert.deepEqual(Array.from(secret), [0xab, 0xab, 0xab, 0xab]);
}).pipe(Effect.provide(makeDeterministicSecretStoreLayer(0xab))),
);
it.effect("reuses an existing secret instead of regenerating it", () =>
Effect.gen(function* () {
const secretStore = yield* ServerSecretStore;
@@ -180,9 +207,10 @@ it.layer(NodeServices.layer)("ServerSecretStoreLive", (it) => {
);
const persisted = yield* secretStore.get("session-signing-key");
expect(persisted).not.toBeNull();
expect(Array.from(first)).toEqual(Array.from(persisted ?? new Uint8Array()));
expect(Array.from(second)).toEqual(Array.from(persisted ?? new Uint8Array()));
assert.isTrue(Option.isSome(persisted));
const persistedBytes = Option.getOrThrow(persisted);
assert.deepEqual(Array.from(first), Array.from(persistedBytes));
assert.deepEqual(Array.from(second), Array.from(persistedBytes));
}).pipe(Effect.provide(makeConcurrentCreateSecretStoreLayer())),
);
@@ -1,8 +1,8 @@
import * as Crypto from "node:crypto";
import * as Crypto from "effect/Crypto";
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 Predicate from "effect/Predicate";
import * as PlatformError from "effect/PlatformError";
@@ -15,6 +15,7 @@ import {
} from "../Services/ServerSecretStore.ts";
export const makeServerSecretStore = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
@@ -37,10 +38,10 @@ export const makeServerSecretStore = Effect.gen(function* () {
const get: ServerSecretStoreShape["get"] = (name) =>
fileSystem.readFile(resolveSecretPath(name)).pipe(
Effect.map((bytes) => Uint8Array.from(bytes)),
Effect.map((bytes) => Option.some(Uint8Array.from(bytes))),
Effect.catch((cause) =>
cause.reason._tag === "NotFound"
? Effect.succeed(null)
? Effect.succeed(Option.none())
: Effect.fail(
new SecretStoreError({
message: `Failed to read secret ${name}.`,
@@ -52,26 +53,37 @@ export const makeServerSecretStore = Effect.gen(function* () {
const set: ServerSecretStoreShape["set"] = (name, value) => {
const secretPath = resolveSecretPath(name);
const tempPath = `${secretPath}.${Crypto.randomUUID()}.tmp`;
return Effect.gen(function* () {
yield* fileSystem.writeFile(tempPath, value);
yield* fileSystem.chmod(tempPath, 0o600);
yield* fileSystem.rename(tempPath, secretPath);
yield* fileSystem.chmod(secretPath, 0o600);
}).pipe(
Effect.catch((cause) =>
fileSystem.remove(tempPath).pipe(
Effect.ignore,
Effect.flatMap(() =>
Effect.fail(
new SecretStoreError({
message: `Failed to persist secret ${name}.`,
cause,
}),
return crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new SecretStoreError({
message: `Failed to generate temporary secret path for ${name}.`,
cause,
}),
),
Effect.flatMap((uuid) => {
const tempPath = `${secretPath}.${uuid}.tmp`;
return Effect.gen(function* () {
yield* fileSystem.writeFile(tempPath, value);
yield* fileSystem.chmod(tempPath, 0o600);
yield* fileSystem.rename(tempPath, secretPath);
yield* fileSystem.chmod(secretPath, 0o600);
}).pipe(
Effect.catch((cause) =>
fileSystem.remove(tempPath).pipe(
Effect.ignore,
Effect.flatMap(() =>
Effect.fail(
new SecretStoreError({
message: `Failed to persist secret ${name}.`,
cause,
}),
),
),
),
),
),
),
);
}),
);
};
@@ -101,27 +113,39 @@ export const makeServerSecretStore = Effect.gen(function* () {
const getOrCreateRandom: ServerSecretStoreShape["getOrCreateRandom"] = (name, bytes) =>
get(name).pipe(
Effect.flatMap((existing) => {
if (existing) {
return Effect.succeed(existing);
if (Option.isSome(existing)) {
return Effect.succeed(existing.value);
}
const generated = Crypto.randomBytes(bytes);
return create(name, generated).pipe(
Effect.as(Uint8Array.from(generated)),
Effect.catchTag("SecretStoreError", (error) =>
isPlatformError(error.cause) && error.cause.reason._tag === "AlreadyExists"
? get(name).pipe(
Effect.flatMap((created) =>
created !== null
? Effect.succeed(created)
: Effect.fail(
new SecretStoreError({
message: `Failed to read secret ${name} after concurrent creation.`,
}),
),
),
)
: Effect.fail(error),
return crypto.randomBytes(bytes).pipe(
Effect.mapError(
(cause) =>
new SecretStoreError({
message: `Failed to generate secret ${name}.`,
cause,
}),
),
Effect.flatMap((generated) =>
create(name, generated).pipe(
Effect.as(Uint8Array.from(generated)),
Effect.catchTag("SecretStoreError", (error) =>
isPlatformError(error.cause) && error.cause.reason._tag === "AlreadyExists"
? get(name).pipe(
Effect.flatMap((created) =>
Option.match(created, {
onSome: Effect.succeed,
onNone: () =>
Effect.fail(
new SecretStoreError({
message: `Failed to read secret ${name} after concurrent creation.`,
}),
),
}),
),
)
: Effect.fail(error),
),
),
),
);
}),
@@ -1,14 +1,18 @@
import * as Data from "effect/Data";
import * as Context from "effect/Context";
import type * as Effect from "effect/Effect";
import type * as Option from "effect/Option";
import * as Schema from "effect/Schema";
export class SecretStoreError extends Data.TaggedError("SecretStoreError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class SecretStoreError extends Schema.TaggedErrorClass<SecretStoreError>()(
"SecretStoreError",
{
message: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {}
export interface ServerSecretStoreShape {
readonly get: (name: string) => Effect.Effect<Uint8Array | null, SecretStoreError>;
readonly get: (name: string) => Effect.Effect<Option.Option<Uint8Array>, SecretStoreError>;
readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
readonly getOrCreateRandom: (
name: string,
@@ -1,4 +1,4 @@
import { describe, expect, it } from "@effect/vitest";
import { assert, describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -66,6 +66,51 @@ describe("ProcessDiagnostics", () => {
}),
);
it.effect("parses Windows process rows from schema-decoded JSON output", () =>
Effect.gen(function* () {
const rows = yield* ProcessDiagnostics.parseWindowsProcessRows(
[
"[",
'{"ProcessId":10,"ParentProcessId":1,"Name":"node.exe","CommandLine":"node server.js","Status":"Running","WorkingSetSize":1024,"PercentProcessorTime":1.5},',
'{"ProcessId":0,"ParentProcessId":1,"Name":"invalid.exe","WorkingSetSize":2048,"PercentProcessorTime":2},',
'{"ProcessId":11,"ParentProcessId":10,"Name":"agent.exe","CommandLine":null,"Status":null,"WorkingSetSize":2048.4,"PercentProcessorTime":3.25}',
"]",
].join(""),
);
assert.deepEqual(rows, [
{
pid: 10,
ppid: 1,
pgid: null,
status: "Running",
cpuPercent: 1.5,
rssBytes: 1024,
elapsed: "",
command: "node server.js",
},
{
pid: 11,
ppid: 10,
pgid: null,
status: "Live",
cpuPercent: 3.25,
rssBytes: 2048,
elapsed: "",
command: "agent.exe",
},
]);
}),
);
it.effect("ignores malformed Windows process JSON output", () =>
Effect.gen(function* () {
const rows = yield* ProcessDiagnostics.parseWindowsProcessRows("{not-json");
assert.deepEqual(rows, []);
}),
);
it.effect("aggregates only descendants of the server process", () =>
Effect.sync(() => {
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
@@ -30,6 +30,21 @@ const PROCESS_QUERY_TIMEOUT_MS = 1_000;
const POSIX_PROCESS_QUERY_COMMAND = "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=";
const PROCESS_QUERY_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
const WindowsProcessRecord = Schema.Struct({
ProcessId: Schema.Number,
ParentProcessId: Schema.Number,
Name: Schema.optional(Schema.NullOr(Schema.String)),
CommandLine: Schema.optional(Schema.NullOr(Schema.String)),
Status: Schema.optional(Schema.NullOr(Schema.String)),
WorkingSetSize: Schema.optional(Schema.NullOr(Schema.Number)),
PercentProcessorTime: Schema.optional(Schema.NullOr(Schema.Number)),
});
type WindowsProcessRecord = Schema.Schema.Type<typeof WindowsProcessRecord>;
const WindowsProcessRecordsJson = Schema.fromJsonString(
Schema.Union([Schema.Array(WindowsProcessRecord), WindowsProcessRecord]),
);
const decodeWindowsProcessRecordsJson = Schema.decodeUnknownEffect(WindowsProcessRecordsJson);
export interface ProcessDiagnosticsShape {
readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;
readonly signal: (input: {
@@ -139,51 +154,62 @@ export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow>
return rows;
}
function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
if (typeof value !== "object" || value === null) return null;
const record = value as Record<string, unknown>;
const pid = typeof record.ProcessId === "number" ? record.ProcessId : null;
const ppid = typeof record.ParentProcessId === "number" ? record.ParentProcessId : null;
function normalizeWindowsProcessRow(record: WindowsProcessRecord): Option.Option<ProcessRow> {
const pid = record.ProcessId;
const ppid = record.ParentProcessId;
const commandLine =
typeof record.CommandLine === "string" && record.CommandLine.trim().length > 0
record.CommandLine !== null &&
record.CommandLine !== undefined &&
record.CommandLine.trim().length > 0
? record.CommandLine
: typeof record.Name === "string"
: record.Name !== null && record.Name !== undefined && record.Name.trim().length > 0
? record.Name
: null;
: undefined;
const workingSet =
typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
record.WorkingSetSize !== null &&
record.WorkingSetSize !== undefined &&
Number.isFinite(record.WorkingSetSize)
? Math.max(0, Math.round(record.WorkingSetSize))
: 0;
const cpuPercent =
typeof record.PercentProcessorTime === "number" && Number.isFinite(record.PercentProcessorTime)
record.PercentProcessorTime !== null &&
record.PercentProcessorTime !== undefined &&
Number.isFinite(record.PercentProcessorTime)
? Math.max(0, record.PercentProcessorTime)
: 0;
if (!pid || pid <= 0 || ppid === null || ppid < 0 || !commandLine) return null;
return {
if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(ppid) || ppid < 0 || !commandLine) {
return Option.none();
}
return Option.some({
pid,
ppid,
pgid: null,
status: typeof record.Status === "string" && record.Status.length > 0 ? record.Status : "Live",
status:
record.Status !== null && record.Status !== undefined && record.Status.length > 0
? record.Status
: "Live",
cpuPercent,
rssBytes: workingSet,
elapsed: "",
command: commandLine,
};
});
}
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
if (output.trim().length === 0) return [];
try {
const parsed = JSON.parse(output) as unknown;
const records = Array.isArray(parsed) ? parsed : [parsed];
return records.flatMap((record) => {
const row = normalizeWindowsProcessRow(record);
return row ? [row] : [];
});
} catch {
return [];
}
export function parseWindowsProcessRows(output: string): Effect.Effect<ReadonlyArray<ProcessRow>> {
if (output.trim().length === 0) return Effect.succeed([]);
return decodeWindowsProcessRecordsJson(output).pipe(
Effect.map((parsed) => {
const records = Array.isArray(parsed) ? parsed : [parsed];
return records.flatMap((record) =>
Option.match(normalizeWindowsProcessRow(record), {
onNone: () => [],
onSome: (row) => [row],
}),
);
}),
Effect.catch(() => Effect.succeed([])),
);
}
export function buildDescendantEntries(
@@ -365,7 +391,7 @@ function readWindowsProcessRows(): Effect.Effect<
? Effect.fail(
toProcessDiagnosticsError(result.stderr.trim() || "PowerShell process query failed."),
)
: Effect.succeed(parseWindowsProcessRows(result.stdout)),
: parseWindowsProcessRows(result.stdout),
),
);
}
+5 -1
View File
@@ -31,6 +31,7 @@ import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
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 Equal from "effect/Equal";
import * as PubSub from "effect/PubSub";
@@ -349,7 +350,10 @@ const makeServerSettings = Effect.gen(function* () {
);
environment.push({
...variable,
value: secret ? textDecoder.decode(secret) : "",
value: Option.match(secret, {
onSome: (bytes) => textDecoder.decode(bytes),
onNone: () => "",
}),
});
}
providerInstances[instanceId] = {