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

ApnsClient.ts

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