Open History to see the last commit
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/sql/SqlClient";
7
8export class TurnItemPositionStoreError extends Schema.TaggedError<TurnItemPositionStoreError>()(
9 "TurnItemPositionStoreError",
10 {
11 threadId: ThreadId,
12 turnItemId: TurnItemId,
13 cause: Schema.optional(Schema.Defect()),
14 },
15) {}
16
17const isTurnItemPositionStoreError = Schema.is(TurnItemPositionStoreError);
18
19export interface TurnItemPositionStoreV2Shape {
20 readonly allocate: (input: {
21 readonly threadId: ThreadId;
22 readonly turnItemId: TurnItemId;
23 readonly runId: RunId | null;
24 readonly runOrdinal?: number;
25 }) => Effect.Effect<number, TurnItemPositionStoreError>;
26 readonly normalize: (
27 item: OrchestrationV2TurnItem,
28 runOrdinal?: number,
29 ) => Effect.Effect<OrchestrationV2TurnItem, TurnItemPositionStoreError>;
30}
31
32export class TurnItemPositionStoreV2 extends Context.Service<
33 TurnItemPositionStoreV2,
34 TurnItemPositionStoreV2Shape
35>()("t3/orchestration-v2/TurnItemPositionStore/TurnItemPositionStoreV2") {}
36
37export const layer: Layer.Layer<TurnItemPositionStoreV2, never, SqlClient.SqlClient> = Layer.effect(
38 TurnItemPositionStoreV2,
39 Effect.gen(function* () {
40 const sql = yield* SqlClient.SqlClient;
41
42 const allocate: TurnItemPositionStoreV2Shape["allocate"] =
43 /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
44 Effect.fnUntraced(
45 function* ({ threadId, turnItemId, runId, runOrdinal: suppliedRunOrdinal }) {
46 const existing = yield* sql<{ readonly ordinal: number }>`
47 SELECT ordinal
48 FROM orchestration_v2_turn_item_positions
49 WHERE thread_id = ${threadId} AND turn_item_id = ${turnItemId}
50 LIMIT 1
51 `;
52 if (existing[0] !== undefined) return existing[0].ordinal;
53
54 const runRows =
55 runId === null
56 ? []
57 : yield* sql<{ readonly ordinal: number }>`
58 SELECT ordinal
59 FROM orchestration_v2_projection_runs
60 WHERE thread_id = ${threadId} AND run_id = ${runId}
61 LIMIT 1
62 `;
63 const runOrdinal = suppliedRunOrdinal ?? runRows[0]?.ordinal ?? null;
64 const lowerBound = runOrdinal === null ? 0 : runOrdinal * 1_000_000;
65 const upperBound = runOrdinal === null ? 999_999 : lowerBound + 999_999;
66 yield* sql`
67 INSERT INTO orchestration_v2_turn_item_positions (thread_id, turn_item_id, ordinal)
68 SELECT
69 ${threadId},
70 ${turnItemId},
71 COALESCE(MAX(ordinal), ${lowerBound}) + 1
72 FROM orchestration_v2_turn_item_positions
73 WHERE thread_id = ${threadId}
74 AND ordinal >= ${lowerBound}
75 AND ordinal <= ${upperBound}
76 ON CONFLICT(thread_id, turn_item_id) DO NOTHING
77 `;
78 const rows = yield* sql<{ readonly ordinal: number }>`
79 SELECT ordinal
80 FROM orchestration_v2_turn_item_positions
81 WHERE thread_id = ${threadId} AND turn_item_id = ${turnItemId}
82 LIMIT 1
83 `;
84 const ordinal = rows[0]?.ordinal;
85 if (ordinal === undefined) {
86 return yield* new TurnItemPositionStoreError({
87 threadId,
88 turnItemId,
89 cause: "Position allocation returned no row.",
90 });
91 }
92 return ordinal;
93 },
94 (effect, { threadId, turnItemId }) =>
95 effect.pipe(
96 Effect.mapError((cause) =>
97 isTurnItemPositionStoreError(cause)
98 ? cause
99 : new TurnItemPositionStoreError({ threadId, turnItemId, cause }),
100 ),
101 ),
102 );
103
104 return TurnItemPositionStoreV2.of({
105 allocate,
106 // Per-event normalization shares the enclosing orchestration span.
107 normalize: Effect.fnUntraced(function* (item, runOrdinal) {
108 return yield* allocate({
109 threadId: item.threadId,
110 turnItemId: item.id,
111 runId: item.runId,
112 ...(runOrdinal === undefined ? {} : { runOrdinal }),
113 }).pipe(Effect.map((ordinal) => (item.ordinal === ordinal ? item : { ...item, ordinal })));
114 }),
115 });
116 }),
117);