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

main
ts 326 lines 10.5 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 deviceBody,
12 deviceConfigOf,
13 deviceGrantsOf,
14 deviceMetadataOf,
15 encodeOwnershipLine,
16 expandPath,
17 findOwnedNodeNodeDevice,
18 frequencyRangesOf,
19 getNodeDevice,
20 hasOwnershipMarker,
21 lastSegment,
22 listNodeNodeDevices,
23 MAX_DISPLAY_NAME_LENGTH,
24 ownedByAlchemy,
25 ownershipLabels,
26 parentOf,
27 parseOwnership,
28 replaceOnIdentity,
29 retryDelete,
30 sameJson,
31 sameText,
32 scanOwnedNodeNodeDevice,
33 toDisplayName,
34 toSerialNumber,
35 updateMaskOf,
36 waitUntilGone,
37 walkNodeChildren,
38 type DeviceConfig,
39 type DeviceGrant,
40 type DeviceMetadata,
41 type FrequencyRange,
42 } from "./internal.ts";
43
44 export type NodesNodesDeviceProps = {
45 /**
46 * Parent nested SAS node, as `nodes/{node}/nodes/{node}`.
47 * Immutable — changing it replaces the device.
48 */
49 parent: string;
50 /**
51 * Server-assigned device resource name
52 * (`nodes/{node}/nodes/{node}/devices/{device}`). Immutable — changing it
53 * replaces the device.
54 */
55 name?: string;
56 /**
57 * Display name. SAS Portal devices have no labels field, so Alchemy
58 * stamps ownership into a `[alchemy …]` prefix and strips it from
59 * attributes.
60 */
61 displayName?: string;
62 /**
63 * Manufacturer serial number. Immutable — changing it replaces the
64 * device.
65 */
66 serialNumber?: string;
67 /**
68 * FCC identifier of the CBSD. Immutable — changing it replaces the
69 * device.
70 */
71 fccId?: string;
72 /**
73 * Frequency ranges available for new grants.
74 */
75 grantRangeAllowlists?: FrequencyRange[];
76 /**
77 * Device configuration supplied through the SAS Portal API.
78 */
79 preloadedConfig?: DeviceConfig;
80 /**
81 * Overridable device metadata (ICG, CCG, antenna model).
82 */
83 deviceMetadata?: DeviceMetadata;
84 };
85
86 export type NodesNodesDevice = Resource<
87 "GCP.SasPortal.NodesNodesDevice",
88 NodesNodesDeviceProps,
89 {
90 /** Resource name `nodes/{node}/nodes/{node}/devices/{device}`. */
91 name: string;
92 /** Device id (last path segment). */
93 deviceId: string;
94 /** Parent resource name. */
95 parent: string;
96 /** Project id used when the device was reconciled. */
97 project: string;
98 /** User-facing display name with the Alchemy prefix stripped. */
99 displayName: string | undefined;
100 /** Manufacturer serial number. */
101 serialNumber: string | undefined;
102 /** FCC identifier. */
103 fccId: string | undefined;
104 /** Grant-range allowlists. */
105 grantRangeAllowlists: FrequencyRange[] | undefined;
106 /** Portal-supplied configuration. */
107 preloadedConfig: DeviceConfig | undefined;
108 /** Current SAS-registered configuration. */
109 activeConfig: DeviceConfig | undefined;
110 /** Overridable device metadata. */
111 deviceMetadata: DeviceMetadata | undefined;
112 /** Device state. */
113 state: string | undefined;
114 /** Grants held by the device. */
115 grants: DeviceGrant[] | undefined;
116 },
117 never,
118 Providers
119 >;
120
121 /**
122 * A Spectrum Access System (SAS) Portal CBSD under a nested node.
123 *
124 * SAS Portal devices have no labels field, so Alchemy stamps ownership
125 * into `displayName` for `list` / nuke. Parent, FCC id, and serial
126 * number are identity. Display name, grant allowlists, preloaded
127 * config, and metadata update in place.
128 *
129 * ### Creating a Device
130 * **Example:** Category A CBSD
131 * ```typescript
132 * const device = yield* GCP.SasPortal.NodesNodesDevice("Cbsd", {
133 * parent: child.name,
134 * displayName: "sector-a",
135 * fccId: "TESTFCC",
136 * serialNumber: "SN1001",
137 * });
138 * ```
139 *
140 * ### Updating a Device
141 * Change props on the same logical id; the engine keeps the physical id.
142 *
143 * **Example:** Rename
144 * ```typescript
145 * const device = yield* GCP.SasPortal.NodesNodesDevice("Cbsd", {
146 * parent: child.name,
147 * displayName: "sector-a-2",
148 * fccId: "TESTFCC",
149 * serialNumber: "SN1001",
150 * });
151 * ```
152 *
153 * @resource
154 * @category SasPortal
155 */
156 export const NodesNodesDevice = Resource<NodesNodesDevice>("GCP.SasPortal.NodesNodesDevice");
157
158 export class NodesNodesDeviceNotResolved extends Data.TaggedError(
159 "GCP.SasPortal.NodesNodesDeviceNotResolved",
160 )<{
161 parent: string;
162 resourceName: string;
163 }> {}
164
165 const toAttrs = (device: sasportal.SasPortalDevice, parent: string, project: string) => {
166 const name = device.name ?? "";
167 return {
168 name,
169 deviceId: lastSegment(name),
170 parent: parentOf(name) || parent,
171 project,
172 displayName: parseOwnership(device.displayName).text,
173 serialNumber: device.serialNumber,
174 fccId: device.fccId,
175 grantRangeAllowlists: frequencyRangesOf(device.grantRangeAllowlists),
176 preloadedConfig: deviceConfigOf(device.preloadedConfig),
177 activeConfig: deviceConfigOf(device.activeConfig),
178 deviceMetadata: deviceMetadataOf(device.deviceMetadata),
179 state: device.state,
180 grants: deviceGrantsOf(device.grants),
181 };
182 };
183
184 export const NodesNodesDeviceProvider = () =>
185 Provider.succeed(NodesNodesDevice, {
186 stables: ["name", "deviceId", "parent", "project", "serialNumber", "fccId"],
187
188 diff: Effect.fn(function* ({ news, olds, output }) {
189 if (!isResolved(news)) return undefined;
190 return replaceOnIdentity({
191 previousParent: olds?.parent ?? output?.parent,
192 nextParent: expandPath(news.parent),
193 previousId: olds?.name ?? output?.name,
194 nextId: news.name,
195 extra:
196 (news.serialNumber !== undefined &&
197 output?.serialNumber !== undefined &&
198 news.serialNumber !== output.serialNumber) ||
199 (news.fccId !== undefined && output?.fccId !== undefined && news.fccId !== output.fccId),
200 });
201 }),
202
203 read: Effect.fn(function* ({ id, olds, output }) {
204 const env = yield* GcpEnvironment.current;
205 const parent = expandPath(olds?.parent ?? output?.parent ?? "");
206 const name = olds?.name ?? output?.name ?? "";
207 let existing = yield* getNodeDevice(name);
208 let locatedParent = existing ? parentOf(existing.name ?? "") || parent : parent;
209 if (existing === undefined) {
210 const found =
211 (yield* findOwnedNodeNodeDevice(id, parent)) ??
212 (yield* scanOwnedNodeNodeDevice(id, parent));
213 existing = found?.row;
214 locatedParent = found?.parent ?? locatedParent;
215 }
216 if (existing === undefined) return undefined;
217 const attrs = toAttrs(existing, locatedParent, env.project);
218 return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs);
219 }),
220
221 list: () =>
222 Effect.gen(function* () {
223 const env = yield* GcpEnvironment.current;
224 const parents = yield* walkNodeChildren();
225 const pages = yield* Effect.forEach(
226 parents,
227 (entry) => {
228 const parent = entry.node.name ?? "";
229 return parent.length === 0
230 ? Effect.succeed([])
231 : listNodeNodeDevices(parent).pipe(
232 Effect.map((rows) =>
233 rows
234 .filter((row) => hasOwnershipMarker(row.displayName))
235 .map((row) => toAttrs(row, parent, env.project)),
236 ),
237 );
238 },
239 { concurrency: 4 },
240 );
241 return pages.flat();
242 }),
243
244 reconcile: Effect.fn(function* ({ id, news, output }) {
245 const env = yield* GcpEnvironment.current;
246 const parent = expandPath(news.parent);
247 const ownership = yield* ownershipLabels(id);
248 const displayName = encodeOwnershipLine(
249 ownership,
250 yield* toDisplayName(id, news.displayName, output?.displayName),
251 MAX_DISPLAY_NAME_LENGTH,
252 );
253 const serialNumber = yield* toSerialNumber(id, news.serialNumber, output?.serialNumber);
254 const desired = deviceBody({
255 displayName,
256 serialNumber,
257 fccId: news.fccId ?? output?.fccId,
258 grantRangeAllowlists: news.grantRangeAllowlists,
259 preloadedConfig: news.preloadedConfig,
260 deviceMetadata: news.deviceMetadata,
261 });
262
263 let current = yield* getNodeDevice(news.name ?? output?.name ?? "");
264 if (current === undefined) {
265 const found =
266 (yield* findOwnedNodeNodeDevice(id, parent)) ??
267 (yield* scanOwnedNodeNodeDevice(id, parent));
268 current = found?.row;
269 }
270
271 if (current === undefined) {
272 const created = yield* sasportal
273 .createNodesNodesDevices({
274 parent,
275 body: desired,
276 })
277 .pipe(
278 Effect.catchTag("Conflict", () =>
279 findOwnedNodeNodeDevice(id, parent).pipe(Effect.map((found) => found?.row)),
280 ),
281 );
282 current = created ?? undefined;
283 }
284
285 if (current === undefined) {
286 return yield* new NodesNodesDeviceNotResolved({
287 parent,
288 resourceName: news.name ?? output?.name ?? displayName,
289 });
290 }
291
292 const name = current.name ?? news.name ?? output?.name ?? "";
293 const nameChanged = !sameText(current.displayName, displayName);
294 const allowlistsChanged =
295 news.grantRangeAllowlists !== undefined &&
296 !sameJson(frequencyRangesOf(current.grantRangeAllowlists), news.grantRangeAllowlists);
297 const configChanged =
298 news.preloadedConfig !== undefined &&
299 !sameJson(deviceConfigOf(current.preloadedConfig), news.preloadedConfig);
300 const metadataChanged =
301 news.deviceMetadata !== undefined &&
302 !sameJson(deviceMetadataOf(current.deviceMetadata), news.deviceMetadata);
303 if (nameChanged || allowlistsChanged || configChanged || metadataChanged) {
304 current = yield* sasportal.patchNodesDevices({
305 name,
306 updateMask: updateMaskOf(
307 "displayName",
308 news.grantRangeAllowlists !== undefined ? "grantRangeAllowlists" : undefined,
309 news.preloadedConfig !== undefined ? "preloadedConfig" : undefined,
310 news.deviceMetadata !== undefined ? "deviceMetadata" : undefined,
311 ),
312 body: desired,
313 });
314 }
315
316 return toAttrs(current, parent, env.project);
317 }),
318
319 delete: Effect.fn(function* ({ output }) {
320 if (!output.name) return;
321 yield* retryDelete(sasportal.deleteNodesDevices({ name: output.name })).pipe(
322 Effect.catchTag("NotFound", () => Effect.void),
323 );
324 yield* waitUntilGone(getNodeDevice(output.name));
325 }),
326 });