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

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