answer-runs-workflow.ts
This file
Path
apps/platform/src/adapters/answer-runs-workflow.ts
63 lines · 1.9 KiB · TypeScript
Last changed by
Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
History of this fileTake it
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364import { AnswerRuns } from "@repo/project/answer-runs";import type { ProjectName } from "@repo/protocol/ids";import { Effect, Layer, Schema } from "effect";
import { AnswerParams } from "../answer-runs.ts";
export interface AnswerInstance { readonly id: string; readonly restart: () => Promise<void>; readonly status: () => Promise<{ readonly status: InstanceStatus["status"] }>;}
export interface AnswerWorkflow { readonly create: (options: { readonly id: string; readonly params: typeof AnswerParams.Encoded; }) => Promise<{ readonly id: string }>; readonly get: (id: string) => Promise<AnswerInstance>;}
const encodeParams = Schema.encodeEffect(AnswerParams);
// A run ends whenever the answer waits; the project starts the same request again once it can go on.const ended: ReadonlySet<InstanceStatus["status"]> = new Set([ "complete", "errored", "terminated",]);
const runAgain = (instance: AnswerInstance) => Effect.gen(function* () { const { status } = yield* Effect.tryPromise(() => instance.status());
if (ended.has(status)) { yield* Effect.tryPromise(() => instance.restart()); } });
export const AnswerRunsWorkflow = ( workflow: AnswerWorkflow, project: ProjectName): Layer.Layer<AnswerRuns> => Layer.succeed( AnswerRuns, AnswerRuns.of({ start: (requestId) => Effect.gen(function* () { const params = yield* encodeParams({ project, requestId });
yield* Effect.tryPromise(() => workflow.create({ id: requestId, params }) ).pipe( // The id is taken: the run was started before. Effect.catch((error) => Effect.tryPromise(() => workflow.get(requestId)).pipe( Effect.mapError(() => error), Effect.flatMap(runAgain) ) ) ); }).pipe(Effect.orDie), }) );