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(["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: "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 === "update" && input.alert ? liveActivityAlertPayload(input.alert) : {}),
144 "content-state": contentState(state),
145 "stale-date": timestamp + STALE_AFTER_SECONDS,
146 },
147 },
148 };
149}
150
151function notificationThreadId(notification: ApnsNotificationPayload): string {
152 return notification.threadId.length > 0
153 ? `${notification.environmentId}/${notification.threadId}`
154 : "t3-agent-alerts";
155}
156
157function makePushNotificationRequest(input: {
158 readonly token: string;
159 readonly notification: ApnsNotificationPayload;
160}): ApnsPushNotificationRequest {
161 return {
162 token: input.token,
163 priority: "10",
164 payload: {
165 aps: {
166 alert: {
167 title: input.notification.title,
168 body: input.notification.body,
169 },
170 sound: "default",
171 "thread-id": notificationThreadId(input.notification),
172 },
173 // Expo iOS exposes userInfo.body as notification.content.data for remote pushes.
174 body: {
175 environmentId: input.notification.environmentId,
176 threadId: input.notification.threadId,
177 deepLink: input.notification.deepLink,
178 },
179 },
180 };
181}
182
183function apnsReasonFromBody(body: string): string | undefined {
184 if (body.trim().length === 0) {
185 return undefined;
186 }
187 return Option.match(decodeApnsErrorResponseJson(body), {
188 onNone: () => body,
189 onSome: (parsed) => parsed.reason ?? body,
190 });
191}
192
193export class ApnsClient extends Context.Service<
194 ApnsClient,
195 {
196 readonly makeLiveActivityRequest: typeof makeLiveActivityRequest;
197 readonly makePushNotificationRequest: typeof makePushNotificationRequest;
198 readonly sendLiveActivityRequest: (input: {
199 readonly credentials: ApnsCredentials;
200 readonly request: ApnsLiveActivityRequest;
201 readonly issuedAtUnixSeconds: number;
202 }) => Effect.Effect<ApnsDeliveryResult, ApnsError>;
203 readonly sendPushNotificationRequest: (input: {
204 readonly credentials: ApnsCredentials;
205 readonly request: ApnsPushNotificationRequest;
206 readonly issuedAtUnixSeconds: number;
207 }) => Effect.Effect<ApnsDeliveryResult, ApnsError>;
208 }
209>()("t3code-relay/agentActivity/ApnsClient") {}
210
211const make = Effect.gen(function* () {
212 const httpClient = yield* HttpClient.HttpClient;
213 const providerTokens = yield* ApnsProviderTokens.ApnsProviderTokens;
214
215 const sendLiveActivityRequest: ApnsClient["Service"]["sendLiveActivityRequest"] = Effect.fn(
216 "relay.apns.send_live_activity_request",
217 )(function* (input) {
218 yield* Effect.annotateCurrentSpan({ "relay.apns.event": input.request.event });
219 const jwt = yield* providerTokens.getJwt({
220 ...input.credentials,
221 issuedAtUnixSeconds: input.issuedAtUnixSeconds,
222 });
223 const host =
224 input.credentials.environment === "production"
225 ? "https://api.push.apple.com"
226 : "https://api.sandbox.push.apple.com";
227 const response = yield* HttpClientRequest.post(`${host}/3/device/${input.request.token}`).pipe(
228 HttpClientRequest.setHeaders({
229 authorization: `bearer ${jwt}`,
230 "apns-priority": input.request.priority,
231 "apns-push-type": "liveactivity",
232 "apns-topic": `${input.credentials.bundleId}.push-type.liveactivity`,
233 }),
234 HttpClientRequest.bodyJson(input.request.payload),
235 Effect.flatMap(httpClient.execute),
236 Effect.timeout(APNS_HTTP_STAGE_TIMEOUT),
237 Effect.mapError(
238 (cause) =>
239 new ApnsHttpRequestError({
240 requestKind: "live-activity",
241 event: input.request.event,
242 environment: input.credentials.environment,
243 bundleId: input.credentials.bundleId,
244 tokenSuffix: input.request.token.slice(-8),
245 stage: "send",
246 status: null,
247 cause,
248 }),
249 ),
250 );
251 const responseText = yield* response.text.pipe(
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: "read-response",
262 status: response.status,
263 cause,
264 }),
265 ),
266 );
267 const reason = apnsReasonFromBody(responseText);
268 return {
269 ok: response.status >= 200 && response.status < 300,
270 status: response.status,
271 ...(reason === undefined ? {} : { reason }),
272 apnsId: Option.getOrNull(Headers.get(response.headers, "apns-id")),
273 };
274 });
275
276 const sendPushNotificationRequest: ApnsClient["Service"]["sendPushNotificationRequest"] =
277 Effect.fn("relay.apns.send_push_notification_request")(function* (input) {
278 yield* Effect.annotateCurrentSpan({ "relay.apns.event": "push_notification" });
279 const jwt = yield* providerTokens.getJwt({
280 ...input.credentials,
281 issuedAtUnixSeconds: input.issuedAtUnixSeconds,
282 });
283 const host =
284 input.credentials.environment === "production"
285 ? "https://api.push.apple.com"
286 : "https://api.sandbox.push.apple.com";
287 const response = yield* HttpClientRequest.post(
288 `${host}/3/device/${input.request.token}`,
289 ).pipe(
290 HttpClientRequest.setHeaders({
291 authorization: `bearer ${jwt}`,
292 "apns-priority": input.request.priority,
293 "apns-push-type": "alert",
294 "apns-topic": input.credentials.bundleId,
295 }),
296 HttpClientRequest.bodyJson(input.request.payload),
297 Effect.flatMap(httpClient.execute),
298 Effect.timeout(APNS_HTTP_STAGE_TIMEOUT),
299 Effect.mapError(
300 (cause) =>
301 new ApnsHttpRequestError({
302 requestKind: "push-notification",
303 event: null,
304 environment: input.credentials.environment,
305 bundleId: input.credentials.bundleId,
306 tokenSuffix: input.request.token.slice(-8),
307 stage: "send",
308 status: null,
309 cause,
310 }),
311 ),
312 );
313 const responseText = yield* response.text.pipe(
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: "read-response",
324 status: response.status,
325 cause,
326 }),
327 ),
328 );
329 const reason = apnsReasonFromBody(responseText);
330 return {
331 ok: response.status >= 200 && response.status < 300,
332 status: response.status,
333 ...(reason === undefined ? {} : { reason }),
334 apnsId: Option.getOrNull(Headers.get(response.headers, "apns-id")),
335 };
336 });
337
338 return ApnsClient.of({
339 makeLiveActivityRequest,
340 makePushNotificationRequest,
341 sendLiveActivityRequest,
342 sendPushNotificationRequest,
343 });
344});
345
346export const layer = Layer.effect(ApnsClient, make);