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/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 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). 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;
41}
42
43interface ApnsPushNotificationRequest {
44 readonly token: string;
45 readonly priority: "10";
46 readonly payload: unknown;
47}
48
49export interface ApnsDeliveryResult {
50 readonly ok: boolean;
51 readonly status: number;
52 readonly reason?: string;
53 readonly apnsId: string | null;
54}
55
56export class ApnsHttpRequestError extends Schema.TaggedError<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 }
72}
73
74export type ApnsError = ApnsJwtEncodingError | ApnsJwtSigningError | ApnsHttpRequestError;
75
76const decodeApnsErrorResponseJson = Schema.decodeUnknownOption(
77 Schema.fromJsonString(
78 Schema.Struct({
79 reason: Schema.optional(Schema.String),
80 }),
81 ),
82);
83function contentState(state: RelayAgentActivityAggregateState) {
84 return {
85 name: LIVE_ACTIVITY_NAME,
86 props: JSON.stringify(state),
87 };
88}
89
90interface LiveActivityRequestBase {
91 readonly token: string;
92 readonly nowEpochSeconds: number;
93 readonly nowIso: string;
94}
95
96type MakeLiveActivityRequestInput =
97 | (LiveActivityRequestBase & {
98 readonly event: "end";
99 readonly state: RelayAgentActivityAggregateState | null;
100 readonly alert?: ApnsLiveActivityAlert | null;
101 })
102 | (LiveActivityRequestBase & {
103 readonly event: "start" | "update";
104 readonly state: RelayAgentActivityAggregateState;
105 readonly alert?: ApnsLiveActivityAlert | null;
106 });
107
108// An alert dict on an update/end makes it an "alerting" update: iOS wakes the
109// screen and plays the haptic (the Apple Sports score-change behavior) instead
110// of silently redrawing the activity.
111function liveActivityAlertPayload(alert: ApnsLiveActivityAlert) {
112 return {
113 alert: {
114 title: alert.title,
115 body: alert.body,
116 sound: "default",
117 },
118 };
119}
120
121function makeLiveActivityRequest(input: MakeLiveActivityRequestInput): ApnsLiveActivityRequest {
122 const timestamp = input.nowEpochSeconds;
123 if (input.event === "end") {
124 return {
125 token: input.token,
126 event: input.event,
127 priority: "10",
128 payload: {
129 aps: {
130 timestamp,
131 event: "end",
132 ...(input.state ? { "content-state": contentState(input.state) } : {}),
133 ...(input.alert ? liveActivityAlertPayload(input.alert) : {}),
134 "dismissal-date":
135 timestamp + (input.state ? DISMISS_AFTER_SECONDS : CONTENTLESS_DISMISS_AFTER_SECONDS),
136 },
137 },
138 };
139 }
140
141 const state = input.state;
142 return {
143 token: input.token,
144 event: input.event,
145 // Alerting updates must land immediately; routine redraws stay at the
146 // budget-friendly low priority.
147 priority: input.event === "update" && !input.alert ? "5" : "10",
148 payload: {
149 aps: {
150 timestamp,
151 event: input.event,
152 ...(input.event === "start"
153 ? {
154 "attributes-type": "LiveActivityAttributes",
155 attributes: {},
156 "input-push-token": 1,
157 alert: {
158 title: state.title,
159 body: state.subtitle,
160 },
161 }
162 : {}),
163 ...(input.event === "update" && input.alert ? liveActivityAlertPayload(input.alert) : {}),
164 "content-state": contentState(state),
165 "stale-date": timestamp + STALE_AFTER_SECONDS,
166 },
167 },
168 };
169}
170
171function makePushNotificationRequest(input: {
172 readonly token: string;
173 readonly notification: ApnsNotificationPayload;
174}): ApnsPushNotificationRequest {
175 return {
176 token: input.token,
177 priority: "10",
178 payload: {
179 aps: {
180 alert: {
181 title: input.notification.title,
182 body: input.notification.body,
183 },
184 sound: "default",
185 },
186 environmentId: input.notification.environmentId,
187 threadId: input.notification.threadId,
188 deepLink: input.notification.deepLink,
189 },
190 };
191}
192
193function apnsReasonFromBody(body: string): string | undefined {
194 if (body.trim().length === 0) {
195 return undefined;
196 }
197 return Option.match(decodeApnsErrorResponseJson(body), {
198 onNone: () => body,
199 onSome: (parsed) => parsed.reason ?? body,
200 });
201}
202
203export class ApnsClient extends Context.Service<
204 ApnsClient,
205 {
206 readonly makeLiveActivityRequest: typeof makeLiveActivityRequest;
207 readonly makePushNotificationRequest: typeof makePushNotificationRequest;
208 readonly sendLiveActivityRequest: (input: {
209 readonly credentials: ApnsCredentials;
210 readonly request: ApnsLiveActivityRequest;
211 readonly issuedAtUnixSeconds: number;
212 }) => Effect.Effect<ApnsDeliveryResult, ApnsError>;
213 readonly sendPushNotificationRequest: (input: {
214 readonly credentials: ApnsCredentials;
215 readonly request: ApnsPushNotificationRequest;
216 readonly issuedAtUnixSeconds: number;
217 }) => Effect.Effect<ApnsDeliveryResult, ApnsError>;
218 }
219>()("t3code-relay/agentActivity/ApnsClient") {}
220
221export const make = Effect.gen(function* () {
222 const httpClient = yield* HttpClient.HttpClient;
223 const providerTokens = yield* ApnsProviderTokens.ApnsProviderTokens;
224
225 const sendLiveActivityRequest: ApnsClient["Service"]["sendLiveActivityRequest"] = Effect.fn(
226 "relay.apns.send_live_activity_request",
227 )(function* (input) {
228 yield* Effect.annotateCurrentSpan({ "relay.apns.event": input.request.event });
229 const jwt = yield* providerTokens.getJwt({
230 ...input.credentials,
231 issuedAtUnixSeconds: input.issuedAtUnixSeconds,
232 });
233 const host =
234 input.credentials.environment === "production"
235 ? "https://api.push.apple.com"
236 : "https://api.sandbox.push.apple.com";
237 const response = yield* HttpClientRequest.post(`${host}/3/device/${input.request.token}`).pipe(
238 HttpClientRequest.setHeaders({
239 authorization: `bearer ${jwt}`,
240 "apns-priority": input.request.priority,
241 "apns-push-type": "liveactivity",
242 "apns-topic": `${input.credentials.bundleId}.push-type.liveactivity`,
243 }),
244 HttpClientRequest.bodyJson(input.request.payload),
245 Effect.flatMap(httpClient.execute),
246 Effect.timeout(APNS_HTTP_STAGE_TIMEOUT),
247 Effect.mapError(
248 (cause) =>
249 new ApnsHttpRequestError({
250 requestKind: "live-activity",
251 event: input.request.event,
252 environment: input.credentials.environment,
253 bundleId: input.credentials.bundleId,
254 tokenSuffix: input.request.token.slice(-8),
255 stage: "send",
256 status: null,
257 cause,
258 }),
259 ),
260 );
261 const responseText = yield* response.text.pipe(
262 Effect.timeout(APNS_HTTP_STAGE_TIMEOUT),
263 Effect.mapError(
264 (cause) =>
265 new ApnsHttpRequestError({
266 requestKind: "live-activity",
267 event: input.request.event,
268 environment: input.credentials.environment,
269 bundleId: input.credentials.bundleId,
270 tokenSuffix: input.request.token.slice(-8),
271 stage: "read-response",
272 status: response.status,
273 cause,
274 }),
275 ),
276 );
277 const reason = apnsReasonFromBody(responseText);
278 return {
279 ok: response.status >= 200 && response.status < 300,
280 status: response.status,
281 ...(reason === undefined ? {} : { reason }),
282 apnsId: Option.getOrNull(Headers.get(response.headers, "apns-id")),
283 };
284 });
285
286 const sendPushNotificationRequest: ApnsClient["Service"]["sendPushNotificationRequest"] =
287 Effect.fn("relay.apns.send_push_notification_request")(function* (input) {
288 yield* Effect.annotateCurrentSpan({ "relay.apns.event": "push_notification" });
289 const jwt = yield* providerTokens.getJwt({
290 ...input.credentials,
291 issuedAtUnixSeconds: input.issuedAtUnixSeconds,
292 });
293 const host =
294 input.credentials.environment === "production"
295 ? "https://api.push.apple.com"
296 : "https://api.sandbox.push.apple.com";
297 const response = yield* HttpClientRequest.post(
298 `${host}/3/device/${input.request.token}`,
299 ).pipe(
300 HttpClientRequest.setHeaders({
301 authorization: `bearer ${jwt}`,
302 "apns-priority": input.request.priority,
303 "apns-push-type": "alert",
304 "apns-topic": input.credentials.bundleId,
305 }),
306 HttpClientRequest.bodyJson(input.request.payload),
307 Effect.flatMap(httpClient.execute),
308 Effect.timeout(APNS_HTTP_STAGE_TIMEOUT),
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.timeout(APNS_HTTP_STAGE_TIMEOUT),
325 Effect.mapError(
326 (cause) =>
327 new ApnsHttpRequestError({
328 requestKind: "push-notification",
329 event: null,
330 environment: input.credentials.environment,
331 bundleId: input.credentials.bundleId,
332 tokenSuffix: input.request.token.slice(-8),
333 stage: "read-response",
334 status: response.status,
335 cause,
336 }),
337 ),
338 );
339 const reason = apnsReasonFromBody(responseText);
340 return {
341 ok: response.status >= 200 && response.status < 300,
342 status: response.status,
343 ...(reason === undefined ? {} : { reason }),
344 apnsId: Option.getOrNull(Headers.get(response.headers, "apns-id")),
345 };
346 });
347
348 return ApnsClient.of({
349 makeLiveActivityRequest,
350 makePushNotificationRequest,
351 sendLiveActivityRequest,
352 sendPushNotificationRequest,
353 });
354});
355
356export const layer = Layer.effect(ApnsClient, make);