Open History to see the last commit
1import type {
2 RelayAgentActivityAggregateState,
3 RelayAgentAwarenessPreferences,
4 RelayDeliveryKind,
5 RelayDeliveryResult,
6} from "@t3tools/contracts/relay";
7import {
8 RelayAgentActivityAggregateState as RelayAgentActivityAggregateStateSchema,
9 RelayAgentAwarenessPreferences as RelayAgentAwarenessPreferencesSchema,
10 RelayDeliveryKind as RelayDeliveryKindSchema,
11} from "@t3tools/contracts/relay";
12import * as Context from "effect/Context";
13import * as DateTime from "effect/DateTime";
14import * as Effect from "effect/Effect";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as Redacted from "effect/Redacted";
18import * as Schema from "effect/Schema";
19
20import {
21 isExpiredAgentActivityState,
22 isTerminalPhase,
23 sanitizeAgentActivityAggregateState,
24 sanitizeApnsNotificationPayload,
25} from "./agentActivityPayloads.ts";
26import * as Apns from "./ApnsClient.ts";
27import {
28 ApnsDeliveryJobLiveActivityAggregateMissing,
29 ApnsDeliveryJobPushNotificationMissing,
30 ApnsDeliveryJobQueuePayloadInvalid,
31 type ApnsLiveActivityAlert,
32 type ApnsNotificationPayload,
33 SignedApnsDeliveryJob,
34 isApnsDeliveryJobVerificationError,
35 verifySignedApnsDeliveryJob,
36 type ApnsDeliveryJobVerificationError,
37} from "./apnsDeliveryJobs.ts";
38import * as AgentActivityRows from "./AgentActivityRows.ts";
39import * as DeliveryAttempts from "./DeliveryAttempts.ts";
40import * as LiveActivities from "./LiveActivities.ts";
41import * as RelayConfiguration from "../Config.ts";
42import * as ApnsDeliveryQueue from "./ApnsDeliveryQueue.ts";
43import { withSpanAttributes } from "../observability.ts";
44
45const MIN_LIVE_ACTIVITY_UPDATE_INTERVAL_MS = 15_000;
46// How long a just-armed card may sit with an empty aggregate before an end is
47// warranted; covers the gap between arming on send and the environment's
48// first publish reaching the relay.
49const FRESHLY_ARMED_GRACE_MS = 2 * 60 * 1_000;
50const PERMANENT_APNS_TOKEN_REASONS = new Set([
51 "BadDeviceToken",
52 "DeviceTokenNotForTopic",
53 "Unregistered",
54]);
55
56type LiveActivityDeliveryKind = Extract<
57 RelayDeliveryKind,
58 "live_activity_start" | "live_activity_update" | "live_activity_end"
59>;
60
61type ChosenLiveActivityDelivery =
62 | {
63 readonly kind: "live_activity_start" | "live_activity_update";
64 readonly token: string;
65 readonly aggregate: RelayAgentActivityAggregateState;
66 readonly alert: ApnsLiveActivityAlert | null;
67 }
68 | {
69 readonly kind: "live_activity_end";
70 readonly token: string;
71 readonly aggregate: RelayAgentActivityAggregateState | null;
72 readonly alert: ApnsLiveActivityAlert | null;
73 };
74
75type ChosenPushNotificationDelivery = {
76 readonly kind: "push_notification";
77 readonly token: string;
78 readonly notification: ApnsNotificationPayload;
79};
80
81type ChosenDelivery = ChosenLiveActivityDelivery | ChosenPushNotificationDelivery;
82
83export type ApnsDeliveryError =
84 | ApnsDeliveryQueue.ApnsDeliveryQueueError
85 | ApnsDeliveryJobVerificationError
86 | ApnsDeliveryJobClaimInFlight
87 | DeliveryAttempts.DeliveryAttemptRecordPersistenceError
88 | LiveActivities.LiveActivityTargetListPersistenceError
89 | LiveActivities.LiveActivityDeliveryMarkPersistenceError;
90
91export class ApnsDeliveryJobClaimInFlight extends Schema.TaggedErrorClass<ApnsDeliveryJobClaimInFlight>()(
92 "ApnsDeliveryJobClaimInFlight",
93 {
94 sourceJobId: Schema.String,
95 },
96) {
97 override get message(): string {
98 return `APNs delivery job '${this.sourceJobId}' is already in flight`;
99 }
100}
101
102export class ApnsDeliveryTransportError extends Schema.TaggedErrorClass<ApnsDeliveryTransportError>()(
103 "ApnsDeliveryTransportError",
104 {
105 deviceId: Schema.String,
106 kind: RelayDeliveryKindSchema,
107 sourceJobId: Schema.NullOr(Schema.String),
108 apnsErrorTag: Schema.Literals([
109 "ApnsJwtEncodingError",
110 "ApnsJwtSigningError",
111 "ApnsHttpRequestError",
112 ]),
113 requestStage: Schema.NullOr(Schema.Literals(["send", "read-response"])),
114 cause: Schema.Defect(),
115 },
116) {
117 override get message(): string {
118 return `APNs ${this.kind} delivery failed for device ${this.deviceId}.`;
119 }
120}
121
122export const isApnsDeliveryTransportError = Schema.is(ApnsDeliveryTransportError);
123
124const decodeRelayAgentActivityAggregateStateJson = Schema.decodeUnknownOption(
125 Schema.fromJsonString(RelayAgentActivityAggregateStateSchema),
126);
127const decodeRelayAgentAwarenessPreferencesJson = Schema.decodeUnknownOption(
128 Schema.fromJsonString(RelayAgentAwarenessPreferencesSchema),
129);
130const decodeSignedApnsDeliveryJob = Schema.decodeUnknownEffect(SignedApnsDeliveryJob);
131
132function parseAggregate(value: string | null): RelayAgentActivityAggregateState | null {
133 if (!value) {
134 return null;
135 }
136 return Option.getOrNull(decodeRelayAgentActivityAggregateStateJson(value));
137}
138
139function parsePreferences(value: string): RelayAgentAwarenessPreferences | null {
140 return Option.getOrNull(decodeRelayAgentAwarenessPreferencesJson(value));
141}
142
143function aggregateNeedsAttention(aggregate: RelayAgentActivityAggregateState): boolean {
144 return aggregate.activities.some(
145 (row) => row.phase === "waiting_for_approval" || row.phase === "waiting_for_input",
146 );
147}
148
149function isAttentionPhase(phase: string): boolean {
150 return phase === "waiting_for_approval" || phase === "waiting_for_input";
151}
152
153// Honors the same per-event notification switches the push channel uses; a
154// missing/corrupt preferences blob only disables nothing (matching how the
155// liveActivitiesEnabled check treats it), since every registration writes one.
156function alertAllowedForPhase(
157 preferences: RelayAgentAwarenessPreferences | null,
158 phase: string,
159): boolean {
160 if (preferences === null) {
161 return true;
162 }
163 switch (phase) {
164 case "waiting_for_approval":
165 return preferences.notifyOnApproval;
166 case "waiting_for_input":
167 return preferences.notifyOnInput;
168 case "completed":
169 return preferences.notifyOnCompletion;
170 case "failed":
171 return preferences.notifyOnFailure;
172 default:
173 return false;
174 }
175}
176
177// Alert copy for an update whose aggregate contains threads that were NOT in an
178// attention phase in the previously delivered aggregate. A null previous
179// aggregate means there is no known baseline (fresh registration, replay after
180// data loss) — alerting there would buzz on reconnect, not on a transition.
181export function alertForAttentionTransition(input: {
182 readonly previousAggregate: RelayAgentActivityAggregateState | null;
183 readonly nextAggregate: RelayAgentActivityAggregateState;
184 readonly preferences: RelayAgentAwarenessPreferences | null;
185}): ApnsLiveActivityAlert | null {
186 if (input.previousAggregate === null) {
187 return null;
188 }
189 const previouslyAttention = new Set(
190 input.previousAggregate.activities
191 .filter((row) => isAttentionPhase(row.phase))
192 .map((row) => row.threadId),
193 );
194 const newlyAttention = input.nextAggregate.activities.filter(
195 (row) =>
196 isAttentionPhase(row.phase) &&
197 !previouslyAttention.has(row.threadId) &&
198 alertAllowedForPhase(input.preferences, row.phase),
199 );
200 const first = newlyAttention[0];
201 if (!first) {
202 return null;
203 }
204 if (newlyAttention.length === 1) {
205 return { title: first.threadTitle, body: `${first.status}: ${first.projectTitle}` };
206 }
207 return {
208 title: `${newlyAttention.length} agents need attention`,
209 body: newlyAttention.map((row) => row.threadTitle).join(", "),
210 };
211}
212
213// Alert copy for an update whose aggregate contains threads that finished
214// (Done/Failed) since the previously delivered aggregate — the mid-flight
215// completion buzz while other agents keep the activity alive. Requires the
216// thread to have been present and non-terminal before, so a baseline-less
217// replay or a row that merely fell off the display cap never rings.
218function newlyTerminalRows(
219 previousAggregate: RelayAgentActivityAggregateState | null,
220 nextAggregate: RelayAgentActivityAggregateState,
221): ReadonlyArray<RelayAgentActivityAggregateState["activities"][number]> {
222 if (previousAggregate === null) {
223 return [];
224 }
225 const previousPhases = new Map(
226 previousAggregate.activities.map((row) => [row.threadId, row.phase]),
227 );
228 return nextAggregate.activities.filter((row) => {
229 if (row.phase !== "completed" && row.phase !== "failed") {
230 return false;
231 }
232 const previousPhase = previousPhases.get(row.threadId);
233 return (
234 previousPhase !== undefined && previousPhase !== "completed" && previousPhase !== "failed"
235 );
236 });
237}
238
239function isFreshTerminalRow(
240 row: RelayAgentActivityAggregateState["activities"][number],
241 nowMs: number,
242): boolean {
243 const updatedAtMs = Option.match(DateTime.make(row.updatedAt), {
244 onNone: () => null,
245 onSome: (dt) => dt.epochMilliseconds,
246 });
247 return updatedAtMs !== null && nowMs - updatedAtMs <= TERMINAL_NOTIFICATION_FRESHNESS_MS;
248}
249
250export function alertForNewlyTerminal(input: {
251 readonly previousAggregate: RelayAgentActivityAggregateState | null;
252 readonly nextAggregate: RelayAgentActivityAggregateState;
253 readonly preferences: RelayAgentAwarenessPreferences | null;
254 readonly nowMs: number;
255}): ApnsLiveActivityAlert | null {
256 const newlyTerminal = newlyTerminalRows(input.previousAggregate, input.nextAggregate).filter(
257 (row) =>
258 alertAllowedForPhase(input.preferences, row.phase) &&
259 // Replays of old aggregates (server restarts, redeliveries) repaint
260 // state without ringing; only fresh completions buzz.
261 isFreshTerminalRow(row, input.nowMs),
262 );
263 const first = newlyTerminal[0];
264 if (!first) {
265 return null;
266 }
267 if (newlyTerminal.length === 1) {
268 return { title: first.threadTitle, body: `${first.status}: ${first.projectTitle}` };
269 }
270 return {
271 title: `${newlyTerminal.length} agents finished`,
272 body: newlyTerminal.map((row) => row.threadTitle).join(", "),
273 };
274}
275
276// Alert copy for an end event carrying a terminal (Done/Failed) aggregate.
277export function alertForTerminalAggregate(input: {
278 readonly aggregate: RelayAgentActivityAggregateState | null;
279 readonly preferences: RelayAgentAwarenessPreferences | null;
280}): ApnsLiveActivityAlert | null {
281 const row = input.aggregate?.activities[0];
282 if (!row || (row.phase !== "completed" && row.phase !== "failed")) {
283 return null;
284 }
285 if (!alertAllowedForPhase(input.preferences, row.phase)) {
286 return null;
287 }
288 return { title: row.threadTitle, body: `${row.status}: ${row.projectTitle}` };
289}
290
291function shouldUpdateLiveActivity(input: {
292 readonly previousAggregate: RelayAgentActivityAggregateState | null;
293 readonly nextAggregate: RelayAgentActivityAggregateState;
294 readonly lastDeliveryAt: string | null;
295 readonly nowMs: number;
296}): boolean {
297 if (!input.previousAggregate) {
298 return true;
299 }
300 if (JSON.stringify(input.previousAggregate) === JSON.stringify(input.nextAggregate)) {
301 return false;
302 }
303 if (input.previousAggregate.activeCount !== input.nextAggregate.activeCount) {
304 return true;
305 }
306 if (aggregateNeedsAttention(input.nextAggregate)) {
307 return true;
308 }
309 // A thread finishing must never be throttled away: when a completion and a
310 // new start land in the same window, activeCount is unchanged and the Done
311 // transition (and its alert) would otherwise be suppressed.
312 if (newlyTerminalRows(input.previousAggregate, input.nextAggregate).length > 0) {
313 return true;
314 }
315 const lastDeliveryAtMs =
316 input.lastDeliveryAt === null
317 ? null
318 : Option.match(DateTime.make(input.lastDeliveryAt), {
319 onNone: () => Number.NaN,
320 onSome: (dt) => dt.epochMilliseconds,
321 });
322 return (
323 lastDeliveryAtMs === null ||
324 Number.isNaN(lastDeliveryAtMs) ||
325 input.nowMs - lastDeliveryAtMs >= MIN_LIVE_ACTIVITY_UPDATE_INTERVAL_MS
326 );
327}
328
329// Completions replayed long after the fact (server restarts republish every
330// recently-finished thread) must not ring the device again.
331const TERMINAL_NOTIFICATION_FRESHNESS_MS = 2 * 60 * 1_000;
332
333function notificationForAggregate(input: {
334 readonly target: LiveActivities.TargetRow;
335 readonly aggregate: RelayAgentActivityAggregateState | null;
336 readonly nowMs: number;
337}): ApnsNotificationPayload | null {
338 if (!input.target.push_token || input.aggregate === null) {
339 return null;
340 }
341 const preferences = parsePreferences(input.target.preferences_json);
342 if (!preferences?.notificationsEnabled) {
343 return null;
344 }
345 const activity = input.aggregate.activities[0];
346 if (!activity) {
347 return null;
348 }
349 if (activity.phase === "completed" || activity.phase === "failed") {
350 const updatedAtMs = Option.match(DateTime.make(activity.updatedAt), {
351 onNone: () => null,
352 onSome: (dt) => dt.epochMilliseconds,
353 });
354 if (updatedAtMs === null || input.nowMs - updatedAtMs > TERMINAL_NOTIFICATION_FRESHNESS_MS) {
355 return null;
356 }
357 }
358 const enabled =
359 (activity.phase === "waiting_for_approval" && preferences.notifyOnApproval) ||
360 (activity.phase === "waiting_for_input" && preferences.notifyOnInput) ||
361 (activity.phase === "completed" && preferences.notifyOnCompletion) ||
362 (activity.phase === "failed" && preferences.notifyOnFailure);
363 if (!enabled) {
364 return null;
365 }
366 return {
367 title: activity.threadTitle,
368 body: `${activity.status}: ${activity.projectTitle}`,
369 environmentId: activity.environmentId,
370 threadId: activity.threadId,
371 deepLink: activity.deepLink,
372 phase: activity.phase,
373 updatedAt: activity.updatedAt,
374 };
375}
376
377// "suppressed" means a Live Activity owns this state but no update is due
378// (unchanged or throttled); callers must not fall back to an alert push, or
379// every republish of a waiting aggregate would ring the device.
380function chooseLiveActivityDelivery(input: {
381 readonly target: LiveActivities.TargetRow;
382 readonly aggregate: RelayAgentActivityAggregateState | null;
383 readonly nowMs: number;
384}): ChosenLiveActivityDelivery | "suppressed" | null {
385 const preferences = parsePreferences(input.target.preferences_json);
386 if (preferences?.liveActivitiesEnabled === false) {
387 return input.target.activity_push_token
388 ? {
389 kind: "live_activity_end",
390 token: input.target.activity_push_token,
391 aggregate: null,
392 alert: null,
393 }
394 : null;
395 }
396 // Activities are started by the app in the foreground, never remotely.
397 // Without a registered token there is nothing addressable; attention
398 // transitions fall back to the push notification channel until the user
399 // next arms the card from the app.
400 if (!input.target.activity_push_token) {
401 return null;
402 }
403 // An armed card always shows content: live agents, or recently finished
404 // ones (the publisher keeps Done/Failed rows in the aggregate for a
405 // while). A null aggregate means there is truly nothing left to show, so
406 // the card ends — arming is cheap now that the app re-arms on any open
407 // with content.
408 if (input.aggregate === null) {
409 // Except right after arming: the app arms the card the moment the user
410 // starts work, and the token registration's replay can land before the
411 // environment's first publish for the brand-new thread. Ending here
412 // would retire the token and orphan the card at its seed content, so a
413 // freshly armed card keeps its seed until real state arrives.
414 const armedAtMs = Option.match(
415 input.target.remote_started_at === null
416 ? Option.none()
417 : DateTime.make(input.target.remote_started_at),
418 { onNone: () => null, onSome: (dt) => dt.epochMilliseconds },
419 );
420 if (armedAtMs !== null && input.nowMs - armedAtMs < FRESHLY_ARMED_GRACE_MS) {
421 return null;
422 }
423 return {
424 kind: "live_activity_end",
425 token: input.target.activity_push_token,
426 aggregate: null,
427 alert: null,
428 };
429 }
430 const nextAggregate = input.aggregate;
431 const previousAggregate = parseAggregate(input.target.last_aggregate_json);
432 return shouldUpdateLiveActivity({
433 previousAggregate,
434 nextAggregate,
435 lastDeliveryAt: input.target.last_live_activity_delivery_at,
436 nowMs: input.nowMs,
437 })
438 ? {
439 kind: "live_activity_update",
440 token: input.target.activity_push_token,
441 aggregate: nextAggregate,
442 alert:
443 alertForAttentionTransition({
444 previousAggregate,
445 nextAggregate,
446 preferences,
447 }) ??
448 alertForNewlyTerminal({
449 previousAggregate,
450 nextAggregate,
451 preferences,
452 nowMs: input.nowMs,
453 }),
454 }
455 : "suppressed";
456}
457
458function chooseDelivery(input: {
459 readonly target: LiveActivities.TargetRow;
460 readonly aggregate: RelayAgentActivityAggregateState | null;
461 readonly nowMs: number;
462}): ChosenDelivery | null {
463 const liveActivityDelivery = chooseLiveActivityDelivery(input);
464 if (liveActivityDelivery === "suppressed") {
465 return null;
466 }
467 if (liveActivityDelivery) {
468 return liveActivityDelivery;
469 }
470 const notification = notificationForAggregate(input);
471 return notification && input.target.push_token
472 ? {
473 kind: "push_notification",
474 token: input.target.push_token,
475 notification,
476 }
477 : null;
478}
479
480function deliveryEvent(kind: LiveActivityDeliveryKind): Apns.ApnsLiveActivityEvent {
481 switch (kind) {
482 case "live_activity_start":
483 return "start";
484 case "live_activity_update":
485 return "update";
486 case "live_activity_end":
487 return "end";
488 }
489}
490
491function isPermanentApnsTokenFailure(result: Apns.ApnsDeliveryResult): boolean {
492 return (
493 !result.ok &&
494 (result.status === 410 ||
495 (result.status === 400 &&
496 result.reason !== undefined &&
497 PERMANENT_APNS_TOKEN_REASONS.has(result.reason)))
498 );
499}
500
501function duplicateJobResult(input: {
502 readonly deviceId: string;
503 readonly kind: RelayDeliveryKind;
504}): RelayDeliveryResult {
505 return {
506 deviceId: input.deviceId,
507 kind: input.kind,
508 ok: true,
509 apnsStatus: null,
510 apnsReason: "Duplicate APNs delivery job skipped.",
511 apnsId: null,
512 };
513}
514
515function staleJobResult(input: {
516 readonly deviceId: string;
517 readonly kind: RelayDeliveryKind;
518}): RelayDeliveryResult {
519 return {
520 deviceId: input.deviceId,
521 kind: input.kind,
522 ok: true,
523 apnsStatus: null,
524 apnsReason: "Stale APNs delivery job skipped.",
525 apnsId: null,
526 };
527}
528
529function deliveryAttemptOutcome(result: Apns.ApnsDeliveryResult) {
530 return {
531 ...(result.status === 0 ? {} : { apnsStatus: result.status }),
532 ...(result.reason === undefined ? {} : { apnsReason: result.reason }),
533 apnsId: result.apnsId,
534 ...(result.status === 0 ? { transportError: result.reason ?? "APNs request failed." } : {}),
535 };
536}
537
538const recoverApnsDeliveryTransportError = (
539 input: {
540 readonly deviceId: string;
541 readonly kind: RelayDeliveryKind;
542 readonly sourceJobId: string | null;
543 },
544 cause: Apns.ApnsError,
545): Effect.Effect<Apns.ApnsDeliveryResult> => {
546 const error = new ApnsDeliveryTransportError({
547 deviceId: input.deviceId,
548 kind: input.kind,
549 sourceJobId: input.sourceJobId,
550 apnsErrorTag: cause._tag,
551 requestStage: cause._tag === "ApnsHttpRequestError" ? cause.stage : null,
552 cause,
553 });
554 return Effect.logError(error.message).pipe(
555 Effect.annotateLogs({
556 error: Redacted.make(error, { label: error._tag }),
557 "error.type": error._tag,
558 "error.apns_error_tag": error.apnsErrorTag,
559 ...(error.requestStage === null ? {} : { "error.request_stage": error.requestStage }),
560 ...(error.stack === undefined ? {} : { "error.stack": error.stack }),
561 "relay.mobile.device_id": error.deviceId,
562 "relay.delivery.kind": error.kind,
563 ...(error.sourceJobId === null ? {} : { "relay.delivery.job_id": error.sourceJobId }),
564 }),
565 Effect.as({
566 ok: false,
567 status: 0,
568 reason: cause.message,
569 apnsId: null,
570 }),
571 );
572};
573
574interface LiveActivityDeliveryTarget {
575 readonly user_id: string;
576 readonly device_id: string;
577 readonly bundle_id?: string | null;
578 readonly aps_environment?: "sandbox" | "production" | null;
579}
580
581// Devices register the bundle id and APS environment of the build they run
582// (dev/preview/prod variants have distinct bundle ids; development-signed
583// builds get sandbox tokens). Sending with mismatched routing yields
584// DeviceTokenNotForTopic/BadDeviceToken, so per-device values override the
585// relay-wide defaults when present.
586function credentialsForTarget(
587 credentials: RelayConfiguration.RelayConfiguration["Service"]["apns"],
588 target: LiveActivityDeliveryTarget,
589): RelayConfiguration.RelayConfiguration["Service"]["apns"] {
590 return {
591 ...credentials,
592 ...(target.bundle_id ? { bundleId: target.bundle_id } : {}),
593 ...(target.aps_environment ? { environment: target.aps_environment } : {}),
594 };
595}
596
597function expectedCurrentToken(input: {
598 readonly target: LiveActivities.TargetRow;
599 readonly kind: RelayDeliveryKind;
600}): string | null {
601 switch (input.kind) {
602 case "live_activity_start":
603 return input.target.push_to_start_token;
604 case "live_activity_update":
605 case "live_activity_end":
606 return input.target.activity_push_token;
607 case "push_notification":
608 return input.target.push_token;
609 }
610}
611
612interface SendLiveActivityDeliveryInputBase {
613 readonly target: LiveActivityDeliveryTarget;
614 readonly token: string;
615 readonly sourceJobId?: string | null;
616}
617
618export type SendLiveActivityDeliveryInput =
619 | (SendLiveActivityDeliveryInputBase & {
620 readonly kind: "live_activity_start" | "live_activity_update";
621 readonly aggregate: RelayAgentActivityAggregateState;
622 readonly alert?: ApnsLiveActivityAlert | null;
623 })
624 | (SendLiveActivityDeliveryInputBase & {
625 readonly kind: "live_activity_end";
626 readonly aggregate: RelayAgentActivityAggregateState | null;
627 readonly alert?: ApnsLiveActivityAlert | null;
628 });
629
630function makeLiveActivityDeliveryRequest(
631 apns: Apns.ApnsClient["Service"],
632 input: SendLiveActivityDeliveryInput,
633 now: DateTime.DateTime,
634) {
635 const epochSeconds = Math.floor(now.epochMilliseconds / 1_000);
636 const base = {
637 token: input.token,
638 nowEpochSeconds: epochSeconds,
639 nowIso: DateTime.formatIso(now),
640 };
641 switch (input.kind) {
642 case "live_activity_start":
643 case "live_activity_update":
644 return {
645 epochSeconds,
646 iso: base.nowIso,
647 request: apns.makeLiveActivityRequest({
648 ...base,
649 event: deliveryEvent(input.kind),
650 state: input.aggregate,
651 alert: input.alert ?? null,
652 }),
653 };
654 case "live_activity_end":
655 return {
656 epochSeconds,
657 iso: base.nowIso,
658 request: apns.makeLiveActivityRequest({
659 ...base,
660 event: "end",
661 state: input.aggregate,
662 alert: input.alert ?? null,
663 }),
664 };
665 }
666}
667
668export class ApnsDeliveries extends Context.Service<
669 ApnsDeliveries,
670 {
671 readonly sendForTarget: (input: {
672 readonly target: LiveActivities.TargetRow;
673 readonly aggregate: RelayAgentActivityAggregateState | null;
674 readonly nowMs: number;
675 }) => Effect.Effect<RelayDeliveryResult | null, ApnsDeliveryError>;
676 readonly sendPushNotificationForTarget: (input: {
677 readonly target: LiveActivities.TargetRow;
678 readonly aggregate: RelayAgentActivityAggregateState | null;
679 }) => Effect.Effect<RelayDeliveryResult | null, ApnsDeliveryError>;
680 readonly sendLiveActivity: (
681 input: SendLiveActivityDeliveryInput,
682 ) => Effect.Effect<RelayDeliveryResult, ApnsDeliveryError>;
683 readonly processSignedJob: (
684 body: unknown,
685 ) => Effect.Effect<RelayDeliveryResult, ApnsDeliveryError>;
686 readonly sendPushNotification: (input: {
687 readonly target: LiveActivityDeliveryTarget;
688 readonly token: string;
689 readonly sourceJobId?: string | null;
690 readonly notification: ApnsNotificationPayload;
691 }) => Effect.Effect<RelayDeliveryResult, ApnsDeliveryError>;
692 }
693>()("t3code-relay/agentActivity/ApnsDeliveries") {}
694
695export const make = Effect.gen(function* () {
696 const attempts = yield* DeliveryAttempts.DeliveryAttempts;
697 const liveActivities = yield* LiveActivities.LiveActivities;
698 const deliveryQueue = yield* ApnsDeliveryQueue.ApnsDeliveryQueue;
699 const config = yield* RelayConfiguration.RelayConfiguration;
700 const apns = yield* Apns.ApnsClient;
701 const activityRows = yield* AgentActivityRows.AgentActivityRows;
702
703 // Start jobs are decided at publish time, but consecutive publishes land in
704 // the same queue batch: a start chosen from a running aggregate can be
705 // delivered moments after a newer terminal publish already ended the user's
706 // work, birthing an orphan activity that shows stale content forever (no
707 // token is ever registered for it, so nothing can update or end it).
708 // Re-validate at delivery time that the user still has live work; fail open
709 // on persistence errors so a database hiccup never drops a legitimate start.
710 const userStillHasLiveWork = Effect.fnUntraced(function* (userId: string) {
711 const now = yield* DateTime.now;
712 return yield* activityRows.listForUser({ userId }).pipe(
713 Effect.map((states) =>
714 states.some(
715 (state) =>
716 !isTerminalPhase(state) && !isExpiredAgentActivityState(state, now.epochMilliseconds),
717 ),
718 ),
719 Effect.catchCause((cause) =>
720 Effect.logWarning("live-work recheck failed; allowing queued start", { cause }).pipe(
721 Effect.as(true),
722 ),
723 ),
724 );
725 });
726
727 const stateIdentityIsCurrent = Effect.fnUntraced(function* (input: {
728 readonly userId: string;
729 readonly environmentId: string;
730 readonly threadId: string;
731 readonly phase: RelayAgentActivityAggregateState["activities"][number]["phase"];
732 readonly updatedAt: string;
733 }) {
734 return yield* activityRows
735 .getForUserThread({
736 userId: input.userId,
737 environmentId: input.environmentId,
738 threadId: input.threadId,
739 })
740 .pipe(
741 Effect.map(
742 (current) =>
743 current !== null &&
744 current.phase === input.phase &&
745 current.updatedAt === input.updatedAt,
746 ),
747 // A transient persistence failure must not permanently discard a
748 // legitimate alert. Fail open and let the signed job's retry/dedupe
749 // protections handle transport failures as usual.
750 Effect.catchCause((cause) =>
751 Effect.logWarning("agent-activity state recheck failed; allowing queued delivery", {
752 cause,
753 environmentId: input.environmentId,
754 threadId: input.threadId,
755 }).pipe(Effect.as(true)),
756 ),
757 );
758 });
759
760 const aggregateRowsAreCurrent = Effect.fnUntraced(function* (input: {
761 readonly userId: string;
762 readonly aggregate: RelayAgentActivityAggregateState;
763 }) {
764 return yield* activityRows.listForUser({ userId: input.userId }).pipe(
765 Effect.map((currentStates) => {
766 const currentByThread = new Map(
767 currentStates.map((current) => [
768 `${current.environmentId}\u0000${current.threadId}`,
769 current,
770 ]),
771 );
772 return input.aggregate.activities.every((row) => {
773 const current = currentByThread.get(`${row.environmentId}\u0000${row.threadId}`);
774 return (
775 current !== undefined &&
776 current.phase === row.phase &&
777 current.updatedAt === row.updatedAt
778 );
779 });
780 }),
781 Effect.catchCause((cause) =>
782 Effect.logWarning("agent-activity aggregate recheck failed; allowing queued delivery", {
783 cause,
784 userId: input.userId,
785 }).pipe(Effect.as(true)),
786 ),
787 );
788 });
789
790 const notificationStateIsCurrent = Effect.fnUntraced(function* (input: {
791 readonly userId: string;
792 readonly notification: ApnsNotificationPayload;
793 }) {
794 // Jobs from older relay versions do not carry a state identity. Preserve
795 // backwards compatibility and only revalidate newly queued jobs.
796 if (input.notification.phase === undefined || input.notification.updatedAt === undefined) {
797 return true;
798 }
799 return yield* stateIdentityIsCurrent({
800 userId: input.userId,
801 environmentId: input.notification.environmentId,
802 threadId: input.notification.threadId,
803 phase: input.notification.phase,
804 updatedAt: input.notification.updatedAt,
805 });
806 });
807
808 const isCurrentSignedJobToken = Effect.fnUntraced(function* (input: {
809 readonly target: LiveActivityDeliveryTarget;
810 readonly kind: RelayDeliveryKind;
811 readonly token: string;
812 }) {
813 return yield* liveActivities.listTargets({ userId: input.target.user_id }).pipe(
814 Effect.map((targets) => {
815 const currentTarget = targets.find((row) => row.device_id === input.target.device_id);
816 return (
817 currentTarget !== undefined &&
818 expectedCurrentToken({ target: currentTarget, kind: input.kind }) === input.token
819 );
820 }),
821 );
822 });
823
824 const sendLiveActivity: ApnsDeliveries["Service"]["sendLiveActivity"] = Effect.fn(
825 "relay.apns_deliveries.send_live_activity",
826 )(function* (input) {
827 yield* Effect.annotateCurrentSpan({
828 "relay.mobile.device_id": input.target.device_id,
829 "relay.delivery.kind": input.kind,
830 ...(input.sourceJobId ? { "relay.delivery.job_id": input.sourceJobId } : {}),
831 });
832 const now = yield* DateTime.now;
833 const aggregate =
834 input.aggregate === null ? null : sanitizeAgentActivityAggregateState(input.aggregate);
835 const { epochSeconds, iso, request } = makeLiveActivityDeliveryRequest(
836 apns,
837 { ...input, aggregate } as SendLiveActivityDeliveryInput,
838 now,
839 );
840 const recoverTransportError = (cause: Apns.ApnsError) =>
841 recoverApnsDeliveryTransportError(
842 {
843 deviceId: input.target.device_id,
844 kind: input.kind,
845 sourceJobId: input.sourceJobId ?? null,
846 },
847 cause,
848 );
849 if (input.sourceJobId) {
850 const claim = yield* attempts.claimSourceJob({
851 userId: input.target.user_id,
852 environmentId: null,
853 threadId: null,
854 deviceId: input.target.device_id,
855 kind: input.kind,
856 sourceJobId: input.sourceJobId,
857 token: input.token,
858 });
859 if (claim === "completed") {
860 return duplicateJobResult({ deviceId: input.target.device_id, kind: input.kind });
861 }
862 if (claim === "in_flight") {
863 return yield* new ApnsDeliveryJobClaimInFlight({ sourceJobId: input.sourceJobId });
864 }
865 const tokenIsCurrent = yield* isCurrentSignedJobToken({
866 target: input.target,
867 kind: input.kind,
868 token: input.token,
869 });
870 if (!tokenIsCurrent) {
871 yield* attempts.completeSourceJob({
872 sourceJobId: input.sourceJobId,
873 apnsReason: "Stale APNs delivery job skipped.",
874 });
875 return staleJobResult({ deviceId: input.target.device_id, kind: input.kind });
876 }
877 if (
878 input.kind !== "live_activity_start" &&
879 aggregate !== null &&
880 !(yield* aggregateRowsAreCurrent({
881 userId: input.target.user_id,
882 aggregate,
883 }))
884 ) {
885 yield* attempts.completeSourceJob({
886 sourceJobId: input.sourceJobId,
887 apnsReason: "Stale agent activity state skipped.",
888 });
889 return staleJobResult({ deviceId: input.target.device_id, kind: input.kind });
890 }
891 }
892 if (
893 input.kind === "live_activity_start" &&
894 !(yield* userStillHasLiveWork(input.target.user_id))
895 ) {
896 yield* liveActivities.clearStartQueued({
897 userId: input.target.user_id,
898 deviceId: input.target.device_id,
899 });
900 if (input.sourceJobId) {
901 yield* attempts.completeSourceJob({
902 sourceJobId: input.sourceJobId,
903 apnsReason: "Stale APNs start job skipped.",
904 });
905 }
906 return staleJobResult({ deviceId: input.target.device_id, kind: input.kind });
907 }
908 const result = yield* apns
909 .sendLiveActivityRequest({
910 credentials: credentialsForTarget(config.apns, input.target),
911 request,
912 issuedAtUnixSeconds: epochSeconds,
913 })
914 .pipe(
915 Effect.catchTags({
916 ApnsJwtEncodingError: recoverTransportError,
917 ApnsJwtSigningError: recoverTransportError,
918 ApnsHttpRequestError: recoverTransportError,
919 }),
920 );
921 if (result.ok) {
922 yield* liveActivities.markDelivery({
923 userId: input.target.user_id,
924 deviceId: input.target.device_id,
925 kind: input.kind,
926 aggregate,
927 deliveredAt: iso,
928 });
929 } else if (isPermanentApnsTokenFailure(result)) {
930 yield* liveActivities.invalidateDeliveryToken({
931 userId: input.target.user_id,
932 deviceId: input.target.device_id,
933 kind: input.kind,
934 invalidatedAt: iso,
935 });
936 } else if (input.kind === "live_activity_start") {
937 yield* liveActivities.clearStartQueued({
938 userId: input.target.user_id,
939 deviceId: input.target.device_id,
940 });
941 }
942 if (input.sourceJobId) {
943 yield* attempts.completeSourceJob({
944 sourceJobId: input.sourceJobId,
945 ...deliveryAttemptOutcome(result),
946 });
947 } else {
948 yield* attempts.record({
949 userId: input.target.user_id,
950 environmentId: null,
951 threadId: null,
952 deviceId: input.target.device_id,
953 kind: input.kind,
954 token: input.token,
955 ...deliveryAttemptOutcome(result),
956 });
957 }
958 return {
959 deviceId: input.target.device_id,
960 kind: input.kind,
961 ok: result.ok,
962 apnsStatus: result.status === 0 ? null : result.status,
963 apnsReason: result.reason ?? null,
964 apnsId: result.apnsId,
965 };
966 });
967
968 const sendPushNotification: ApnsDeliveries["Service"]["sendPushNotification"] = Effect.fn(
969 "relay.apns_deliveries.send_push_notification",
970 )(function* (input) {
971 yield* Effect.annotateCurrentSpan({
972 "relay.mobile.device_id": input.target.device_id,
973 "relay.delivery.kind": "push_notification",
974 ...(input.sourceJobId ? { "relay.delivery.job_id": input.sourceJobId } : {}),
975 });
976 const now = yield* DateTime.now;
977 const epochSeconds = Math.floor(now.epochMilliseconds / 1_000);
978 const notification = sanitizeApnsNotificationPayload(input.notification);
979 yield* Effect.annotateCurrentSpan({
980 "relay.environment_id": notification.environmentId,
981 "relay.thread_id": notification.threadId,
982 });
983 const request = apns.makePushNotificationRequest({
984 token: input.token,
985 notification,
986 });
987 const recoverTransportError = (cause: Apns.ApnsError) =>
988 recoverApnsDeliveryTransportError(
989 {
990 deviceId: input.target.device_id,
991 kind: "push_notification",
992 sourceJobId: input.sourceJobId ?? null,
993 },
994 cause,
995 );
996 if (input.sourceJobId) {
997 const claim = yield* attempts.claimSourceJob({
998 userId: input.target.user_id,
999 environmentId: notification.environmentId,
1000 threadId: notification.threadId,
1001 deviceId: input.target.device_id,
1002 kind: "push_notification",
1003 sourceJobId: input.sourceJobId,
1004 token: input.token,
1005 });
1006 if (claim === "completed") {
1007 return duplicateJobResult({
1008 deviceId: input.target.device_id,
1009 kind: "push_notification",
1010 });
1011 }
1012 if (claim === "in_flight") {
1013 return yield* new ApnsDeliveryJobClaimInFlight({ sourceJobId: input.sourceJobId });
1014 }
1015 const tokenIsCurrent = yield* isCurrentSignedJobToken({
1016 target: input.target,
1017 kind: "push_notification",
1018 token: input.token,
1019 });
1020 if (!tokenIsCurrent) {
1021 yield* attempts.completeSourceJob({
1022 sourceJobId: input.sourceJobId,
1023 apnsReason: "Stale APNs delivery job skipped.",
1024 });
1025 return staleJobResult({
1026 deviceId: input.target.device_id,
1027 kind: "push_notification",
1028 });
1029 }
1030 if (
1031 !(yield* notificationStateIsCurrent({
1032 userId: input.target.user_id,
1033 notification,
1034 }))
1035 ) {
1036 yield* attempts.completeSourceJob({
1037 sourceJobId: input.sourceJobId,
1038 apnsReason: "Stale agent activity state skipped.",
1039 });
1040 return staleJobResult({
1041 deviceId: input.target.device_id,
1042 kind: "push_notification",
1043 });
1044 }
1045 }
1046 const result = yield* apns
1047 .sendPushNotificationRequest({
1048 credentials: credentialsForTarget(config.apns, input.target),
1049 request,
1050 issuedAtUnixSeconds: epochSeconds,
1051 })
1052 .pipe(
1053 Effect.catchTags({
1054 ApnsJwtEncodingError: recoverTransportError,
1055 ApnsJwtSigningError: recoverTransportError,
1056 ApnsHttpRequestError: recoverTransportError,
1057 }),
1058 );
1059 if (isPermanentApnsTokenFailure(result)) {
1060 yield* liveActivities.invalidateDeliveryToken({
1061 userId: input.target.user_id,
1062 deviceId: input.target.device_id,
1063 kind: "push_notification",
1064 invalidatedAt: DateTime.formatIso(now),
1065 });
1066 }
1067 if (input.sourceJobId) {
1068 yield* attempts.completeSourceJob({
1069 sourceJobId: input.sourceJobId,
1070 ...deliveryAttemptOutcome(result),
1071 });
1072 } else {
1073 yield* attempts.record({
1074 userId: input.target.user_id,
1075 environmentId: notification.environmentId,
1076 threadId: notification.threadId,
1077 deviceId: input.target.device_id,
1078 kind: "push_notification",
1079 token: input.token,
1080 ...deliveryAttemptOutcome(result),
1081 });
1082 }
1083 return {
1084 deviceId: input.target.device_id,
1085 kind: "push_notification" as const,
1086 ok: result.ok,
1087 apnsStatus: result.status === 0 ? null : result.status,
1088 apnsReason: result.reason ?? null,
1089 apnsId: result.apnsId,
1090 };
1091 });
1092
1093 const processSignedJob: ApnsDeliveries["Service"]["processSignedJob"] = Effect.fn(
1094 "relay.apns_deliveries.process_signed_job",
1095 )(function* (body) {
1096 const signedJob = yield* decodeSignedApnsDeliveryJob(body).pipe(
1097 Effect.mapError(
1098 (cause) =>
1099 new ApnsDeliveryJobQueuePayloadInvalid({
1100 receivedType: Array.isArray(body) ? "array" : body === null ? "null" : typeof body,
1101 cause,
1102 }),
1103 ),
1104 );
1105 const now = yield* DateTime.now;
1106 const payload = verifySignedApnsDeliveryJob({
1107 secret: config.apnsDeliveryJobSigningSecret,
1108 job: signedJob,
1109 nowMs: now.epochMilliseconds,
1110 });
1111 if (isApnsDeliveryJobVerificationError(payload)) {
1112 return yield* payload;
1113 }
1114 yield* Effect.annotateCurrentSpan({
1115 "relay.mobile.device_id": payload.target.deviceId,
1116 "relay.delivery.kind": payload.kind,
1117 "relay.delivery.job_id": payload.jobId,
1118 });
1119 return yield* Effect.suspend(() => {
1120 switch (payload.kind) {
1121 case "live_activity_start":
1122 case "live_activity_update":
1123 if (payload.aggregate === null) {
1124 return Effect.fail(
1125 new ApnsDeliveryJobLiveActivityAggregateMissing({
1126 jobId: payload.jobId,
1127 kind: payload.kind,
1128 userId: payload.target.userId,
1129 deviceId: payload.target.deviceId,
1130 }),
1131 );
1132 }
1133 return sendLiveActivity({
1134 target: {
1135 user_id: payload.target.userId,
1136 device_id: payload.target.deviceId,
1137 bundle_id: payload.target.bundleId ?? null,
1138 aps_environment: payload.target.apsEnvironment ?? null,
1139 },
1140 token: payload.target.token,
1141 sourceJobId: payload.jobId,
1142 kind: payload.kind,
1143 aggregate: payload.aggregate,
1144 alert: payload.alert ?? null,
1145 });
1146 case "live_activity_end":
1147 return sendLiveActivity({
1148 target: {
1149 user_id: payload.target.userId,
1150 device_id: payload.target.deviceId,
1151 bundle_id: payload.target.bundleId ?? null,
1152 aps_environment: payload.target.apsEnvironment ?? null,
1153 },
1154 token: payload.target.token,
1155 sourceJobId: payload.jobId,
1156 kind: payload.kind,
1157 aggregate: payload.aggregate,
1158 alert: payload.alert ?? null,
1159 });
1160 case "push_notification":
1161 if (payload.notification === null) {
1162 return Effect.fail(
1163 new ApnsDeliveryJobPushNotificationMissing({
1164 jobId: payload.jobId,
1165 userId: payload.target.userId,
1166 deviceId: payload.target.deviceId,
1167 }),
1168 );
1169 }
1170 return sendPushNotification({
1171 target: {
1172 user_id: payload.target.userId,
1173 device_id: payload.target.deviceId,
1174 bundle_id: payload.target.bundleId ?? null,
1175 aps_environment: payload.target.apsEnvironment ?? null,
1176 },
1177 token: payload.target.token,
1178 sourceJobId: payload.jobId,
1179 notification: payload.notification,
1180 });
1181 }
1182 }).pipe(withSpanAttributes({ "user.id": payload.target.userId }));
1183 });
1184
1185 return ApnsDeliveries.of({
1186 sendLiveActivity,
1187 sendPushNotification,
1188 processSignedJob,
1189 sendPushNotificationForTarget: Effect.fnUntraced(function* (input) {
1190 const now = yield* DateTime.now;
1191 const notification = notificationForAggregate({
1192 target: input.target,
1193 aggregate: input.aggregate,
1194 nowMs: now.epochMilliseconds,
1195 });
1196 const token = input.target.push_token;
1197 return yield* notification && token
1198 ? deliveryQueue.enqueuePushNotification({
1199 userId: input.target.user_id,
1200 deviceId: input.target.device_id,
1201 token,
1202 bundleId: input.target.bundle_id,
1203 apsEnvironment: input.target.aps_environment,
1204 notification,
1205 })
1206 : Effect.succeed(null);
1207 }),
1208 sendForTarget: Effect.fnUntraced(function* (input) {
1209 const delivery = chooseDelivery({
1210 target: input.target,
1211 aggregate: input.aggregate,
1212 nowMs: input.nowMs,
1213 });
1214 if (!delivery) {
1215 return null;
1216 }
1217 if (delivery.kind === "push_notification") {
1218 const result = yield* deliveryQueue.enqueuePushNotification({
1219 userId: input.target.user_id,
1220 deviceId: input.target.device_id,
1221 token: delivery.token,
1222 bundleId: input.target.bundle_id,
1223 apsEnvironment: input.target.aps_environment,
1224 notification: delivery.notification,
1225 });
1226 return result;
1227 }
1228 const notification = notificationForAggregate({
1229 target: input.target,
1230 aggregate: input.aggregate,
1231 nowMs: input.nowMs,
1232 });
1233 // The end event doubles as the "task finished" moment. When a companion
1234 // push notification is about to ring the device (below), the activity end
1235 // stays silent; otherwise the end itself carries the alert so LA-only
1236 // users still get the buzz.
1237 const alert =
1238 delivery.kind === "live_activity_end"
1239 ? notification && input.target.push_token
1240 ? null
1241 : alertForTerminalAggregate({
1242 aggregate: delivery.aggregate,
1243 preferences: parsePreferences(input.target.preferences_json),
1244 })
1245 : delivery.alert;
1246 const result = yield* deliveryQueue.enqueueLiveActivity({
1247 userId: input.target.user_id,
1248 deviceId: input.target.device_id,
1249 kind: delivery.kind,
1250 token: delivery.token,
1251 bundleId: input.target.bundle_id,
1252 apsEnvironment: input.target.aps_environment,
1253 aggregate: delivery.aggregate,
1254 alert,
1255 });
1256 if (delivery.kind === "live_activity_end" && notification && input.target.push_token) {
1257 yield* deliveryQueue.enqueuePushNotification({
1258 userId: input.target.user_id,
1259 deviceId: input.target.device_id,
1260 token: input.target.push_token,
1261 bundleId: input.target.bundle_id,
1262 apsEnvironment: input.target.aps_environment,
1263 notification,
1264 });
1265 }
1266 if (delivery.kind === "live_activity_start") {
1267 const now = yield* DateTime.now;
1268 yield* liveActivities.markStartQueued({
1269 userId: input.target.user_id,
1270 deviceId: input.target.device_id,
1271 queuedAt: DateTime.formatIso(now),
1272 });
1273 }
1274 return result;
1275 }),
1276 });
1277});
1278
1279export const layer = Layer.effect(ApnsDeliveries, make);