Open History to see the last commit
1import * as Alchemy from "alchemy";
2import * as Cloudflare from "alchemy/Cloudflare";
3import * as Crypto from "effect/Crypto";
4import * as Context from "effect/Context";
5import * as DateTime from "effect/DateTime";
6import * as Effect from "effect/Effect";
7import * as Layer from "effect/Layer";
8import * as Schema from "effect/Schema";
9
10import {
11 RelayDeliveryKind as RelayDeliveryKindSchema,
12 type RelayDeliveryResult,
13} from "@t3tools/contracts/relay";
14
15import {
16 sanitizeAgentActivityAggregateState,
17 sanitizeApnsNotificationPayload,
18} from "./agentActivityPayloads.ts";
19import {
20 expiresAtForJob,
21 makeApnsDeliveryJobPayload,
22 signApnsDeliveryJob,
23 type ApnsDeliveryJobPayload,
24 type SignedApnsDeliveryJob,
25} from "./apnsDeliveryJobs.ts";
26import * as RelayConfiguration from "../Config.ts";
27
28export class ApnsDeliveryQueueSendError extends Schema.TaggedErrorClass<ApnsDeliveryQueueSendError>()(
29 "ApnsDeliveryQueueSendError",
30 {
31 operation: Schema.Literals(["generate-job-id", "send"]),
32 jobId: Schema.NullOr(Schema.String),
33 kind: RelayDeliveryKindSchema,
34 userId: Schema.String,
35 deviceId: Schema.String,
36 cause: Schema.Defect(),
37 },
38) {
39 override get message(): string {
40 return `Failed to enqueue APNs ${this.kind.replaceAll("_", " ")} delivery during ${this.operation} for device ${this.deviceId}.`;
41 }
42}
43
44export type ApnsDeliveryQueueError = ApnsDeliveryQueueSendError;
45
46export class ApnsDeliveryQueueSender extends Context.Service<
47 ApnsDeliveryQueueSender,
48 {
49 readonly send: (body: SignedApnsDeliveryJob) => Effect.Effect<void, Cloudflare.QueueSendError>;
50 }
51>()("t3code-relay/agentActivity/ApnsDeliveryQueue/ApnsDeliveryQueueSender") {}
52
53export class ApnsDeliveryQueue extends Context.Service<
54 ApnsDeliveryQueue,
55 {
56 readonly enqueueLiveActivity: (input: {
57 readonly kind: ApnsDeliveryJobPayload["kind"];
58 readonly userId: string;
59 readonly deviceId: string;
60 readonly token: string;
61 readonly bundleId?: string | null;
62 readonly apsEnvironment?: "sandbox" | "production" | null;
63 readonly aggregate: ApnsDeliveryJobPayload["aggregate"];
64 readonly alert?: ApnsDeliveryJobPayload["alert"];
65 }) => Effect.Effect<RelayDeliveryResult, ApnsDeliveryQueueError>;
66 readonly enqueuePushNotification: (input: {
67 readonly userId: string;
68 readonly deviceId: string;
69 readonly token: string;
70 readonly bundleId?: string | null;
71 readonly apsEnvironment?: "sandbox" | "production" | null;
72 readonly notification: NonNullable<ApnsDeliveryJobPayload["notification"]>;
73 }) => Effect.Effect<RelayDeliveryResult, ApnsDeliveryQueueError>;
74 }
75>()("t3code-relay/agentActivity/ApnsDeliveryQueue") {}
76
77export const make = Effect.gen(function* () {
78 const sender = yield* ApnsDeliveryQueueSender;
79 const crypto = yield* Crypto.Crypto;
80 const config = yield* RelayConfiguration.RelayConfiguration;
81
82 return ApnsDeliveryQueue.of({
83 enqueueLiveActivity: Effect.fn("relay.apns_delivery_queue.enqueue_live_activity")(
84 function* (input) {
85 yield* Effect.annotateCurrentSpan({
86 "relay.mobile.device_id": input.deviceId,
87 "relay.delivery.kind": input.kind,
88 });
89 const now = yield* DateTime.now;
90 const jobId = yield* crypto.randomUUIDv4.pipe(
91 Effect.mapError(
92 (cause) =>
93 new ApnsDeliveryQueueSendError({
94 operation: "generate-job-id",
95 jobId: null,
96 kind: input.kind,
97 userId: input.userId,
98 deviceId: input.deviceId,
99 cause,
100 }),
101 ),
102 );
103 yield* Effect.annotateCurrentSpan({ "relay.delivery.job_id": jobId });
104 const payload = makeApnsDeliveryJobPayload({
105 ...input,
106 aggregate:
107 input.aggregate === null ? null : sanitizeAgentActivityAggregateState(input.aggregate),
108 jobId,
109 createdAt: DateTime.formatIso(now),
110 expiresAt: expiresAtForJob(now.epochMilliseconds),
111 });
112 const signed = signApnsDeliveryJob({
113 secret: config.apnsDeliveryJobSigningSecret,
114 payload,
115 });
116 yield* sender.send(signed).pipe(
117 Effect.mapError(
118 (cause) =>
119 new ApnsDeliveryQueueSendError({
120 operation: "send",
121 jobId,
122 kind: input.kind,
123 userId: input.userId,
124 deviceId: input.deviceId,
125 cause,
126 }),
127 ),
128 );
129 return {
130 deviceId: input.deviceId,
131 kind: input.kind,
132 ok: true,
133 queued: true,
134 apnsStatus: null,
135 apnsReason: null,
136 apnsId: null,
137 };
138 },
139 ),
140 enqueuePushNotification: Effect.fn("relay.apns_delivery_queue.enqueue_push_notification")(
141 function* (input) {
142 yield* Effect.annotateCurrentSpan({
143 "relay.mobile.device_id": input.deviceId,
144 "relay.delivery.kind": "push_notification",
145 "relay.environment_id": input.notification.environmentId,
146 "relay.thread_id": input.notification.threadId,
147 });
148 const now = yield* DateTime.now;
149 const jobId = yield* crypto.randomUUIDv4.pipe(
150 Effect.mapError(
151 (cause) =>
152 new ApnsDeliveryQueueSendError({
153 operation: "generate-job-id",
154 jobId: null,
155 kind: "push_notification",
156 userId: input.userId,
157 deviceId: input.deviceId,
158 cause,
159 }),
160 ),
161 );
162 yield* Effect.annotateCurrentSpan({ "relay.delivery.job_id": jobId });
163 const payload = makeApnsDeliveryJobPayload({
164 kind: "push_notification",
165 userId: input.userId,
166 deviceId: input.deviceId,
167 token: input.token,
168 bundleId: input.bundleId,
169 apsEnvironment: input.apsEnvironment,
170 aggregate: null,
171 notification: sanitizeApnsNotificationPayload(input.notification),
172 jobId,
173 createdAt: DateTime.formatIso(now),
174 expiresAt: expiresAtForJob(now.epochMilliseconds),
175 });
176 const signed = signApnsDeliveryJob({
177 secret: config.apnsDeliveryJobSigningSecret,
178 payload,
179 });
180 yield* sender.send(signed).pipe(
181 Effect.mapError(
182 (cause) =>
183 new ApnsDeliveryQueueSendError({
184 operation: "send",
185 jobId,
186 kind: "push_notification",
187 userId: input.userId,
188 deviceId: input.deviceId,
189 cause,
190 }),
191 ),
192 );
193 return {
194 deviceId: input.deviceId,
195 kind: "push_notification" as const,
196 ok: true,
197 queued: true,
198 apnsStatus: null,
199 apnsReason: null,
200 apnsId: null,
201 };
202 },
203 ),
204 });
205});
206
207export const layer = Layer.effect(ApnsDeliveryQueue, make);
208
209export const layerCloudflareQueues = (
210 sender: Cloudflare.QueueSender,
211 alchemyRuntimeContext: Alchemy.BaseRuntimeContext,
212) =>
213 layer.pipe(
214 Layer.provide(
215 Layer.succeed(
216 ApnsDeliveryQueueSender,
217 ApnsDeliveryQueueSender.of({
218 send: (body) =>
219 sender
220 .send(body)
221 .pipe(Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext)),
222 }),
223 ),
224 ),
225 );