more effect: error handling

This commit is contained in:
Julius Marminge committed 2026-02-22 01:43:53 -08:00
1 parent 9ef01eb97e
commit 2c8e35ceb8
11 files changed
+846 -260

No files matched your search

+126
View File
@@ -0,0 +1,126 @@
import { ParseResult, Schema } from "effect";
export class PersistenceSqlError extends Schema.TaggedError<PersistenceSqlError>()(
"PersistenceSqlError",
{
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `SQL error in ${this.operation}: ${this.detail}`;
}
}
export class PersistenceDecodeError extends Schema.TaggedError<PersistenceDecodeError>()(
"PersistenceDecodeError",
{
operation: Schema.String,
issue: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Decode error in ${this.operation}: ${this.issue}`;
}
}
export class PersistenceSerializationError extends Schema.TaggedError<PersistenceSerializationError>()(
"PersistenceSerializationError",
{
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Serialization error in ${this.operation}: ${this.detail}`;
}
}
export class ProjectValidationError extends Schema.TaggedError<ProjectValidationError>()(
"ProjectValidationError",
{
operation: Schema.String,
issue: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Project validation failed in ${this.operation}: ${this.issue}`;
}
}
export class ProjectPathMissingError extends Schema.TaggedError<ProjectPathMissingError>()(
"ProjectPathMissingError",
{
cwd: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Project path does not exist: ${this.cwd}`;
}
}
export class ProjectNotFoundError extends Schema.TaggedError<ProjectNotFoundError>()(
"ProjectNotFoundError",
{
projectId: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Project not found: ${this.projectId}`;
}
}
export type ProjectRepositoryError =
| PersistenceSqlError
| PersistenceDecodeError
| PersistenceSerializationError
| ProjectValidationError
| ProjectPathMissingError
| ProjectNotFoundError;
export type OrchestrationEventRepositoryError =
| PersistenceSqlError
| PersistenceDecodeError
| PersistenceSerializationError;
export function toPersistenceSqlError(operation: string) {
return (cause: unknown): PersistenceSqlError =>
new PersistenceSqlError({
operation,
detail: `Failed to execute ${operation}`,
cause,
});
}
export function toPersistenceDecodeError(operation: string) {
return (error: ParseResult.ParseError): PersistenceDecodeError =>
new PersistenceDecodeError({
operation,
issue: ParseResult.TreeFormatter.formatErrorSync(error),
cause: error,
});
}
export function toPersistenceDecodeCauseError(operation: string) {
return (cause: unknown): PersistenceDecodeError =>
new PersistenceDecodeError({
operation,
issue: `Failed to execute ${operation}`,
cause,
});
}
export function toPersistenceSerializationError(operation: string) {
return (cause: unknown): PersistenceSerializationError =>
new PersistenceSerializationError({
operation,
detail: `Failed to execute ${operation}`,
cause,
});
}
@@ -80,9 +80,8 @@ describe("OrchestrationEventRepository", () => {
)
.get() as { name: string } | undefined;
expect(tableRow?.name).toBeDefined();
if (!tableRow) {
throw new Error("Expected migrations table to exist");
}
expect(tableRow).toBeDefined();
if (!tableRow) return;
const migrationRows = db
.prepare(
@@ -4,13 +4,20 @@ import * as SqlClient from "@effect/sql/SqlClient";
import * as SqlSchema from "@effect/sql/SqlSchema";
import { Effect, Layer, Schema } from "effect";
import {
toPersistenceDecodeCauseError,
toPersistenceDecodeError,
toPersistenceSerializationError,
toPersistenceSqlError,
type OrchestrationEventRepositoryError,
} from "../Errors";
import { makeSqlitePersistenceLive } from "./Sqlite";
import {
OrchestrationEventRepository,
type OrchestrationEventRepositoryShape,
} from "../Services/OrchestrationEvents";
const decodeEvent = Schema.decodeUnknownSync(OrchestrationEventSchema);
const decodeEvent = Schema.decodeUnknown(OrchestrationEventSchema);
const EventRowSchema = Schema.Struct({
sequence: Schema.Number,
@@ -40,17 +47,27 @@ const ReadFromSequenceRequestSchema = Schema.Struct({
limit: Schema.Number,
});
function eventRowToOrchestrationEvent(row: EventRow): OrchestrationEvent {
return decodeEvent({
sequence: row.sequence,
eventId: row.eventId,
type: row.type,
aggregateType: row.aggregateType,
aggregateId: row.aggregateId,
occurredAt: row.occurredAt,
commandId: row.commandId,
payload: JSON.parse(row.payloadJson) as unknown,
});
function eventRowToOrchestrationEvent(
row: EventRow,
operation: string,
): Effect.Effect<OrchestrationEvent, OrchestrationEventRepositoryError> {
return Effect.try({
try: () => JSON.parse(row.payloadJson) as unknown,
catch: toPersistenceDecodeCauseError(`${operation}:parsePayloadJson`),
}).pipe(
Effect.flatMap((payload) =>
decodeEvent({
sequence: row.sequence,
eventId: row.eventId,
type: row.type,
aggregateType: row.aggregateType,
aggregateId: row.aggregateId,
occurredAt: row.occurredAt,
commandId: row.commandId,
payload,
}).pipe(Effect.mapError(toPersistenceDecodeError(`${operation}:decodeEvent`))),
),
);
}
const makeRepository = Effect.gen(function* () {
@@ -113,23 +130,42 @@ const makeRepository = Effect.gen(function* () {
});
const append: OrchestrationEventRepositoryShape["append"] = (event) =>
appendEventRow({
eventId: event.eventId,
type: event.type,
aggregateType: event.aggregateType,
aggregateId: event.aggregateId,
occurredAt: event.occurredAt,
commandId: event.commandId,
payloadJson: JSON.stringify(event.payload),
}).pipe(Effect.map(eventRowToOrchestrationEvent), Effect.orDie);
Effect.try({
try: () => JSON.stringify(event.payload),
catch: toPersistenceSerializationError("OrchestrationEventRepository.append:encodePayload"),
}).pipe(
Effect.flatMap((payloadJson) =>
appendEventRow({
eventId: event.eventId,
type: event.type,
aggregateType: event.aggregateType,
aggregateId: event.aggregateId,
occurredAt: event.occurredAt,
commandId: event.commandId,
payloadJson,
}).pipe(
Effect.mapError(toPersistenceSqlError("OrchestrationEventRepository.append:insert")),
Effect.flatMap((row) =>
eventRowToOrchestrationEvent(row, "OrchestrationEventRepository.append:rowToEvent"),
),
),
),
);
const readFromSequence: OrchestrationEventRepositoryShape["readFromSequence"] = (
sequenceExclusive,
limit = 1_000,
) =>
readEventRowsFromSequence({ sequenceExclusive, limit }).pipe(
Effect.map((rows) => rows.map(eventRowToOrchestrationEvent)),
Effect.orDie,
Effect.mapError(toPersistenceSqlError("OrchestrationEventRepository.readFromSequence:query")),
Effect.flatMap((rows) =>
Effect.forEach(rows, (row) =>
eventRowToOrchestrationEvent(
row,
"OrchestrationEventRepository.readFromSequence:rowToEvent",
),
),
),
);
return {
+154 -37
View File
@@ -8,6 +8,7 @@ import type {
ProjectListResult,
ProjectRecord,
ProjectScript,
ProjectUpdateScriptsInput,
ProjectUpdateScriptsResult,
} from "@t3tools/contracts";
import {
@@ -22,6 +23,16 @@ import * as SqlClient from "@effect/sql/SqlClient";
import * as SqlSchema from "@effect/sql/SqlSchema";
import { Effect, Layer, Option, Schema } from "effect";
import {
PersistenceDecodeError,
ProjectNotFoundError,
ProjectPathMissingError,
ProjectValidationError,
toPersistenceDecodeCauseError,
toPersistenceSerializationError,
toPersistenceSqlError,
type ProjectRepositoryError,
} from "../Errors";
import { ProjectRepository, type ProjectRepositoryShape } from "../Services/Projects";
const ProjectRowSchema = Schema.Struct({
@@ -98,25 +109,101 @@ function inferProjectName(cwd: string): string {
return name.length > 0 ? name : "project";
}
function parseScriptsJson(raw: string): ProjectScript[] {
try {
const parsed = JSON.parse(raw) as unknown;
const scripts = projectScriptsSchema.parse(parsed);
return normalizeProjectScripts(scripts);
} catch {
return [];
function parseProjectScripts(
value: unknown,
operation: string,
): Effect.Effect<ProjectScript[], PersistenceDecodeError> {
const parsed = projectScriptsSchema.safeParse(value);
if (!parsed.success) {
return Effect.fail(
new PersistenceDecodeError({
operation,
issue: parsed.error.message,
cause: (parsed.error as { cause?: unknown }).cause,
}),
);
}
return Effect.succeed(normalizeProjectScripts(parsed.data));
}
function rowToProjectRecord(row: ProjectRow): ProjectRecord {
return projectRecordSchema.parse({
id: row.id,
cwd: row.cwd,
name: row.name,
scripts: parseScriptsJson(row.scriptsJson),
createdAt: row.createdAt,
updatedAt: row.updatedAt,
});
function decodeScriptsJson(
raw: string,
operation: string,
): Effect.Effect<ProjectScript[], ProjectRepositoryError> {
return Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: toPersistenceDecodeCauseError(`${operation}:parseScriptsJson`),
}).pipe(Effect.flatMap((value) => parseProjectScripts(value, `${operation}:decodeScripts`)));
}
function rowToProjectRecord(
row: ProjectRow,
operation: string,
): Effect.Effect<ProjectRecord, ProjectRepositoryError> {
return decodeScriptsJson(row.scriptsJson, `${operation}:scripts`).pipe(
Effect.flatMap((scripts) => {
const parsed = projectRecordSchema.safeParse({
id: row.id,
cwd: row.cwd,
name: row.name,
scripts,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
});
if (!parsed.success) {
return Effect.fail(
new PersistenceDecodeError({
operation: `${operation}:projectRecord`,
issue: parsed.error.message,
cause: (parsed.error as { cause?: unknown }).cause,
}),
);
}
return Effect.succeed(parsed.data);
}),
);
}
function decodeAddInput(rawInput: ProjectAddInput) {
const parsed = projectAddInputSchema.safeParse(rawInput);
if (!parsed.success) {
return Effect.fail(
new ProjectValidationError({
operation: "ProjectRepository.add",
issue: parsed.error.message,
cause: (parsed.error as { cause?: unknown }).cause,
}),
);
}
return Effect.succeed(parsed.data);
}
function decodeUpdateScriptsInput(rawInput: ProjectUpdateScriptsInput) {
const parsed = projectUpdateScriptsInputSchema.safeParse(rawInput);
if (!parsed.success) {
return Effect.fail(
new ProjectValidationError({
operation: "ProjectRepository.updateScripts",
issue: parsed.error.message,
cause: (parsed.error as { cause?: unknown }).cause,
}),
);
}
return Effect.succeed(parsed.data);
}
function decodeRemoveInput(rawInput: unknown) {
const parsed = projectRemoveInputSchema.safeParse(rawInput);
if (!parsed.success) {
return Effect.fail(
new ProjectValidationError({
operation: "ProjectRepository.remove",
issue: parsed.error.message,
cause: (parsed.error as { cause?: unknown }).cause,
}),
);
}
return Effect.succeed(parsed.data);
}
const makeRepository = Effect.gen(function* () {
@@ -231,24 +318,31 @@ const makeRepository = Effect.gen(function* () {
const list: ProjectRepositoryShape["list"] = () =>
listProjectRows(undefined).pipe(
Effect.map((rows): ProjectListResult => rows.map(rowToProjectRecord)),
Effect.map((projects) =>
projects.map((project) => ({ ...project, scripts: cloneScripts(project.scripts) })),
Effect.mapError(toPersistenceSqlError("ProjectRepository.list:query")),
Effect.flatMap((rows) =>
Effect.forEach(rows, (row) =>
rowToProjectRecord(row, "ProjectRepository.list:rowToProject"),
),
),
Effect.map(
(projects): ProjectListResult =>
projects.map((project) => ({ ...project, scripts: cloneScripts(project.scripts) })),
),
Effect.orDie,
);
const add: ProjectRepositoryShape["add"] = (rawInput) =>
Effect.gen(function* () {
const input = projectAddInputSchema.parse(rawInput as ProjectAddInput);
const input = yield* decodeAddInput(rawInput);
const normalizedCwd = normalizeCwd(input.cwd);
if (!isDirectory(normalizedCwd)) {
return yield* Effect.fail(new Error(`Project path does not exist: ${normalizedCwd}`));
return yield* Effect.fail(new ProjectPathMissingError({ cwd: normalizedCwd }));
}
const existing = yield* findProjectByCwd({ cwd: normalizedCwd }).pipe(Effect.orDie);
const existing = yield* findProjectByCwd({ cwd: normalizedCwd }).pipe(
Effect.mapError(toPersistenceSqlError("ProjectRepository.add:findByCwd")),
);
if (Option.isSome(existing)) {
const project = rowToProjectRecord(existing.value);
const project = yield* rowToProjectRecord(existing.value, "ProjectRepository.add:existing");
const result: ProjectAddResult = {
project: {
...project,
@@ -267,9 +361,9 @@ const makeRepository = Effect.gen(function* () {
scriptsJson: "[]",
createdAt: now,
updatedAt: now,
}).pipe(Effect.orDie);
}).pipe(Effect.mapError(toPersistenceSqlError("ProjectRepository.add:insert")));
const created = rowToProjectRecord(row);
const created = yield* rowToProjectRecord(row, "ProjectRepository.add:created");
const result: ProjectAddResult = {
project: {
...created,
@@ -282,27 +376,48 @@ const makeRepository = Effect.gen(function* () {
const remove: ProjectRepositoryShape["remove"] = (rawInput) =>
Effect.gen(function* () {
const input = projectRemoveInputSchema.parse(rawInput);
yield* deleteProject({ id: input.id }).pipe(Effect.orDie);
const input = yield* decodeRemoveInput(rawInput);
const existing = yield* findProjectById({ id: input.id }).pipe(
Effect.mapError(toPersistenceSqlError("ProjectRepository.remove:findById")),
);
if (Option.isNone(existing)) {
return yield* Effect.fail(new ProjectNotFoundError({ projectId: input.id }));
}
yield* deleteProject({ id: input.id }).pipe(
Effect.mapError(toPersistenceSqlError("ProjectRepository.remove:delete")),
);
});
const updateScripts: ProjectRepositoryShape["updateScripts"] = (rawInput) =>
Effect.gen(function* () {
const input = projectUpdateScriptsInputSchema.parse(rawInput);
const existing = yield* findProjectById({ id: input.id }).pipe(Effect.orDie);
const input = yield* decodeUpdateScriptsInput(rawInput);
const existing = yield* findProjectById({ id: input.id }).pipe(
Effect.mapError(toPersistenceSqlError("ProjectRepository.updateScripts:findById")),
);
if (Option.isNone(existing)) {
return yield* Effect.fail(new Error(`Project not found: ${input.id}`));
return yield* Effect.fail(new ProjectNotFoundError({ projectId: input.id }));
}
const nextScripts = normalizeProjectScripts(projectScriptsSchema.parse(input.scripts));
const nextScripts = yield* parseProjectScripts(
input.scripts,
"ProjectRepository.updateScripts:decodeScripts",
);
const scriptsJson = yield* Effect.try({
try: () => JSON.stringify(nextScripts),
catch: toPersistenceSerializationError("ProjectRepository.updateScripts:encodeScripts"),
});
const nextUpdatedAt = new Date().toISOString();
const updatedRow = yield* updateProjectScripts({
id: input.id,
scriptsJson: JSON.stringify(nextScripts),
scriptsJson,
updatedAt: nextUpdatedAt,
}).pipe(Effect.orDie);
}).pipe(Effect.mapError(toPersistenceSqlError("ProjectRepository.updateScripts:update")));
const updated = rowToProjectRecord(updatedRow);
const updated = yield* rowToProjectRecord(
updatedRow,
"ProjectRepository.updateScripts:updated",
);
const result: ProjectUpdateScriptsResult = {
project: {
...updated,
@@ -314,17 +429,19 @@ const makeRepository = Effect.gen(function* () {
const pruneMissing: ProjectRepositoryShape["pruneMissing"] = () =>
listProjectRows(undefined).pipe(
Effect.mapError(toPersistenceSqlError("ProjectRepository.pruneMissing:query")),
Effect.flatMap((rows) =>
Effect.forEach(rows, (row) => {
const normalizedCwd = normalizeCwd(row.cwd);
if (isDirectory(normalizedCwd)) {
return Effect.void;
}
return deleteProject({ id: row.id }).pipe(Effect.orDie);
return deleteProject({ id: row.id }).pipe(
Effect.mapError(toPersistenceSqlError("ProjectRepository.pruneMissing:delete")),
);
}),
),
Effect.asVoid,
Effect.orDie,
);
return {
@@ -1,18 +1,59 @@
/**
* OrchestrationEventRepository - Repository interface for orchestration events.
*
* Uses Effect `Context.Tag` for dependency injection and exposes typed
* persistence/decode errors for event append and replay operations.
*
* @module OrchestrationEventRepository
*/
import type { OrchestrationEvent } from "@t3tools/contracts";
import { Context } from "effect";
import type { Effect } from "effect";
import type { OrchestrationEventRepositoryError } from "../Errors";
export interface OrchestrationEventRepositoryShape {
/**
* Persist a new orchestration event.
*
* @param event - Event payload without sequence (assigned by storage).
* @returns Effect containing the stored event with assigned sequence.
*/
readonly append: (
event: Omit<OrchestrationEvent, "sequence">,
) => Effect.Effect<OrchestrationEvent>;
) => Effect.Effect<OrchestrationEvent, OrchestrationEventRepositoryError>;
/**
* Replay events after the provided sequence.
*
* @param sequenceExclusive - Sequence cursor (exclusive).
* @param limit - Maximum number of events to return.
* @returns Effect containing ordered events.
*/
readonly readFromSequence: (
sequenceExclusive: number,
limit?: number,
) => Effect.Effect<OrchestrationEvent[]>;
readonly readAll: () => Effect.Effect<OrchestrationEvent[]>;
) => Effect.Effect<OrchestrationEvent[], OrchestrationEventRepositoryError>;
/**
* Read all events from the beginning of the stream.
*
* @returns Effect containing all stored events.
*/
readonly readAll: () => Effect.Effect<OrchestrationEvent[], OrchestrationEventRepositoryError>;
}
/**
* OrchestrationEventRepository - Context tag for orchestration event persistence.
*
* @example
* ```ts
* const program = Effect.gen(function* () {
* const events = yield* OrchestrationEventRepository
* return yield* events.readAll()
* })
* ```
*/
export class OrchestrationEventRepository extends Context.Tag("orchestration/EventRepository")<
OrchestrationEventRepository,
OrchestrationEventRepositoryShape
@@ -1,3 +1,11 @@
/**
* ProjectRepository - Repository interface for project persistence.
*
* Uses Effect `Context.Tag` for dependency injection and returns typed
* domain errors for all operations.
*
* @module ProjectRepository
*/
import type {
ProjectAddInput,
ProjectAddResult,
@@ -9,16 +17,61 @@ import type {
import { Context } from "effect";
import type { Effect } from "effect";
import type { ProjectRepositoryError } from "../Errors";
export interface ProjectRepositoryShape {
readonly list: () => Effect.Effect<ProjectListResult>;
readonly add: (input: ProjectAddInput) => Effect.Effect<ProjectAddResult, Error>;
readonly remove: (input: ProjectRemoveInput) => Effect.Effect<void, Error>;
/**
* List all persisted projects.
*
* @returns Effect containing all project records.
*/
readonly list: () => Effect.Effect<ProjectListResult, ProjectRepositoryError>;
/**
* Add a project by cwd, or return the existing project when the cwd already exists.
*
* @param input - Project creation payload.
* @returns Effect containing the project and whether it was newly created.
*/
readonly add: (input: ProjectAddInput) => Effect.Effect<ProjectAddResult, ProjectRepositoryError>;
/**
* Remove a persisted project.
*
* @param input - Project removal payload.
* @returns Effect containing void.
*/
readonly remove: (input: ProjectRemoveInput) => Effect.Effect<void, ProjectRepositoryError>;
/**
* Update the scripts for an existing project.
*
* @param input - Script update payload.
* @returns Effect containing the updated project.
*/
readonly updateScripts: (
input: ProjectUpdateScriptsInput,
) => Effect.Effect<ProjectUpdateScriptsResult, Error>;
readonly pruneMissing: () => Effect.Effect<void>;
) => Effect.Effect<ProjectUpdateScriptsResult, ProjectRepositoryError>;
/**
* Remove projects whose cwd no longer exists on disk.
*
* @returns Effect containing void.
*/
readonly pruneMissing: () => Effect.Effect<void, ProjectRepositoryError>;
}
/**
* ProjectRepository - Context tag for project persistence dependency injection.
*
* @example
* ```ts
* const program = Effect.gen(function* () {
* const projects = yield* ProjectRepository
* return yield* projects.list()
* })
* ```
*/
export class ProjectRepository extends Context.Tag("persistence/ProjectRepository")<
ProjectRepository,
ProjectRepositoryShape