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

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