@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 161 lines 5.22 KB
Raw
1 import * as amp from "@distilled.cloud/aws/amp";
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 * Id of the AMP workspace the policy is attached to. A workspace has at
12 * most one resource-based policy. Changing the workspace replaces the
13 * policy.
14 */
15 workspaceId: string;
16 /**
17 * The IAM resource-based policy document (JSON) that grants other
18 * principals or accounts access to the workspace (e.g. `aps:RemoteWrite`,
19 * `aps:QueryMetrics`). Updated in place.
20 */
21 policyDocument: string;
22 }
23
24 export interface ResourcePolicy extends Resource<
25 "AWS.AMP.ResourcePolicy",
26 ResourcePolicyProps,
27 {
28 workspaceId: string;
29 policyStatus: string;
30 revisionId: string;
31 },
32 never,
33 Providers
34 > {}
35
36 /**
37 * The resource-based policy of an Amazon Managed Service for Prometheus
38 * workspace — grants cross-account or fine-grained same-account access to
39 * the workspace's data plane (remote-write, query). A workspace has at most
40 * one.
41 *
42 * ### Creating a Resource Policy
43 * **Example:** Allow Another Account to Query the Workspace
44 * ```typescript
45 * const workspace = yield* AMP.Workspace("Metrics", {});
46 * const policy = yield* AMP.ResourcePolicy("Sharing", {
47 * workspaceId: workspace.workspaceId,
48 * policyDocument: JSON.stringify({
49 * Version: "2012-10-17",
50 * Statement: [
51 * {
52 * Effect: "Allow",
53 * Principal: { AWS: "arn:aws:iam::123456789012:root" },
54 * Action: ["aps:QueryMetrics"],
55 * Resource: workspace.workspaceArn,
56 * },
57 * ],
58 * }),
59 * });
60 * ```
61 *
62 * @resource
63 */
64 export const ResourcePolicy = Resource<ResourcePolicy>("AWS.AMP.ResourcePolicy");
65
66 /** Order-insensitive canonical form of a JSON policy document. */
67 const canonicalJson = (document: string): string => {
68 const sort = (value: unknown): unknown =>
69 Array.isArray(value)
70 ? value.map(sort)
71 : value !== null && typeof value === "object"
72 ? Object.fromEntries(
73 Object.entries(value as Record<string, unknown>)
74 .sort(([a], [b]) => a.localeCompare(b))
75 .map(([k, v]) => [k, sort(v)]),
76 )
77 : value;
78 try {
79 return JSON.stringify(sort(JSON.parse(document)));
80 } catch {
81 return document;
82 }
83 };
84
85 export const ResourcePolicyProvider = () =>
86 Provider.effect(
87 ResourcePolicy,
88 Effect.gen(function* () {
89 /** Describe the policy; typed not-found → undefined. */
90 const describe = Effect.fn(function* (workspaceId: string) {
91 return yield* amp
92 .describeResourcePolicy({ workspaceId })
93 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
94 });
95
96 const toAttrs = (
97 workspaceId: string,
98 policy: { policyStatus: string; revisionId: string },
99 ) => ({
100 workspaceId,
101 policyStatus: policy.policyStatus,
102 revisionId: policy.revisionId,
103 });
104
105 return {
106 stables: ["workspaceId"],
107
108 diff: Effect.fn(function* ({ olds, news }) {
109 if (!isResolved(news)) return undefined;
110 if (olds?.workspaceId !== news.workspaceId) {
111 return { action: "replace" } as const;
112 }
113 }),
114
115 read: Effect.fn(function* ({ olds, output }) {
116 const workspaceId = output?.workspaceId ?? olds?.workspaceId;
117 if (!workspaceId) return undefined;
118 const policy = yield* describe(workspaceId);
119 if (policy === undefined) return undefined;
120 // Resource policies are not taggable — ownership is implied by
121 // the owned parent workspace.
122 return toAttrs(workspaceId, policy);
123 }),
124
125 reconcile: Effect.fn(function* ({ news, session }) {
126 const workspaceId = news!.workspaceId;
127
128 // 1. Observe — the live policy is authoritative.
129 const existing = yield* describe(workspaceId);
130
131 // 2/3. Ensure + sync — `putResourcePolicy` is a true upsert;
132 // call it only when the canonical document drifts.
133 const policy =
134 existing !== undefined &&
135 canonicalJson(existing.policyDocument) === canonicalJson(news!.policyDocument)
136 ? existing
137 : yield* amp.putResourcePolicy({
138 workspaceId,
139 policyDocument: news!.policyDocument,
140 revisionId: existing?.revisionId,
141 });
142
143 yield* session.note(workspaceId);
144 return toAttrs(workspaceId, policy);
145 }),
146
147 delete: Effect.fn(function* ({ output }) {
148 yield* amp.deleteResourcePolicy({ workspaceId: output.workspaceId }).pipe(
149 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
150 Effect.retry({
151 while: (e) => e._tag === "ConflictException",
152 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(20)]),
153 }),
154 );
155 }),
156
157 // Singleton sub-resource keyed by its parent workspace.
158 list: () => Effect.succeed([]),
159 };
160 }),
161 );