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

ApnsClient.ts

359 lines12.1 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 environmentId: input.notification.environmentId,
190 threadId: input.notification.threadId,
191 deepLink: input.notification.deepLink,
192 },
193 };
195​
196function apnsReasonFromBody(body: string): string | undefined {
197 if (body.trim().length === 0) {
198 return undefined;
199 }
200 return Option.match(decodeApnsErrorResponseJson(body), {
201 onNone: () => body,
202 onSome: (parsed) => parsed.reason ?? body,
203 });
205​
206export class ApnsClient extends Context.Service<
207 ApnsClient,
208 {
209 readonly makeLiveActivityRequest: typeof makeLiveActivityRequest;
210 readonly makePushNotificationRequest: typeof makePushNotificationRequest;
211 readonly sendLiveActivityRequest: (input: {
212 readonly credentials: ApnsCredentials;
213 readonly request: ApnsLiveActivityRequest;
214 readonly issuedAtUnixSeconds: number;
215 }) => Effect.Effect<ApnsDeliveryResult, ApnsError>;
216 readonly sendPushNotificationRequest: (input: {
217 readonly credentials: ApnsCredentials;
218 readonly request: ApnsPushNotificationRequest;
219 readonly issuedAtUnixSeconds: number;
220 }) => Effect.Effect<ApnsDeliveryResult, ApnsError>;
221 }
222>()("t3code-relay/agentActivity/ApnsClient") {}
223​
224export const make = Effect.gen(function* () {
225 const httpClient = yield* HttpClient.HttpClient;
226 const providerTokens = yield* ApnsProviderTokens.ApnsProviderTokens;
227​
228 const sendLiveActivityRequest: ApnsClient["Service"]["sendLiveActivityRequest"] = Effect.fn(
229 "relay.apns.send_live_activity_request",
230 )(function* (input) {
231 yield* Effect.annotateCurrentSpan({ "relay.apns.event": input.request.event });
232 const jwt = yield* providerTokens.getJwt({
233 ...input.credentials,
234 issuedAtUnixSeconds: input.issuedAtUnixSeconds,
235 });
236 const host =
237 input.credentials.environment === "production"
238 ? "https://api.push.apple.com"
239 : "https://api.sandbox.push.apple.com";
240 const response = yield* HttpClientRequest.post(`${host}/3/device/${input.request.token}`).pipe(
241 HttpClientRequest.setHeaders({
242 authorization: `bearer ${jwt}`,
243 "apns-priority": input.request.priority,
244 "apns-push-type": "liveactivity",
245 "apns-topic": `${input.credentials.bundleId}.push-type.liveactivity`,
246 }),
247 HttpClientRequest.bodyJson(input.request.payload),
248 Effect.flatMap(httpClient.execute),
249 Effect.timeout(APNS_HTTP_STAGE_TIMEOUT),
250 Effect.mapError(
251 (cause) =>
252 new ApnsHttpRequestError({
253 requestKind: "live-activity",
254 event: input.request.event,
255 environment: input.credentials.environment,
256 bundleId: input.credentials.bundleId,
257 tokenSuffix: input.request.token.slice(-8),
258 stage: "send",
259 status: null,
260 cause,
261 }),
262 ),
263 );
264 const responseText = yield* response.text.pipe(
265 Effect.timeout(APNS_HTTP_STAGE_TIMEOUT),
266 Effect.mapError(
267 (cause) =>
268 new ApnsHttpRequestError({
269 requestKind: "live-activity",
270 event: input.request.event,
271 environment: input.credentials.environment,
272 bundleId: input.credentials.bundleId,
273 tokenSuffix: input.request.token.slice(-8),
274 stage: "read-response",
275 status: response.status,
276 cause,
277 }),
278 ),
279 );
280 const reason = apnsReasonFromBody(responseText);
281 return {
282 ok: response.status >= 200 && response.status < 300,
283 status: response.status,
284 ...(reason === undefined ? {} : { reason }),
285 apnsId: Option.getOrNull(Headers.get(response.headers, "apns-id")),
286 };
287 });
288​
289 const sendPushNotificationRequest: ApnsClient["Service"]["sendPushNotificationRequest"] =
290 Effect.fn("relay.apns.send_push_notification_request")(function* (input) {
291 yield* Effect.annotateCurrentSpan({ "relay.apns.event": "push_notification" });
292 const jwt = yield* providerTokens.getJwt({
293 ...input.credentials,
294 issuedAtUnixSeconds: input.issuedAtUnixSeconds,
295 });
296 const host =
297 input.credentials.environment === "production"
298 ? "https://api.push.apple.com"
299 : "https://api.sandbox.push.apple.com";
300 const response = yield* HttpClientRequest.post(
301 `${host}/3/device/${input.request.token}`,
302 ).pipe(
303 HttpClientRequest.setHeaders({
304 authorization: `bearer ${jwt}`,
305 "apns-priority": input.request.priority,
306 "apns-push-type": "alert",
307 "apns-topic": input.credentials.bundleId,
308 }),
309 HttpClientRequest.bodyJson(input.request.payload),
310 Effect.flatMap(httpClient.execute),
311 Effect.timeout(APNS_HTTP_STAGE_TIMEOUT),
312 Effect.mapError(
313 (cause) =>
314 new ApnsHttpRequestError({
315 requestKind: "push-notification",
316 event: null,
317 environment: input.credentials.environment,
318 bundleId: input.credentials.bundleId,
319 tokenSuffix: input.request.token.slice(-8),
320 stage: "send",
321 status: null,
322 cause,
323 }),
324 ),
325 );
326 const responseText = yield* response.text.pipe(
327 Effect.timeout(APNS_HTTP_STAGE_TIMEOUT),
328 Effect.mapError(
329 (cause) =>
330 new ApnsHttpRequestError({
331 requestKind: "push-notification",
332 event: null,
333 environment: input.credentials.environment,
334 bundleId: input.credentials.bundleId,
335 tokenSuffix: input.request.token.slice(-8),
336 stage: "read-response",
337 status: response.status,
338 cause,
339 }),
340 ),
341 );
342 const reason = apnsReasonFromBody(responseText);
343 return {
344 ok: response.status >= 200 && response.status < 300,
345 status: response.status,
346 ...(reason === undefined ? {} : { reason }),
347 apnsId: Option.getOrNull(Headers.get(response.headers, "apns-id")),
348 };
349 });
350​
351 return ApnsClient.of({
352 makeLiveActivityRequest,
353 makePushNotificationRequest,
354 sendLiveActivityRequest,
355 sendPushNotificationRequest,
356 });
357});
358​
359export const layer = Layer.effect(ApnsClient, make);