Open History to see the last commit
1import type {
2 RelayClientDeviceRecord,
3 RelayDeviceRegistrationRequest,
4} from "@t3tools/contracts/relay";
5import * as Context from "effect/Context";
6import * as DateTime from "effect/DateTime";
7import * as Effect from "effect/Effect";
8import * as Layer from "effect/Layer";
9import * as Schema from "effect/Schema";
10import { and, eq } from "drizzle-orm";
11import { sql } from "drizzle-orm";
12
13import * as RelayDb from "../db.ts";
14import { relayLiveActivities, relayMobileDevices } from "../persistence/schema.ts";
15
16export class DeviceRegistrationPersistenceError extends Schema.TaggedErrorClass<DeviceRegistrationPersistenceError>()(
17 "DeviceRegistrationPersistenceError",
18 {
19 userId: Schema.String,
20 deviceId: Schema.String,
21 stage: Schema.Literals(["claim-push-token", "claim-push-to-start-token", "upsert-device"]),
22 cause: Schema.Defect(),
23 },
24) {
25 override get message(): string {
26 return `Failed to persist mobile device registration for ${this.userId}/${this.deviceId} during ${this.stage}.`;
27 }
28}
29
30export class DeviceUnregistrationPersistenceError extends Schema.TaggedErrorClass<DeviceUnregistrationPersistenceError>()(
31 "DeviceUnregistrationPersistenceError",
32 {
33 userId: Schema.String,
34 deviceId: Schema.String,
35 stage: Schema.Literals(["delete-live-activity", "delete-device"]),
36 cause: Schema.Defect(),
37 },
38) {
39 override get message(): string {
40 return `Failed to unregister mobile device ${this.userId}/${this.deviceId} during ${this.stage}.`;
41 }
42}
43
44export class DeviceListPersistenceError extends Schema.TaggedErrorClass<DeviceListPersistenceError>()(
45 "DeviceListPersistenceError",
46 {
47 userId: Schema.String,
48 cause: Schema.Defect(),
49 },
50) {
51 override get message(): string {
52 return `Failed to list mobile devices for ${this.userId}.`;
53 }
54}
55
56export class Devices extends Context.Service<
57 Devices,
58 {
59 readonly register: (input: {
60 readonly userId: string;
61 readonly registration: RelayDeviceRegistrationRequest;
62 }) => Effect.Effect<void, DeviceRegistrationPersistenceError>;
63 readonly unregister: (input: {
64 readonly userId: string;
65 readonly deviceId: string;
66 }) => Effect.Effect<void, DeviceUnregistrationPersistenceError>;
67 readonly listForUser: (input: {
68 readonly userId: string;
69 }) => Effect.Effect<ReadonlyArray<RelayClientDeviceRecord>, DeviceListPersistenceError>;
70 }
71>()("t3code-relay/agentActivity/Devices") {}
72
73export const make = Effect.gen(function* () {
74 const db = yield* RelayDb.RelayDb;
75
76 return Devices.of({
77 register: Effect.fn("relay.devices.register")(function* (input) {
78 yield* Effect.annotateCurrentSpan({
79 "relay.mobile.device_id": input.registration.deviceId,
80 });
81 const updatedAt = DateTime.formatIso(yield* DateTime.now);
82 const registration = input.registration;
83
84 yield* Effect.all(
85 [
86 registration.pushToken
87 ? db
88 .update(relayMobileDevices)
89 .set({ pushToken: null, updatedAt })
90 .where(eq(relayMobileDevices.pushToken, registration.pushToken))
91 .pipe(
92 Effect.mapError(
93 (cause) =>
94 new DeviceRegistrationPersistenceError({
95 userId: input.userId,
96 deviceId: registration.deviceId,
97 stage: "claim-push-token",
98 cause,
99 }),
100 ),
101 )
102 : Effect.void,
103 registration.pushToStartToken
104 ? db
105 .update(relayMobileDevices)
106 .set({ pushToStartToken: null, updatedAt })
107 .where(eq(relayMobileDevices.pushToStartToken, registration.pushToStartToken))
108 .pipe(
109 Effect.mapError(
110 (cause) =>
111 new DeviceRegistrationPersistenceError({
112 userId: input.userId,
113 deviceId: registration.deviceId,
114 stage: "claim-push-to-start-token",
115 cause,
116 }),
117 ),
118 )
119 : Effect.void,
120 ],
121 { discard: true },
122 );
123
124 yield* db
125 .insert(relayMobileDevices)
126 .values({
127 userId: input.userId,
128 deviceId: registration.deviceId,
129 label: registration.label,
130 platform: registration.platform,
131 iosMajorVersion: registration.iosMajorVersion,
132 appVersion: registration.appVersion ?? null,
133 pushToken: registration.pushToken ?? null,
134 pushToStartToken: registration.pushToStartToken ?? null,
135 preferencesJson: registration.preferences,
136 createdAt: updatedAt,
137 updatedAt,
138 })
139 .onConflictDoUpdate({
140 target: [relayMobileDevices.userId, relayMobileDevices.deviceId],
141 set: {
142 platform: registration.platform,
143 label: registration.label,
144 iosMajorVersion: registration.iosMajorVersion,
145 appVersion: registration.appVersion ?? null,
146 pushToken: sql`coalesce(excluded.push_token, ${relayMobileDevices.pushToken})`,
147 pushToStartToken: sql`coalesce(
148 excluded.push_to_start_token,
149 ${relayMobileDevices.pushToStartToken}
150 )`,
151 preferencesJson: registration.preferences,
152 updatedAt,
153 },
154 })
155 .pipe(
156 Effect.mapError(
157 (cause) =>
158 new DeviceRegistrationPersistenceError({
159 userId: input.userId,
160 deviceId: registration.deviceId,
161 stage: "upsert-device",
162 cause,
163 }),
164 ),
165 );
166 }),
167 unregister: Effect.fn("relay.devices.unregister")(function* (input) {
168 yield* Effect.annotateCurrentSpan({
169 "relay.mobile.device_id": input.deviceId,
170 });
171 yield* Effect.all(
172 [
173 db
174 .delete(relayLiveActivities)
175 .where(
176 and(
177 eq(relayLiveActivities.userId, input.userId),
178 eq(relayLiveActivities.deviceId, input.deviceId),
179 ),
180 )
181 .pipe(
182 Effect.mapError(
183 (cause) =>
184 new DeviceUnregistrationPersistenceError({
185 userId: input.userId,
186 deviceId: input.deviceId,
187 stage: "delete-live-activity",
188 cause,
189 }),
190 ),
191 ),
192 db
193 .delete(relayMobileDevices)
194 .where(
195 and(
196 eq(relayMobileDevices.userId, input.userId),
197 eq(relayMobileDevices.deviceId, input.deviceId),
198 ),
199 )
200 .pipe(
201 Effect.mapError(
202 (cause) =>
203 new DeviceUnregistrationPersistenceError({
204 userId: input.userId,
205 deviceId: input.deviceId,
206 stage: "delete-device",
207 cause,
208 }),
209 ),
210 ),
211 ],
212 { discard: true },
213 );
214 }),
215 listForUser: Effect.fn("relay.devices.listForUser")(function* (input) {
216 const rows = yield* db
217 .select({
218 deviceId: relayMobileDevices.deviceId,
219 label: relayMobileDevices.label,
220 platform: relayMobileDevices.platform,
221 iosMajorVersion: relayMobileDevices.iosMajorVersion,
222 appVersion: relayMobileDevices.appVersion,
223 preferences: relayMobileDevices.preferencesJson,
224 updatedAt: relayMobileDevices.updatedAt,
225 })
226 .from(relayMobileDevices)
227 .where(eq(relayMobileDevices.userId, input.userId))
228 .pipe(
229 Effect.mapError(
230 (cause) => new DeviceListPersistenceError({ userId: input.userId, cause }),
231 ),
232 );
233 return rows.map((row) => ({
234 deviceId: row.deviceId,
235 label: row.label,
236 platform: row.platform,
237 iosMajorVersion: row.iosMajorVersion,
238 appVersion: row.appVersion,
239 notifications: {
240 enabled: row.preferences.notificationsEnabled,
241 notifyOnApproval: row.preferences.notifyOnApproval,
242 notifyOnInput: row.preferences.notifyOnInput,
243 notifyOnCompletion: row.preferences.notifyOnCompletion,
244 notifyOnFailure: row.preferences.notifyOnFailure,
245 },
246 liveActivities: {
247 enabled: row.preferences.liveActivitiesEnabled,
248 },
249 updatedAt: row.updatedAt,
250 }));
251 }),
252 });
253});
254
255export const layer = Layer.effect(Devices, make);