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

EnvironmentLinks.ts

433 lines15.3 KB

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;
20​
21export interface AgentAwarenessDeliveryUserRecord {
22 readonly userId: string;
23 readonly notificationsEnabled: boolean;
24 readonly liveActivitiesEnabled: boolean;
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 }
40​
41export class EnvironmentLinkUserListPersistenceError extends Schema.TaggedError<EnvironmentLinkUserListPersistenceError>()(
42 "EnvironmentLinkUserListPersistenceError",
43 {
44 operation: Schema.Literals(["list-users", "list-delivery-users"]),
45 environmentId: Schema.String,
46 cause: Schema.Defect(),
47 },
48) {
49 override get message(): string {
50 return `Environment link user query '${this.operation}' failed for environment '${this.environmentId}'`;
51 }
53​
54export class EnvironmentPublicKeyListPersistenceError extends Schema.TaggedError<EnvironmentPublicKeyListPersistenceError>()(
55 "EnvironmentPublicKeyListPersistenceError",
56 {
57 environmentId: Schema.String,
58 cause: Schema.Defect(),
59 },
60) {
61 override get message(): string {
62 return `Failed to list public keys for environment '${this.environmentId}'`;
63 }
65​
66export class EnvironmentLinkListPersistenceError extends Schema.TaggedError<EnvironmentLinkListPersistenceError>()(
67 "EnvironmentLinkListPersistenceError",
68 {
69 userId: Schema.String,
70 cause: Schema.Defect(),
71 },
72) {
73 override get message(): string {
74 return `Failed to list environment links for user '${this.userId}'`;
75 }
77​
78export class EnvironmentLinkLookupPersistenceError extends Schema.TaggedError<EnvironmentLinkLookupPersistenceError>()(
79 "EnvironmentLinkLookupPersistenceError",
80 {
81 userId: Schema.String,
82 environmentId: Schema.String,
83 cause: Schema.Defect(),
84 },
85) {
86 override get message(): string {
87 return `Failed to look up environment link for user '${this.userId}', environment '${this.environmentId}'`;
88 }
90​
91export class EnvironmentLinkRevokePersistenceError extends Schema.TaggedError<EnvironmentLinkRevokePersistenceError>()(
92 "EnvironmentLinkRevokePersistenceError",
93 {
94 userId: Schema.String,
95 environmentId: Schema.String,
96 cause: Schema.Defect(),
97 },
98) {
99 override get message(): string {
100 return `Failed to revoke environment link for user '${this.userId}', environment '${this.environmentId}'`;
101 }
103​
104export class EnvironmentLinks extends Context.Service<
105 EnvironmentLinks,
106 {
107 readonly upsert: (input: {
108 readonly userId: string;
109 readonly request: RelayEnvironmentLinkRequest;
110 readonly proof: RelayEnvironmentLinkProofPayload;
111 readonly endpoint: RelayManagedEndpoint;
112 }) => Effect.Effect<void, EnvironmentLinkUpsertPersistenceError>;
113 readonly listUsersForEnvironment: (input: {
114 readonly environmentId: string;
115 }) => Effect.Effect<ReadonlyArray<string>, EnvironmentLinkUserListPersistenceError>;
116 readonly listDeliveryUsersForEnvironment: (input: {
117 readonly environmentId: string;
118 readonly environmentPublicKey: string;
119 }) => Effect.Effect<
120 ReadonlyArray<AgentAwarenessDeliveryUserRecord>,
121 EnvironmentLinkUserListPersistenceError
122 >;
123 readonly listPublicKeysForEnvironment: (input: {
124 readonly environmentId: string;
125 }) => Effect.Effect<ReadonlyArray<string>, EnvironmentPublicKeyListPersistenceError>;
126 readonly listForUser: (input: {
127 readonly userId: string;
128 }) => Effect.Effect<
129 ReadonlyArray<RelayClientEnvironmentRecord>,
130 EnvironmentLinkListPersistenceError
131 >;
132 readonly getForUser: (input: {
133 readonly userId: string;
134 readonly environmentId: string;
135 }) => Effect.Effect<RelayLinkedEnvironmentRecord | null, EnvironmentLinkLookupPersistenceError>;
136 readonly revokeForUser: (input: {
137 readonly userId: string;
138 readonly environmentId: string;
139 }) => Effect.Effect<boolean, EnvironmentLinkRevokePersistenceError>;
140 }
141>()("t3code-relay/environments/EnvironmentLinks") {}
142​
143function agentAwarenessDeliveryUserCondition(environmentId: string) {
144 return and(
145 eq(relayEnvironmentLinks.environmentId, environmentId),
146 isNull(relayEnvironmentLinks.revokedAt),
147 or(
148 eq(relayEnvironmentLinks.notificationsEnabled, true),
149 eq(relayEnvironmentLinks.liveActivitiesEnabled, true),
150 ),
151 );
153​
154function agentAwarenessDeliveryUserKeyCondition(input: {
155 readonly environmentId: string;
156 readonly environmentPublicKey: string;
157}) {
158 return and(
159 agentAwarenessDeliveryUserCondition(input.environmentId),
160 eq(relayEnvironmentLinks.environmentPublicKey, input.environmentPublicKey),
161 );
163​
164const make = Effect.gen(function* () {
165 const db = yield* RelayDb.RelayDb;
166​
167 return EnvironmentLinks.of({
168 upsert: Effect.fn("relay.environment_links.upsert")(function* (input) {
169 yield* Effect.annotateCurrentSpan({
170 "relay.environment_id": input.proof.environmentId,
171 });
172 const now = DateTime.formatIso(yield* DateTime.now);
173 const { request, proof } = input;
174 const environmentId = proof.environmentId;
175 const { endpoint } = input;
176 yield* db
177 .insert(relayEnvironmentLinks)
178 .values({
179 userId: input.userId,
180 environmentId,
181 environmentLabel: proof.descriptor.label,
182 environmentPublicKey: proof.environmentPublicKey,
183 endpointHttpBaseUrl: endpoint.httpBaseUrl,
184 endpointWsBaseUrl: endpoint.wsBaseUrl,
185 endpointProviderKind: endpoint.providerKind,
186 notificationsEnabled: request.notificationsEnabled,
187 liveActivitiesEnabled: request.liveActivitiesEnabled,
188 managedTunnelsEnabled: request.managedTunnelsEnabled,
189 createdByDeviceId: request.deviceId ?? null,
190 revokedAt: null,
191 createdAt: now,
192 updatedAt: now,
193 })
194 .onConflictDoUpdate({
195 target: [relayEnvironmentLinks.userId, relayEnvironmentLinks.environmentId],
196 set: {
197 environmentPublicKey: proof.environmentPublicKey,
198 environmentLabel: proof.descriptor.label,
199 endpointHttpBaseUrl: endpoint.httpBaseUrl,
200 endpointWsBaseUrl: endpoint.wsBaseUrl,
201 endpointProviderKind: endpoint.providerKind,
202 notificationsEnabled: request.notificationsEnabled,
203 liveActivitiesEnabled: request.liveActivitiesEnabled,
204 managedTunnelsEnabled: request.managedTunnelsEnabled,
205 createdByDeviceId: request.deviceId ?? null,
206 revokedAt: null,
207 updatedAt: now,
208 },
209 })
210 .pipe(
211 Effect.mapError(
212 (cause) =>
213 new EnvironmentLinkUpsertPersistenceError({
214 userId: input.userId,
215 environmentId,
216 ...(request.deviceId === undefined ? {} : { deviceId: request.deviceId }),
217 cause,
218 }),
219 ),
220 );
221 }),
222​
223 listUsersForEnvironment: Effect.fn("relay.environment_links.list_users_for_environment")(
224 function* (input) {
225 yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });
226 return yield* db
227 .select({ userId: relayEnvironmentLinks.userId })
228 .from(relayEnvironmentLinks)
229 .where(agentAwarenessDeliveryUserCondition(input.environmentId))
230 .pipe(
231 Effect.map((rows) => rows.map((row) => row.userId)),
232 Effect.mapError(
233 (cause) =>
234 new EnvironmentLinkUserListPersistenceError({
235 operation: "list-users",
236 environmentId: input.environmentId,
237 cause,
238 }),
239 ),
240 );
241 },
242 ),
243​
244 listDeliveryUsersForEnvironment: Effect.fn(
245 "relay.environment_links.list_delivery_users_for_environment",
246 )(function* (input) {
247 yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });
248 return yield* db
249 .select({
250 userId: relayEnvironmentLinks.userId,
251 notificationsEnabled: relayEnvironmentLinks.notificationsEnabled,
252 liveActivitiesEnabled: relayEnvironmentLinks.liveActivitiesEnabled,
253 })
254 .from(relayEnvironmentLinks)
255 .where(agentAwarenessDeliveryUserKeyCondition(input))
256 .pipe(
257 Effect.map((rows) =>
258 rows.map((row) => ({
259 userId: row.userId,
260 notificationsEnabled: row.notificationsEnabled,
261 liveActivitiesEnabled: row.liveActivitiesEnabled,
262 })),
263 ),
264 Effect.mapError(
265 (cause) =>
266 new EnvironmentLinkUserListPersistenceError({
267 operation: "list-delivery-users",
268 environmentId: input.environmentId,
269 cause,
270 }),
271 ),
272 );
273 }),
274​
275 listPublicKeysForEnvironment: Effect.fn(
276 "relay.environment_links.list_public_keys_for_environment",
277 )(function* (input) {
278 yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });
279 return yield* db
280 .select({ environmentPublicKey: relayEnvironmentLinks.environmentPublicKey })
281 .from(relayEnvironmentLinks)
282 .where(
283 and(
284 eq(relayEnvironmentLinks.environmentId, input.environmentId),
285 isNull(relayEnvironmentLinks.revokedAt),
286 ),
287 )
288 .pipe(
289 Effect.map((rows) => [
290 ...new Set(rows.map((row) => row.environmentPublicKey).filter((key) => key.length > 0)),
291 ]),
292 Effect.mapError(
293 (cause) =>
294 new EnvironmentPublicKeyListPersistenceError({
295 environmentId: input.environmentId,
296 cause,
297 }),
298 ),
299 );
300 }),
301​
302 listForUser: Effect.fn("relay.environment_links.list_for_user")(function* (input) {
303 return yield* db
304 .select({
305 environmentId: relayEnvironmentLinks.environmentId,
306 environmentLabel: relayEnvironmentLinks.environmentLabel,
307 endpointHttpBaseUrl: relayEnvironmentLinks.endpointHttpBaseUrl,
308 endpointWsBaseUrl: relayEnvironmentLinks.endpointWsBaseUrl,
309 endpointProviderKind: relayEnvironmentLinks.endpointProviderKind,
310 createdAt: relayEnvironmentLinks.createdAt,
311 })
312 .from(relayEnvironmentLinks)
313 .where(
314 and(
315 eq(relayEnvironmentLinks.userId, input.userId),
316 isNull(relayEnvironmentLinks.revokedAt),
317 ),
318 )
319 .pipe(
320 Effect.map((rows) =>
321 rows.map((row) => ({
322 environmentId: row.environmentId as RelayClientEnvironmentRecord["environmentId"],
323 label:
324 row.environmentLabel.trim().length > 0 ? row.environmentLabel : row.environmentId,
325 endpoint: {
326 httpBaseUrl: row.endpointHttpBaseUrl,
327 wsBaseUrl: row.endpointWsBaseUrl,
328 providerKind:
329 row.endpointProviderKind as RelayClientEnvironmentRecord["endpoint"]["providerKind"],
330 },
331 linkedAt: row.createdAt,
332 })),
333 ),
334 Effect.mapError(
335 (cause) =>
336 new EnvironmentLinkListPersistenceError({
337 userId: input.userId,
338 cause,
339 }),
340 ),
341 );
342 }),
343​
344 getForUser: Effect.fn("relay.environment_links.get_for_user")(function* (input) {
345 yield* Effect.annotateCurrentSpan({
346 "relay.environment_id": input.environmentId,
347 });
348 return yield* db
349 .select({
350 environmentId: relayEnvironmentLinks.environmentId,
351 environmentLabel: relayEnvironmentLinks.environmentLabel,
352 environmentPublicKey: relayEnvironmentLinks.environmentPublicKey,
353 endpointHttpBaseUrl: relayEnvironmentLinks.endpointHttpBaseUrl,
354 endpointWsBaseUrl: relayEnvironmentLinks.endpointWsBaseUrl,
355 endpointProviderKind: relayEnvironmentLinks.endpointProviderKind,
356 createdAt: relayEnvironmentLinks.createdAt,
357 })
358 .from(relayEnvironmentLinks)
359 .where(
360 and(
361 eq(relayEnvironmentLinks.userId, input.userId),
362 eq(relayEnvironmentLinks.environmentId, input.environmentId),
363 isNull(relayEnvironmentLinks.revokedAt),
364 ),
365 )
366 .limit(1)
367 .pipe(
368 Effect.map((rows) => {
369 const row = rows[0];
370 return row
371 ? {
372 environmentId: row.environmentId as RelayClientEnvironmentRecord["environmentId"],
373 label:
374 row.environmentLabel.trim().length > 0
375 ? row.environmentLabel
376 : row.environmentId,
377 endpoint: {
378 httpBaseUrl: row.endpointHttpBaseUrl,
379 wsBaseUrl: row.endpointWsBaseUrl,
380 providerKind:
381 row.endpointProviderKind as RelayClientEnvironmentRecord["endpoint"]["providerKind"],
382 },
383 environmentPublicKey: row.environmentPublicKey,
384 linkedAt: row.createdAt,
385 }
386 : null;
387 }),
388 Effect.mapError(
389 (cause) =>
390 new EnvironmentLinkLookupPersistenceError({
391 userId: input.userId,
392 environmentId: input.environmentId,
393 cause,
394 }),
395 ),
396 );
397 }),
398​
399 revokeForUser: Effect.fn("relay.environment_links.revoke_for_user")(function* (input) {
400 yield* Effect.annotateCurrentSpan({
401 "relay.environment_id": input.environmentId,
402 });
403 const revokedAt = DateTime.formatIso(yield* DateTime.now);
404 const rows = yield* db
405 .update(relayEnvironmentLinks)
406 .set({
407 revokedAt,
408 updatedAt: revokedAt,
409 })
410 .where(
411 and(
412 eq(relayEnvironmentLinks.userId, input.userId),
413 eq(relayEnvironmentLinks.environmentId, input.environmentId),
414 isNull(relayEnvironmentLinks.revokedAt),
415 ),
416 )
417 .returning({ environmentId: relayEnvironmentLinks.environmentId })
418 .pipe(
419 Effect.mapError(
420 (cause) =>
421 new EnvironmentLinkRevokePersistenceError({
422 userId: input.userId,
423 environmentId: input.environmentId,
424 cause,
425 }),
426 ),
427 );
428 return rows.length > 0;
429 }),
430 });
431});
432​
433export const layer = Layer.effect(EnvironmentLinks, make);