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

main
ts 245 lines 8.81 KB
Raw
1 import * as b2bi from "@distilled.cloud/aws/b2bi";
2 import * as logs from "@distilled.cloud/aws/cloudwatch-logs";
3 import { unownedUnlessPrevious } from "alchemy/AdoptPolicy";
4 import { isResolved } from "alchemy/Diff";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Redacted from "effect/Redacted";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import { readB2biTags, syncB2biTags, toWireTags } from "./internal.ts";
13
14 export interface ProfileProps {
15 /**
16 * The name of the profile.
17 */
18 name: string;
19 /**
20 * Name for the business associated with this profile.
21 */
22 businessName: string;
23 /**
24 * The phone number associated with the business, in E.164 format
25 * (e.g. `+1234567890`).
26 */
27 phone: string;
28 /**
29 * The email address associated with this customer profile.
30 */
31 email?: string;
32 /**
33 * Whether Amazon Web Services logs each event in an Amazon CloudWatch log
34 * group for the profile. Immutable after creation — changing it replaces
35 * the profile.
36 * @default "ENABLED"
37 */
38 logging?: "ENABLED" | "DISABLED";
39 /**
40 * User-defined tags for the profile.
41 */
42 tags?: Record<string, string>;
43 }
44
45 export interface Profile extends Resource<
46 "AWS.B2BI.Profile",
47 ProfileProps,
48 {
49 /**
50 * Service-assigned unique ID of the profile.
51 */
52 profileId: string;
53 /**
54 * ARN of the profile.
55 */
56 profileArn: string;
57 /**
58 * Name of the profile.
59 */
60 name: string;
61 /**
62 * Business name associated with the profile.
63 */
64 businessName: string;
65 /**
66 * CloudWatch log group created for the profile when logging is enabled.
67 */
68 logGroupName: string | undefined;
69 },
70 never,
71 Providers
72 > {}
73
74 /**
75 * An AWS B2B Data Interchange (B2BI) customer profile. A profile is the
76 * mechanism used to model a distinct private network; you can have up to
77 * five profiles per account. Profiles are credential-free and fully
78 * self-service, so their lifecycle is directly testable.
79 * ### Creating a Profile
80 * **Example:** Basic Profile
81 * ```typescript
82 * const profile = yield* B2BI.Profile("Acme", {
83 * name: "Acme Trading",
84 * businessName: "Acme Corp",
85 * phone: "+15555550100",
86 * email: "edi@acme.example",
87 * });
88 * ```
89 *
90 * ### Disabling CloudWatch Logging
91 * **Example:** Logging Disabled
92 * ```typescript
93 * const profile = yield* B2BI.Profile("Acme", {
94 * name: "Acme Trading",
95 * businessName: "Acme Corp",
96 * phone: "+15555550100",
97 * logging: "DISABLED",
98 * });
99 * ```
100 *
101 * @resource
102 */
103 export const Profile = Resource<Profile>("AWS.B2BI.Profile");
104
105 const toAttrs = (r: b2bi.GetProfileResponse | b2bi.CreateProfileResponse) => ({
106 profileId: r.profileId,
107 profileArn: r.profileArn,
108 name: r.name,
109 businessName: r.businessName,
110 logGroupName: r.logGroupName,
111 });
112
113 export const ProfileProvider = () =>
114 Provider.effect(
115 Profile,
116 Effect.gen(function* () {
117 /** Find a profile by its user-facing name across all pages. */
118 const findByName = (name: string) =>
119 b2bi.listProfiles.items({}).pipe(
120 Stream.filter((s) => s.name === name),
121 Stream.runHead,
122 Effect.flatMap((head) =>
123 head._tag === "Some"
124 ? b2bi
125 .getProfile({ profileId: head.value.profileId })
126 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined))
127 : Effect.undefined,
128 ),
129 );
130
131 return {
132 stables: ["profileId", "profileArn"],
133
134 diff: Effect.fn(function* ({ olds = {}, news }) {
135 if (!isResolved(news)) return undefined;
136 // logging has no member on updateProfile — it is immutable after
137 // create, so a change forces a replacement. Delete-first: profiles
138 // are recovered by name (findByName) and capped at 5 per account.
139 if ((olds.logging ?? "ENABLED") !== (news.logging ?? "ENABLED")) {
140 return { action: "replace", deleteFirst: true } as const;
141 }
142 }),
143
144 read: Effect.fn(function* ({ id, olds, output, previous }) {
145 const found = output?.profileId
146 ? yield* b2bi
147 .getProfile({ profileId: output.profileId })
148 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined))
149 : yield* findByName(olds?.name ?? "");
150 if (found === undefined) return undefined;
151 const attrs = toAttrs(found);
152 const tags = yield* readB2biTags(attrs.profileArn);
153 return (yield* hasAlchemyTags(id, tags))
154 ? attrs
155 : unownedUnlessPrevious(attrs, previous, "profileId");
156 }),
157
158 reconcile: Effect.fn(function* ({ id, news, output, session }) {
159 const internalTags = yield* createInternalTags(id);
160 const desiredTags = { ...internalTags, ...news.tags };
161
162 // 1. Observe — cloud state is authoritative; output caches the id.
163 let live = output?.profileId
164 ? yield* b2bi
165 .getProfile({ profileId: output.profileId })
166 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined))
167 : yield* findByName(news.name);
168
169 // 2. Ensure — create if missing.
170 if (live === undefined) {
171 const created = yield* b2bi.createProfile({
172 name: news.name,
173 businessName: news.businessName,
174 phone: news.phone,
175 email: news.email,
176 logging: news.logging ?? "ENABLED",
177 tags: toWireTags(desiredTags),
178 });
179 live = yield* b2bi.getProfile({ profileId: created.profileId });
180 } else {
181 // 3. Sync — converge mutable settings (name/businessName/phone/
182 // email). logging is immutable after create (diff replaces).
183 // phone/email are sensitive members that may decode as Redacted.
184 const unwrap = (v: string | Redacted.Redacted<string> | undefined) =>
185 Redacted.isRedacted(v) ? Redacted.value(v) : v;
186 const nameDrift = live.name !== news.name;
187 const bizDrift = live.businessName !== news.businessName;
188 const phoneDrift = unwrap(live.phone) !== news.phone;
189 const emailDrift = news.email !== undefined && unwrap(live.email) !== news.email;
190 if (nameDrift || bizDrift || phoneDrift || emailDrift) {
191 yield* b2bi.updateProfile({
192 profileId: live.profileId,
193 name: news.name,
194 businessName: news.businessName,
195 phone: news.phone,
196 email: news.email,
197 });
198 live = yield* b2bi.getProfile({ profileId: live.profileId });
199 }
200 }
201
202 // 3b. Sync tags against observed cloud tags.
203 yield* syncB2biTags(live.profileArn, desiredTags);
204
205 yield* session.note(live.profileId);
206 return toAttrs(live);
207 }),
208
209 delete: Effect.fn(function* ({ output }) {
210 yield* b2bi
211 .deleteProfile({ profileId: output.profileId })
212 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
213 // B2BI auto-creates /aws/vendedlogs/b2bi/profile/{profileId} when
214 // logging is ENABLED and deleteProfile does NOT remove it — every
215 // deleted profile would leak an orphaned log group. Reap it
216 // (idempotently) using the service-reported name when available.
217 const logGroupName =
218 output.logGroupName ?? `/aws/vendedlogs/b2bi/profile/${output.profileId}`;
219 yield* logs
220 .deleteLogGroup({ logGroupName })
221 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
222 // NOTE: profile creation also auto-creates the shared account-level
223 // /aws/vendedlogs/b2bi/default log group. That group is a
224 // service-managed singleton and MUST NOT be reaped here: B2BI's
225 // internal log-delivery bookkeeping references it, and deleting it
226 // opens a ~60-90s window where subsequent B2BI creates in the
227 // account fail with "Unable to perform CreateLogDelivery"
228 // (verified live with /aws/vendedlogs/b2bi/transformers).
229 }),
230
231 list: () =>
232 b2bi.listProfiles.items({}).pipe(
233 Stream.mapEffect((s) =>
234 b2bi.getProfile({ profileId: s.profileId }).pipe(
235 Effect.map(toAttrs),
236 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
237 ),
238 ),
239 Stream.filter((item) => item !== undefined),
240 Stream.runCollect,
241 Effect.map((chunk) => Array.from(chunk)),
242 ),
243 };
244 }),
245 );