@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 316 lines 10.7 KB
Raw
1 import * as cloudcontrolspartner from "@distilled.cloud/gcp/cloudcontrolspartner_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 customerName,
12 encodeDisplayName,
13 findOwnedCustomer,
14 getCustomer,
15 hasOwnershipMarker,
16 listCustomers,
17 listLocationParents,
18 locationParent,
19 normalizeLocation,
20 organizationIdOf,
21 organizationParent,
22 ownedByAlchemy,
23 ownershipLabels,
24 parseName,
25 parseOwnership,
26 replaceOn,
27 resolveOrganization,
28 sameText,
29 toCustomerId,
30 toCustomerResourceId,
31 toDisplayName,
32 tryResolveOrganization,
33 } from "./internal.ts";
34
35 export type CustomerOnboardingState = cloudcontrolspartner.CustomerOnboardingState;
36
37 export type CustomerProps = {
38 /**
39 * Partner organization (`organizations/{organization}` or the numeric
40 * id). Defaults to `GOOGLE_CLOUDCONTROLSPARTNER_ORGANIZATION`,
41 * `GOOGLE_ORGANIZATION_ID`, or the project's Resource Manager
42 * ancestor. Immutable — changing it replaces the customer.
43 */
44 organization?: string;
45 /**
46 * Partner-operated Google Cloud location (`us-central1`, …).
47 * Immutable — changing it replaces the customer. `US-CENTRAL1` is
48 * accepted and normalized to `us-central1`.
49 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
50 */
51 location?: string;
52 /**
53 * Customer Google Cloud organization id. Becomes the last segment of
54 * `organizations/{organization}/locations/{location}/customers/{customer}`.
55 * Required on create and must be a valid organization id. Immutable —
56 * changing it replaces the customer.
57 */
58 customerId?: string;
59 /**
60 * Display name for the customer. Cloud Controls Partner customers
61 * have no labels field, so Alchemy ownership is stored in a
62 * `[alchemy …]` prefix and stripped from attributes.
63 */
64 displayName?: string;
65 };
66
67 export type Customer = Resource<
68 "GCP.CloudControlsPartner.Customer",
69 CustomerProps,
70 {
71 /** Resource name `organizations/{organization}/locations/{location}/customers/{customer}`. */
72 name: string;
73 /** Customer organization id (last path segment). */
74 customerId: string;
75 /** Partner organization resource name. */
76 organization: string;
77 /** Partner organization id. */
78 organizationId: string;
79 /** Location id. */
80 location: string;
81 /** Parent `organizations/{organization}/locations/{location}`. */
82 parent: string;
83 /** Project id of the deploying stack. */
84 project: string;
85 /** User display name with the Alchemy ownership prefix stripped. */
86 displayName: string | undefined;
87 /** Customer organization domain extracted from Resource Manager. */
88 organizationDomain: string | undefined;
89 /** Whether the customer has finished onboarding. */
90 isOnboarded: boolean;
91 /** Onboarding step state reported by the partner API. */
92 customerOnboardingState: CustomerOnboardingState | undefined;
93 },
94 never,
95 Providers
96 >;
97
98 /**
99 * A Cloud Controls Partner customer of a sovereign-controls partner.
100 *
101 * Customers have no labels field — Alchemy stamps ownership into
102 * `displayName` for `list` / nuke. Partner organization, location, and
103 * customer organization id are identity. Display name updates in place.
104 *
105 * Creating customers requires Cloud Controls Partner (Sovereign
106 * Controls by Partners) access. The `customerId` must be the customer's
107 * Google Cloud organization id.
108 *
109 * ### Creating a Customer
110 * **Example:** Generated display name
111 * ```typescript
112 * const customer = yield* GCP.CloudControlsPartner.Customer("Acme", {
113 * organization: "organizations/123",
114 * location: "us-central1",
115 * customerId: "456",
116 * });
117 * ```
118 *
119 * **Example:** Explicit display name
120 * ```typescript
121 * const customer = yield* GCP.CloudControlsPartner.Customer("Acme", {
122 * organization: "123",
123 * customerId: "456",
124 * displayName: "Acme Corp",
125 * });
126 * ```
127 *
128 * ### Updating a Customer
129 * Re-declare the same logical id with changed props; the engine keeps the
130 * physical resource and updates it in place.
131 *
132 * **Example:** Rename
133 * ```typescript
134 * const customer = yield* GCP.CloudControlsPartner.Customer("Acme", {
135 * organization: "organizations/123",
136 * customerId: "456",
137 * displayName: "Acme Corporation",
138 * });
139 * ```
140 *
141 * @resource
142 * @category CloudControlsPartner
143 */
144 export const Customer = Resource<Customer>("GCP.CloudControlsPartner.Customer");
145
146 export class CustomerNotResolved extends Data.TaggedError(
147 "GCP.CloudControlsPartner.CustomerNotResolved",
148 )<{
149 resourceName: string;
150 }> {}
151
152 const toAttrs = (
153 customer: cloudcontrolspartner.Customer,
154 organization: string,
155 project: string,
156 ) => {
157 const name = customer.name ?? "";
158 const parsed = parseName(name);
159 const org = parsed.organization || organizationParent(organization);
160 return {
161 name,
162 customerId: parsed.customerId || toCustomerId(name) || "",
163 organization: org,
164 organizationId: organizationIdOf(org),
165 location: parsed.location,
166 parent: parsed.parent || locationParent(org, parsed.location),
167 project,
168 displayName: parseOwnership(customer.displayName).text,
169 organizationDomain: customer.organizationDomain,
170 isOnboarded: customer.isOnboarded === true,
171 customerOnboardingState: customer.customerOnboardingState,
172 };
173 };
174
175 export const CustomerProvider = () =>
176 Provider.succeed(Customer, {
177 stables: [
178 "name",
179 "customerId",
180 "organization",
181 "organizationId",
182 "location",
183 "parent",
184 "project",
185 "organizationDomain",
186 ],
187
188 diff: Effect.fn(function* ({ news, olds, output }) {
189 if (!isResolved(news)) return undefined;
190 const env = yield* GcpEnvironment.current;
191 const previousLocation = normalizeLocation(olds?.location ?? output?.location ?? env.region);
192 const nextLocation = normalizeLocation(
193 news.location ?? olds?.location ?? output?.location ?? env.region,
194 );
195 const previousOrg = olds?.organization ?? output?.organization;
196 const nextOrg = news.organization;
197 return (
198 replaceOn(
199 toCustomerId(olds?.customerId ?? output?.customerId),
200 toCustomerId(news.customerId),
201 ) ??
202 replaceOn(
203 previousOrg !== undefined ? organizationParent(previousOrg) : undefined,
204 nextOrg !== undefined ? organizationParent(nextOrg) : undefined,
205 ) ??
206 replaceOn(previousLocation, nextLocation)
207 );
208 }),
209
210 read: Effect.fn(function* ({ id, olds, output }) {
211 const env = yield* GcpEnvironment.current;
212 const organization = yield* resolveOrganization(
213 olds?.organization ?? output?.organization,
214 output?.organization,
215 );
216 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
217 const customerId = yield* toCustomerResourceId(
218 id,
219 olds?.customerId ?? output?.customerId,
220 output?.name,
221 );
222 const name = output?.name ?? customerName(organization, location, customerId);
223 let existing = yield* getCustomer(name);
224 if (existing === undefined) {
225 existing = yield* findOwnedCustomer(id, locationParent(organization, location));
226 }
227 if (existing === undefined) return undefined;
228 const attrs = toAttrs(existing, organization, env.project);
229 return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs);
230 }),
231
232 list: () =>
233 Effect.gen(function* () {
234 const env = yield* GcpEnvironment.current;
235 const organization = yield* tryResolveOrganization();
236 if (organization === undefined) return [];
237 const pages = yield* Effect.forEach(
238 listLocationParents(organization, env.region),
239 (parent) => listCustomers(parent),
240 { concurrency: 3 },
241 );
242 const byName = new Map<string, ReturnType<typeof toAttrs>>();
243 for (const customer of pages.flat()) {
244 if (!hasOwnershipMarker(customer.displayName)) continue;
245 const attrs = toAttrs(customer, organization, env.project);
246 if (attrs.name.length > 0) byName.set(attrs.name, attrs);
247 }
248 return [...byName.values()];
249 }),
250
251 reconcile: Effect.fn(function* ({ id, news, output }) {
252 const env = yield* GcpEnvironment.current;
253 const organization = yield* resolveOrganization(news.organization, output?.organization);
254 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
255 const customerId = yield* toCustomerResourceId(
256 id,
257 news.customerId,
258 output?.customerId ?? output?.name,
259 );
260 const parent = locationParent(organization, location);
261 const name = customerName(organization, location, customerId);
262 const ownership = yield* ownershipLabels(id);
263 const displayName = encodeDisplayName(
264 ownership,
265 yield* toDisplayName(id, news.displayName, output?.displayName),
266 );
267
268 let current = yield* getCustomer(output?.name ?? name);
269 if (current === undefined) {
270 current = yield* findOwnedCustomer(id, parent);
271 }
272
273 if (current === undefined) {
274 const created = yield* cloudcontrolspartner
275 .createOrganizationsLocationsCustomers({
276 parent,
277 customerId,
278 body: { displayName },
279 })
280 .pipe(
281 Effect.catchTag("Conflict", () =>
282 getCustomer(name).pipe(
283 Effect.flatMap((existing) =>
284 existing !== undefined ? Effect.succeed(existing) : findOwnedCustomer(id, parent),
285 ),
286 ),
287 ),
288 );
289 current = created ?? undefined;
290 }
291
292 if (current === undefined) {
293 return yield* new CustomerNotResolved({ resourceName: name });
294 }
295
296 const currentName = current.name ?? name;
297 if (!sameText(current.displayName, displayName) && currentName.length > 0) {
298 current = yield* cloudcontrolspartner.patchOrganizationsLocationsCustomers({
299 name: currentName,
300 updateMask: "display_name",
301 body: { displayName },
302 });
303 }
304
305 const latest = (yield* getCustomer(current.name ?? currentName)) ?? current;
306 return toAttrs(latest, organization, env.project);
307 }),
308
309 delete: Effect.fn(function* ({ output }) {
310 const name = output.name;
311 if (!name) return;
312 yield* cloudcontrolspartner
313 .deleteOrganizationsLocationsCustomers({ name })
314 .pipe(Effect.catchTag("NotFound", () => Effect.void));
315 }),
316 });