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

ApnsClient.ts

355 lines11.9 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// Updates only flow on domain events, so a healthy agent can be silent for
19// minutes (long tool calls, pending approvals). Two minutes made iOS dim
20// perfectly healthy activities; ten minutes still bounds how long a dead
21// environment can look alive.
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.TaggedErrorClass<ApnsHttpRequestError>()(
55 "ApnsHttpRequestError",
56 {
57 requestKind: ApnsRequestKindSchema,
58 event: Schema.NullOr(ApnsLiveActivityEventSchema),
59 environment: ApnsEnvironmentSchema,
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 const ApnsError = Schema.Union([
73 ApnsJwtEncodingError,
74 ApnsJwtSigningError,
75 ApnsHttpRequestError,
76]);
77export type ApnsError = typeof ApnsError.Type;
78​
79const decodeApnsErrorResponseJson = Schema.decodeUnknownOption(
80 Schema.fromJsonString(
81 Schema.Struct({
82 reason: Schema.optional(Schema.String),
83 }),
84 ),
85);
86function contentState(state: RelayAgentActivityAggregateState) {
87 return {
88 name: LIVE_ACTIVITY_NAME,
89 props: JSON.stringify(state),
90 };
92​
93interface LiveActivityRequestBase {
94 readonly token: string;
95 readonly nowEpochSeconds: number;
96 readonly nowIso: string;
98​
99type MakeLiveActivityRequestInput =
100 | (LiveActivityRequestBase & {
101 readonly event: "end";
102 readonly state: RelayAgentActivityAggregateState | null;
103 readonly alert?: ApnsLiveActivityAlert | null;
104 })
105 | (LiveActivityRequestBase & {
106 readonly event: "start" | "update";
107 readonly state: RelayAgentActivityAggregateState;
108 readonly alert?: ApnsLiveActivityAlert | null;
109 });
110​
111// An alert dict on an update/end makes it an "alerting" update: iOS wakes the
112// screen and plays the haptic (the Apple Sports score-change behavior) instead
113// of silently redrawing the activity.
114function liveActivityAlertPayload(alert: ApnsLiveActivityAlert) {
115 return {
116 alert: {
117 title: alert.title,
118 body: alert.body,
119 sound: "default",
120 },
121 };
123​
124function makeLiveActivityRequest(input: MakeLiveActivityRequestInput): ApnsLiveActivityRequest {
125 const timestamp = input.nowEpochSeconds;
126 if (input.event === "end") {
127 return {
128 token: input.token,
129 event: input.event,
130 priority: "10",
131 payload: {
132 aps: {
133 timestamp,
134 event: "end",
135 ...(input.state ? { "content-state": contentState(input.state) } : {}),
136 ...(input.alert ? liveActivityAlertPayload(input.alert) : {}),
137 "dismissal-date":
138 timestamp + (input.state ? DISMISS_AFTER_SECONDS : CONTENTLESS_DISMISS_AFTER_SECONDS),
139 },
140 },
141 };
142 }
143​
144 const state = input.state;
145 return {
146 token: input.token,
147 event: input.event,
148 // Alerting updates must land immediately; routine redraws stay at the
149 // budget-friendly low priority.
150 priority: input.event === "update" && !input.alert ? "5" : "10",
151 payload: {
152 aps: {
153 timestamp,
154 event: input.event,
155 ...(input.event === "start"
156 ? {
157 "attributes-type": "LiveActivityAttributes",
158 attributes: {},
159 "input-push-token": 1,
160 alert: {
161 title: state.title,
162 body: state.subtitle,
163 },
164 }
165 : {}),
166 ...(input.event === "update" && input.alert ? liveActivityAlertPayload(input.alert) : {}),
167 "content-state": contentState(state),
168 "stale-date": timestamp + STALE_AFTER_SECONDS,
169 },
170 },
171 };
173​
174function makePushNotificationRequest(input: {
175 readonly token: string;
176 readonly notification: ApnsNotificationPayload;
177}): ApnsPushNotificationRequest {
178 return {
179 token: input.token,
180 priority: "10",
181 payload: {
182 aps: {
183 alert: {
184 title: input.notification.title,
185 body: input.notification.body,
186 },
187 sound: "default",
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.mapError(
250 (cause) =>
251 new ApnsHttpRequestError({
252 requestKind: "live-activity",
253 event: input.request.event,
254 environment: input.credentials.environment,
255 bundleId: input.credentials.bundleId,
256 tokenSuffix: input.request.token.slice(-8),
257 stage: "send",
258 status: null,
259 cause,
260 }),
261 ),
262 );
263 const responseText = yield* response.text.pipe(
264 Effect.mapError(
265 (cause) =>
266 new ApnsHttpRequestError({
267 requestKind: "live-activity",
268 event: input.request.event,
269 environment: input.credentials.environment,
270 bundleId: input.credentials.bundleId,
271 tokenSuffix: input.request.token.slice(-8),
272 stage: "read-response",
273 status: response.status,
274 cause,
275 }),
276 ),
277 );
278 const reason = apnsReasonFromBody(responseText);
279 return {
280 ok: response.status >= 200 && response.status < 300,
281 status: response.status,
282 ...(reason === undefined ? {} : { reason }),
283 apnsId: Option.getOrNull(Headers.get(response.headers, "apns-id")),
284 };
285 });
286​
287 const sendPushNotificationRequest: ApnsClient["Service"]["sendPushNotificationRequest"] =
288 Effect.fn("relay.apns.send_push_notification_request")(function* (input) {
289 yield* Effect.annotateCurrentSpan({ "relay.apns.event": "push_notification" });
290 const jwt = yield* providerTokens.getJwt({
291 ...input.credentials,
292 issuedAtUnixSeconds: input.issuedAtUnixSeconds,
293 });
294 const host =
295 input.credentials.environment === "production"
296 ? "https://api.push.apple.com"
297 : "https://api.sandbox.push.apple.com";
298 const response = yield* HttpClientRequest.post(
299 `${host}/3/device/${input.request.token}`,
300 ).pipe(
301 HttpClientRequest.setHeaders({
302 authorization: `bearer ${jwt}`,
303 "apns-priority": input.request.priority,
304 "apns-push-type": "alert",
305 "apns-topic": input.credentials.bundleId,
306 }),
307 HttpClientRequest.bodyJson(input.request.payload),
308 Effect.flatMap(httpClient.execute),
309 Effect.mapError(
310 (cause) =>
311 new ApnsHttpRequestError({
312 requestKind: "push-notification",
313 event: null,
314 environment: input.credentials.environment,
315 bundleId: input.credentials.bundleId,
316 tokenSuffix: input.request.token.slice(-8),
317 stage: "send",
318 status: null,
319 cause,
320 }),
321 ),
322 );
323 const responseText = yield* response.text.pipe(
324 Effect.mapError(
325 (cause) =>
326 new ApnsHttpRequestError({
327 requestKind: "push-notification",
328 event: null,
329 environment: input.credentials.environment,
330 bundleId: input.credentials.bundleId,
331 tokenSuffix: input.request.token.slice(-8),
332 stage: "read-response",
333 status: response.status,
334 cause,
335 }),
336 ),
337 );
338 const reason = apnsReasonFromBody(responseText);
339 return {
340 ok: response.status >= 200 && response.status < 300,
341 status: response.status,
342 ...(reason === undefined ? {} : { reason }),
343 apnsId: Option.getOrNull(Headers.get(response.headers, "apns-id")),
344 };
345 });
346​
347 return ApnsClient.of({
348 makeLiveActivityRequest,
349 makePushNotificationRequest,
350 sendLiveActivityRequest,
351 sendPushNotificationRequest,
352 });
353});
354​
355export const layer = Layer.effect(ApnsClient, make);