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

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