Open History to see the last commit
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 } 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 }
26}
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 }
39}
40
41export class AgentActivityRowListPersistenceError extends Schema.TaggedErrorClass<AgentActivityRowListPersistenceError>()(
42 "AgentActivityRowListPersistenceError",
43 {
44 userId: Schema.String,
45 cause: Schema.Defect(),
46 },
47) {
48 override get message(): string {
49 return `Failed to list agent activity state for user ${this.userId}.`;
50 }
51}
52
53export class AgentActivityRows extends Context.Service<
54 AgentActivityRows,
55 {
56 readonly upsert: (input: {
57 readonly environmentPublicKey: string;
58 readonly state: RelayAgentActivityState;
59 }) => Effect.Effect<void, AgentActivityRowUpsertPersistenceError>;
60 readonly remove: (input: {
61 readonly environmentId: string;
62 readonly environmentPublicKey: string;
63 readonly threadId: string;
64 }) => Effect.Effect<void, AgentActivityRowDeletePersistenceError>;
65 readonly listForUser: (input: {
66 readonly userId: string;
67 }) => Effect.Effect<
68 ReadonlyArray<RelayAgentActivityState>,
69 AgentActivityRowListPersistenceError
70 >;
71 }
72>()("t3code-relay/agentActivity/AgentActivityRows") {}
73
74const decodeJsonString = Schema.decodeEffect(Schema.UnknownFromJsonString);
75const encodeJsonValue = Schema.encodeEffect(Schema.UnknownFromJsonString);
76
77const encodeRelayAgentActivityStateJson = Schema.encodeEffect(
78 Schema.fromJsonString(RelayAgentActivityStateSchema),
79);
80
81const decodeRelayAgentActivityStateJson = Schema.decodeUnknownOption(
82 Schema.fromJsonString(RelayAgentActivityStateSchema),
83);
84
85export const make = Effect.gen(function* () {
86 const db = yield* RelayDb.RelayDb;
87
88 return AgentActivityRows.of({
89 upsert: Effect.fn("relay.agent_activity_rows.upsert")(function* (input) {
90 yield* Effect.annotateCurrentSpan({
91 "relay.environment_id": input.state.environmentId,
92 "relay.thread_id": input.state.threadId,
93 });
94 const now = yield* DateTime.now;
95 const stateJson = yield* encodeRelayAgentActivityStateJson(input.state).pipe(
96 Effect.flatMap(decodeJsonString),
97 Effect.map(Function.cast<unknown, RelayAgentActivityState>),
98 Effect.mapError(
99 (cause) =>
100 new AgentActivityRowUpsertPersistenceError({
101 environmentId: input.state.environmentId,
102 threadId: input.state.threadId,
103 cause,
104 }),
105 ),
106 );
107 yield* db
108 .insert(relayAgentActivityRows)
109 .values({
110 environmentId: input.state.environmentId,
111 environmentPublicKey: input.environmentPublicKey,
112 threadId: input.state.threadId,
113 stateJson,
114 updatedAt: input.state.updatedAt,
115 createdAt: DateTime.formatIso(now),
116 })
117 .onConflictDoUpdate({
118 target: [
119 relayAgentActivityRows.environmentId,
120 relayAgentActivityRows.environmentPublicKey,
121 relayAgentActivityRows.threadId,
122 ],
123 set: {
124 stateJson,
125 updatedAt: input.state.updatedAt,
126 },
127 })
128 .pipe(
129 Effect.mapError(
130 (cause) =>
131 new AgentActivityRowUpsertPersistenceError({
132 environmentId: input.state.environmentId,
133 threadId: input.state.threadId,
134 cause,
135 }),
136 ),
137 );
138 }),
139
140 remove: Effect.fn("relay.agent_activity_rows.remove")(function* (input) {
141 yield* Effect.annotateCurrentSpan({
142 "relay.environment_id": input.environmentId,
143 "relay.thread_id": input.threadId,
144 });
145 yield* db
146 .delete(relayAgentActivityRows)
147 .where(
148 and(
149 eq(relayAgentActivityRows.environmentId, input.environmentId),
150 eq(relayAgentActivityRows.environmentPublicKey, input.environmentPublicKey),
151 eq(relayAgentActivityRows.threadId, input.threadId),
152 ),
153 )
154 .pipe(
155 Effect.mapError(
156 (cause) =>
157 new AgentActivityRowDeletePersistenceError({
158 environmentId: input.environmentId,
159 threadId: input.threadId,
160 cause,
161 }),
162 ),
163 );
164 }),
165
166 listForUser: Effect.fn("relay.agent_activity_rows.list_for_user")(function* (input) {
167 return yield* db
168 .select({ stateJson: relayAgentActivityRows.stateJson })
169 .from(relayAgentActivityRows)
170 .innerJoin(
171 relayEnvironmentLinks,
172 and(
173 eq(relayEnvironmentLinks.environmentId, relayAgentActivityRows.environmentId),
174 eq(
175 relayEnvironmentLinks.environmentPublicKey,
176 relayAgentActivityRows.environmentPublicKey,
177 ),
178 ),
179 )
180 .where(
181 and(
182 eq(relayEnvironmentLinks.userId, input.userId),
183 isNull(relayEnvironmentLinks.revokedAt),
184 eq(relayEnvironmentLinks.liveActivitiesEnabled, true),
185 ),
186 )
187 .orderBy(desc(relayAgentActivityRows.updatedAt))
188 .pipe(
189 Effect.flatMap((rows) =>
190 Effect.forEach(rows, (row) => encodeJsonValue(row.stateJson), {
191 concurrency: "unbounded",
192 }),
193 ),
194 Effect.map((rows) =>
195 rows.flatMap((row) => Option.toArray(decodeRelayAgentActivityStateJson(row))),
196 ),
197 Effect.mapError(
198 (cause) =>
199 new AgentActivityRowListPersistenceError({
200 userId: input.userId,
201 cause,
202 }),
203 ),
204 );
205 }),
206 });
207});
208
209export const layer = Layer.effect(AgentActivityRows, make);