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

EnvironmentLinks.ts

489 lines18.1 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, sql } 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 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 }
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 }
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 }
77​
78export class EnvironmentLinkEnvironmentLookupPersistenceError extends Schema.TaggedError<EnvironmentLinkEnvironmentLookupPersistenceError>()(
79 "EnvironmentLinkEnvironmentLookupPersistenceError",
80 {
81 environmentId: Schema.String,
82 cause: Schema.Defect(),
83 },
84) {
85 override get message(): string {
86 return `Failed to look up active managed links for environment '${this.environmentId}'`;
87 }
89​
90export class EnvironmentLinkRevokePersistenceError extends Schema.TaggedError<EnvironmentLinkRevokePersistenceError>()(
91 "EnvironmentLinkRevokePersistenceError",
92 {
93 userId: Schema.String,
94 environmentId: Schema.String,
95 cause: Schema.Defect(),
96 },
97) {
98 override get message(): string {
99 return `Failed to revoke environment link for user '${this.userId}', environment '${this.environmentId}'`;
100 }
102​
103export class EnvironmentLinks extends Context.Service<
104 EnvironmentLinks,
105 {
106 readonly upsert: (input: {
107 readonly userId: string;
108 readonly request: RelayEnvironmentLinkRequest;
109 readonly proof: RelayEnvironmentLinkProofPayload;
110 readonly endpoint: RelayManagedEndpoint;
111 }) => Effect.Effect<void, EnvironmentLinkUpsertPersistenceError>;
112 readonly listDeliveryUsersForEnvironment: (input: {
113 readonly environmentId: string;
114 readonly environmentPublicKey: string;
115 }) => Effect.Effect<
116 ReadonlyArray<AgentAwarenessDeliveryUserRecord>,
117 EnvironmentLinkUserListPersistenceError
118 >;
119 readonly listForUser: (input: {
120 readonly userId: string;
121 }) => Effect.Effect<
122 ReadonlyArray<RelayClientEnvironmentRecord>,
123 EnvironmentLinkListPersistenceError
124 >;
125 readonly getForUser: (input: {
126 readonly userId: string;
127 readonly environmentId: string;
128 }) => Effect.Effect<RelayLinkedEnvironmentRecord | null, EnvironmentLinkLookupPersistenceError>;
129 /**
130 * Active relay-managed links for an environment, narrowed to one user or to
131 * links proven by one environment key. The environment id alone is public
132 * and any account can link it, so callers acting on it must narrow.
133 */
134 readonly findActiveManagedForEnvironment: (input: {
135 readonly environmentId: string;
136 readonly userId?: string;
137 readonly environmentPublicKey?: string;
138 }) => Effect.Effect<
139 ReadonlyArray<
140 RelayLinkedEnvironmentRecord & {
141 readonly userId: string;
142 readonly holdWebhooksWhileOffline: boolean;
143 }
144 >,
145 EnvironmentLinkEnvironmentLookupPersistenceError
146 >;
147 readonly setHoldWebhooksWhileOffline: (input: {
148 readonly environmentId: string;
149 readonly environmentPublicKey: string;
150 readonly holdWebhooksWhileOffline: boolean;
151 }) => Effect.Effect<void, EnvironmentLinkEnvironmentLookupPersistenceError>;
152 readonly revokeForUser: (input: {
153 readonly userId: string;
154 readonly environmentId: string;
155 }) => Effect.Effect<boolean, EnvironmentLinkRevokePersistenceError>;
156 }
157>()("t3code-relay/environments/EnvironmentLinks") {}
158​
159function agentAwarenessDeliveryUserKeyCondition(input: {
160 readonly environmentId: string;
161 readonly environmentPublicKey: string;
162}) {
163 return and(
164 eq(relayEnvironmentLinks.environmentId, input.environmentId),
165 isNull(relayEnvironmentLinks.revokedAt),
166 or(
167 eq(relayEnvironmentLinks.notificationsEnabled, true),
168 eq(relayEnvironmentLinks.liveActivitiesEnabled, true),
169 ),
170 eq(relayEnvironmentLinks.environmentPublicKey, input.environmentPublicKey),
171 );
173​
174const make = Effect.gen(function* () {
175 const db = yield* RelayDb.RelayDb;
176​
177 return EnvironmentLinks.of({
178 upsert: Effect.fn("relay.environment_links.upsert")(function* (input) {
179 yield* Effect.annotateCurrentSpan({
180 "relay.environment_id": input.proof.environmentId,
181 });
182 const now = DateTime.formatIso(yield* DateTime.now);
183 const { request, proof } = input;
184 const environmentId = proof.environmentId;
185 // The webhook-hold opt-in belongs to the environment: a new or re-made
186 // link carries it over from the environment's other active links. Only
187 // links proven by the same key count; an environment id is public, so
188 // anyone can link one and switch the opt-in on for their own link.
189 const inheritedHoldWebhooks = sql<boolean>`EXISTS (
190 SELECT 1 FROM ${relayEnvironmentLinks} AS other
191 WHERE other.environment_id = ${environmentId}
192 AND other.environment_public_key = ${proof.environmentPublicKey}
193 AND other.revoked_at IS NULL
194 AND other.hold_webhooks_while_offline
195 )`;
196 const { endpoint } = input;
197 yield* db
198 .insert(relayEnvironmentLinks)
199 .values({
200 userId: input.userId,
201 environmentId,
202 holdWebhooksWhileOffline: inheritedHoldWebhooks,
203 environmentLabel: proof.descriptor.label,
204 environmentPublicKey: proof.environmentPublicKey,
205 endpointHttpBaseUrl: endpoint.httpBaseUrl,
206 endpointWsBaseUrl: endpoint.wsBaseUrl,
207 endpointProviderKind: endpoint.providerKind,
208 notificationsEnabled: request.notificationsEnabled,
209 liveActivitiesEnabled: request.liveActivitiesEnabled,
210 managedTunnelsEnabled: request.managedTunnelsEnabled,
211 createdByDeviceId: request.deviceId ?? null,
212 revokedAt: null,
213 createdAt: now,
214 updatedAt: now,
215 })
216 .onConflictDoUpdate({
217 target: [relayEnvironmentLinks.userId, relayEnvironmentLinks.environmentId],
218 set: {
219 environmentPublicKey: proof.environmentPublicKey,
220 environmentLabel: proof.descriptor.label,
221 endpointHttpBaseUrl: endpoint.httpBaseUrl,
222 endpointWsBaseUrl: endpoint.wsBaseUrl,
223 endpointProviderKind: endpoint.providerKind,
224 notificationsEnabled: request.notificationsEnabled,
225 liveActivitiesEnabled: request.liveActivitiesEnabled,
226 managedTunnelsEnabled: request.managedTunnelsEnabled,
227 createdByDeviceId: request.deviceId ?? null,
228 revokedAt: null,
229 updatedAt: now,
230 holdWebhooksWhileOffline: inheritedHoldWebhooks,
231 },
232 })
233 .pipe(
234 Effect.mapError(
235 (cause) =>
236 new EnvironmentLinkUpsertPersistenceError({
237 userId: input.userId,
238 environmentId,
239 ...(request.deviceId === undefined ? {} : { deviceId: request.deviceId }),
240 cause,
241 }),
242 ),
243 );
244 }),
245​
246 listDeliveryUsersForEnvironment: Effect.fn(
247 "relay.environment_links.list_delivery_users_for_environment",
248 )(function* (input) {
249 yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });
250 return yield* db
251 .select({
252 userId: relayEnvironmentLinks.userId,
253 notificationsEnabled: relayEnvironmentLinks.notificationsEnabled,
254 liveActivitiesEnabled: relayEnvironmentLinks.liveActivitiesEnabled,
255 })
256 .from(relayEnvironmentLinks)
257 .where(agentAwarenessDeliveryUserKeyCondition(input))
258 .pipe(
259 Effect.map((rows) =>
260 rows.map((row) => ({
261 userId: row.userId,
262 notificationsEnabled: row.notificationsEnabled,
263 liveActivitiesEnabled: row.liveActivitiesEnabled,
264 })),
265 ),
266 Effect.mapError(
267 (cause) =>
268 new EnvironmentLinkUserListPersistenceError({
269 environmentId: input.environmentId,
270 cause,
271 }),
272 ),
273 );
274 }),
275​
276 listForUser: Effect.fn("relay.environment_links.list_for_user")(function* (input) {
277 return yield* db
278 .select({
279 environmentId: relayEnvironmentLinks.environmentId,
280 environmentLabel: relayEnvironmentLinks.environmentLabel,
281 endpointHttpBaseUrl: relayEnvironmentLinks.endpointHttpBaseUrl,
282 endpointWsBaseUrl: relayEnvironmentLinks.endpointWsBaseUrl,
283 endpointProviderKind: relayEnvironmentLinks.endpointProviderKind,
284 createdAt: relayEnvironmentLinks.createdAt,
285 })
286 .from(relayEnvironmentLinks)
287 .where(
288 and(
289 eq(relayEnvironmentLinks.userId, input.userId),
290 isNull(relayEnvironmentLinks.revokedAt),
291 ),
292 )
293 .pipe(
294 Effect.map((rows) =>
295 rows.map((row) => ({
296 environmentId: row.environmentId as RelayClientEnvironmentRecord["environmentId"],
297 label:
298 row.environmentLabel.trim().length > 0 ? row.environmentLabel : row.environmentId,
299 endpoint: {
300 httpBaseUrl: row.endpointHttpBaseUrl,
301 wsBaseUrl: row.endpointWsBaseUrl,
302 providerKind:
303 row.endpointProviderKind as RelayClientEnvironmentRecord["endpoint"]["providerKind"],
304 },
305 linkedAt: row.createdAt,
306 })),
307 ),
308 Effect.mapError(
309 (cause) =>
310 new EnvironmentLinkListPersistenceError({
311 userId: input.userId,
312 cause,
313 }),
314 ),
315 );
316 }),
317​
318 getForUser: Effect.fn("relay.environment_links.get_for_user")(function* (input) {
319 yield* Effect.annotateCurrentSpan({
320 "relay.environment_id": input.environmentId,
321 });
322 return yield* db
323 .select({
324 environmentId: relayEnvironmentLinks.environmentId,
325 environmentLabel: relayEnvironmentLinks.environmentLabel,
326 environmentPublicKey: relayEnvironmentLinks.environmentPublicKey,
327 endpointHttpBaseUrl: relayEnvironmentLinks.endpointHttpBaseUrl,
328 endpointWsBaseUrl: relayEnvironmentLinks.endpointWsBaseUrl,
329 endpointProviderKind: relayEnvironmentLinks.endpointProviderKind,
330 createdAt: relayEnvironmentLinks.createdAt,
331 })
332 .from(relayEnvironmentLinks)
333 .where(
334 and(
335 eq(relayEnvironmentLinks.userId, input.userId),
336 eq(relayEnvironmentLinks.environmentId, input.environmentId),
337 isNull(relayEnvironmentLinks.revokedAt),
338 ),
339 )
340 .limit(1)
341 .pipe(
342 Effect.map((rows) => {
343 const row = rows[0];
344 return row
345 ? {
346 environmentId: row.environmentId as RelayClientEnvironmentRecord["environmentId"],
347 label:
348 row.environmentLabel.trim().length > 0
349 ? row.environmentLabel
350 : row.environmentId,
351 endpoint: {
352 httpBaseUrl: row.endpointHttpBaseUrl,
353 wsBaseUrl: row.endpointWsBaseUrl,
354 providerKind:
355 row.endpointProviderKind as RelayClientEnvironmentRecord["endpoint"]["providerKind"],
356 },
357 environmentPublicKey: row.environmentPublicKey,
358 linkedAt: row.createdAt,
359 }
360 : null;
361 }),
362 Effect.mapError(
363 (cause) =>
364 new EnvironmentLinkLookupPersistenceError({
365 userId: input.userId,
366 environmentId: input.environmentId,
367 cause,
368 }),
369 ),
370 );
371 }),
372​
373 findActiveManagedForEnvironment: Effect.fn(
374 "relay.environment_links.find_active_managed_for_environment",
375 )(function* (input) {
376 yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });
377 return yield* db
378 .select({
379 userId: relayEnvironmentLinks.userId,
380 environmentId: relayEnvironmentLinks.environmentId,
381 environmentLabel: relayEnvironmentLinks.environmentLabel,
382 environmentPublicKey: relayEnvironmentLinks.environmentPublicKey,
383 endpointHttpBaseUrl: relayEnvironmentLinks.endpointHttpBaseUrl,
384 endpointWsBaseUrl: relayEnvironmentLinks.endpointWsBaseUrl,
385 endpointProviderKind: relayEnvironmentLinks.endpointProviderKind,
386 createdAt: relayEnvironmentLinks.createdAt,
387 holdWebhooksWhileOffline: relayEnvironmentLinks.holdWebhooksWhileOffline,
388 })
389 .from(relayEnvironmentLinks)
390 .where(
391 and(
392 eq(relayEnvironmentLinks.environmentId, input.environmentId),
393 isNull(relayEnvironmentLinks.revokedAt),
394 eq(relayEnvironmentLinks.endpointProviderKind, "cloudflare_tunnel"),
395 eq(relayEnvironmentLinks.managedTunnelsEnabled, true),
396 input.userId === undefined ? undefined : eq(relayEnvironmentLinks.userId, input.userId),
397 input.environmentPublicKey === undefined
398 ? undefined
399 : eq(relayEnvironmentLinks.environmentPublicKey, input.environmentPublicKey),
400 ),
401 )
402 .pipe(
403 Effect.map((rows) =>
404 rows.map((row) => ({
405 userId: row.userId,
406 environmentId: row.environmentId as RelayClientEnvironmentRecord["environmentId"],
407 label:
408 row.environmentLabel.trim().length > 0 ? row.environmentLabel : row.environmentId,
409 endpoint: {
410 httpBaseUrl: row.endpointHttpBaseUrl,
411 wsBaseUrl: row.endpointWsBaseUrl,
412 providerKind:
413 row.endpointProviderKind as RelayClientEnvironmentRecord["endpoint"]["providerKind"],
414 },
415 environmentPublicKey: row.environmentPublicKey,
416 linkedAt: row.createdAt,
417 holdWebhooksWhileOffline: row.holdWebhooksWhileOffline,
418 })),
419 ),
420 Effect.mapError(
421 (cause) =>
422 new EnvironmentLinkEnvironmentLookupPersistenceError({
423 environmentId: input.environmentId,
424 cause,
425 }),
426 ),
427 );
428 }),
429​
430 setHoldWebhooksWhileOffline: Effect.fn(
431 "relay.environment_links.set_hold_webhooks_while_offline",
432 )(function* (input) {
433 yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });
434 yield* db
435 .update(relayEnvironmentLinks)
436 .set({ holdWebhooksWhileOffline: input.holdWebhooksWhileOffline })
437 .where(
438 and(
439 eq(relayEnvironmentLinks.environmentId, input.environmentId),
440 eq(relayEnvironmentLinks.environmentPublicKey, input.environmentPublicKey),
441 isNull(relayEnvironmentLinks.revokedAt),
442 ),
443 )
444 .pipe(
445 Effect.mapError(
446 (cause) =>
447 new EnvironmentLinkEnvironmentLookupPersistenceError({
448 environmentId: input.environmentId,
449 cause,
450 }),
451 ),
452 );
453 }),
454​
455 revokeForUser: Effect.fn("relay.environment_links.revoke_for_user")(function* (input) {
456 yield* Effect.annotateCurrentSpan({
457 "relay.environment_id": input.environmentId,
458 });
459 const revokedAt = DateTime.formatIso(yield* DateTime.now);
460 const rows = yield* db
461 .update(relayEnvironmentLinks)
462 .set({
463 revokedAt,
464 updatedAt: revokedAt,
465 })
466 .where(
467 and(
468 eq(relayEnvironmentLinks.userId, input.userId),
469 eq(relayEnvironmentLinks.environmentId, input.environmentId),
470 isNull(relayEnvironmentLinks.revokedAt),
471 ),
472 )
473 .returning({ environmentId: relayEnvironmentLinks.environmentId })
474 .pipe(
475 Effect.mapError(
476 (cause) =>
477 new EnvironmentLinkRevokePersistenceError({
478 userId: input.userId,
479 environmentId: input.environmentId,
480 cause,
481 }),
482 ),
483 );
484 return rows.length > 0;
485 }),
486 });
487});
488​
489export const layer = Layer.effect(EnvironmentLinks, make);