more ffect: Service/Layer separation

This commit is contained in:
Julius Marminge authored and Julius Marminge committed 2026-02-26 13:20:36 -08:00
1 parent fa1663c131
commit bbf4e6bd3c
10 files changed
+110 -44

No files matched your search

+1 -1
View File
@@ -6,8 +6,8 @@ import type { OrchestrationEvent } from "@t3tools/contracts";
import { Effect } from "effect";
import { afterEach, describe, expect, it } from "vitest";
import type { OrchestrationEventRepositoryShape } from "../persistence/Services/OrchestrationEvents";
import { OrchestrationEngine } from "./engine";
import type { OrchestrationEventRepositoryShape } from "./eventRepository";
const tempDirs: string[] = [];
+2 -2
View File
@@ -20,8 +20,8 @@ import {
} from "effect";
import { createLogger } from "../logger";
import type { OrchestrationEventRepositoryShape } from "./eventRepository";
import { makeSqliteOrchestrationEventRepository } from "./eventStore";
import type { OrchestrationEventRepositoryShape } from "../persistence/Services/OrchestrationEvents";
import { makeSqliteOrchestrationEventRepository } from "../persistence/Layers/OrchestrationEvents";
import { createEmptyReadModel, reduceEvent } from "./reducer";
import { UI_ENTITY_CONTRACTS } from "./uiContractInventory";
@@ -1,20 +0,0 @@
import type { OrchestrationEvent } from "@t3tools/contracts";
import { Context } from "effect";
import type { Effect } from "effect";
export interface OrchestrationEventRepositoryShape {
readonly append: (
event: Omit<OrchestrationEvent, "sequence">,
) => Effect.Effect<OrchestrationEvent>;
readonly readFromSequence: (
sequenceExclusive: number,
limit?: number,
) => Effect.Effect<OrchestrationEvent[]>;
readonly readAll: () => Effect.Effect<OrchestrationEvent[]>;
readonly close: () => void;
}
export class OrchestrationEventRepository extends Context.Tag("orchestration/EventRepository")<
OrchestrationEventRepository,
OrchestrationEventRepositoryShape
>() {}
@@ -1,90 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { DatabaseSync } from "node:sqlite";
import { Runtime } from "effect";
import { afterEach, describe, expect, it } from "vitest";
import { makeSqliteOrchestrationEventRepository } from "./eventStore";
const tempDirs: string[] = [];
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
describe("SqliteEventStore", () => {
it("persists and replays events across restarts", async () => {
const stateDir = makeTempDir("t3code-event-store-");
const dbPath = path.join(stateDir, "orchestration.sqlite");
const runtime = Runtime.defaultRuntime;
const createdAt = new Date().toISOString();
const first = makeSqliteOrchestrationEventRepository(dbPath);
const saved = await Runtime.runPromise(runtime)(
first.append({
eventId: "event-1",
type: "project.created",
aggregateType: "project",
aggregateId: "project-1",
occurredAt: createdAt,
commandId: "cmd-1",
payload: { id: "project-1", name: "demo" },
}),
);
expect(saved.sequence).toBe(1);
first.close();
const second = makeSqliteOrchestrationEventRepository(dbPath);
const replayed = await Runtime.runPromise(runtime)(second.readFromSequence(0));
expect(replayed).toEqual([saved]);
second.close();
});
it("creates and reuses the migrator tracking table", async () => {
const stateDir = makeTempDir("t3code-event-store-migrations-");
const dbPath = path.join(stateDir, "orchestration.sqlite");
const runtime = Runtime.defaultRuntime;
const first = makeSqliteOrchestrationEventRepository(dbPath);
await Runtime.runPromise(runtime)(first.readAll());
first.close();
const second = makeSqliteOrchestrationEventRepository(dbPath);
await Runtime.runPromise(runtime)(second.readAll());
second.close();
const db = new DatabaseSync(dbPath, { readOnly: true });
const tableRow = db
.prepare(
`
SELECT name
FROM sqlite_master
WHERE type = 'table' AND name = 'orchestration_sql_migrations'
`,
)
.get() as { name: string } | undefined;
expect(tableRow?.name).toBe("orchestration_sql_migrations");
const migrationRows = db
.prepare(
`
SELECT *
FROM orchestration_sql_migrations
`,
)
.all() as Array<Record<string, unknown>>;
expect(migrationRows).toHaveLength(1);
expect(Object.values(migrationRows[0] ?? {}).length).toBeGreaterThan(0);
db.close();
});
});
-190
View File
@@ -1,190 +0,0 @@
import fs from "node:fs";
import path from "node:path";
import type { OrchestrationEvent } from "@t3tools/contracts";
import { OrchestrationEventSchema } from "@t3tools/contracts";
import type { SqlClient as SqlClientService } from "@effect/sql/SqlClient";
import * as SqlClient from "@effect/sql/SqlClient";
import * as SqlSchema from "@effect/sql/SqlSchema";
import * as SqliteClient from "@effect/sql-sqlite-node/SqliteClient";
import { Effect, ManagedRuntime, Schema } from "effect";
import type { OrchestrationEventRepositoryShape } from "./eventRepository";
import { runOrchestrationMigrations } from "./migrations";
const decodeEvent = Schema.decodeUnknownSync(OrchestrationEventSchema);
const EventRowSchema = Schema.Struct({
sequence: Schema.Number,
eventId: Schema.String,
type: Schema.String,
aggregateType: Schema.String,
aggregateId: Schema.String,
occurredAt: Schema.String,
commandId: Schema.NullOr(Schema.String),
payloadJson: Schema.String,
});
type EventRow = Schema.Schema.Type<typeof EventRowSchema>;
const AppendEventRequestSchema = Schema.Struct({
eventId: Schema.String,
type: Schema.String,
aggregateType: Schema.String,
aggregateId: Schema.String,
occurredAt: Schema.String,
commandId: Schema.NullOr(Schema.String),
payloadJson: Schema.String,
});
const ReadFromSequenceRequestSchema = Schema.Struct({
sequenceExclusive: Schema.Number,
limit: Schema.Number,
});
const appendEventRow = SqlSchema.single({
Request: AppendEventRequestSchema,
Result: EventRowSchema,
execute: (request) =>
Effect.flatMap(SqlClient.SqlClient, (sql) =>
sql`
INSERT INTO orchestration_events (
event_id,
event_type,
aggregate_type,
aggregate_id,
occurred_at,
command_id,
payload_json
)
VALUES (
${request.eventId},
${request.type},
${request.aggregateType},
${request.aggregateId},
${request.occurredAt},
${request.commandId},
${request.payloadJson}
)
RETURNING
sequence,
event_id AS "eventId",
event_type AS "type",
aggregate_type AS "aggregateType",
aggregate_id AS "aggregateId",
occurred_at AS "occurredAt",
command_id AS "commandId",
payload_json AS "payloadJson"
`,
),
});
const readEventRowsFromSequence = SqlSchema.findAll({
Request: ReadFromSequenceRequestSchema,
Result: EventRowSchema,
execute: (request) =>
Effect.flatMap(SqlClient.SqlClient, (sql) =>
sql`
SELECT
sequence,
event_id AS "eventId",
event_type AS "type",
aggregate_type AS "aggregateType",
aggregate_id AS "aggregateId",
occurred_at AS "occurredAt",
command_id AS "commandId",
payload_json AS "payloadJson"
FROM orchestration_events
WHERE sequence > ${request.sequenceExclusive}
ORDER BY sequence ASC
LIMIT ${request.limit}
`,
),
});
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,
});
}
export function makeSqliteOrchestrationEventRepository(
dbPath: string,
): OrchestrationEventRepositoryShape {
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
const runtime: ManagedRuntime.ManagedRuntime<SqlClientService, unknown> = ManagedRuntime.make(
SqliteClient.layer({
filename: dbPath,
}),
);
let closed = false;
const provideSql = <A, E>(
effect: Effect.Effect<A, E, SqlClientService>,
): Effect.Effect<A, E | unknown> => Effect.provide(effect, runtime);
const initialize = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`PRAGMA journal_mode = WAL;`;
yield* sql`PRAGMA foreign_keys = ON;`;
yield* runOrchestrationMigrations;
});
const initialized = runtime.runPromise(initialize).then(() => undefined);
const ensureInitialized = Effect.promise(() => initialized);
const append: OrchestrationEventRepositoryShape["append"] = (event) =>
Effect.gen(function* () {
yield* ensureInitialized;
const row = yield* provideSql(
appendEventRow({
eventId: event.eventId,
type: event.type,
aggregateType: event.aggregateType,
aggregateId: event.aggregateId,
occurredAt: event.occurredAt,
commandId: event.commandId,
payloadJson: JSON.stringify(event.payload),
}),
);
return eventRowToOrchestrationEvent(row);
}).pipe(Effect.orDie);
const readFromSequence: OrchestrationEventRepositoryShape["readFromSequence"] = (
sequenceExclusive,
limit = 1_000,
) =>
Effect.gen(function* () {
yield* ensureInitialized;
const rows = yield* provideSql(
readEventRowsFromSequence({
sequenceExclusive,
limit,
}),
);
return rows.map(eventRowToOrchestrationEvent);
}).pipe(Effect.orDie);
const close = (): void => {
if (closed) {
return;
}
closed = true;
void runtime.dispose();
};
return {
append,
readFromSequence,
readAll: () => readFromSequence(0, Number.MAX_SAFE_INTEGER),
close,
};
}
+2 -2
View File
@@ -2,9 +2,9 @@ import path from "node:path";
import { Effect, Layer } from "effect";
import { OrchestrationEventRepository } from "./eventRepository";
import { OrchestrationEventRepository } from "../persistence/Services/OrchestrationEvents";
import { makeSqliteOrchestrationEventRepository } from "../persistence/Layers/OrchestrationEvents";
import { OrchestrationEngine } from "./engine";
import { makeSqliteOrchestrationEventRepository } from "./eventStore";
import { OrchestrationConfig, OrchestrationEngineService } from "./services";
export const OrchestrationEventRepositoryLive = Layer.effect(
@@ -1,31 +0,0 @@
import * as Migrator from "@effect/sql/Migrator";
import * as SqlClient from "@effect/sql/SqlClient";
import { Effect } from "effect";
const ORCHESTRATION_MIGRATIONS = Migrator.fromRecord({
"0001_create_orchestration_events": Effect.flatMap(SqlClient.SqlClient, (sql) =>
Effect.gen(function* () {
yield* sql`
CREATE TABLE IF NOT EXISTS orchestration_events (
sequence INTEGER PRIMARY KEY AUTOINCREMENT,
event_id TEXT NOT NULL UNIQUE,
event_type TEXT NOT NULL,
aggregate_type TEXT NOT NULL,
aggregate_id TEXT NOT NULL,
occurred_at TEXT NOT NULL,
command_id TEXT,
payload_json TEXT NOT NULL
)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_orch_events_aggregate
ON orchestration_events(aggregate_type, aggregate_id, sequence)
`;
}),
),
});
export const runOrchestrationMigrations = Migrator.make({})({
loader: ORCHESTRATION_MIGRATIONS,
table: "orchestration_sql_migrations",
});