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 // The drizzle handle is alchemy's lazy proxy chain: it only becomes a
85 // real Effect when consumed via `yield*`. Handing it to Effect.all sends
86 // the raw Proxy into the fiber runtime, which spins the isolate at 100%
87 // CPU (registrations then hang until the client aborts) — keep every db
88 // chain directly yielded.
89 if (registration.pushToken) {
90 yield* db
91 .update(relayMobileDevices)
92 .set({ pushToken: null, updatedAt })
93 .where(eq(relayMobileDevices.pushToken, registration.pushToken))
94 .pipe(
95 Effect.mapError(
96 (cause) =>
97 new DeviceRegistrationPersistenceError({
98 userId: input.userId,
99 deviceId: registration.deviceId,
100 stage: "claim-push-token",
101 cause,
102 }),
103 ),
104 );
105 }
106 if (registration.pushToStartToken) {
107 yield* db
108 .update(relayMobileDevices)
109 .set({ pushToStartToken: null, updatedAt })
110 .where(eq(relayMobileDevices.pushToStartToken, registration.pushToStartToken))
111 .pipe(
112 Effect.mapError(
113 (cause) =>
114 new DeviceRegistrationPersistenceError({
115 userId: input.userId,
116 deviceId: registration.deviceId,
117 stage: "claim-push-to-start-token",
118 cause,
119 }),
120 ),
121 );
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 bundleId: registration.bundleId ?? null,
134 apsEnvironment: registration.apsEnvironment ?? null,
135 pushToken: registration.pushToken ?? null,
136 pushToStartToken: registration.pushToStartToken ?? null,
137 preferencesJson: registration.preferences,
138 createdAt: updatedAt,
139 updatedAt,
140 })
141 .onConflictDoUpdate({
142 target: [relayMobileDevices.userId, relayMobileDevices.deviceId],
143 set: {
144 platform: registration.platform,
145 label: registration.label,
146 iosMajorVersion: registration.iosMajorVersion,
147 appVersion: registration.appVersion ?? null,
148 // Preserve routing from newer app builds when an older build
149 // re-registers without these fields.
150 bundleId: sql`coalesce(excluded.bundle_id, ${relayMobileDevices.bundleId})`,
151 apsEnvironment: sql`coalesce(
152 excluded.aps_environment,
153 ${relayMobileDevices.apsEnvironment}
154 )`,
155 pushToken: sql`coalesce(excluded.push_token, ${relayMobileDevices.pushToken})`,
156 pushToStartToken: sql`coalesce(
157 excluded.push_to_start_token,
158 ${relayMobileDevices.pushToStartToken}
159 )`,
160 preferencesJson: registration.preferences,
161 updatedAt,
162 },
163 })
164 .pipe(
165 Effect.mapError(
166 (cause) =>
167 new DeviceRegistrationPersistenceError({
168 userId: input.userId,
169 deviceId: registration.deviceId,
170 stage: "upsert-device",
171 cause,
172 }),
173 ),
174 );
175 }),
176 unregister: Effect.fn("relay.devices.unregister")(function* (input) {
177 yield* Effect.annotateCurrentSpan({
178 "relay.mobile.device_id": input.deviceId,
179 });
180 // Same proxy-chain constraint as register above: db chains must be
181 // consumed via `yield*`, never passed to Effect.all.
182 yield* db
183 .delete(relayLiveActivities)
184 .where(
185 and(
186 eq(relayLiveActivities.userId, input.userId),
187 eq(relayLiveActivities.deviceId, input.deviceId),
188 ),
189 )
190 .pipe(
191 Effect.mapError(
192 (cause) =>
193 new DeviceUnregistrationPersistenceError({
194 userId: input.userId,
195 deviceId: input.deviceId,
196 stage: "delete-live-activity",
197 cause,
198 }),
199 ),
200 );
201 yield* db
202 .delete(relayMobileDevices)
203 .where(
204 and(
205 eq(relayMobileDevices.userId, input.userId),
206 eq(relayMobileDevices.deviceId, input.deviceId),
207 ),
208 )
209 .pipe(
210 Effect.mapError(
211 (cause) =>
212 new DeviceUnregistrationPersistenceError({
213 userId: input.userId,
214 deviceId: input.deviceId,
215 stage: "delete-device",
216 cause,
217 }),
218 ),
219 );
220 }),
221 listForUser: Effect.fn("relay.devices.listForUser")(function* (input) {
222 const rows = yield* db
223 .select({
224 deviceId: relayMobileDevices.deviceId,
225 label: relayMobileDevices.label,
226 platform: relayMobileDevices.platform,
227 iosMajorVersion: relayMobileDevices.iosMajorVersion,
228 appVersion: relayMobileDevices.appVersion,
229 preferences: relayMobileDevices.preferencesJson,
230 updatedAt: relayMobileDevices.updatedAt,
231 })
232 .from(relayMobileDevices)
233 .where(eq(relayMobileDevices.userId, input.userId))
234 .pipe(
235 Effect.mapError(
236 (cause) => new DeviceListPersistenceError({ userId: input.userId, cause }),
237 ),
238 );
239 return rows.map((row) => ({
240 deviceId: row.deviceId,
241 label: row.label,
242 platform: row.platform,
243 iosMajorVersion: row.iosMajorVersion,
244 appVersion: row.appVersion,
245 notifications: {
246 enabled: row.preferences.notificationsEnabled,
247 notifyOnApproval: row.preferences.notifyOnApproval,
248 notifyOnInput: row.preferences.notifyOnInput,
249 notifyOnCompletion: row.preferences.notifyOnCompletion,
250 notifyOnFailure: row.preferences.notifyOnFailure,
251 },
252 liveActivities: {
253 enabled: row.preferences.liveActivitiesEnabled,
254 },
255 updatedAt: row.updatedAt,
256 }));
257 }),
258 });
259});
260
261export const layer = Layer.effect(Devices, make);