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

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