Open History to see the last commit
1import {
2 CommandId,
3 EventId,
4 IsoDateTime,
5 MessageId,
6 ModelSelection,
7 NonNegativeInt,
8 OrchestrationProposedPlanId,
9 ProviderInteractionMode,
10 RuntimeMode,
11 ThreadId,
12 TrimmedNonEmptyString,
13} from "@t3tools/contracts";
14import * as Context from "effect/Context";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as Schema from "effect/Schema";
18import * as SqlClient from "effect/unstable/sql/SqlClient";
19import * as SqlSchema from "effect/unstable/sql/SqlSchema";
20
21import { toPersistenceDecodeError, toPersistenceSqlError } from "./Errors.ts";
22import type { ProjectionRepositoryError } from "./Errors.ts";
23
24export const ProjectionQueuedTurnStatus = Schema.Literals(["queued", "handoff"]);
25
26export const ProjectionQueuedTurn = Schema.Struct({
27 messageId: MessageId,
28 threadId: ThreadId,
29 eventId: EventId,
30 commandId: CommandId,
31 modelSelection: Schema.NullOr(ModelSelection),
32 titleSeed: Schema.NullOr(TrimmedNonEmptyString),
33 runtimeMode: RuntimeMode,
34 interactionMode: ProviderInteractionMode,
35 sourceProposedPlanThreadId: Schema.NullOr(ThreadId),
36 sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
37 queuedAt: IsoDateTime,
38 eventSequence: NonNegativeInt,
39 status: ProjectionQueuedTurnStatus,
40});
41export type ProjectionQueuedTurn = typeof ProjectionQueuedTurn.Type;
42
43export const ProjectionQueuedTurnMessageInput = Schema.Struct({
44 messageId: MessageId,
45});
46export const ProjectionQueuedTurnThreadInput = Schema.Struct({
47 threadId: ThreadId,
48});
49
50export class ProjectionQueuedTurnRepository extends Context.Service<
51 ProjectionQueuedTurnRepository,
52 {
53 readonly upsert: (row: ProjectionQueuedTurn) => Effect.Effect<void, ProjectionRepositoryError>;
54 readonly markHandoff: (
55 input: typeof ProjectionQueuedTurnMessageInput.Type,
56 ) => Effect.Effect<void, ProjectionRepositoryError>;
57 readonly deleteByMessageId: (
58 input: typeof ProjectionQueuedTurnMessageInput.Type,
59 ) => Effect.Effect<void, ProjectionRepositoryError>;
60 readonly deleteHandoffByThreadId: (
61 input: typeof ProjectionQueuedTurnThreadInput.Type,
62 ) => Effect.Effect<void, ProjectionRepositoryError>;
63 readonly deleteByThreadId: (
64 input: typeof ProjectionQueuedTurnThreadInput.Type,
65 ) => Effect.Effect<void, ProjectionRepositoryError>;
66 readonly listByThreadId: (
67 input: typeof ProjectionQueuedTurnThreadInput.Type,
68 ) => Effect.Effect<ReadonlyArray<ProjectionQueuedTurn>, ProjectionRepositoryError>;
69 readonly listAll: Effect.Effect<ReadonlyArray<ProjectionQueuedTurn>, ProjectionRepositoryError>;
70 }
71>()("t3/persistence/ProjectionQueuedTurns/ProjectionQueuedTurnRepository") {}
72
73const ProjectionQueuedTurnDbRow = Schema.Struct({
74 ...ProjectionQueuedTurn.fields,
75 modelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
76});
77
78export const make = Effect.gen(function* () {
79 const sql = yield* SqlClient.SqlClient;
80
81 const upsertRow = SqlSchema.void({
82 Request: ProjectionQueuedTurn,
83 execute: (row) => sql`
84 INSERT INTO projection_thread_turn_queue (
85 message_id,
86 thread_id,
87 event_id,
88 command_id,
89 model_selection_json,
90 title_seed,
91 runtime_mode,
92 interaction_mode,
93 source_proposed_plan_thread_id,
94 source_proposed_plan_id,
95 queued_at,
96 event_sequence,
97 status
98 ) VALUES (
99 ${row.messageId},
100 ${row.threadId},
101 ${row.eventId},
102 ${row.commandId},
103 ${row.modelSelection === null ? null : JSON.stringify(row.modelSelection)},
104 ${row.titleSeed},
105 ${row.runtimeMode},
106 ${row.interactionMode},
107 ${row.sourceProposedPlanThreadId},
108 ${row.sourceProposedPlanId},
109 ${row.queuedAt},
110 ${row.eventSequence},
111 ${row.status}
112 )
113 ON CONFLICT (message_id) DO UPDATE SET
114 thread_id = excluded.thread_id,
115 event_id = excluded.event_id,
116 command_id = excluded.command_id,
117 model_selection_json = excluded.model_selection_json,
118 title_seed = excluded.title_seed,
119 runtime_mode = excluded.runtime_mode,
120 interaction_mode = excluded.interaction_mode,
121 source_proposed_plan_thread_id = excluded.source_proposed_plan_thread_id,
122 source_proposed_plan_id = excluded.source_proposed_plan_id,
123 queued_at = excluded.queued_at,
124 event_sequence = excluded.event_sequence,
125 status = excluded.status
126 `,
127 });
128
129 const markHandoffRow = SqlSchema.void({
130 Request: ProjectionQueuedTurnMessageInput,
131 execute: ({ messageId }) => sql`
132 UPDATE projection_thread_turn_queue
133 SET status = 'handoff'
134 WHERE message_id = ${messageId}
135 AND status = 'queued'
136 `,
137 });
138
139 const deleteMessageRow = SqlSchema.void({
140 Request: ProjectionQueuedTurnMessageInput,
141 execute: ({ messageId }) => sql`
142 DELETE FROM projection_thread_turn_queue
143 WHERE message_id = ${messageId}
144 `,
145 });
146
147 const deleteHandoffThreadRows = SqlSchema.void({
148 Request: ProjectionQueuedTurnThreadInput,
149 execute: ({ threadId }) => sql`
150 DELETE FROM projection_thread_turn_queue
151 WHERE thread_id = ${threadId}
152 AND status = 'handoff'
153 `,
154 });
155
156 const deleteThreadRows = SqlSchema.void({
157 Request: ProjectionQueuedTurnThreadInput,
158 execute: ({ threadId }) => sql`
159 DELETE FROM projection_thread_turn_queue
160 WHERE thread_id = ${threadId}
161 `,
162 });
163
164 const listThreadRows = SqlSchema.findAll({
165 Request: ProjectionQueuedTurnThreadInput,
166 Result: ProjectionQueuedTurnDbRow,
167 execute: ({ threadId }) => sql`
168 SELECT
169 message_id AS "messageId",
170 thread_id AS "threadId",
171 event_id AS "eventId",
172 command_id AS "commandId",
173 model_selection_json AS "modelSelection",
174 title_seed AS "titleSeed",
175 runtime_mode AS "runtimeMode",
176 interaction_mode AS "interactionMode",
177 source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
178 source_proposed_plan_id AS "sourceProposedPlanId",
179 queued_at AS "queuedAt",
180 event_sequence AS "eventSequence",
181 status
182 FROM projection_thread_turn_queue
183 WHERE thread_id = ${threadId}
184 ORDER BY event_sequence ASC
185 `,
186 });
187
188 const listAllRows = SqlSchema.findAll({
189 Request: Schema.Void,
190 Result: ProjectionQueuedTurnDbRow,
191 execute: () => sql`
192 SELECT
193 message_id AS "messageId",
194 thread_id AS "threadId",
195 event_id AS "eventId",
196 command_id AS "commandId",
197 model_selection_json AS "modelSelection",
198 title_seed AS "titleSeed",
199 runtime_mode AS "runtimeMode",
200 interaction_mode AS "interactionMode",
201 source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
202 source_proposed_plan_id AS "sourceProposedPlanId",
203 queued_at AS "queuedAt",
204 event_sequence AS "eventSequence",
205 status
206 FROM projection_thread_turn_queue
207 ORDER BY event_sequence ASC
208 `,
209 });
210
211 const mapError = (operation: string) =>
212 Effect.mapError((cause: unknown) =>
213 Schema.isSchemaError(cause)
214 ? toPersistenceDecodeError(`${operation}:decode`)(cause)
215 : toPersistenceSqlError(operation)(cause),
216 );
217 const upsert: ProjectionQueuedTurnRepository["Service"]["upsert"] = (row) =>
218 upsertRow(row).pipe(mapError("ProjectionQueuedTurnRepository.upsert:query"));
219 const markHandoff: ProjectionQueuedTurnRepository["Service"]["markHandoff"] = (input) =>
220 markHandoffRow(input).pipe(mapError("ProjectionQueuedTurnRepository.markHandoff:query"));
221 const deleteByMessageId: ProjectionQueuedTurnRepository["Service"]["deleteByMessageId"] = (
222 input,
223 ) =>
224 deleteMessageRow(input).pipe(
225 mapError("ProjectionQueuedTurnRepository.deleteByMessageId:query"),
226 );
227 const deleteHandoffByThreadId: ProjectionQueuedTurnRepository["Service"]["deleteHandoffByThreadId"] =
228 (input) =>
229 deleteHandoffThreadRows(input).pipe(
230 mapError("ProjectionQueuedTurnRepository.deleteHandoffByThreadId:query"),
231 );
232 const deleteByThreadId: ProjectionQueuedTurnRepository["Service"]["deleteByThreadId"] = (input) =>
233 deleteThreadRows(input).pipe(mapError("ProjectionQueuedTurnRepository.deleteByThreadId:query"));
234 const listByThreadId: ProjectionQueuedTurnRepository["Service"]["listByThreadId"] = (input) =>
235 listThreadRows(input).pipe(mapError("ProjectionQueuedTurnRepository.listByThreadId:query"));
236 const listAll: ProjectionQueuedTurnRepository["Service"]["listAll"] = listAllRows(undefined).pipe(
237 mapError("ProjectionQueuedTurnRepository.listAll:query"),
238 );
239
240 return {
241 upsert,
242 markHandoff,
243 deleteByMessageId,
244 deleteHandoffByThreadId,
245 deleteByThreadId,
246 listByThreadId,
247 listAll,
248 } satisfies ProjectionQueuedTurnRepository["Service"];
249});
250
251export const layer = Layer.effect(ProjectionQueuedTurnRepository, make);