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

AgentActivityRows.ts

300 lines10.1 KB

1import type { RelayAgentActivityState } from "@t3tools/contracts/relay";
2import { RelayAgentActivityState as RelayAgentActivityStateSchema } from "@t3tools/contracts/relay";
3import * as Context from "effect/Context";
4import * as DateTime from "effect/DateTime";
5import * as Effect from "effect/Effect";
6import * as Function from "effect/Function";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as Schema from "effect/Schema";
10import { and, desc, eq, isNull, lt, sql } from "drizzle-orm";
11​
12import * as RelayDb from "../db.ts";
13import { relayAgentActivityRows, relayEnvironmentLinks } from "../persistence/schema.ts";
14​
15export class AgentActivityRowUpsertPersistenceError extends Schema.TaggedErrorClass<AgentActivityRowUpsertPersistenceError>()(
16 "AgentActivityRowUpsertPersistenceError",
17 {
18 environmentId: Schema.String,
19 threadId: Schema.String,
20 cause: Schema.Defect(),
21 },
22) {
23 override get message(): string {
24 return `Failed to persist agent activity state for environment ${this.environmentId}, thread ${this.threadId}.`;
25 }
27​
28export class AgentActivityRowDeletePersistenceError extends Schema.TaggedErrorClass<AgentActivityRowDeletePersistenceError>()(
29 "AgentActivityRowDeletePersistenceError",
30 {
31 environmentId: Schema.String,
32 threadId: Schema.String,
33 cause: Schema.Defect(),
34 },
35) {
36 override get message(): string {
37 return `Failed to delete agent activity state for environment ${this.environmentId}, thread ${this.threadId}.`;
38 }
40​
41export class AgentActivityRowPruneTerminalPersistenceError extends Schema.TaggedErrorClass<AgentActivityRowPruneTerminalPersistenceError>()(
42 "AgentActivityRowPruneTerminalPersistenceError",
43 {
44 updatedBefore: Schema.String,
45 cause: Schema.Defect(),
46 },
47) {
48 override get message(): string {
49 return `Failed to prune terminal agent activity rows updated before ${this.updatedBefore}.`;
50 }
52​
53export class AgentActivityRowListPersistenceError extends Schema.TaggedErrorClass<AgentActivityRowListPersistenceError>()(
54 "AgentActivityRowListPersistenceError",
55 {
56 userId: Schema.String,
57 cause: Schema.Defect(),
58 },
59) {
60 override get message(): string {
61 return `Failed to list agent activity state for user ${this.userId}.`;
62 }
64​
65export class AgentActivityRows extends Context.Service<
66 AgentActivityRows,
67 {
68 readonly upsert: (input: {
69 readonly environmentPublicKey: string;
70 readonly state: RelayAgentActivityState;
71 }) => Effect.Effect<void, AgentActivityRowUpsertPersistenceError>;
72 readonly pruneTerminal: (input: {
73 readonly updatedBefore: string;
74 }) => Effect.Effect<void, AgentActivityRowPruneTerminalPersistenceError>;
75 readonly remove: (input: {
76 readonly environmentId: string;
77 readonly environmentPublicKey: string;
78 readonly threadId: string;
79 }) => Effect.Effect<void, AgentActivityRowDeletePersistenceError>;
80 readonly listForUser: (input: {
81 readonly userId: string;
82 }) => Effect.Effect<
83 ReadonlyArray<RelayAgentActivityState>,
84 AgentActivityRowListPersistenceError
85 >;
86 readonly getForUserThread: (input: {
87 readonly userId: string;
88 readonly environmentId: string;
89 readonly threadId: string;
90 }) => Effect.Effect<RelayAgentActivityState | null, AgentActivityRowListPersistenceError>;
91 }
92>()("t3code-relay/agentActivity/AgentActivityRows") {}
93​
94const decodeJsonString = Schema.decodeEffect(Schema.UnknownFromJsonString);
95const encodeJsonValue = Schema.encodeEffect(Schema.UnknownFromJsonString);
96​
97const encodeRelayAgentActivityStateJson = Schema.encodeEffect(
98 Schema.fromJsonString(RelayAgentActivityStateSchema),
99);
100​
101const decodeRelayAgentActivityStateJson = Schema.decodeUnknownOption(
102 Schema.fromJsonString(RelayAgentActivityStateSchema),
103);
104​
105export const make = Effect.gen(function* () {
106 const db = yield* RelayDb.RelayDb;
107​
108 return AgentActivityRows.of({
109 upsert: Effect.fn("relay.agent_activity_rows.upsert")(function* (input) {
110 yield* Effect.annotateCurrentSpan({
111 "relay.environment_id": input.state.environmentId,
112 "relay.thread_id": input.state.threadId,
113 });
114 const now = yield* DateTime.now;
115 const stateJson = yield* encodeRelayAgentActivityStateJson(input.state).pipe(
116 Effect.flatMap(decodeJsonString),
117 Effect.map(Function.cast<unknown, RelayAgentActivityState>),
118 Effect.mapError(
119 (cause) =>
120 new AgentActivityRowUpsertPersistenceError({
121 environmentId: input.state.environmentId,
122 threadId: input.state.threadId,
123 cause,
124 }),
125 ),
126 );
127 yield* db
128 .insert(relayAgentActivityRows)
129 .values({
130 environmentId: input.state.environmentId,
131 environmentPublicKey: input.environmentPublicKey,
132 threadId: input.state.threadId,
133 stateJson,
134 updatedAt: input.state.updatedAt,
135 createdAt: DateTime.formatIso(now),
136 })
137 .onConflictDoUpdate({
138 target: [
139 relayAgentActivityRows.environmentId,
140 relayAgentActivityRows.environmentPublicKey,
141 relayAgentActivityRows.threadId,
142 ],
143 set: {
144 stateJson,
145 updatedAt: input.state.updatedAt,
146 },
147 })
148 .pipe(
149 Effect.mapError(
150 (cause) =>
151 new AgentActivityRowUpsertPersistenceError({
152 environmentId: input.state.environmentId,
153 threadId: input.state.threadId,
154 cause,
155 }),
156 ),
157 );
158 }),
159​
160 remove: Effect.fn("relay.agent_activity_rows.remove")(function* (input) {
161 yield* Effect.annotateCurrentSpan({
162 "relay.environment_id": input.environmentId,
163 "relay.thread_id": input.threadId,
164 });
165 yield* db
166 .delete(relayAgentActivityRows)
167 .where(
168 and(
169 eq(relayAgentActivityRows.environmentId, input.environmentId),
170 eq(relayAgentActivityRows.environmentPublicKey, input.environmentPublicKey),
171 eq(relayAgentActivityRows.threadId, input.threadId),
172 ),
173 )
174 .pipe(
175 Effect.mapError(
176 (cause) =>
177 new AgentActivityRowDeletePersistenceError({
178 environmentId: input.environmentId,
179 threadId: input.threadId,
180 cause,
181 }),
182 ),
183 );
184 }),
185​
186 pruneTerminal: Effect.fn("relay.agent_activity_rows.prune_terminal")(function* (input) {
187 yield* Effect.annotateCurrentSpan({
188 "relay.agent_activity_prune.before": input.updatedBefore,
189 });
190 yield* db
191 .delete(relayAgentActivityRows)
192 .where(
193 and(
194 sql`${relayAgentActivityRows.stateJson} ->> 'phase' IN ('completed', 'failed')`,
195 lt(relayAgentActivityRows.updatedAt, input.updatedBefore),
196 ),
197 )
198 .pipe(
199 Effect.mapError(
200 (cause) =>
201 new AgentActivityRowPruneTerminalPersistenceError({
202 updatedBefore: input.updatedBefore,
203 cause,
204 }),
205 ),
206 );
207 }),
208​
209 listForUser: Effect.fn("relay.agent_activity_rows.list_for_user")(function* (input) {
210 return yield* db
211 .select({ stateJson: relayAgentActivityRows.stateJson })
212 .from(relayAgentActivityRows)
213 .innerJoin(
214 relayEnvironmentLinks,
215 and(
216 eq(relayEnvironmentLinks.environmentId, relayAgentActivityRows.environmentId),
217 eq(
218 relayEnvironmentLinks.environmentPublicKey,
219 relayAgentActivityRows.environmentPublicKey,
220 ),
221 ),
222 )
223 .where(
224 and(
225 eq(relayEnvironmentLinks.userId, input.userId),
226 isNull(relayEnvironmentLinks.revokedAt),
227 eq(relayEnvironmentLinks.liveActivitiesEnabled, true),
228 ),
229 )
230 .orderBy(desc(relayAgentActivityRows.updatedAt))
231 .pipe(
232 Effect.flatMap((rows) =>
233 Effect.forEach(rows, (row) => encodeJsonValue(row.stateJson), {
234 concurrency: "unbounded",
235 }),
236 ),
237 Effect.map((rows) =>
238 rows.flatMap((row) => Option.toArray(decodeRelayAgentActivityStateJson(row))),
239 ),
240 Effect.mapError(
241 (cause) =>
242 new AgentActivityRowListPersistenceError({
243 userId: input.userId,
244 cause,
245 }),
246 ),
247 );
248 }),
249​
250 getForUserThread: Effect.fn("relay.agent_activity_rows.get_for_user_thread")(function* (input) {
251 return yield* db
252 .select({ stateJson: relayAgentActivityRows.stateJson })
253 .from(relayAgentActivityRows)
254 .innerJoin(
255 relayEnvironmentLinks,
256 and(
257 eq(relayEnvironmentLinks.environmentId, relayAgentActivityRows.environmentId),
258 eq(
259 relayEnvironmentLinks.environmentPublicKey,
260 relayAgentActivityRows.environmentPublicKey,
261 ),
262 ),
263 )
264 .where(
265 and(
266 eq(relayEnvironmentLinks.userId, input.userId),
267 isNull(relayEnvironmentLinks.revokedAt),
268 eq(relayAgentActivityRows.environmentId, input.environmentId),
269 eq(relayAgentActivityRows.threadId, input.threadId),
270 ),
271 )
272 .orderBy(desc(relayAgentActivityRows.updatedAt))
273 .pipe(
274 Effect.flatMap((rows) =>
275 Effect.forEach(rows, (row) => encodeJsonValue(row.stateJson), {
276 concurrency: "unbounded",
277 }),
278 ),
279 Effect.map((rows) => {
280 for (const row of rows) {
281 const decoded = decodeRelayAgentActivityStateJson(row);
282 if (Option.isSome(decoded)) {
283 return decoded.value;
284 }
285 }
286 return null;
287 }),
288 Effect.mapError(
289 (cause) =>
290 new AgentActivityRowListPersistenceError({
291 userId: input.userId,
292 cause,
293 }),
294 ),
295 );
296 }),
297 });
298});
299​
300export const layer = Layer.effect(AgentActivityRows, make);