The best way to control Claude Code, Codex and more from any computer or phone

main
ts 283 lines 10.2 KB
Raw
1 import * as sns from "@distilled.cloud/aws/sns";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Redacted from "effect/Redacted";
8 import * as Stream from "effect/Stream";
9 import { AWSEnvironment } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11
12 export type PlatformApplicationArn = string;
13
14 export interface PlatformApplicationProps {
15 /**
16 * Name of the platform application. Up to 256 characters of letters,
17 * numbers, underscores, hyphens, and periods.
18 * @default ${app}-${stage}-${id}
19 */
20 name?: string;
21 /**
22 * Push notification platform, e.g. `GCM` (Firebase Cloud Messaging),
23 * `APNS`, `APNS_SANDBOX`, `ADM`, or `BAIDU`. Changing the platform
24 * replaces the application.
25 */
26 platform: string;
27 /**
28 * Platform credential — the FCM API key / service account JSON (GCM), the
29 * APNS private key, or the ADM client secret. SNS validates the credential
30 * at creation time. Write-only: SNS never returns it, so it is pushed on
31 * create/adopt and whenever the configured value changes.
32 */
33 platformCredential: Redacted.Redacted<string>;
34 /**
35 * Platform principal — the APNS SSL certificate or ADM client id. Not
36 * applicable for GCM. Write-only like `platformCredential`.
37 */
38 platformPrincipal?: Redacted.Redacted<string>;
39 /**
40 * Additional mutable SNS platform application attributes keyed by AWS
41 * attribute name, such as `EventEndpointCreated`, `EventDeliveryFailure`,
42 * `SuccessFeedbackRoleArn`, or `SuccessFeedbackSampleRate`.
43 */
44 attributes?: Record<string, string>;
45 }
46
47 export interface PlatformApplication extends Resource<
48 "AWS.SNS.PlatformApplication",
49 PlatformApplicationProps,
50 {
51 /** ARN of the platform application. */
52 platformApplicationArn: PlatformApplicationArn;
53 /** Name of the platform application. */
54 name: string;
55 /** Push notification platform (e.g. `GCM`, `APNS`). */
56 platform: string;
57 /** Whether the platform application is enabled (credentials valid). */
58 enabled: boolean;
59 /** Observed non-sensitive SNS attributes keyed by AWS attribute name. */
60 attributes: Record<string, string>;
61 },
62 never,
63 Providers
64 > {}
65
66 /**
67 * An Amazon SNS platform application for mobile push notifications (FCM,
68 * APNS, ADM, Baidu).
69 *
70 * A platform application holds the push service credentials; device tokens
71 * are registered against it at runtime with the
72 * `CreatePlatformEndpoint` binding, and messages are delivered with
73 * `PublishToEndpoint`. SNS validates the credential when the application is
74 * created, so a real push-service credential is required.
75 * ### Creating Platform Applications
76 * **Example:** FCM (GCM) Application
77 * ```typescript
78 * import * as SNS from "@alchemy.run/aws/SNS";
79 * import * as Redacted from "effect/Redacted";
80 *
81 * const app = yield* SNS.PlatformApplication("PushApp", {
82 * platform: "GCM",
83 * platformCredential: Redacted.make(process.env.FCM_API_KEY!),
84 * });
85 * ```
86 *
87 * **Example:** APNS Application
88 * ```typescript
89 * const app = yield* SNS.PlatformApplication("IosPushApp", {
90 * platform: "APNS",
91 * platformCredential: Redacted.make(apnsPrivateKey),
92 * platformPrincipal: Redacted.make(apnsCertificate),
93 * });
94 * ```
95 *
96 * ### Runtime Endpoints
97 * **Example:** Register a Device Token at Runtime
98 * ```typescript
99 * // init
100 * const createEndpoint = yield* SNS.CreatePlatformEndpoint(app);
101 * const publishToEndpoint = yield* SNS.PublishToEndpoint(app);
102 *
103 * // runtime
104 * const endpoint = yield* createEndpoint({ Token: deviceToken });
105 * yield* publishToEndpoint({
106 * TargetArn: endpoint.EndpointArn!,
107 * Message: "hello",
108 * });
109 * ```
110 *
111 * @resource
112 */
113 export const PlatformApplication = Resource<PlatformApplication>("AWS.SNS.PlatformApplication");
114
115 export const PlatformApplicationProvider = () =>
116 Provider.succeed(PlatformApplication, {
117 list: Effect.fn(function* () {
118 const applications = yield* sns.listPlatformApplications.pages({}).pipe(
119 Stream.runCollect,
120 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.PlatformApplications ?? [])),
121 );
122
123 return applications.flatMap((application) => {
124 const arn = application.PlatformApplicationArn;
125 if (!arn) return [];
126 return [toApplicationAttributes(arn, application.Attributes)];
127 });
128 }),
129 read: Effect.fn(function* ({ id, olds, output }) {
130 const arn =
131 output?.platformApplicationArn ?? (yield* toApplicationArn(id, olds ?? { platform: "" }));
132 return yield* readApplication(arn);
133 }),
134 stables: ["platformApplicationArn", "name", "platform"],
135 diff: Effect.fn(function* ({ id, news, olds }) {
136 if (!isResolved(news)) return undefined;
137 if (news.platform !== olds.platform) {
138 return { action: "replace" } as const;
139 }
140 const oldName = yield* toApplicationName(id, olds);
141 const newName = yield* toApplicationName(id, news);
142 if (oldName !== newName) {
143 return { action: "replace" } as const;
144 }
145 }),
146 reconcile: Effect.fn(function* ({ id, news, olds, output, session }) {
147 const name = yield* toApplicationName(id, news);
148 const arn = output?.platformApplicationArn ?? (yield* toApplicationArn(id, news));
149
150 // Observe — the credential attributes are write-only, so observation
151 // covers existence plus the non-sensitive mutable attributes.
152 const observed = yield* sns
153 .getPlatformApplicationAttributes({ PlatformApplicationArn: arn })
154 .pipe(
155 Effect.map((response) => toAttributeMap(response.Attributes)),
156 Effect.catchTag("NotFoundException", () => Effect.undefined),
157 );
158
159 const credentialAttributes: Record<string, string> = {
160 PlatformCredential: Redacted.value(news.platformCredential),
161 ...(news.platformPrincipal
162 ? { PlatformPrincipal: Redacted.value(news.platformPrincipal) }
163 : undefined),
164 };
165 const desiredAttributes = toAttributeMap(news.attributes);
166
167 // Ensure — create carries the full attribute set (credentials +
168 // mutable attributes) in one call.
169 if (observed === undefined) {
170 const created = yield* sns.createPlatformApplication({
171 Name: name,
172 Platform: news.platform,
173 Attributes: { ...desiredAttributes, ...credentialAttributes },
174 });
175 const platformApplicationArn = created.PlatformApplicationArn ?? arn;
176 yield* session.note(platformApplicationArn);
177 const state = yield* readApplication(platformApplicationArn);
178 return state ?? toApplicationAttributes(platformApplicationArn, desiredAttributes);
179 }
180
181 // Sync — mutable non-secret attributes diff observed vs desired;
182 // removed previously-managed keys reset to "". Credentials cannot be
183 // observed, so they are pushed on adoption (`olds` absent) or when the
184 // configured value changes (`olds` is only a hint to skip a no-op).
185 const updates: Record<string, string> = {};
186 for (const [key, value] of Object.entries(desiredAttributes)) {
187 if (observed[key] !== value) {
188 updates[key] = value;
189 }
190 }
191 for (const key of Object.keys(toAttributeMap(olds?.attributes))) {
192 if (!(key in desiredAttributes)) {
193 updates[key] = "";
194 }
195 }
196
197 const credentialChanged =
198 olds === undefined ||
199 Redacted.value(olds.platformCredential) !== Redacted.value(news.platformCredential) ||
200 (olds.platformPrincipal === undefined) !== (news.platformPrincipal === undefined) ||
201 (olds.platformPrincipal !== undefined &&
202 news.platformPrincipal !== undefined &&
203 Redacted.value(olds.platformPrincipal) !== Redacted.value(news.platformPrincipal));
204 if (credentialChanged) {
205 Object.assign(updates, credentialAttributes);
206 }
207
208 if (Object.keys(updates).length > 0) {
209 yield* sns.setPlatformApplicationAttributes({
210 PlatformApplicationArn: arn,
211 Attributes: updates,
212 });
213 }
214
215 yield* session.note(arn);
216 const state = yield* readApplication(arn);
217 return state ?? toApplicationAttributes(arn, desiredAttributes);
218 }),
219 delete: Effect.fn(function* ({ output }) {
220 // `DeletePlatformApplication` is idempotent — deleting a non-existent
221 // application succeeds — so only genuine failures propagate.
222 yield* sns.deletePlatformApplication({
223 PlatformApplicationArn: output.platformApplicationArn,
224 });
225 }),
226 });
227
228 const toApplicationName = Effect.fn(function* (
229 id: string,
230 props: Pick<PlatformApplicationProps, "name">,
231 ) {
232 if (props.name) {
233 return props.name;
234 }
235 return yield* createPhysicalName({ id, maxLength: 256 });
236 });
237
238 const toApplicationArn = Effect.fn(function* (
239 id: string,
240 props: Pick<PlatformApplicationProps, "name" | "platform">,
241 ) {
242 const name = yield* toApplicationName(id, props);
243 const { accountId, region } = yield* AWSEnvironment.current;
244 return `arn:aws:sns:${region}:${accountId}:app/${props.platform}/${name}`;
245 });
246
247 const toAttributeMap = (
248 attributes: Record<string, string | undefined> | undefined,
249 ): Record<string, string> =>
250 Object.fromEntries(
251 Object.entries(attributes ?? {}).filter(
252 (entry): entry is [string, string] => typeof entry[1] === "string",
253 ),
254 );
255
256 const toApplicationAttributes = (
257 arn: string,
258 attributes: Record<string, string | undefined> | undefined,
259 ) => {
260 const observed = toAttributeMap(attributes);
261 // arn:aws:sns:{region}:{account}:app/{Platform}/{Name}
262 const [, platform = "", name = ""] = arn.split(":").at(-1)?.split("/") ?? [];
263 return {
264 platformApplicationArn: arn,
265 name,
266 platform,
267 enabled: observed.Enabled !== "false",
268 attributes: observed,
269 };
270 };
271
272 const readApplication = Effect.fn(function* (arn: string) {
273 const observed = yield* sns
274 .getPlatformApplicationAttributes({ PlatformApplicationArn: arn })
275 .pipe(
276 Effect.map((response) => toAttributeMap(response.Attributes)),
277 Effect.catchTag("NotFoundException", () => Effect.undefined),
278 );
279 if (observed === undefined) {
280 return undefined;
281 }
282 return toApplicationAttributes(arn, observed);
283 });