Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ApnsDeliveryQueue.ts

218 lines7.0 KB

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 }
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 aggregate: ApnsDeliveryJobPayload["aggregate"];
62 }) => Effect.Effect<RelayDeliveryResult, ApnsDeliveryQueueError>;
63 readonly enqueuePushNotification: (input: {
64 readonly userId: string;
65 readonly deviceId: string;
66 readonly token: string;
67 readonly notification: NonNullable<ApnsDeliveryJobPayload["notification"]>;
68 }) => Effect.Effect<RelayDeliveryResult, ApnsDeliveryQueueError>;
69 }
70>()("t3code-relay/agentActivity/ApnsDeliveryQueue") {}
71​
72export const make = Effect.gen(function* () {
73 const sender = yield* ApnsDeliveryQueueSender;
74 const crypto = yield* Crypto.Crypto;
75 const config = yield* RelayConfiguration.RelayConfiguration;
76​
77 return ApnsDeliveryQueue.of({
78 enqueueLiveActivity: Effect.fn("relay.apns_delivery_queue.enqueue_live_activity")(
79 function* (input) {
80 yield* Effect.annotateCurrentSpan({
81 "relay.mobile.device_id": input.deviceId,
82 "relay.delivery.kind": input.kind,
83 });
84 const now = yield* DateTime.now;
85 const jobId = yield* crypto.randomUUIDv4.pipe(
86 Effect.mapError(
87 (cause) =>
88 new ApnsDeliveryQueueSendError({
89 operation: "generate-job-id",
90 jobId: null,
91 kind: input.kind,
92 userId: input.userId,
93 deviceId: input.deviceId,
94 cause,
95 }),
96 ),
97 );
98 yield* Effect.annotateCurrentSpan({ "relay.delivery.job_id": jobId });
99 const payload = makeApnsDeliveryJobPayload({
100 ...input,
101 aggregate:
102 input.aggregate === null ? null : sanitizeAgentActivityAggregateState(input.aggregate),
103 jobId,
104 createdAt: DateTime.formatIso(now),
105 expiresAt: expiresAtForJob(now.epochMilliseconds),
106 });
107 const signed = signApnsDeliveryJob({
108 secret: config.apnsDeliveryJobSigningSecret,
109 payload,
110 });
111 yield* sender.send(signed).pipe(
112 Effect.mapError(
113 (cause) =>
114 new ApnsDeliveryQueueSendError({
115 operation: "send",
116 jobId,
117 kind: input.kind,
118 userId: input.userId,
119 deviceId: input.deviceId,
120 cause,
121 }),
122 ),
123 );
124 return {
125 deviceId: input.deviceId,
126 kind: input.kind,
127 ok: true,
128 queued: true,
129 apnsStatus: null,
130 apnsReason: null,
131 apnsId: null,
132 };
133 },
134 ),
135 enqueuePushNotification: Effect.fn("relay.apns_delivery_queue.enqueue_push_notification")(
136 function* (input) {
137 yield* Effect.annotateCurrentSpan({
138 "relay.mobile.device_id": input.deviceId,
139 "relay.delivery.kind": "push_notification",
140 "relay.environment_id": input.notification.environmentId,
141 "relay.thread_id": input.notification.threadId,
142 });
143 const now = yield* DateTime.now;
144 const jobId = yield* crypto.randomUUIDv4.pipe(
145 Effect.mapError(
146 (cause) =>
147 new ApnsDeliveryQueueSendError({
148 operation: "generate-job-id",
149 jobId: null,
150 kind: "push_notification",
151 userId: input.userId,
152 deviceId: input.deviceId,
153 cause,
154 }),
155 ),
156 );
157 yield* Effect.annotateCurrentSpan({ "relay.delivery.job_id": jobId });
158 const payload = makeApnsDeliveryJobPayload({
159 kind: "push_notification",
160 userId: input.userId,
161 deviceId: input.deviceId,
162 token: input.token,
163 aggregate: null,
164 notification: sanitizeApnsNotificationPayload(input.notification),
165 jobId,
166 createdAt: DateTime.formatIso(now),
167 expiresAt: expiresAtForJob(now.epochMilliseconds),
168 });
169 const signed = signApnsDeliveryJob({
170 secret: config.apnsDeliveryJobSigningSecret,
171 payload,
172 });
173 yield* sender.send(signed).pipe(
174 Effect.mapError(
175 (cause) =>
176 new ApnsDeliveryQueueSendError({
177 operation: "send",
178 jobId,
179 kind: "push_notification",
180 userId: input.userId,
181 deviceId: input.deviceId,
182 cause,
183 }),
184 ),
185 );
186 return {
187 deviceId: input.deviceId,
188 kind: "push_notification" as const,
189 ok: true,
190 queued: true,
191 apnsStatus: null,
192 apnsReason: null,
193 apnsId: null,
194 };
195 },
196 ),
197 });
198});
199​
200export const layer = Layer.effect(ApnsDeliveryQueue, make);
201​
202export const layerCloudflareQueues = (
203 sender: Cloudflare.QueueSender,
204 alchemyRuntimeContext: Alchemy.BaseRuntimeContext,
205) =>
206 layer.pipe(
207 Layer.provide(
208 Layer.succeed(
209 ApnsDeliveryQueueSender,
210 ApnsDeliveryQueueSender.of({
211 send: (body) =>
212 sender
213 .send(body)
214 .pipe(Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext)),
215 }),
216 ),
217 ),
218 );