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

main
ts 173 lines 5.74 KB
Raw
1 import * as rum from "@distilled.cloud/aws/rum";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Schedule from "effect/Schedule";
7 import type { Providers } from "../Providers.ts";
8
9 export interface ResourcePolicyProps {
10 /**
11 * Name of the CloudWatch RUM app monitor the policy is attached to. An app
12 * monitor has at most one resource-based policy. Changing the app monitor
13 * replaces the policy.
14 */
15 appMonitorName: string;
16 /**
17 * The IAM resource-based policy document (JSON) that controls who may send
18 * events to the app monitor. RUM only accepts `rum:PutRumEvents` as the
19 * statement action. Updated in place. Maximum size is 4 KB.
20 */
21 policyDocument: string;
22 }
23
24 export interface ResourcePolicy extends Resource<
25 "AWS.RUM.ResourcePolicy",
26 ResourcePolicyProps,
27 {
28 /**
29 * Name of the app monitor the policy is attached to.
30 */
31 appMonitorName: string;
32 /**
33 * Revision id of the policy document, changed on every update.
34 */
35 policyRevisionId: string | undefined;
36 },
37 never,
38 Providers
39 > {}
40
41 /**
42 * The resource-based policy of a CloudWatch RUM app monitor — controls which
43 * principals may send events to (`rum:PutRumEvents`) or read data from the
44 * app monitor. An app monitor has at most one.
45 *
46 * ### Creating a Resource Policy
47 * **Example:** Allow the Account to Send RUM Events
48 * ```typescript
49 * const monitor = yield* RUM.AppMonitor("SiteMonitor", {
50 * domain: "example.com",
51 * });
52 * const policy = yield* RUM.ResourcePolicy("SitePolicy", {
53 * appMonitorName: monitor.appMonitorName,
54 * policyDocument: monitor.appMonitorArn.map((arn) =>
55 * JSON.stringify({
56 * Version: "2012-10-17",
57 * Statement: [
58 * {
59 * Effect: "Allow",
60 * Principal: { AWS: "arn:aws:iam::123456789012:root" },
61 * Action: ["rum:PutRumEvents"],
62 * Resource: arn,
63 * },
64 * ],
65 * }),
66 * ),
67 * });
68 * ```
69 *
70 * @resource
71 */
72 export const ResourcePolicy = Resource<ResourcePolicy>("AWS.RUM.ResourcePolicy");
73
74 /** Order-insensitive canonical form of a JSON policy document. */
75 const canonicalJson = (document: string): string => {
76 const sort = (value: unknown): unknown =>
77 Array.isArray(value)
78 ? value.map(sort)
79 : value !== null && typeof value === "object"
80 ? Object.fromEntries(
81 Object.entries(value as Record<string, unknown>)
82 .sort(([a], [b]) => a.localeCompare(b))
83 .map(([k, v]) => [k, sort(v)]),
84 )
85 : value;
86 try {
87 return JSON.stringify(sort(JSON.parse(document)));
88 } catch {
89 return document;
90 }
91 };
92
93 export const ResourcePolicyProvider = () =>
94 Provider.effect(
95 ResourcePolicy,
96 Effect.gen(function* () {
97 /** Read the live policy; typed not-found (policy or monitor) → undefined. */
98 const describe = Effect.fn(function* (appMonitorName: string) {
99 return yield* rum
100 .getResourcePolicy({ Name: appMonitorName })
101 .pipe(
102 Effect.catchTag(
103 ["PolicyNotFoundException", "ResourceNotFoundException"],
104 () => Effect.undefined,
105 ),
106 );
107 });
108
109 return {
110 stables: ["appMonitorName"],
111
112 diff: Effect.fn(function* ({ olds, news }) {
113 if (!isResolved(news)) return undefined;
114 if (olds?.appMonitorName !== news.appMonitorName) {
115 return { action: "replace" } as const;
116 }
117 }),
118
119 read: Effect.fn(function* ({ olds, output }) {
120 const appMonitorName = output?.appMonitorName ?? olds?.appMonitorName;
121 if (!appMonitorName) return undefined;
122 const policy = yield* describe(appMonitorName);
123 if (policy === undefined) return undefined;
124 // Resource policies are not taggable — ownership is implied by the
125 // owned parent app monitor.
126 return { appMonitorName, policyRevisionId: policy.PolicyRevisionId };
127 }),
128
129 reconcile: Effect.fn(function* ({ news, session }) {
130 const appMonitorName = news!.appMonitorName;
131
132 // 1. Observe — the live policy is authoritative.
133 const existing = yield* describe(appMonitorName);
134
135 // 2/3. Ensure + sync — `putResourcePolicy` is a true upsert; call
136 // it only when the canonical document drifts (the observed
137 // revision id guards against concurrent writers).
138 const policy =
139 existing?.PolicyDocument !== undefined &&
140 canonicalJson(existing.PolicyDocument) === canonicalJson(news!.policyDocument)
141 ? existing
142 : yield* rum.putResourcePolicy({
143 Name: appMonitorName,
144 PolicyDocument: news!.policyDocument,
145 PolicyRevisionId: existing?.PolicyRevisionId,
146 });
147
148 yield* session.note(appMonitorName);
149 return {
150 appMonitorName,
151 policyRevisionId: policy.PolicyRevisionId,
152 };
153 }),
154
155 delete: Effect.fn(function* ({ output }) {
156 yield* rum.deleteResourcePolicy({ Name: output.appMonitorName }).pipe(
157 // idempotent — the policy (or its whole monitor) may be gone
158 Effect.catchTag(
159 ["PolicyNotFoundException", "ResourceNotFoundException"],
160 () => Effect.void,
161 ),
162 Effect.retry({
163 while: (e) => e._tag === "ConflictException",
164 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(8)]),
165 }),
166 );
167 }),
168
169 // Singleton sub-resource keyed by its parent app monitor.
170 list: () => Effect.succeed([]),
171 };
172 }),
173 );