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

ApnsClient.test.ts

440 lines14.7 KB

1// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync.
2import * as NodeCrypto from "node:crypto";
3​
4import { EnvironmentId, ThreadId } from "@t3tools/contracts";
5import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";
6import { describe, expect, it } from "@effect/vitest";
7import * as DateTime from "effect/DateTime";
8import * as Deferred from "effect/Deferred";
9import * as Effect from "effect/Effect";
10import * as Fiber from "effect/Fiber";
11import * as Layer from "effect/Layer";
12import * as Redacted from "effect/Redacted";
13import * as Schema from "effect/Schema";
14import * as TestClock from "effect/testing/TestClock";
15import * as HttpClient from "effect/http/HttpClient";
16import * as HttpClientError from "effect/http/HttpClientError";
17import * as HttpClientResponse from "effect/http/HttpClientResponse";
18​
19import type { ApnsCredentials } from "../Config.ts";
20import * as ApnsClient from "./ApnsClient.ts";
21import * as ApnsProviderTokens from "./ApnsProviderTokens.ts";
22​
23const isApnsJwtSigningError = Schema.is(ApnsClient.ApnsJwtSigningError);
24const isApnsHttpRequestError = Schema.is(ApnsClient.ApnsHttpRequestError);
25​
26const layerTest = ApnsClient.layer.pipe(
27 Layer.provide(ApnsProviderTokens.layer),
28 Layer.provide(
29 Layer.succeed(
30 HttpClient.HttpClient,
31 HttpClient.make(() => Effect.die("unexpected APNs HTTP request")),
32 ),
33 ),
34);
35​
36describe("ApnsClient", () => {
37 const now = DateTime.makeUnsafe(0);
38 const state: RelayAgentActivityAggregateState = {
39 title: "T3 Code",
40 subtitle: "Agent work in progress",
41 activeCount: 1,
42 updatedAt: DateTime.formatIso(now),
43 activities: [
44 {
45 environmentId: EnvironmentId.make("env"),
46 threadId: ThreadId.make("thread"),
47 projectTitle: "Project",
48 threadTitle: "Thread",
49 modelTitle: "gpt-5.4",
50 phase: "running" as const,
51 status: "Working",
52 updatedAt: DateTime.formatIso(now),
53 deepLink: "/",
54 },
55 ],
56 };
57​
58 it.effect("requests an update push token when remotely starting a Live Activity", () =>
59 Effect.gen(function* () {
60 const apns = yield* ApnsClient.ApnsClient;
61 const request = apns.makeLiveActivityRequest({
62 event: "start",
63 token: "token",
64 state,
65 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
66 nowIso: DateTime.formatIso(now),
67 });
68​
69 expect(request.priority).toBe("10");
70 expect(request.payload).toMatchObject({
71 aps: {
72 event: "start",
73 "attributes-type": "LiveActivityAttributes",
74 "input-push-token": 1,
75 "content-state": {
76 name: "AgentActivity",
77 },
78 },
79 });
80 }).pipe(Effect.provide(layerTest)),
81 );
82​
83 it.effect("builds a low-priority update payload", () =>
84 Effect.gen(function* () {
85 const apns = yield* ApnsClient.ApnsClient;
86 const request = apns.makeLiveActivityRequest({
87 event: "update",
88 token: "token",
89 state,
90 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
91 nowIso: DateTime.formatIso(now),
92 });
93​
94 expect(request.priority).toBe("5");
95 expect(request.payload).toMatchObject({
96 aps: {
97 event: "update",
98 "content-state": {
99 name: "AgentActivity",
100 },
101 },
102 });
103 }).pipe(Effect.provide(layerTest)),
104 );
105​
106 it.effect("builds a high-priority alerting update payload when an alert is attached", () =>
107 Effect.gen(function* () {
108 const apns = yield* ApnsClient.ApnsClient;
109 const request = apns.makeLiveActivityRequest({
110 event: "update",
111 token: "token",
112 state,
113 alert: { title: "Thread", body: "Approval: Project" },
114 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
115 nowIso: DateTime.formatIso(now),
116 });
117​
118 expect(request.priority).toBe("10");
119 expect(request.payload).toMatchObject({
120 aps: {
121 event: "update",
122 alert: {
123 title: "Thread",
124 body: "Approval: Project",
125 sound: "default",
126 },
127 },
128 });
129 }).pipe(Effect.provide(layerTest)),
130 );
131​
132 it.effect("builds an end payload with a dismissal date", () =>
133 Effect.gen(function* () {
134 const apns = yield* ApnsClient.ApnsClient;
135 const request = apns.makeLiveActivityRequest({
136 event: "end",
137 token: "token",
138 state,
139 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
140 nowIso: DateTime.formatIso(now),
141 });
142​
143 expect(request.priority).toBe("10");
144 expect(request.payload).toMatchObject({
145 aps: {
146 event: "end",
147 "dismissal-date": 300,
148 },
149 });
150​
151 const contentless = apns.makeLiveActivityRequest({
152 event: "end",
153 token: "token",
154 state: null,
155 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
156 nowIso: DateTime.formatIso(now),
157 });
158 expect(contentless.payload).toMatchObject({
159 aps: {
160 event: "end",
161 "dismissal-date": 15,
162 },
163 });
164 }).pipe(Effect.provide(layerTest)),
165 );
166​
167 it.effect("builds a standard APNs alert payload with routing metadata", () =>
168 Effect.gen(function* () {
169 const apns = yield* ApnsClient.ApnsClient;
170 const request = apns.makePushNotificationRequest({
171 token: "push-token",
172 notification: {
173 title: "Thread",
174 body: "Input: Project",
175 environmentId: "env",
176 threadId: "thread",
177 deepLink: "/threads/env/thread",
178 },
179 });
180​
181 expect(request.priority).toBe("10");
182 expect(request.payload).toMatchObject({
183 aps: {
184 alert: {
185 title: "Thread",
186 body: "Input: Project",
187 },
188 sound: "default",
189 "thread-id": "env/thread",
190 },
191 environmentId: "env",
192 threadId: "thread",
193 deepLink: "/threads/env/thread",
194 });
195 }).pipe(Effect.provide(layerTest)),
196 );
197​
198 it.effect("preserves JWT signing context and the crypto cause", () =>
199 Effect.gen(function* () {
200 const apns = yield* ApnsClient.ApnsClient;
201 const request = apns.makePushNotificationRequest({
202 token: "push-token",
203 notification: {
204 title: "Thread",
205 body: "Input: Project",
206 environmentId: "env",
207 threadId: "thread",
208 deepLink: "/threads/env/thread",
209 },
210 });
211 const error = yield* Effect.flip(
212 apns.sendPushNotificationRequest({
213 credentials: {
214 teamId: "team-1",
215 keyId: "key-1",
216 privateKey: Redacted.make("not-a-private-key"),
217 bundleId: "com.t3tools.test",
218 environment: "sandbox",
219 },
220 request,
221 issuedAtUnixSeconds: 123,
222 }),
223 );
224​
225 expect(isApnsJwtSigningError(error)).toBe(true);
226 if (!isApnsJwtSigningError(error)) {
227 return yield* Effect.die("expected APNs JWT signing error");
228 }
229 expect(error).toMatchObject({
230 teamId: "team-1",
231 keyId: "key-1",
232 issuedAtUnixSeconds: 0,
233 cause: expect.any(Error),
234 message: "Failed to sign APNs JWT for key key-1.",
235 });
236 }).pipe(Effect.provide(layerTest)),
237 );
238​
239 it.effect("preserves APNs request context and the HTTP cause", () => {
240 const httpCause = new Error("network unavailable");
241 const { privateKey } = NodeCrypto.generateKeyPairSync("ec", {
242 namedCurve: "prime256v1",
243 privateKeyEncoding: { type: "pkcs8", format: "pem" },
244 publicKeyEncoding: { type: "spki", format: "pem" },
245 });
246 const credentials = {
247 teamId: "team-1",
248 keyId: "key-1",
249 privateKey: Redacted.make(privateKey),
250 bundleId: "com.t3tools.test",
251 environment: "sandbox",
252 } satisfies ApnsCredentials;
253 const failingHttpClient = HttpClient.make((request) =>
254 Effect.fail(
255 new HttpClientError.HttpClientError({
256 reason: new HttpClientError.TransportError({ request, cause: httpCause }),
257 }),
258 ),
259 );
260 const layer = ApnsClient.layer.pipe(
261 Layer.provide(ApnsProviderTokens.layer),
262 Layer.provide(Layer.succeed(HttpClient.HttpClient, failingHttpClient)),
263 );
264​
265 return Effect.gen(function* () {
266 const apns = yield* ApnsClient.ApnsClient;
267 const request = apns.makePushNotificationRequest({
268 token: "long-push-token",
269 notification: {
270 title: "Thread",
271 body: "Input: Project",
272 environmentId: "env",
273 threadId: "thread",
274 deepLink: "/threads/env/thread",
275 },
276 });
277 const error = yield* Effect.flip(
278 apns.sendPushNotificationRequest({
279 credentials,
280 request,
281 issuedAtUnixSeconds: 123,
282 }),
283 );
284​
285 expect(isApnsHttpRequestError(error)).toBe(true);
286 if (!isApnsHttpRequestError(error)) {
287 return yield* Effect.die("expected APNs HTTP request error");
288 }
289 expect(error).toMatchObject({
290 requestKind: "push-notification",
291 event: null,
292 environment: "sandbox",
293 bundleId: "com.t3tools.test",
294 tokenSuffix: "sh-token",
295 stage: "send",
296 status: null,
297 message: "APNs push-notification request failed during send in sandbox.",
298 });
299 expect(error.cause).toBeInstanceOf(HttpClientError.HttpClientError);
300 expect((error.cause as HttpClientError.HttpClientError).reason).toMatchObject({
301 _tag: "TransportError",
302 cause: httpCause,
303 });
304 }).pipe(Effect.provide(layer));
305 });
306​
307 it.effect("reuses the signed provider JWT across pushes within the reuse window", () => {
308 ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();
309 const { privateKey } = NodeCrypto.generateKeyPairSync("ec", {
310 namedCurve: "prime256v1",
311 privateKeyEncoding: { type: "pkcs8", format: "pem" },
312 publicKeyEncoding: { type: "spki", format: "pem" },
313 });
314 const credentials = {
315 teamId: "team-jwt-cache",
316 keyId: "key-jwt-cache",
317 privateKey: Redacted.make(privateKey),
318 bundleId: "com.t3tools.test",
319 environment: "sandbox",
320 } satisfies ApnsCredentials;
321 const authorizations: Array<string> = [];
322 const capturingHttpClient = HttpClient.make((request) => {
323 authorizations.push(request.headers.authorization ?? "");
324 return Effect.succeed(
325 HttpClientResponse.fromWeb(
326 request,
327 new Response("", { status: 200, headers: { "apns-id": "apns-id-1" } }),
328 ),
329 );
330 });
331 const layer = ApnsClient.layer.pipe(
332 Layer.provide(ApnsProviderTokens.layer),
333 Layer.provide(Layer.succeed(HttpClient.HttpClient, capturingHttpClient)),
334 );
335​
336 return Effect.gen(function* () {
337 const apns = yield* ApnsClient.ApnsClient;
338 const request = apns.makePushNotificationRequest({
339 token: "push-token",
340 notification: {
341 title: "Thread",
342 body: "Input: Project",
343 environmentId: "env",
344 threadId: "thread",
345 deepLink: "/threads/env/thread",
346 },
347 });
348 const send = (issuedAtUnixSeconds: number) =>
349 apns.sendPushNotificationRequest({ credentials, request, issuedAtUnixSeconds });
350​
351 const window = ApnsProviderTokens.APNS_JWT_REUSE_SECONDS;
352 yield* send(window + 10);
353 yield* send(window * 2 - 1);
354 yield* send(window * 2);
355​
356 expect(authorizations).toHaveLength(3);
357 // Within the 45-minute window APNs must see the byte-identical token;
358 // refreshing it per push trips TooManyProviderTokenUpdates.
359 expect(authorizations[1]).toBe(authorizations[0]);
360 expect(authorizations[2]).not.toBe(authorizations[0]);
361 ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();
362 }).pipe(Effect.provide(layer));
363 });
364​
365 it.effect.each(
366 (["live-activity", "push-notification"] as const).flatMap((requestKind) =>
367 (["send", "read-response"] as const).map((stage) => ({ requestKind, stage })),
368 ),
369 )("aborts a stalled $requestKind $stage after ten seconds", ({ requestKind, stage }) =>
370 Effect.gen(function* () {
371 const started = yield* Deferred.make<void>();
372 const signals: AbortSignal[] = [];
373 const stalledHttpClient = HttpClient.make((request, _url, signal) => {
374 signals.push(signal);
375 const stall = Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never));
376 if (stage === "send") return stall;
377 const response = HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
378 Object.defineProperty(response, "text", { value: stall });
379 return Effect.succeed(response);
380 });
381 const layer = ApnsClient.layer.pipe(
382 Layer.provide(Layer.succeed(HttpClient.HttpClient, stalledHttpClient)),
383 Layer.provide(
384 Layer.succeed(ApnsProviderTokens.ApnsProviderTokens, {
385 getJwt: () => Effect.succeed("test-jwt"),
386 }),
387 ),
388 );
389 const apns = yield* ApnsClient.ApnsClient.pipe(Effect.provide(layer));
390 const credentials = {
391 teamId: "team-timeout",
392 keyId: "key-timeout",
393 privateKey: Redacted.make("unused-test-key"),
394 bundleId: "com.t3tools.test",
395 environment: "sandbox",
396 } satisfies ApnsCredentials;
397 const send =
398 requestKind === "live-activity"
399 ? apns.sendLiveActivityRequest({
400 credentials,
401 issuedAtUnixSeconds: 123,
402 request: apns.makeLiveActivityRequest({
403 event: "update",
404 token: "long-push-token",
405 state,
406 nowEpochSeconds: 123,
407 nowIso: DateTime.formatIso(now),
408 }),
409 })
410 : apns.sendPushNotificationRequest({
411 credentials,
412 issuedAtUnixSeconds: 123,
413 request: apns.makePushNotificationRequest({
414 token: "long-push-token",
415 notification: {
416 title: "Thread",
417 body: "Done",
418 environmentId: "env",
419 threadId: "thread",
420 deepLink: "/",
421 },
422 }),
423 });
424 const fiber = yield* send.pipe(Effect.flip, Effect.forkChild);
425 yield* Deferred.await(started);
426 yield* TestClock.adjust("10 seconds");
427 expect(signals[0]?.aborted).toBe(true);
428 const error = yield* Fiber.join(fiber);
429 expect(error).toMatchObject({
430 _tag: "ApnsHttpRequestError",
431 requestKind,
432 event: requestKind === "live-activity" ? "update" : null,
433 stage,
434 status: stage === "read-response" ? 200 : null,
435 tokenSuffix: "sh-token",
436 cause: { _tag: "TimeoutError" },
437 });
438 }),
439 );
440});