Open History to see the last commit
1import type {
2 RelayClientEnvironmentRecord,
3 RelayEnvironmentLinkProofPayload,
4 RelayEnvironmentLinkRequest,
5 RelayManagedEndpoint,
6} from "@t3tools/contracts/relay";
7import * as Context from "effect/Context";
8import * as DateTime from "effect/DateTime";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Schema from "effect/Schema";
12import { and, eq, isNull, or } from "drizzle-orm";
13
14import * as RelayDb from "../db.ts";
15import { relayEnvironmentLinks } from "../persistence/schema.ts";
16
17export interface RelayLinkedEnvironmentRecord extends RelayClientEnvironmentRecord {
18 readonly environmentPublicKey: string;
19}
20
21export interface AgentAwarenessDeliveryUserRecord {
22 readonly userId: string;
23 readonly notificationsEnabled: boolean;
24 readonly liveActivitiesEnabled: boolean;
25}
26
27export class EnvironmentLinkUpsertPersistenceError extends Schema.TaggedError<EnvironmentLinkUpsertPersistenceError>()(
28 "EnvironmentLinkUpsertPersistenceError",
29 {
30 userId: Schema.String,
31 environmentId: Schema.String,
32 deviceId: Schema.optionalKey(Schema.String),
33 cause: Schema.Defect(),
34 },
35) {
36 override get message(): string {
37 return `Failed to persist environment link for user '${this.userId}', environment '${this.environmentId}'`;
38 }
39}
40
41export class EnvironmentLinkUserListPersistenceError extends Schema.TaggedError<EnvironmentLinkUserListPersistenceError>()(
42 "EnvironmentLinkUserListPersistenceError",
43 {
44 environmentId: Schema.String,
45 cause: Schema.Defect(),
46 },
47) {
48 override get message(): string {
49 return `Environment link user query 'list-delivery-users' failed for environment '${this.environmentId}'`;
50 }
51}
52
53export class EnvironmentLinkListPersistenceError extends Schema.TaggedError<EnvironmentLinkListPersistenceError>()(
54 "EnvironmentLinkListPersistenceError",
55 {
56 userId: Schema.String,
57 cause: Schema.Defect(),
58 },
59) {
60 override get message(): string {
61 return `Failed to list environment links for user '${this.userId}'`;
62 }
63}
64
65export class EnvironmentLinkLookupPersistenceError extends Schema.TaggedError<EnvironmentLinkLookupPersistenceError>()(
66 "EnvironmentLinkLookupPersistenceError",
67 {
68 userId: Schema.String,
69 environmentId: Schema.String,
70 cause: Schema.Defect(),
71 },
72) {
73 override get message(): string {
74 return `Failed to look up environment link for user '${this.userId}', environment '${this.environmentId}'`;
75 }
76}
77
78export class EnvironmentLinkRevokePersistenceError extends Schema.TaggedError<EnvironmentLinkRevokePersistenceError>()(
79 "EnvironmentLinkRevokePersistenceError",
80 {
81 userId: Schema.String,
82 environmentId: Schema.String,
83 cause: Schema.Defect(),
84 },
85) {
86 override get message(): string {
87 return `Failed to revoke environment link for user '${this.userId}', environment '${this.environmentId}'`;
88 }
89}
90
91export class EnvironmentLinks extends Context.Service<
92 EnvironmentLinks,
93 {
94 readonly upsert: (input: {
95 readonly userId: string;
96 readonly request: RelayEnvironmentLinkRequest;
97 readonly proof: RelayEnvironmentLinkProofPayload;
98 readonly endpoint: RelayManagedEndpoint;
99 }) => Effect.Effect<void, EnvironmentLinkUpsertPersistenceError>;
100 readonly listDeliveryUsersForEnvironment: (input: {
101 readonly environmentId: string;
102 readonly environmentPublicKey: string;
103 }) => Effect.Effect<
104 ReadonlyArray<AgentAwarenessDeliveryUserRecord>,
105 EnvironmentLinkUserListPersistenceError
106 >;
107 readonly listForUser: (input: {
108 readonly userId: string;
109 }) => Effect.Effect<
110 ReadonlyArray<RelayClientEnvironmentRecord>,
111 EnvironmentLinkListPersistenceError
112 >;
113 readonly getForUser: (input: {
114 readonly userId: string;
115 readonly environmentId: string;
116 }) => Effect.Effect<RelayLinkedEnvironmentRecord | null, EnvironmentLinkLookupPersistenceError>;
117 readonly revokeForUser: (input: {
118 readonly userId: string;
119 readonly environmentId: string;
120 }) => Effect.Effect<boolean, EnvironmentLinkRevokePersistenceError>;
121 }
122>()("t3code-relay/environments/EnvironmentLinks") {}
123
124function agentAwarenessDeliveryUserKeyCondition(input: {
125 readonly environmentId: string;
126 readonly environmentPublicKey: string;
127}) {
128 return and(
129 eq(relayEnvironmentLinks.environmentId, input.environmentId),
130 isNull(relayEnvironmentLinks.revokedAt),
131 or(
132 eq(relayEnvironmentLinks.notificationsEnabled, true),
133 eq(relayEnvironmentLinks.liveActivitiesEnabled, true),
134 ),
135 eq(relayEnvironmentLinks.environmentPublicKey, input.environmentPublicKey),
136 );
137}
138
139const make = Effect.gen(function* () {
140 const db = yield* RelayDb.RelayDb;
141
142 return EnvironmentLinks.of({
143 upsert: Effect.fn("relay.environment_links.upsert")(function* (input) {
144 yield* Effect.annotateCurrentSpan({
145 "relay.environment_id": input.proof.environmentId,
146 });
147 const now = DateTime.formatIso(yield* DateTime.now);
148 const { request, proof } = input;
149 const environmentId = proof.environmentId;
150 const { endpoint } = input;
151 yield* db
152 .insert(relayEnvironmentLinks)
153 .values({
154 userId: input.userId,
155 environmentId,
156 environmentLabel: proof.descriptor.label,
157 environmentPublicKey: proof.environmentPublicKey,
158 endpointHttpBaseUrl: endpoint.httpBaseUrl,
159 endpointWsBaseUrl: endpoint.wsBaseUrl,
160 endpointProviderKind: endpoint.providerKind,
161 notificationsEnabled: request.notificationsEnabled,
162 liveActivitiesEnabled: request.liveActivitiesEnabled,
163 managedTunnelsEnabled: request.managedTunnelsEnabled,
164 createdByDeviceId: request.deviceId ?? null,
165 revokedAt: null,
166 createdAt: now,
167 updatedAt: now,
168 })
169 .onConflictDoUpdate({
170 target: [relayEnvironmentLinks.userId, relayEnvironmentLinks.environmentId],
171 set: {
172 environmentPublicKey: proof.environmentPublicKey,
173 environmentLabel: proof.descriptor.label,
174 endpointHttpBaseUrl: endpoint.httpBaseUrl,
175 endpointWsBaseUrl: endpoint.wsBaseUrl,
176 endpointProviderKind: endpoint.providerKind,
177 notificationsEnabled: request.notificationsEnabled,
178 liveActivitiesEnabled: request.liveActivitiesEnabled,
179 managedTunnelsEnabled: request.managedTunnelsEnabled,
180 createdByDeviceId: request.deviceId ?? null,
181 revokedAt: null,
182 updatedAt: now,
183 },
184 })
185 .pipe(
186 Effect.mapError(
187 (cause) =>
188 new EnvironmentLinkUpsertPersistenceError({
189 userId: input.userId,
190 environmentId,
191 ...(request.deviceId === undefined ? {} : { deviceId: request.deviceId }),
192 cause,
193 }),
194 ),
195 );
196 }),
197
198 listDeliveryUsersForEnvironment: Effect.fn(
199 "relay.environment_links.list_delivery_users_for_environment",
200 )(function* (input) {
201 yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });
202 return yield* db
203 .select({
204 userId: relayEnvironmentLinks.userId,
205 notificationsEnabled: relayEnvironmentLinks.notificationsEnabled,
206 liveActivitiesEnabled: relayEnvironmentLinks.liveActivitiesEnabled,
207 })
208 .from(relayEnvironmentLinks)
209 .where(agentAwarenessDeliveryUserKeyCondition(input))
210 .pipe(
211 Effect.map((rows) =>
212 rows.map((row) => ({
213 userId: row.userId,
214 notificationsEnabled: row.notificationsEnabled,
215 liveActivitiesEnabled: row.liveActivitiesEnabled,
216 })),
217 ),
218 Effect.mapError(
219 (cause) =>
220 new EnvironmentLinkUserListPersistenceError({
221 environmentId: input.environmentId,
222 cause,
223 }),
224 ),
225 );
226 }),
227
228 listForUser: Effect.fn("relay.environment_links.list_for_user")(function* (input) {
229 return yield* db
230 .select({
231 environmentId: relayEnvironmentLinks.environmentId,
232 environmentLabel: relayEnvironmentLinks.environmentLabel,
233 endpointHttpBaseUrl: relayEnvironmentLinks.endpointHttpBaseUrl,
234 endpointWsBaseUrl: relayEnvironmentLinks.endpointWsBaseUrl,
235 endpointProviderKind: relayEnvironmentLinks.endpointProviderKind,
236 createdAt: relayEnvironmentLinks.createdAt,
237 })
238 .from(relayEnvironmentLinks)
239 .where(
240 and(
241 eq(relayEnvironmentLinks.userId, input.userId),
242 isNull(relayEnvironmentLinks.revokedAt),
243 ),
244 )
245 .pipe(
246 Effect.map((rows) =>
247 rows.map((row) => ({
248 environmentId: row.environmentId as RelayClientEnvironmentRecord["environmentId"],
249 label:
250 row.environmentLabel.trim().length > 0 ? row.environmentLabel : row.environmentId,
251 endpoint: {
252 httpBaseUrl: row.endpointHttpBaseUrl,
253 wsBaseUrl: row.endpointWsBaseUrl,
254 providerKind:
255 row.endpointProviderKind as RelayClientEnvironmentRecord["endpoint"]["providerKind"],
256 },
257 linkedAt: row.createdAt,
258 })),
259 ),
260 Effect.mapError(
261 (cause) =>
262 new EnvironmentLinkListPersistenceError({
263 userId: input.userId,
264 cause,
265 }),
266 ),
267 );
268 }),
269
270 getForUser: Effect.fn("relay.environment_links.get_for_user")(function* (input) {
271 yield* Effect.annotateCurrentSpan({
272 "relay.environment_id": input.environmentId,
273 });
274 return yield* db
275 .select({
276 environmentId: relayEnvironmentLinks.environmentId,
277 environmentLabel: relayEnvironmentLinks.environmentLabel,
278 environmentPublicKey: relayEnvironmentLinks.environmentPublicKey,
279 endpointHttpBaseUrl: relayEnvironmentLinks.endpointHttpBaseUrl,
280 endpointWsBaseUrl: relayEnvironmentLinks.endpointWsBaseUrl,
281 endpointProviderKind: relayEnvironmentLinks.endpointProviderKind,
282 createdAt: relayEnvironmentLinks.createdAt,
283 })
284 .from(relayEnvironmentLinks)
285 .where(
286 and(
287 eq(relayEnvironmentLinks.userId, input.userId),
288 eq(relayEnvironmentLinks.environmentId, input.environmentId),
289 isNull(relayEnvironmentLinks.revokedAt),
290 ),
291 )
292 .limit(1)
293 .pipe(
294 Effect.map((rows) => {
295 const row = rows[0];
296 return row
297 ? {
298 environmentId: row.environmentId as RelayClientEnvironmentRecord["environmentId"],
299 label:
300 row.environmentLabel.trim().length > 0
301 ? row.environmentLabel
302 : row.environmentId,
303 endpoint: {
304 httpBaseUrl: row.endpointHttpBaseUrl,
305 wsBaseUrl: row.endpointWsBaseUrl,
306 providerKind:
307 row.endpointProviderKind as RelayClientEnvironmentRecord["endpoint"]["providerKind"],
308 },
309 environmentPublicKey: row.environmentPublicKey,
310 linkedAt: row.createdAt,
311 }
312 : null;
313 }),
314 Effect.mapError(
315 (cause) =>
316 new EnvironmentLinkLookupPersistenceError({
317 userId: input.userId,
318 environmentId: input.environmentId,
319 cause,
320 }),
321 ),
322 );
323 }),
324
325 revokeForUser: Effect.fn("relay.environment_links.revoke_for_user")(function* (input) {
326 yield* Effect.annotateCurrentSpan({
327 "relay.environment_id": input.environmentId,
328 });
329 const revokedAt = DateTime.formatIso(yield* DateTime.now);
330 const rows = yield* db
331 .update(relayEnvironmentLinks)
332 .set({
333 revokedAt,
334 updatedAt: revokedAt,
335 })
336 .where(
337 and(
338 eq(relayEnvironmentLinks.userId, input.userId),
339 eq(relayEnvironmentLinks.environmentId, input.environmentId),
340 isNull(relayEnvironmentLinks.revokedAt),
341 ),
342 )
343 .returning({ environmentId: relayEnvironmentLinks.environmentId })
344 .pipe(
345 Effect.mapError(
346 (cause) =>
347 new EnvironmentLinkRevokePersistenceError({
348 userId: input.userId,
349 environmentId: input.environmentId,
350 cause,
351 }),
352 ),
353 );
354 return rows.length > 0;
355 }),
356 });
357});
358
359export const layer = Layer.effect(EnvironmentLinks, make);