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

main
ts 122 lines 3.65 KB
Raw
1 import * as organizations from "@distilled.cloud/aws/organizations";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import { createInternalTags, diffTags } from "alchemy/Tags";
4 import * as Effect from "effect/Effect";
5 import * as Redacted from "effect/Redacted";
6 import * as Schedule from "effect/Schedule";
7
8 /**
9 * Distilled decodes `smithy.api#sensitive` strings (`Name`, `Email`,
10 * `MasterAccountEmail`) into `Redacted.Redacted<string>` at runtime.
11 * Attributes and equality checks must unwrap first — comparing the wrapper
12 * against a plain string is always `false` and would persist
13 * `{ "__redacted__": … }` into state.
14 */
15 export const unredact = (
16 value: string | Redacted.Redacted<string> | undefined,
17 ): string | undefined =>
18 value === undefined ? undefined : Redacted.isRedacted(value) ? Redacted.value(value) : value;
19
20 export type OrganizationsTags = Record<string, string>;
21
22 export const createName = (id: string, providedName: string | undefined, maxLength: number) =>
23 providedName
24 ? Effect.succeed(providedName)
25 : createPhysicalName({
26 id,
27 maxLength,
28 });
29
30 export const toTagRecord = (tags: organizations.Tag[] | undefined): OrganizationsTags =>
31 Object.fromEntries(
32 (tags ?? [])
33 .filter(
34 (tag): tag is { Key: string; Value: string } =>
35 typeof tag.Key === "string" && typeof tag.Value === "string",
36 )
37 .map((tag) => [tag.Key, tag.Value]),
38 );
39
40 export const collectPages = <Page extends { NextToken?: string }, Item, E, R>(
41 fetch: (nextToken?: string) => Effect.Effect<Page, E, R>,
42 select: (page: Page) => ReadonlyArray<Item> | undefined,
43 ) =>
44 Effect.gen(function* () {
45 const items: Item[] = [];
46 let nextToken: string | undefined;
47
48 do {
49 const page = yield* fetch(nextToken);
50 items.push(...(select(page) ?? []));
51 nextToken = page.NextToken;
52 } while (nextToken);
53
54 return items;
55 });
56
57 export const retryOrganizations = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
58 effect.pipe(
59 Effect.retry({
60 while: (error: any) =>
61 error?._tag === "ConcurrentModificationException" ||
62 error?._tag === "TooManyRequestsException" ||
63 error?._tag === "ServiceException" ||
64 error?._tag === "FinalizingOrganizationException",
65 schedule: Schedule.max([Schedule.exponential(200), Schedule.recurs(8)]),
66 }),
67 );
68
69 export const createManagedTags = Effect.fn(function* (
70 id: string,
71 tags: Record<string, string> | undefined,
72 ) {
73 return {
74 ...(yield* createInternalTags(id)),
75 ...tags,
76 };
77 });
78
79 export const readResourceTags = (resourceId: string) =>
80 collectPages(
81 (NextToken) => organizations.listTagsForResource({ ResourceId: resourceId, NextToken }),
82 (page) => page.Tags,
83 ).pipe(Effect.map(toTagRecord));
84
85 export const updateResourceTags = Effect.fn(function* ({
86 id,
87 resourceId,
88 olds,
89 news,
90 }: {
91 id: string;
92 resourceId: string;
93 olds: Record<string, string> | undefined;
94 news: Record<string, string> | undefined;
95 }) {
96 // `olds` is freshly read from AWS. Do not synthesize ownership tags into
97 // that baseline: doing so hides missing tags from the diff while returning
98 // them as if they had been persisted.
99 const oldTags = olds ?? {};
100 const newTags = yield* createManagedTags(id, news);
101 const { removed, upsert } = diffTags(oldTags, newTags);
102
103 if (removed.length > 0) {
104 yield* retryOrganizations(
105 organizations.untagResource({
106 ResourceId: resourceId,
107 TagKeys: removed,
108 }),
109 );
110 }
111
112 if (upsert.length > 0) {
113 yield* retryOrganizations(
114 organizations.tagResource({
115 ResourceId: resourceId,
116 Tags: upsert,
117 }),
118 );
119 }
120
121 return newTags;
122 });