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

main
ts 346 lines 11.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 decodeSignedDevice,
12 deviceBody,
13 deviceConfigOf,
14 deviceGrantsOf,
15 deviceMetadataOf,
16 encodeOwnershipLine,
17 expandPath,
18 findDeviceBySerial,
19 findOwnedCustomerNodeDevice,
20 frequencyRangesOf,
21 getNodeDevice,
22 hasOwnershipMarker,
23 lastSegment,
24 listCustomerNodeDevices,
25 MAX_DISPLAY_NAME_LENGTH,
26 ownedByAlchemy,
27 ownershipLabels,
28 parentOf,
29 parseOwnership,
30 replaceOnIdentity,
31 retryDelete,
32 sameJson,
33 sameText,
34 scanOwnedCustomerNodeDevice,
35 signedDeviceBody,
36 toDisplayName,
37 updateMaskOf,
38 waitUntilGone,
39 walkCustomerNodes,
40 type DeviceConfig,
41 type DeviceGrant,
42 type DeviceMetadata,
43 type FrequencyRange,
44 } from "./internal.ts";
45
46 export type SignedCustomersNodesDeviceProps = {
47 /**
48 * Parent SAS node, as `customers/{customer}/nodes/{node}`.
49 * Immutable — changing it replaces the device.
50 */
51 parent: string;
52 /**
53 * Server-assigned device resource name
54 * (`customers/{customer}/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 SignedCustomersNodesDevice = Resource<
98 "GCP.SasPortal.SignedCustomersNodesDevice",
99 SignedCustomersNodesDeviceProps,
100 {
101 /** Resource name `customers/{customer}/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 customer 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.SignedCustomersNodesDevice("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.SignedCustomersNodesDevice("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 SignedCustomersNodesDevice = Resource<SignedCustomersNodesDevice>(
167 "GCP.SasPortal.SignedCustomersNodesDevice",
168 );
169
170 export class SignedCustomersNodesDeviceNotResolved extends Data.TaggedError(
171 "GCP.SasPortal.SignedCustomersNodesDeviceNotResolved",
172 )<{
173 parent: string;
174 resourceName: string;
175 }> {}
176
177 const toAttrs = (device: sasportal.SasPortalDevice, parent: string, project: string) => {
178 const name = device.name ?? "";
179 return {
180 name,
181 deviceId: lastSegment(name),
182 parent: parentOf(name) || parent,
183 project,
184 displayName: parseOwnership(device.displayName).text,
185 serialNumber: device.serialNumber,
186 fccId: device.fccId,
187 grantRangeAllowlists: frequencyRangesOf(device.grantRangeAllowlists),
188 preloadedConfig: deviceConfigOf(device.preloadedConfig),
189 activeConfig: deviceConfigOf(device.activeConfig),
190 deviceMetadata: deviceMetadataOf(device.deviceMetadata),
191 state: device.state,
192 grants: deviceGrantsOf(device.grants),
193 };
194 };
195
196 export const SignedCustomersNodesDeviceProvider = () =>
197 Provider.succeed(SignedCustomersNodesDevice, {
198 stables: ["name", "deviceId", "parent", "project", "serialNumber", "fccId"],
199
200 diff: Effect.fn(function* ({ news, olds, output }) {
201 if (!isResolved(news)) return undefined;
202 return replaceOnIdentity({
203 previousParent: olds?.parent ?? output?.parent,
204 nextParent: expandPath(news.parent),
205 previousId: olds?.name ?? output?.name,
206 nextId: news.name,
207 });
208 }),
209
210 read: Effect.fn(function* ({ id, olds, output }) {
211 const env = yield* GcpEnvironment.current;
212 const parent = expandPath(olds?.parent ?? output?.parent ?? "");
213 const name = olds?.name ?? output?.name ?? "";
214 let existing = yield* getNodeDevice(name);
215 let locatedParent = existing ? parentOf(existing.name ?? "") || parent : parent;
216 if (existing === undefined) {
217 const found =
218 (yield* findOwnedCustomerNodeDevice(id, parent)) ??
219 (yield* scanOwnedCustomerNodeDevice(id, parent));
220 existing = found?.row;
221 locatedParent = found?.parent ?? locatedParent;
222 }
223 if (existing === undefined) return undefined;
224 const attrs = toAttrs(existing, locatedParent, env.project);
225 return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs);
226 }),
227
228 list: () =>
229 Effect.gen(function* () {
230 const env = yield* GcpEnvironment.current;
231 const parents = yield* walkCustomerNodes();
232 const pages = yield* Effect.forEach(
233 parents,
234 (entry) => {
235 const parent = entry.node.name ?? "";
236 return parent.length === 0
237 ? Effect.succeed([])
238 : listCustomerNodeDevices(parent).pipe(
239 Effect.map((rows) =>
240 rows
241 .filter((row) => hasOwnershipMarker(row.displayName))
242 .map((row) => toAttrs(row, parent, env.project)),
243 ),
244 );
245 },
246 { concurrency: 4 },
247 );
248 return pages.flat();
249 }),
250
251 reconcile: Effect.fn(function* ({ id, news, output }) {
252 const env = yield* GcpEnvironment.current;
253 const parent = expandPath(news.parent);
254 const decoded = yield* decodeSignedDevice(news.encodedDevice);
255 const ownership = yield* ownershipLabels(id);
256 const displayName = encodeOwnershipLine(
257 ownership,
258 yield* toDisplayName(id, news.displayName ?? decoded?.displayName, output?.displayName),
259 MAX_DISPLAY_NAME_LENGTH,
260 );
261 const serialNumber = news.serialNumber ?? output?.serialNumber ?? decoded?.serialNumber;
262 const desired = deviceBody({
263 displayName,
264 serialNumber,
265 fccId: news.fccId ?? output?.fccId ?? decoded?.fccId,
266 grantRangeAllowlists: news.grantRangeAllowlists,
267 preloadedConfig: news.preloadedConfig,
268 deviceMetadata: news.deviceMetadata,
269 });
270
271 let current = yield* getNodeDevice(news.name ?? output?.name ?? "");
272 if (current === undefined) {
273 const found =
274 (yield* findOwnedCustomerNodeDevice(id, parent)) ??
275 (yield* scanOwnedCustomerNodeDevice(id, parent));
276 current = found?.row;
277 }
278 if (current === undefined) {
279 const rows = yield* listCustomerNodeDevices(parent);
280 current = findDeviceBySerial(rows, serialNumber);
281 }
282
283 if (current === undefined) {
284 const created = yield* sasportal
285 .createSignedCustomersNodesDevices({
286 parent,
287 body: signedDeviceBody({
288 encodedDevice: news.encodedDevice,
289 installerId: news.installerId,
290 }),
291 })
292 .pipe(
293 Effect.catchTag("Conflict", () =>
294 Effect.gen(function* () {
295 const found = yield* findOwnedCustomerNodeDevice(id, parent);
296 if (found?.row !== undefined) return found.row;
297 const rows = yield* listCustomerNodeDevices(parent);
298 return findDeviceBySerial(rows, serialNumber);
299 }),
300 ),
301 );
302 current = created ?? undefined;
303 }
304
305 if (current === undefined) {
306 return yield* new SignedCustomersNodesDeviceNotResolved({
307 parent,
308 resourceName: news.name ?? output?.name ?? displayName,
309 });
310 }
311
312 const name = current.name ?? news.name ?? output?.name ?? "";
313 const nameChanged = !sameText(current.displayName, displayName);
314 const allowlistsChanged =
315 news.grantRangeAllowlists !== undefined &&
316 !sameJson(frequencyRangesOf(current.grantRangeAllowlists), news.grantRangeAllowlists);
317 const configChanged =
318 news.preloadedConfig !== undefined &&
319 !sameJson(deviceConfigOf(current.preloadedConfig), news.preloadedConfig);
320 const metadataChanged =
321 news.deviceMetadata !== undefined &&
322 !sameJson(deviceMetadataOf(current.deviceMetadata), news.deviceMetadata);
323 if (nameChanged || allowlistsChanged || configChanged || metadataChanged) {
324 current = yield* sasportal.patchNodesDevices({
325 name,
326 updateMask: updateMaskOf(
327 "displayName",
328 news.grantRangeAllowlists !== undefined ? "grantRangeAllowlists" : undefined,
329 news.preloadedConfig !== undefined ? "preloadedConfig" : undefined,
330 news.deviceMetadata !== undefined ? "deviceMetadata" : undefined,
331 ),
332 body: desired,
333 });
334 }
335
336 return toAttrs(current, parent, env.project);
337 }),
338
339 delete: Effect.fn(function* ({ output }) {
340 if (!output.name) return;
341 yield* retryDelete(sasportal.deleteNodesDevices({ name: output.name })).pipe(
342 Effect.catchTag("NotFound", () => Effect.void),
343 );
344 yield* waitUntilGone(getNodeDevice(output.name));
345 }),
346 });