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

main
ts 257 lines 7.78 KB
Raw
1 import * as sasportal from "@distilled.cloud/gcp/sasportal_v1alpha1";
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 encodeOwnershipLine,
12 expandCustomer,
13 findOwnedCustomerNode,
14 getCustomerNode,
15 hasOwnershipMarker,
16 lastSegment,
17 listCustomerNodes,
18 listCustomers,
19 MAX_DISPLAY_NAME_LENGTH,
20 ownedByAlchemy,
21 ownershipLabels,
22 parentOf,
23 parseOwnership,
24 replaceOnIdentity,
25 retryDelete,
26 sameStringList,
27 sameText,
28 scanOwnedCustomerNode,
29 toDisplayName,
30 updateMaskOf,
31 waitUntilGone,
32 } from "./internal.ts";
33
34 export type CustomersNodeProps = {
35 /**
36 * Parent SAS customer, as `customers/{customer}` or the customer id.
37 * Immutable — changing it replaces the node.
38 */
39 parent: string;
40 /**
41 * Server-assigned node resource name
42 * (`customers/{customer}/nodes/{node}`). Immutable — changing it
43 * replaces the node.
44 */
45 name?: string;
46 /**
47 * Display name. SAS Portal nodes have no labels field, so Alchemy
48 * stamps ownership into a `[alchemy …]` prefix and strips it from
49 * attributes.
50 */
51 displayName?: string;
52 /**
53 * SAS user ids used by devices that belong to this node.
54 */
55 sasUserIds?: string[];
56 };
57
58 export type CustomersNode = Resource<
59 "GCP.SasPortal.CustomersNode",
60 CustomersNodeProps,
61 {
62 /** Resource name `customers/{customer}/nodes/{node}`. */
63 name: string;
64 /** Node id (last path segment). */
65 nodeId: string;
66 /** Parent customer resource name. */
67 parent: string;
68 /** Project id used when the node was reconciled. */
69 project: string;
70 /** User-facing display name with the Alchemy prefix stripped. */
71 displayName: string | undefined;
72 /** SAS user ids on the node. */
73 sasUserIds: string[] | undefined;
74 },
75 never,
76 Providers
77 >;
78
79 /**
80 * A Spectrum Access System (SAS) Portal node under a customer.
81 *
82 * SAS Portal nodes have no labels field, so Alchemy stamps ownership
83 * into `displayName` for `list` / nuke. Parent customer is identity.
84 * Display name and SAS user ids update in place.
85 *
86 * ### Creating a Node
87 * **Example:** Generated display name
88 * ```typescript
89 * const node = yield* GCP.SasPortal.CustomersNode("Region", {
90 * parent: "customers/123",
91 * });
92 * ```
93 *
94 * **Example:** Explicit name and SAS user ids
95 * ```typescript
96 * const node = yield* GCP.SasPortal.CustomersNode("Region", {
97 * parent: "customers/123",
98 * displayName: "west",
99 * sasUserIds: ["operator-1"],
100 * });
101 * ```
102 *
103 * ### Updating a Node
104 * Change props on the same logical id; the engine keeps the physical id.
105 *
106 * **Example:** Rename
107 * ```typescript
108 * const node = yield* GCP.SasPortal.CustomersNode("Region", {
109 * parent: "customers/123",
110 * displayName: "west-2",
111 * });
112 * ```
113 *
114 * @resource
115 * @category SasPortal
116 */
117 export const CustomersNode = Resource<CustomersNode>("GCP.SasPortal.CustomersNode");
118
119 export class CustomersNodeNotResolved extends Data.TaggedError(
120 "GCP.SasPortal.CustomersNodeNotResolved",
121 )<{
122 parent: string;
123 resourceName: string;
124 }> {}
125
126 const toAttrs = (node: sasportal.SasPortalNode, parent: string, project: string) => {
127 const name = node.name ?? "";
128 return {
129 name,
130 nodeId: lastSegment(name),
131 parent: parentOf(name) || parent,
132 project,
133 displayName: parseOwnership(node.displayName).text,
134 sasUserIds: node.sasUserIds,
135 };
136 };
137
138 export const CustomersNodeProvider = () =>
139 Provider.succeed(CustomersNode, {
140 stables: ["name", "nodeId", "parent", "project"],
141
142 diff: Effect.fn(function* ({ news, olds, output }) {
143 if (!isResolved(news)) return undefined;
144 return replaceOnIdentity({
145 previousParent: olds?.parent ?? output?.parent,
146 nextParent: expandCustomer(news.parent),
147 previousId: olds?.name ?? output?.name,
148 nextId: news.name,
149 });
150 }),
151
152 read: Effect.fn(function* ({ id, olds, output }) {
153 const env = yield* GcpEnvironment.current;
154 const parent = expandCustomer(olds?.parent ?? output?.parent ?? "");
155 const name = olds?.name ?? output?.name ?? "";
156 let existing = yield* getCustomerNode(name);
157 let locatedParent = existing ? parentOf(existing.name ?? "") || parent : parent;
158 if (existing === undefined) {
159 const found =
160 (yield* findOwnedCustomerNode(id, parent)) ?? (yield* scanOwnedCustomerNode(id));
161 existing = found?.row;
162 locatedParent = found?.parent ?? locatedParent;
163 }
164 if (existing === undefined) return undefined;
165 const attrs = toAttrs(existing, locatedParent, env.project);
166 return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs);
167 }),
168
169 list: () =>
170 Effect.gen(function* () {
171 const env = yield* GcpEnvironment.current;
172 const customers = yield* listCustomers();
173 const pages = yield* Effect.forEach(
174 customers,
175 (customer) =>
176 customer.name
177 ? listCustomerNodes(customer.name).pipe(
178 Effect.map((rows) =>
179 rows
180 .filter((row) => hasOwnershipMarker(row.displayName))
181 .map((row) => toAttrs(row, customer.name ?? "", env.project)),
182 ),
183 )
184 : Effect.succeed([]),
185 { concurrency: 4 },
186 );
187 return pages.flat();
188 }),
189
190 reconcile: Effect.fn(function* ({ id, news, output }) {
191 const env = yield* GcpEnvironment.current;
192 const parent = expandCustomer(news.parent);
193 const ownership = yield* ownershipLabels(id);
194 const displayName = encodeOwnershipLine(
195 ownership,
196 yield* toDisplayName(id, news.displayName, output?.displayName),
197 MAX_DISPLAY_NAME_LENGTH,
198 );
199 const desired: sasportal.SasPortalNode = {
200 displayName,
201 sasUserIds: news.sasUserIds,
202 };
203
204 let current = yield* getCustomerNode(news.name ?? output?.name ?? "");
205 if (current === undefined) {
206 const found =
207 (yield* findOwnedCustomerNode(id, parent)) ?? (yield* scanOwnedCustomerNode(id));
208 current = found?.row;
209 }
210
211 if (current === undefined) {
212 const created = yield* sasportal
213 .createCustomersNodes({
214 parent,
215 body: desired,
216 })
217 .pipe(
218 Effect.catchTag("Conflict", () =>
219 findOwnedCustomerNode(id, parent).pipe(Effect.map((found) => found?.row)),
220 ),
221 );
222 current = created ?? undefined;
223 }
224
225 if (current === undefined) {
226 return yield* new CustomersNodeNotResolved({
227 parent,
228 resourceName: news.name ?? output?.name ?? displayName,
229 });
230 }
231
232 const name = current.name ?? news.name ?? output?.name ?? "";
233 const nameChanged = !sameText(current.displayName, displayName);
234 const usersChanged =
235 news.sasUserIds !== undefined && !sameStringList(current.sasUserIds, news.sasUserIds);
236 if (nameChanged || usersChanged) {
237 current = yield* sasportal.patchCustomersNodes({
238 name,
239 updateMask: updateMaskOf(
240 "displayName",
241 news.sasUserIds !== undefined ? "sasUserIds" : undefined,
242 ),
243 body: desired,
244 });
245 }
246
247 return toAttrs(current, parent, env.project);
248 }),
249
250 delete: Effect.fn(function* ({ output }) {
251 if (!output.name) return;
252 yield* retryDelete(sasportal.deleteCustomersNodes({ name: output.name })).pipe(
253 Effect.catchTag("NotFound", () => Effect.void),
254 );
255 yield* waitUntilGone(getCustomerNode(output.name));
256 }),
257 });