@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, 04:45 UTC

main
ts 247 lines 8.37 KB
Raw
1 import * as ssoAdmin from "@distilled.cloud/aws/sso-admin";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import type { Providers } from "../Providers.ts";
8 import {
9 listInstances,
10 resolveInstance,
11 retryIdentityCenter,
12 toInstanceAttributes,
13 } from "./common.ts";
14
15 export class InstanceInvalidProps extends Data.TaggedError("InstanceInvalidProps")<{
16 readonly message: string;
17 readonly cause?: unknown;
18 }> {}
19
20 export class InstanceUnexpectedResponse extends Data.TaggedError("InstanceUnexpectedResponse")<{
21 readonly message: string;
22 readonly cause?: unknown;
23 }> {}
24
25 export interface InstanceProps {
26 /**
27 * Explicit instance ARN to adopt.
28 */
29 instanceArn?: string;
30 /**
31 * Friendly instance name.
32 *
33 * When `mode` is `"account"`, this name is passed to `CreateInstance`.
34 * When `mode` is `"existing"`, it is used only for discovery.
35 */
36 name?: string;
37 /**
38 * How Alchemy should satisfy this resource.
39 *
40 * `existing` adopts a visible instance and fails if none is found.
41 * `account` creates an account instance when no visible instance matches.
42 *
43 * Organization instances cannot currently be enabled via public API, so
44 * organization-management-account deployments should use `existing`.
45 *
46 * @default "existing"
47 */
48 mode?: "existing" | "account";
49 }
50
51 export interface Instance extends Resource<
52 "AWS.IdentityCenter.Instance",
53 InstanceProps,
54 {
55 /** The ARN of the Identity Center instance. */
56 instanceArn: string;
57 /** The identity store backing the instance. */
58 identityStoreId: string;
59 /** The AWS account that owns the instance. */
60 ownerAccountId: string | undefined;
61 /** The friendly name of the instance, if set. */
62 name: string | undefined;
63 /** The current status of the instance (`ACTIVE`, ...). */
64 status: string | undefined;
65 /** Details when the instance is in a failed state. */
66 statusReason: string | undefined;
67 /** When the instance was created. */
68 createdDate: Date | undefined;
69 /** How the resource was satisfied: `existing` (adopted) or `account` (created). */
70 mode: "existing" | "account";
71 },
72 never,
73 Providers
74 > {}
75
76 /**
77 * An IAM Identity Center instance visible to the current account.
78 *
79 * Use `mode: "existing"` to adopt a pre-enabled organization instance. Use
80 * `mode: "account"` only for standalone or member-account account instances.
81 * ### Discovering Existing Instances
82 * **Example:** Adopt An Existing Instance
83 * ```typescript
84 * const instance = yield* Instance("IdentityCenter", {
85 * mode: "existing",
86 * });
87 * ```
88 *
89 * ### Creating Account Instances
90 * **Example:** Create A Member Account Instance
91 * ```typescript
92 * const instance = yield* Instance("IdentityCenter", {
93 * mode: "account",
94 * name: "customer-a",
95 * });
96 * ```
97 *
98 * @resource
99 */
100 export const Instance = Resource<Instance>("AWS.IdentityCenter.Instance");
101
102 export const InstanceProvider = () =>
103 Provider.effect(
104 Instance,
105 Effect.gen(function* () {
106 return {
107 stables: ["instanceArn", "identityStoreId", "ownerAccountId", "mode"],
108 // Enumerate every Identity Center instance visible to the calling
109 // account (organization + account instances). `ListInstances` is
110 // paginated and fully hydrates each `InstanceMetadata`, so no
111 // per-item read is needed. Accounts with no SSO enabled return an
112 // empty list (not an error). Each item is mapped to the exact `read`
113 // Attributes shape; `mode` defaults to "existing" since enumeration
114 // only observes pre-existing instances.
115 list: () =>
116 Effect.gen(function* () {
117 const instances = yield* listInstances();
118 return instances
119 .filter(
120 (
121 instance,
122 ): instance is ssoAdmin.InstanceMetadata & {
123 InstanceArn: string;
124 IdentityStoreId: string;
125 } => instance.InstanceArn != null && instance.IdentityStoreId != null,
126 )
127 .map((instance) => ({
128 ...toInstanceAttributes(instance),
129 mode: "existing" as const,
130 }));
131 }),
132 diff: Effect.fn(function* ({ olds, news, output }) {
133 if (!isResolved(news)) return;
134 // `instanceArn` and `name` select which instance to adopt. Adding,
135 // removing, or pinning one that matches the adopted instance is a
136 // noop; only a selector pointing at a different instance replaces.
137 // A replace in `account` mode deletes the old instance, so it must
138 // never fire for the same instance.
139 if (
140 (news.instanceArn !== undefined &&
141 news.instanceArn !== (output?.instanceArn ?? olds?.instanceArn)) ||
142 (news.name !== undefined && news.name !== (output?.name ?? olds?.name)) ||
143 (news.mode ?? "existing") !== (output?.mode ?? olds?.mode ?? "existing")
144 ) {
145 return { action: "replace" } as const;
146 }
147 }),
148 read: Effect.fn(function* ({ olds, output }) {
149 const mode = output?.mode ?? olds?.mode ?? "existing";
150 const instance = yield* readInstance({
151 instanceArn: output?.instanceArn ?? olds?.instanceArn,
152 name: olds?.name,
153 });
154 return instance ? { ...instance, mode } : undefined;
155 }),
156 reconcile: Effect.fn(function* ({ news, output, session }) {
157 const mode = output?.mode ?? news.mode ?? "existing";
158
159 // Observe — try to find a visible instance, preferring an
160 // explicit ARN (from output or props) and otherwise scanning
161 // the account.
162 const existing = yield* readInstance({
163 instanceArn: output?.instanceArn ?? news.instanceArn,
164 name: news.name,
165 });
166 if (existing) {
167 yield* session.note(existing.instanceArn);
168 return {
169 ...existing,
170 mode,
171 };
172 }
173
174 // Ensure — for `existing` mode we cannot create one; fail.
175 // Organization instances must be enabled manually in the
176 // management account.
177 if (mode !== "account") {
178 return yield* new InstanceInvalidProps({
179 message:
180 "No visible Identity Center instance was found. Organization instances must be enabled manually in the management account before Alchemy can adopt them.",
181 });
182 }
183
184 // Ensure — `account` mode creates an account instance.
185 const response = yield* retryIdentityCenter(
186 ssoAdmin.createInstance({
187 Name: news.name,
188 }),
189 );
190
191 const created = yield* readInstance({
192 instanceArn: response.InstanceArn,
193 name: news.name,
194 });
195 if (!created) {
196 return yield* new InstanceUnexpectedResponse({
197 message: "failed to resolve Identity Center instance after create",
198 });
199 }
200
201 yield* session.note(created.instanceArn);
202 return {
203 ...created,
204 mode,
205 };
206 }),
207 delete: Effect.fn(function* ({ output }) {
208 if (output.mode !== "account") {
209 return;
210 }
211
212 const existing = yield* readInstance({
213 instanceArn: output.instanceArn,
214 });
215 if (!existing) {
216 return;
217 }
218
219 yield* retryIdentityCenter(
220 ssoAdmin.deleteInstance({
221 InstanceArn: output.instanceArn,
222 }),
223 );
224 }),
225 };
226 }),
227 );
228
229 const readInstance = Effect.fn(function* ({
230 instanceArn,
231 name,
232 }: Pick<InstanceProps, "instanceArn" | "name">) {
233 if (instanceArn) {
234 const instance = yield* resolveInstance(instanceArn).pipe(
235 Effect.orElseSucceed(() => undefined),
236 );
237 return instance ? toInstanceAttributes(instance) : undefined;
238 }
239
240 const instances = yield* listInstances();
241 const match =
242 instances.find((instance) => instance.Name === name) ??
243 (instances.length === 1 ? instances[0] : undefined) ??
244 instances.find((instance) => instance.Status === "ACTIVE");
245
246 return match?.InstanceArn && match.IdentityStoreId ? toInstanceAttributes(match) : undefined;
247 });