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

ApnsClient.ts

362 lines12.2 KB

1import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Schema from "effect/Schema";
7import * as Headers from "effect/http/Headers";
8import * as HttpClient from "effect/http/HttpClient";
9import * as HttpClientRequest from "effect/http/HttpClientRequest";
10import { ApnsEnvironment, type ApnsCredentials } from "../Config.ts";
11import type { ApnsLiveActivityAlert, ApnsNotificationPayload } from "./apnsDeliveryJobs.ts";
12import type { ApnsJwtEncodingError, ApnsJwtSigningError } from "./apnsJwt.ts";
13import * as ApnsProviderTokens from "./ApnsProviderTokens.ts";
14​
15export { ApnsJwtEncodingError, ApnsJwtSigningError } from "./apnsJwt.ts";
16​
17const LIVE_ACTIVITY_NAME = "AgentActivity";
18// Bound sending and reading separately so neither stage can hold a batch open.
19const APNS_HTTP_STAGE_TIMEOUT = "10 seconds";
20// Updates only flow on domain events, so a healthy agent can be silent for
21// minutes (long tool calls, pending approvals).
22const STALE_AFTER_SECONDS = 10 * 60;
23const DISMISS_AFTER_SECONDS = 5 * 60;
24// An end without a final content-state leaves whatever the card last showed
25// frozen on the lock screen until dismissal — get it off quickly instead of
26// parading stale state for the full window.
27const CONTENTLESS_DISMISS_AFTER_SECONDS = 15;
28​
29const ApnsLiveActivityEventSchema = Schema.Literals(["start", "update", "end"]);
30export type ApnsLiveActivityEvent = typeof ApnsLiveActivityEventSchema.Type;
31​
32const ApnsRequestKindSchema = Schema.Literals(["live-activity", "push-notification"]);
33​
34interface ApnsLiveActivityRequest {
35 readonly token: string;
36 readonly event: ApnsLiveActivityEvent;
37 readonly priority: "5" | "10";
38 readonly payload: unknown;
40​
41interface ApnsPushNotificationRequest {
42 readonly token: string;
43 readonly priority: "10";
44 readonly payload: unknown;
46​
47export interface ApnsDeliveryResult {
48 readonly ok: boolean;
49 readonly status: number;
50 readonly reason?: string;
51 readonly apnsId: string | null;
53​
54export class ApnsHttpRequestError extends Schema.TaggedError<ApnsHttpRequestError>()(
55 "ApnsHttpRequestError",
56 {
57 requestKind: ApnsRequestKindSchema,
58 event: Schema.NullOr(ApnsLiveActivityEventSchema),
59 environment: ApnsEnvironment,
60 bundleId: Schema.String,
61 tokenSuffix: Schema.String,
62 stage: Schema.Literals(["send", "read-response"]),
63 status: Schema.NullOr(Schema.Number),
64 cause: Schema.Defect(),
65 },
66) {
67 override get message(): string {
68 return `APNs ${this.requestKind} request failed during ${this.stage} in ${this.environment}.`;
69 }
71​
72export type ApnsError = ApnsJwtEncodingError | ApnsJwtSigningError | ApnsHttpRequestError;
73​
74const decodeApnsErrorResponseJson = Schema.decodeUnknownOption(
75 Schema.fromJsonString(
76 Schema.Struct({
77 reason: Schema.optional(Schema.String),
78 }),
79 ),
80);
81function contentState(state: RelayAgentActivityAggregateState) {
82 return {
83 name: LIVE_ACTIVITY_NAME,
84 props: JSON.stringify(state),
85 };
87​
88interface LiveActivityRequestBase {
89 readonly token: string;
90 readonly nowEpochSeconds: number;
91 readonly nowIso: string;
93​
94type MakeLiveActivityRequestInput =
95 | (LiveActivityRequestBase & {
96 readonly event: "end";
97 readonly state: RelayAgentActivityAggregateState | null;
98 readonly alert?: ApnsLiveActivityAlert | null;
99 })
100 | (LiveActivityRequestBase & {
101 readonly event: "start" | "update";
102 readonly state: RelayAgentActivityAggregateState;
103 readonly alert?: ApnsLiveActivityAlert | null;
104 });
105​
106// An alert dict on an update/end makes it an "alerting" update: iOS wakes the
107// screen and plays the haptic (the Apple Sports score-change behavior) instead
108// of silently redrawing the activity.
109function liveActivityAlertPayload(alert: ApnsLiveActivityAlert) {
110 return {
111 alert: {
112 title: alert.title,
113 body: alert.body,
114 sound: "default",
115 },
116 };
118​
119function makeLiveActivityRequest(input: MakeLiveActivityRequestInput): ApnsLiveActivityRequest {
120 const timestamp = input.nowEpochSeconds;
121 if (input.event === "end") {
122 return {
123 token: input.token,
124 event: input.event,
125 priority: "10",
126 payload: {
127 aps: {
128 timestamp,
129 event: "end",
130 ...(input.state ? { "content-state": contentState(input.state) } : {}),
131 ...(input.alert ? liveActivityAlertPayload(input.alert) : {}),
132 "dismissal-date":
133 timestamp + (input.state ? DISMISS_AFTER_SECONDS : CONTENTLESS_DISMISS_AFTER_SECONDS),
134 },
135 },
136 };
137 }
138​
139 const state = input.state;
140 return {
141 token: input.token,
142 event: input.event,
143 priority: input.event === "update" && !input.alert ? "5" : "10",
144 payload: {
145 aps: {
146 timestamp,
147 event: input.event,
148 ...(input.event === "start"
149 ? {
150 "attributes-type": "LiveActivityAttributes",
151 attributes: {},
152 "input-push-token": 1,
153 alert: {
154 title: state.title,
155 body: state.subtitle,
156 },
157 }
158 : {}),
159 ...(input.event === "update" && input.alert ? liveActivityAlertPayload(input.alert) : {}),
160 "content-state": contentState(state),
161 "stale-date": timestamp + STALE_AFTER_SECONDS,
162 },
163 },
164 };
166​
167function notificationThreadId(notification: ApnsNotificationPayload): string {
168 return notification.threadId.length > 0
169 ? `${notification.environmentId}/${notification.threadId}`
170 : "t3-agent-alerts";
172​
173function makePushNotificationRequest(input: {
174 readonly token: string;
175 readonly notification: ApnsNotificationPayload;
176}): ApnsPushNotificationRequest {
177 return {
178 token: input.token,
179 priority: "10",
180 payload: {
181 aps: {
182 alert: {
183 title: input.notification.title,
184 body: input.notification.body,
185 },
186 sound: "default",
187 "thread-id": notificationThreadId(input.notification),
188 },
189 // Expo iOS exposes userInfo.body as notification.content.data for remote pushes.
190 body: {
191 environmentId: input.notification.environmentId,
192 threadId: input.notification.threadId,
193 deepLink: input.notification.deepLink,
194 },
195 },
196 };
198​
199function apnsReasonFromBody(body: string): string | undefined {
200 if (body.trim().length === 0) {
201 return undefined;
202 }
203 return Option.match(decodeApnsErrorResponseJson(body), {
204 onNone: () => body,
205 onSome: (parsed) => parsed.reason ?? body,
206 });
208​
209export class ApnsClient extends Context.Service<
210 ApnsClient,
211 {
212 readonly makeLiveActivityRequest: typeof makeLiveActivityRequest;
213 readonly makePushNotificationRequest: typeof makePushNotificationRequest;
214 readonly sendLiveActivityRequest: (input: {
215 readonly credentials: ApnsCredentials;
216 readonly request: ApnsLiveActivityRequest;
217 readonly issuedAtUnixSeconds: number;
218 }) => Effect.Effect<ApnsDeliveryResult, ApnsError>;
219 readonly sendPushNotificationRequest: (input: {
220 readonly credentials: ApnsCredentials;
221 readonly request: ApnsPushNotificationRequest;
222 readonly issuedAtUnixSeconds: number;
223 }) => Effect.Effect<ApnsDeliveryResult, ApnsError>;
224 }
225>()("t3code-relay/agentActivity/ApnsClient") {}
226​
227export const make = Effect.gen(function* () {
228 const httpClient = yield* HttpClient.HttpClient;
229 const providerTokens = yield* ApnsProviderTokens.ApnsProviderTokens;
230​
231 const sendLiveActivityRequest: ApnsClient["Service"]["sendLiveActivityRequest"] = Effect.fn(
232 "relay.apns.send_live_activity_request",
233 )(function* (input) {
234 yield* Effect.annotateCurrentSpan({ "relay.apns.event": input.request.event });
235 const jwt = yield* providerTokens.getJwt({
236 ...input.credentials,
237 issuedAtUnixSeconds: input.issuedAtUnixSeconds,
238 });
239 const host =
240 input.credentials.environment === "production"
241 ? "https://api.push.apple.com"
242 : "https://api.sandbox.push.apple.com";
243 const response = yield* HttpClientRequest.post(`${host}/3/device/${input.request.token}`).pipe(
244 HttpClientRequest.setHeaders({
245 authorization: `bearer ${jwt}`,
246 "apns-priority": input.request.priority,
247 "apns-push-type": "liveactivity",
248 "apns-topic": `${input.credentials.bundleId}.push-type.liveactivity`,
249 }),
250 HttpClientRequest.bodyJson(input.request.payload),
251 Effect.flatMap(httpClient.execute),
252 Effect.timeout(APNS_HTTP_STAGE_TIMEOUT),
253 Effect.mapError(
254 (cause) =>
255 new ApnsHttpRequestError({
256 requestKind: "live-activity",
257 event: input.request.event,
258 environment: input.credentials.environment,
259 bundleId: input.credentials.bundleId,
260 tokenSuffix: input.request.token.slice(-8),
261 stage: "send",
262 status: null,
263 cause,
264 }),
265 ),
266 );
267 const responseText = yield* response.text.pipe(
268 Effect.timeout(APNS_HTTP_STAGE_TIMEOUT),
269 Effect.mapError(
270 (cause) =>
271 new ApnsHttpRequestError({
272 requestKind: "live-activity",
273 event: input.request.event,
274 environment: input.credentials.environment,
275 bundleId: input.credentials.bundleId,
276 tokenSuffix: input.request.token.slice(-8),
277 stage: "read-response",
278 status: response.status,
279 cause,
280 }),
281 ),
282 );
283 const reason = apnsReasonFromBody(responseText);
284 return {
285 ok: response.status >= 200 && response.status < 300,
286 status: response.status,
287 ...(reason === undefined ? {} : { reason }),
288 apnsId: Option.getOrNull(Headers.get(response.headers, "apns-id")),
289 };
290 });
291​
292 const sendPushNotificationRequest: ApnsClient["Service"]["sendPushNotificationRequest"] =
293 Effect.fn("relay.apns.send_push_notification_request")(function* (input) {
294 yield* Effect.annotateCurrentSpan({ "relay.apns.event": "push_notification" });
295 const jwt = yield* providerTokens.getJwt({
296 ...input.credentials,
297 issuedAtUnixSeconds: input.issuedAtUnixSeconds,
298 });
299 const host =
300 input.credentials.environment === "production"
301 ? "https://api.push.apple.com"
302 : "https://api.sandbox.push.apple.com";
303 const response = yield* HttpClientRequest.post(
304 `${host}/3/device/${input.request.token}`,
305 ).pipe(
306 HttpClientRequest.setHeaders({
307 authorization: `bearer ${jwt}`,
308 "apns-priority": input.request.priority,
309 "apns-push-type": "alert",
310 "apns-topic": input.credentials.bundleId,
311 }),
312 HttpClientRequest.bodyJson(input.request.payload),
313 Effect.flatMap(httpClient.execute),
314 Effect.timeout(APNS_HTTP_STAGE_TIMEOUT),
315 Effect.mapError(
316 (cause) =>
317 new ApnsHttpRequestError({
318 requestKind: "push-notification",
319 event: null,
320 environment: input.credentials.environment,
321 bundleId: input.credentials.bundleId,
322 tokenSuffix: input.request.token.slice(-8),
323 stage: "send",
324 status: null,
325 cause,
326 }),
327 ),
328 );
329 const responseText = yield* response.text.pipe(
330 Effect.timeout(APNS_HTTP_STAGE_TIMEOUT),
331 Effect.mapError(
332 (cause) =>
333 new ApnsHttpRequestError({
334 requestKind: "push-notification",
335 event: null,
336 environment: input.credentials.environment,
337 bundleId: input.credentials.bundleId,
338 tokenSuffix: input.request.token.slice(-8),
339 stage: "read-response",
340 status: response.status,
341 cause,
342 }),
343 ),
344 );
345 const reason = apnsReasonFromBody(responseText);
346 return {
347 ok: response.status >= 200 && response.status < 300,
348 status: response.status,
349 ...(reason === undefined ? {} : { reason }),
350 apnsId: Option.getOrNull(Headers.get(response.headers, "apns-id")),
351 };
352 });
353​
354 return ApnsClient.of({
355 makeLiveActivityRequest,
356 makePushNotificationRequest,
357 sendLiveActivityRequest,
358 sendPushNotificationRequest,
359 });
360});
361​
362export const layer = Layer.effect(ApnsClient, make);