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

Devices.test.ts

304 lines10.0 KB

1import type { RelayDeviceRegistrationRequest } from "@t3tools/contracts/relay";
2import { describe, expect, it } from "@effect/vitest";
3import type { SQL } from "drizzle-orm";
4import { PgDialect } from "drizzle-orm/pg-core";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7​
8import * as RelayDb from "../db.ts";
9import { relayLiveActivities, relayMobileDevices } from "../persistence/schema.ts";
10import * as Devices from "./Devices.ts";
11​
12const registration: RelayDeviceRegistrationRequest = {
13 deviceId: "device-1" as RelayDeviceRegistrationRequest["deviceId"],
14 label: "Julius's iPhone",
15 platform: "ios",
16 iosMajorVersion: 18,
17 appVersion: "1.0.0" as RelayDeviceRegistrationRequest["appVersion"],
18 pushToken: "apns-device-token" as RelayDeviceRegistrationRequest["pushToken"],
19 pushToStartToken: "push-to-start-token" as RelayDeviceRegistrationRequest["pushToStartToken"],
20 preferences: {
21 notificationsEnabled: true,
22 liveActivitiesEnabled: true,
23 notifyOnApproval: true,
24 notifyOnInput: true,
25 notifyOnCompletion: true,
26 notifyOnFailure: true,
27 },
28};
29​
30describe("Devices", () => {
31 it.effect("claims APNs tokens globally before upserting the current user device", () => {
32 const calls: Array<string> = [];
33 const updateSets: Array<Record<string, unknown>> = [];
34 const updateConditions: Array<SQL> = [];
35 const insertedValues: Array<Record<string, unknown>> = [];
36 const dialect = new PgDialect();
37​
38 const fakeDb = {
39 update: (table: unknown) => {
40 expect(table).toBe(relayMobileDevices);
41 calls.push("update");
42 return {
43 set: (values: Record<string, unknown>) => {
44 updateSets.push(values);
45 calls.push("update.set");
46 return {
47 where: (condition: SQL) => {
48 expect(condition).toBeDefined();
49 updateConditions.push(condition);
50 calls.push("update.where");
51 return Effect.void;
52 },
53 };
54 },
55 };
56 },
57 insert: (table: unknown) => {
58 expect(table).toBe(relayMobileDevices);
59 calls.push("insert");
60 return {
61 values: (values: Record<string, unknown>) => {
62 insertedValues.push(values);
63 calls.push("insert.values");
64 return {
65 onConflictDoUpdate: (config: unknown) => {
66 expect(config).toBeDefined();
67 calls.push("insert.onConflictDoUpdate");
68 return Effect.void;
69 },
70 };
71 },
72 };
73 },
74 } as unknown as RelayDb.RelayDb["Service"];
75​
76 return Effect.gen(function* () {
77 const devices = yield* Devices.Devices;
78 yield* devices.register({ userId: "user-2", registration });
79​
80 expect(calls).toEqual([
81 "update",
82 "update.set",
83 "update.where",
84 "update",
85 "update.set",
86 "update.where",
87 "insert",
88 "insert.values",
89 "insert.onConflictDoUpdate",
90 ]);
91 expect(updateSets).toEqual([
92 expect.objectContaining({ pushToken: null }),
93 expect.objectContaining({ pushToStartToken: null }),
94 ]);
95 expect(updateConditions.map((condition) => dialect.sqlToQuery(condition))).toEqual([
96 {
97 sql: '"relay_mobile_devices"."push_token" = $1',
98 params: ["apns-device-token"],
99 },
100 {
101 sql: '"relay_mobile_devices"."push_to_start_token" = $1',
102 params: ["push-to-start-token"],
103 },
104 ]);
105 expect(insertedValues).toEqual([
106 expect.objectContaining({
107 userId: "user-2",
108 deviceId: "device-1",
109 pushToken: "apns-device-token",
110 pushToStartToken: "push-to-start-token",
111 }),
112 ]);
113 }).pipe(
114 Effect.provide(Devices.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)))),
115 );
116 });
117​
118 it.effect("unregisters APNs state only for the current user device", () => {
119 const calls: Array<string> = [];
120 const deleteConditions: Array<SQL> = [];
121 const dialect = new PgDialect();
122​
123 const fakeDb = {
124 delete: (table: unknown) => {
125 calls.push(table === relayLiveActivities ? "delete.liveActivities" : "delete.devices");
126 return {
127 where: (condition: SQL) => {
128 expect(condition).toBeDefined();
129 deleteConditions.push(condition);
130 calls.push("delete.where");
131 return Effect.void;
132 },
133 };
134 },
135 } as unknown as RelayDb.RelayDb["Service"];
136​
137 return Effect.gen(function* () {
138 const devices = yield* Devices.Devices;
139 yield* devices.unregister({ userId: "user-2", deviceId: "device-1" });
140​
141 expect(calls).toEqual([
142 "delete.liveActivities",
143 "delete.where",
144 "delete.devices",
145 "delete.where",
146 ]);
147 expect(deleteConditions.map((condition) => dialect.sqlToQuery(condition))).toEqual([
148 {
149 sql:
150 '(("relay_live_activities"."user_id" = $1) and ' +
151 '("relay_live_activities"."device_id" = $2))',
152 params: ["user-2", "device-1"],
153 },
154 {
155 sql:
156 '(("relay_mobile_devices"."user_id" = $1) and ' +
157 '("relay_mobile_devices"."device_id" = $2))',
158 params: ["user-2", "device-1"],
159 },
160 ]);
161 }).pipe(
162 Effect.provide(Devices.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)))),
163 );
164 });
165​
166 it.effect("lists safe notification state without exposing APNs tokens", () => {
167 const dialect = new PgDialect();
168 let condition: SQL | null = null;
169 const fakeDb = {
170 select: () => ({
171 from: (table: unknown) => {
172 expect(table).toBe(relayMobileDevices);
173 return {
174 where: (nextCondition: SQL) => {
175 condition = nextCondition;
176 return Effect.succeed([
177 {
178 deviceId: "device-1",
179 label: "Julius's iPhone",
180 platform: "ios" as const,
181 iosMajorVersion: 18,
182 appVersion: "1.0.0",
183 preferences: registration.preferences,
184 updatedAt: "2026-06-01T00:00:00.000Z",
185 },
186 ]);
187 },
188 };
189 },
190 }),
191 } as unknown as RelayDb.RelayDb["Service"];
192​
193 return Effect.gen(function* () {
194 const devices = yield* Devices.Devices;
195 const listed = yield* devices.listForUser({ userId: "user-2" });
196​
197 expect(condition).not.toBeNull();
198 expect(dialect.sqlToQuery(condition!)).toEqual({
199 sql: '"relay_mobile_devices"."user_id" = $1',
200 params: ["user-2"],
201 });
202 expect(listed).toEqual([
203 {
204 deviceId: "device-1",
205 label: "Julius's iPhone",
206 platform: "ios",
207 iosMajorVersion: 18,
208 appVersion: "1.0.0",
209 notifications: {
210 enabled: true,
211 notifyOnApproval: true,
212 notifyOnInput: true,
213 notifyOnCompletion: true,
214 notifyOnFailure: true,
215 },
216 liveActivities: {
217 enabled: true,
218 },
219 updatedAt: "2026-06-01T00:00:00.000Z",
220 },
221 ]);
222 }).pipe(
223 Effect.provide(Devices.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)))),
224 );
225 });
226​
227 it.effect("identifies the failed device registration stage", () => {
228 const cause = new Error("push-token claim failed");
229 const fakeDb = {
230 update: () => ({
231 set: (values: Record<string, unknown>) => ({
232 where: () => ("pushToken" in values ? Effect.fail(cause) : Effect.void),
233 }),
234 }),
235 } as unknown as RelayDb.RelayDb["Service"];
236​
237 return Effect.gen(function* () {
238 const devices = yield* Devices.Devices;
239 const error = yield* devices.register({ userId: "user-2", registration }).pipe(Effect.flip);
240​
241 expect(error).toMatchObject({
242 userId: "user-2",
243 deviceId: "device-1",
244 stage: "claim-push-token",
245 });
246 expect(error.cause).toBe(cause);
247 expect(error.message).toBe(
248 "Failed to persist mobile device registration for user-2/device-1 during claim-push-token.",
249 );
250 }).pipe(
251 Effect.provide(Devices.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)))),
252 );
253 });
254​
255 it.effect("identifies the failed device unregistration stage", () => {
256 const cause = new Error("live activity delete failed");
257 const fakeDb = {
258 delete: (table: unknown) => ({
259 where: () => (table === relayLiveActivities ? Effect.fail(cause) : Effect.void),
260 }),
261 } as unknown as RelayDb.RelayDb["Service"];
262​
263 return Effect.gen(function* () {
264 const devices = yield* Devices.Devices;
265 const error = yield* devices
266 .unregister({ userId: "user-2", deviceId: "device-1" })
267 .pipe(Effect.flip);
268​
269 expect(error).toMatchObject({
270 userId: "user-2",
271 deviceId: "device-1",
272 stage: "delete-live-activity",
273 });
274 expect(error.cause).toBe(cause);
275 expect(error.message).toBe(
276 "Failed to unregister mobile device user-2/device-1 during delete-live-activity.",
277 );
278 }).pipe(
279 Effect.provide(Devices.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)))),
280 );
281 });
282​
283 it.effect("attaches the user to device list failures", () => {
284 const cause = new Error("device list failed");
285 const fakeDb = {
286 select: () => ({
287 from: () => ({
288 where: () => Effect.fail(cause),
289 }),
290 }),
291 } as unknown as RelayDb.RelayDb["Service"];
292​
293 return Effect.gen(function* () {
294 const devices = yield* Devices.Devices;
295 const error = yield* devices.listForUser({ userId: "user-2" }).pipe(Effect.flip);
296​
297 expect(error).toMatchObject({ userId: "user-2" });
298 expect(error.cause).toBe(cause);
299 expect(error.message).toBe("Failed to list mobile devices for user-2.");
300 }).pipe(
301 Effect.provide(Devices.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)))),
302 );
303 });
304});