This commit is contained in:
Julius Marminge committed 2026-02-22 11:07:39 -08:00
1 parent b0c9c2a56e
commit a096fe7372
5 files changed
+104 -113

No files matched your search

+100 -105
View File
@@ -162,130 +162,125 @@ function mapCommandToEvent(command: OrchestrationCommand): Omit<OrchestrationEve
const decodeUnknownCommand = Schema.decodeUnknownEffect(OrchestrationCommandSchema);
const makeOrchestrationEngine =
Effect.gen(function* () {
const logger = createLogger("orchestration");
const eventStore = yield* OrchestrationEventRepository;
const makeOrchestrationEngine = Effect.gen(function* () {
const logger = createLogger("orchestration");
const eventStore = yield* OrchestrationEventRepository;
let readModel = createEmptyReadModel(new Date().toISOString());
let readModel = createEmptyReadModel(new Date().toISOString());
const commandQueue = yield* Queue.unbounded<CommandEnvelope>();
const readModelPubSub = yield* PubSub.unbounded<OrchestrationReadModel>();
const eventPubSub = yield* PubSub.unbounded<OrchestrationEvent>();
const commandQueue = yield* Queue.unbounded<CommandEnvelope>();
const readModelPubSub = yield* PubSub.unbounded<OrchestrationReadModel>();
const eventPubSub = yield* PubSub.unbounded<OrchestrationEvent>();
const readModelListeners = new Set<(snapshot: OrchestrationReadModel) => void>();
const domainEventListeners = new Set<(event: OrchestrationEvent) => void>();
const readModelListeners = new Set<(snapshot: OrchestrationReadModel) => void>();
const domainEventListeners = new Set<(event: OrchestrationEvent) => void>();
const notifyReadModelListeners = (snapshot: OrchestrationReadModel) =>
Effect.forEach(readModelListeners, (listener) =>
Effect.try({
try: () => listener(snapshot),
catch: toListenerCallbackError("read-model"),
}),
).pipe(Effect.asVoid);
const notifyReadModelListeners = (snapshot: OrchestrationReadModel) =>
Effect.forEach(readModelListeners, (listener) =>
Effect.try({
try: () => listener(snapshot),
catch: toListenerCallbackError("read-model"),
}),
).pipe(Effect.asVoid);
const notifyDomainEventListeners = (event: OrchestrationEvent) =>
Effect.forEach(domainEventListeners, (listener) =>
Effect.try({
try: () => listener(event),
catch: toListenerCallbackError("domain-event"),
}),
).pipe(Effect.asVoid);
const notifyDomainEventListeners = (event: OrchestrationEvent) =>
Effect.forEach(domainEventListeners, (listener) =>
Effect.try({
try: () => listener(event),
catch: toListenerCallbackError("domain-event"),
}),
).pipe(Effect.asVoid);
const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> =>
Effect.gen(function* () {
const eventBase = mapCommandToEvent(envelope.command);
const savedEvent = yield* eventStore.append(eventBase);
readModel = yield* reduceEvent(readModel, savedEvent);
const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> =>
Effect.gen(function* () {
const eventBase = mapCommandToEvent(envelope.command);
const savedEvent = yield* eventStore.append(eventBase);
readModel = yield* reduceEvent(readModel, savedEvent);
const snapshot = readModel;
yield* Effect.all([
PubSub.publish(eventPubSub, savedEvent),
PubSub.publish(readModelPubSub, snapshot),
]);
const snapshot = readModel;
yield* Effect.all([
PubSub.publish(eventPubSub, savedEvent),
PubSub.publish(readModelPubSub, snapshot),
]);
yield* notifyDomainEventListeners(savedEvent);
yield* notifyReadModelListeners(snapshot);
yield* notifyDomainEventListeners(savedEvent);
yield* notifyReadModelListeners(snapshot);
yield* Deferred.succeed(envelope.result, { sequence: savedEvent.sequence });
}).pipe(
Effect.catch((error) => Deferred.fail(envelope.result, error).pipe(Effect.asVoid)),
);
yield* Deferred.succeed(envelope.result, { sequence: savedEvent.sequence });
}).pipe(Effect.catch((error) => Deferred.fail(envelope.result, error).pipe(Effect.asVoid)));
const bootstrapReadModel: Effect.Effect<void, OrchestrationDispatchError> = Effect.gen(
function* () {
const existingEvents = yield* eventStore.readAll();
for (const event of existingEvents) {
readModel = yield* reduceEvent(readModel, event);
}
},
);
const bootstrapReadModel: Effect.Effect<void, OrchestrationDispatchError> = Effect.gen(
function* () {
const existingEvents = yield* eventStore.readAll();
for (const event of existingEvents) {
readModel = yield* reduceEvent(readModel, event);
}
},
);
yield* bootstrapReadModel;
yield* bootstrapReadModel;
const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
yield* Effect.forkScoped(worker);
logger.info("orchestration engine started", {
sequence: readModel.sequence,
const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
yield* Effect.forkScoped(worker);
logger.info("orchestration engine started", {
sequence: readModel.sequence,
});
const getSnapshot: OrchestrationEngineShape["getSnapshot"] = () =>
Effect.sync((): OrchestrationReadModel => readModel);
const replayEvents: OrchestrationEngineShape["replayEvents"] = (fromSequenceExclusive) =>
eventStore.readFromSequence(fromSequenceExclusive);
const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
Effect.gen(function* () {
const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();
yield* Queue.offer(commandQueue, { command, result });
return yield* Deferred.await(result);
});
const getSnapshot: OrchestrationEngineShape["getSnapshot"] = () =>
Effect.sync((): OrchestrationReadModel => readModel);
const dispatchUnknown: OrchestrationEngineShape["dispatchUnknown"] = (command) =>
Effect.gen(function* () {
const payload =
typeof command === "string"
? yield* Effect.try({
try: () => JSON.parse(command) as unknown,
catch: toOrchestrationJsonParseError,
})
: command;
const replayEvents: OrchestrationEngineShape["replayEvents"] = (fromSequenceExclusive) =>
eventStore.readFromSequence(fromSequenceExclusive);
const decoded = yield* decodeUnknownCommand(payload).pipe(
Effect.mapError(toOrchestrationCommandDecodeError),
);
const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
Effect.gen(function* () {
const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();
yield* Queue.offer(commandQueue, { command, result });
return yield* Deferred.await(result);
});
return yield* dispatch(decoded);
});
const dispatchUnknown: OrchestrationEngineShape["dispatchUnknown"] = (command) =>
Effect.gen(function* () {
const payload =
typeof command === "string"
? yield* Effect.try({
try: () => JSON.parse(command) as unknown,
catch: toOrchestrationJsonParseError,
})
: command;
const subscribeToReadModel: OrchestrationEngineShape["subscribeToReadModel"] = (callback) =>
Effect.sync(() => {
readModelListeners.add(callback);
return () => {
readModelListeners.delete(callback);
};
});
const decoded = yield* decodeUnknownCommand(payload).pipe(
Effect.mapError(toOrchestrationCommandDecodeError),
);
const subscribeToDomainEvents: OrchestrationEngineShape["subscribeToDomainEvents"] = (callback) =>
Effect.sync(() => {
domainEventListeners.add(callback);
return () => {
domainEventListeners.delete(callback);
};
});
return yield* dispatch(decoded);
});
const subscribeToReadModel: OrchestrationEngineShape["subscribeToReadModel"] = (callback) =>
Effect.sync(() => {
readModelListeners.add(callback);
return () => {
readModelListeners.delete(callback);
};
});
const subscribeToDomainEvents: OrchestrationEngineShape["subscribeToDomainEvents"] = (
callback,
) =>
Effect.sync(() => {
domainEventListeners.add(callback);
return () => {
domainEventListeners.delete(callback);
};
});
return {
getSnapshot,
replayEvents,
dispatchUnknown,
dispatch,
subscribeToReadModel,
subscribeToDomainEvents,
} satisfies OrchestrationEngineShape;
});
return {
getSnapshot,
replayEvents,
dispatchUnknown,
dispatch,
subscribeToReadModel,
subscribeToDomainEvents,
} satisfies OrchestrationEngineShape;
});
export const OrchestrationEngineLive = Layer.effect(
OrchestrationEngineService,
+1 -1
View File
@@ -36,7 +36,7 @@ function decodeForEvent<A>(
): Effect.Effect<A, OrchestrationReducerDecodeError> {
return Schema.decodeUnknownEffect(schema)(value).pipe(
Effect.mapError(toReducerDecodeError(`${eventType}:${field}`)),
) as Effect.Effect<A, OrchestrationReducerDecodeError>
) as Effect.Effect<A, OrchestrationReducerDecodeError>;
}
const ThreadCreatedPayloadSchema = Schema.Struct({
@@ -3,7 +3,7 @@ import os from "node:os";
import path from "node:path";
import { DatabaseSync } from "node:sqlite";
import { ManagedRuntime, Effect } from "effect";
import { ManagedRuntime, Effect } from "effect";
import { afterEach, describe, expect, it } from "vitest";
import { OrchestrationEventRepository } from "../Services/OrchestrationEvents.ts";
@@ -57,7 +57,6 @@ describe("OrchestrationEventRepository", () => {
const stateDir = makeTempDir("t3code-event-store-migrations-");
const dbPath = path.join(stateDir, "orchestration.sqlite");
const firstRuntime = ManagedRuntime.make(makeSqliteOrchestrationEventRepositoryLive(dbPath));
const first = await firstRuntime.runPromise(Effect.service(OrchestrationEventRepository));
await firstRuntime.runPromise(first.readAll());
@@ -381,7 +381,7 @@ const makeRepository = Effect.gen(function* () {
Effect.mapError(toPersistenceSqlError("ProjectRepository.remove:findById")),
);
if (Option.isNone(existing)) {
return yield* (new ProjectNotFoundError({ projectId: input.id }));
return yield* new ProjectNotFoundError({ projectId: input.id });
}
yield* deleteProject({ id: input.id }).pipe(
@@ -396,7 +396,7 @@ const makeRepository = Effect.gen(function* () {
Effect.mapError(toPersistenceSqlError("ProjectRepository.updateScripts:findById")),
);
if (Option.isNone(existing)) {
return yield* (new ProjectNotFoundError({ projectId: input.id }));
return yield* new ProjectNotFoundError({ projectId: input.id });
}
const nextScripts = yield* parseProjectScripts(
@@ -5,8 +5,6 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqliteClient from "@effect/sql-sqlite-node/SqliteClient";
import { Effect, Layer, ServiceMap } from "effect";
import { runMigrations } from "../Migrations.ts";
export interface PersistenceConfigShape {
@@ -38,7 +36,6 @@ export function makeSqlitePersistenceLive(dbPath: string) {
).pipe(Layer.provide(SqliteClientLive));
}
export const SqlitePersistenceLive = Layer.unwrap(
Effect.map(Effect.service(PersistenceConfig), ({ dbPath }) => makeSqlitePersistenceLive(dbPath)),
);