Open History to see the last commit
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// Event-only updates can leave healthy agents silent for minutes.
21const STALE_AFTER_SECONDS = 10 * 60;
22const DISMISS_AFTER_SECONDS = 5 * 60;
23// Without final content, the card freezes at stale state; dismiss it promptly.
24const CONTENTLESS_DISMISS_AFTER_SECONDS = 15;
25
26const ApnsLiveActivityEventSchema = Schema.Literals(["start", "update", "end"]);
27export type ApnsLiveActivityEvent = typeof ApnsLiveActivityEventSchema.Type;
28
29const ApnsRequestKindSchema = Schema.Literals(["live-activity", "push-notification"]);
30
31interface ApnsLiveActivityRequest {
32 readonly token: string;
33 readonly event: ApnsLiveActivityEvent;
34 readonly priority: "5" | "10";
35 readonly payload: unknown;
36}
37
38interface ApnsPushNotificationRequest {
39 readonly token: string;
40 readonly priority: "10";
41 readonly payload: unknown;
42}
43
44export interface ApnsDeliveryResult {
45 readonly ok: boolean;
46 readonly status: number;
47 readonly reason?: string;
48 readonly apnsId: string | null;
49}
50
51export class ApnsHttpRequestError extends Schema.TaggedError<ApnsHttpRequestError>()(
52 "ApnsHttpRequestError",
53 {
54 requestKind: ApnsRequestKindSchema,
55 event: Schema.NullOr(ApnsLiveActivityEventSchema),
56 environment: ApnsEnvironment,
57 bundleId: Schema.String,
58 tokenSuffix: Schema.String,
59 stage: Schema.Literals(["send", "read-response"]),
60 status: Schema.NullOr(Schema.Number),
61 cause: Schema.Defect(),
62 },
63) {
64 override get message(): string {
65 return `APNs ${this.requestKind} request failed during ${this.stage} in ${this.environment}.`;
66 }
67}
68
69export type ApnsError = ApnsJwtEncodingError | ApnsJwtSigningError | ApnsHttpRequestError;
70
71const decodeApnsErrorResponseJson = Schema.decodeUnknownOption(
72 Schema.fromJsonString(
73 Schema.Struct({
74 reason: Schema.optional(Schema.String),
75 }),
76 ),
77);
78function contentState(state: RelayAgentActivityAggregateState) {
79 return {
80 name: LIVE_ACTIVITY_NAME,
81 props: JSON.stringify(state),
82 };
83}
84
85interface LiveActivityRequestBase {
86 readonly token: string;
87 readonly nowEpochSeconds: number;
88 readonly nowIso: string;
89}
90
91type MakeLiveActivityRequestInput =
92 | (LiveActivityRequestBase & {
93 readonly event: "end";
94 readonly state: RelayAgentActivityAggregateState | null;
95 readonly alert?: ApnsLiveActivityAlert | null;
96 })
97 | (LiveActivityRequestBase & {
98 readonly event: "start" | "update";
99 readonly state: RelayAgentActivityAggregateState;
100 readonly alert?: ApnsLiveActivityAlert | null;
101 });
102
103// Alert dictionaries wake the iOS screen and trigger haptics instead of silently refreshing.
104function liveActivityAlertPayload(alert: ApnsLiveActivityAlert) {
105 return {
106 alert: {
107 title: alert.title,
108 body: alert.body,
109 sound: "default",
110 },
111 };
112}
113
114function makeLiveActivityRequest(input: MakeLiveActivityRequestInput): ApnsLiveActivityRequest {
115 const timestamp = input.nowEpochSeconds;
116 if (input.event === "end") {
117 return {
118 token: input.token,
119 event: input.event,
120 priority: "10",
121 payload: {
122 aps: {
123 timestamp,
124 event: "end",
125 ...(input.state ? { "content-state": contentState(input.state) } : {}),
126 ...(input.alert ? liveActivityAlertPayload(input.alert) : {}),
127 "dismissal-date":
128 timestamp + (input.state ? DISMISS_AFTER_SECONDS : CONTENTLESS_DISMISS_AFTER_SECONDS),
129 },
130 },
131 };
132 }
133
134 const state = input.state;
135 return {
136 token: input.token,
137 event: input.event,
138 priority: input.event === "update" && !input.alert ? "5" : "10",
139 payload: {
140 aps: {
141 timestamp,
142 event: input.event,
143 ...(input.event === "start"
144 ? {
145 "attributes-type": "LiveActivityAttributes",
146 attributes: {},
147 "input-push-token": 1,
148 alert: {
149 title: state.title,
150 body: state.subtitle,
151 },
152 }
153 : {}),
154 ...(input.event === "update" && input.alert ? liveActivityAlertPayload(input.alert) : {}),
155 "content-state": contentState(state),
156 "stale-date": timestamp + STALE_AFTER_SECONDS,
157 },
158 },
159 };
160}
161
162function notificationThreadId(notification: ApnsNotificationPayload): string {
163 return notification.threadId.length > 0
164 ? `${notification.environmentId}/${notification.threadId}`
165 : "t3-agent-alerts";
166}
167
168function makePushNotificationRequest(input: {
169 readonly token: string;
170 readonly notification: ApnsNotificationPayload;
171}): ApnsPushNotificationRequest {
172 return {
173 token: input.token,
174 priority: "10",
175 payload: {
176 aps: {
177 alert: {
178 title: input.notification.title,
179 body: input.notification.body,
180 },
181 sound: "default",
182 "thread-id": notificationThreadId(input.notification),
183 },
184 // Expo iOS exposes userInfo.body as notification.content.data for remote pushes.
185 body: {
186 environmentId: input.notification.environmentId,
187 threadId: input.notification.threadId,
188 deepLink: input.notification.deepLink,
189 },
190 },
191 };
192}
193
194function apnsReasonFromBody(body: string): string | undefined {
195 if (body.trim().length === 0) {
196 return undefined;
197 }
198 return Option.match(decodeApnsErrorResponseJson(body), {
199 onNone: () => body,
200 onSome: (parsed) => parsed.reason ?? body,
201 });
202}
203
204export class ApnsClient extends Context.Service<
205 ApnsClient,
206 {
207 readonly makeLiveActivityRequest: typeof makeLiveActivityRequest;
208 readonly makePushNotificationRequest: typeof makePushNotificationRequest;
209 readonly sendLiveActivityRequest: (input: {
210 readonly credentials: ApnsCredentials;
211 readonly request: ApnsLiveActivityRequest;
212 readonly issuedAtUnixSeconds: number;
213 }) => Effect.Effect<ApnsDeliveryResult, ApnsError>;
214 readonly sendPushNotificationRequest: (input: {
215 readonly credentials: ApnsCredentials;
216 readonly request: ApnsPushNotificationRequest;
217 readonly issuedAtUnixSeconds: number;
218 }) => Effect.Effect<ApnsDeliveryResult, ApnsError>;
219 }
220>()("t3code-relay/agentActivity/ApnsClient") {}
221
222export const make = Effect.gen(function* () {
223 const httpClient = yield* HttpClient.HttpClient;
224 const providerTokens = yield* ApnsProviderTokens.ApnsProviderTokens;
225
226 const sendLiveActivityRequest: ApnsClient["Service"]["sendLiveActivityRequest"] = Effect.fn(
227 "relay.apns.send_live_activity_request",
228 )(function* (input) {
229 yield* Effect.annotateCurrentSpan({ "relay.apns.event": input.request.event });
230 const jwt = yield* providerTokens.getJwt({
231 ...input.credentials,
232 issuedAtUnixSeconds: input.issuedAtUnixSeconds,
233 });
234 const host =
235 input.credentials.environment === "production"
236 ? "https://api.push.apple.com"
237 : "https://api.sandbox.push.apple.com";
238 const response = yield* HttpClientRequest.post(`${host}/3/device/${input.request.token}`).pipe(
239 HttpClientRequest.setHeaders({
240 authorization: `bearer ${jwt}`,
241 "apns-priority": input.request.priority,
242 "apns-push-type": "liveactivity",
243 "apns-topic": `${input.credentials.bundleId}.push-type.liveactivity`,
244 }),
245 HttpClientRequest.bodyJson(input.request.payload),
246 Effect.flatMap(httpClient.execute),
247 Effect.timeout(APNS_HTTP_STAGE_TIMEOUT),
248 Effect.mapError(
249 (cause) =>
250 new ApnsHttpRequestError({
251 requestKind: "live-activity",
252 event: input.request.event,
253 environment: input.credentials.environment,
254 bundleId: input.credentials.bundleId,
255 tokenSuffix: input.request.token.slice(-8),
256 stage: "send",
257 status: null,
258 cause,
259 }),
260 ),
261 );
262 const responseText = yield* response.text.pipe(
263 Effect.timeout(APNS_HTTP_STAGE_TIMEOUT),
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.timeout(APNS_HTTP_STAGE_TIMEOUT),
310 Effect.mapError(
311 (cause) =>
312 new ApnsHttpRequestError({
313 requestKind: "push-notification",
314 event: null,
315 environment: input.credentials.environment,
316 bundleId: input.credentials.bundleId,
317 tokenSuffix: input.request.token.slice(-8),
318 stage: "send",
319 status: null,
320 cause,
321 }),
322 ),
323 );
324 const responseText = yield* response.text.pipe(
325 Effect.timeout(APNS_HTTP_STAGE_TIMEOUT),
326 Effect.mapError(
327 (cause) =>
328 new ApnsHttpRequestError({
329 requestKind: "push-notification",
330 event: null,
331 environment: input.credentials.environment,
332 bundleId: input.credentials.bundleId,
333 tokenSuffix: input.request.token.slice(-8),
334 stage: "read-response",
335 status: response.status,
336 cause,
337 }),
338 ),
339 );
340 const reason = apnsReasonFromBody(responseText);
341 return {
342 ok: response.status >= 200 && response.status < 300,
343 status: response.status,
344 ...(reason === undefined ? {} : { reason }),
345 apnsId: Option.getOrNull(Headers.get(response.headers, "apns-id")),
346 };
347 });
348
349 return ApnsClient.of({
350 makeLiveActivityRequest,
351 makePushNotificationRequest,
352 sendLiveActivityRequest,
353 sendPushNotificationRequest,
354 });
355});
356
357export const layer = Layer.effect(ApnsClient, make);