Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

TurnItemPositionStore.ts

105 lines3.7 KB

1import { OrchestrationV2TurnItem, RunId, ThreadId, TurnItemId } from "@t3tools/contracts";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Schema from "effect/Schema";
6import * as SqlClient from "effect/unstable/sql/SqlClient";
7​
8export class TurnItemPositionStoreError extends Schema.TaggedErrorClass<TurnItemPositionStoreError>()(
9 "TurnItemPositionStoreError",
10 {
11 threadId: ThreadId,
12 turnItemId: TurnItemId,
13 cause: Schema.optional(Schema.Defect()),
14 },
15) {}
16​
17export interface TurnItemPositionStoreV2Shape {
18 readonly allocate: (input: {
19 readonly threadId: ThreadId;
20 readonly turnItemId: TurnItemId;
21 readonly runId: RunId | null;
22 readonly runOrdinal?: number;
23 }) => Effect.Effect<number, TurnItemPositionStoreError>;
24 readonly normalize: (
25 item: OrchestrationV2TurnItem,
26 runOrdinal?: number,
27 ) => Effect.Effect<OrchestrationV2TurnItem, TurnItemPositionStoreError>;
29​
30export class TurnItemPositionStoreV2 extends Context.Service<
31 TurnItemPositionStoreV2,
32 TurnItemPositionStoreV2Shape
33>()("t3/orchestration-v2/TurnItemPositionStore/TurnItemPositionStoreV2") {}
34​
35export const layer: Layer.Layer<TurnItemPositionStoreV2, never, SqlClient.SqlClient> = Layer.effect(
36 TurnItemPositionStoreV2,
37 Effect.gen(function* () {
38 const sql = yield* SqlClient.SqlClient;
39​
40 const allocate: TurnItemPositionStoreV2Shape["allocate"] = ({
41 threadId,
42 turnItemId,
43 runId,
44 runOrdinal: suppliedRunOrdinal,
45 }) =>
46 Effect.gen(function* () {
47 const runRows =
48 runId === null
49 ? []
50 : yield* sql<{ readonly ordinal: number }>`
51 SELECT ordinal
52 FROM orchestration_v2_projection_runs
53 WHERE thread_id = ${threadId} AND run_id = ${runId}
54 LIMIT 1
55 `;
56 const runOrdinal = suppliedRunOrdinal ?? runRows[0]?.ordinal ?? null;
57 const lowerBound = runOrdinal === null ? 0 : runOrdinal * 1_000_000;
58 const upperBound = runOrdinal === null ? 999_999 : lowerBound + 999_999;
59 yield* sql`
60 INSERT INTO orchestration_v2_turn_item_positions (thread_id, turn_item_id, ordinal)
61 SELECT
62 ${threadId},
63 ${turnItemId},
64 COALESCE(MAX(ordinal), ${lowerBound}) + 1
65 FROM orchestration_v2_turn_item_positions
66 WHERE thread_id = ${threadId}
67 AND ordinal >= ${lowerBound}
68 AND ordinal <= ${upperBound}
69 ON CONFLICT(thread_id, turn_item_id) DO NOTHING
70 `;
71 const rows = yield* sql<{ readonly ordinal: number }>`
72 SELECT ordinal
73 FROM orchestration_v2_turn_item_positions
74 WHERE thread_id = ${threadId} AND turn_item_id = ${turnItemId}
75 LIMIT 1
76 `;
77 const ordinal = rows[0]?.ordinal;
78 if (ordinal === undefined) {
79 return yield* new TurnItemPositionStoreError({
80 threadId,
81 turnItemId,
82 cause: "Position allocation returned no row.",
83 });
84 }
85 return ordinal;
86 }).pipe(
87 Effect.mapError((cause) =>
88 Schema.is(TurnItemPositionStoreError)(cause)
89 ? cause
90 : new TurnItemPositionStoreError({ threadId, turnItemId, cause }),
91 ),
92 );
93​
94 return TurnItemPositionStoreV2.of({
95 allocate,
96 normalize: (item, runOrdinal) =>
97 allocate({
98 threadId: item.threadId,
99 turnItemId: item.id,
100 runId: item.runId,
101 ...(runOrdinal === undefined ? {} : { runOrdinal }),
102 }).pipe(Effect.map((ordinal) => (item.ordinal === ordinal ? item : { ...item, ordinal }))),
103 });
104 }),
105);