@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 328 lines 10.9 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 findOwnedCustomerDeploymentDevice,
18 frequencyRangesOf,
19 getDeploymentDevice,
20 hasOwnershipMarker,
21 lastSegment,
22 listCustomerDeploymentDevices,
23 MAX_DISPLAY_NAME_LENGTH,
24 ownedByAlchemy,
25 ownershipLabels,
26 parentOf,
27 parseOwnership,
28 replaceOnIdentity,
29 retryDelete,
30 sameJson,
31 sameText,
32 scanOwnedCustomerDeploymentDevice,
33 toDisplayName,
34 toSerialNumber,
35 updateMaskOf,
36 waitUntilGone,
37 walkCustomerDeployments,
38 type DeviceConfig,
39 type DeviceGrant,
40 type DeviceMetadata,
41 type FrequencyRange,
42 } from "./internal.ts";
43
44 export type CustomersDeploymentsDeviceProps = {
45 /**
46 * Parent SAS deployment, as `customers/{customer}/deployments/{deployment}`.
47 * Immutable — changing it replaces the device.
48 */
49 parent: string;
50 /**
51 * Server-assigned device resource name
52 * (`customers/{customer}/deployments/{deployment}/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 CustomersDeploymentsDevice = Resource<
87 "GCP.SasPortal.CustomersDeploymentsDevice",
88 CustomersDeploymentsDeviceProps,
89 {
90 /** Resource name `customers/{customer}/deployments/{deployment}/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 customer deployment.
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.CustomersDeploymentsDevice("Cbsd", {
133 * parent: deployment.name,
134 * displayName: "rooftop-1",
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.CustomersDeploymentsDevice("Cbsd", {
146 * parent: deployment.name,
147 * displayName: "rooftop-1-2",
148 * fccId: "TESTFCC",
149 * serialNumber: "SN1001",
150 * });
151 * ```
152 *
153 * @resource
154 * @category SasPortal
155 */
156 export const CustomersDeploymentsDevice = Resource<CustomersDeploymentsDevice>(
157 "GCP.SasPortal.CustomersDeploymentsDevice",
158 );
159
160 export class CustomersDeploymentsDeviceNotResolved extends Data.TaggedError(
161 "GCP.SasPortal.CustomersDeploymentsDeviceNotResolved",
162 )<{
163 parent: string;
164 resourceName: string;
165 }> {}
166
167 const toAttrs = (device: sasportal.SasPortalDevice, parent: string, project: string) => {
168 const name = device.name ?? "";
169 return {
170 name,
171 deviceId: lastSegment(name),
172 parent: parentOf(name) || parent,
173 project,
174 displayName: parseOwnership(device.displayName).text,
175 serialNumber: device.serialNumber,
176 fccId: device.fccId,
177 grantRangeAllowlists: frequencyRangesOf(device.grantRangeAllowlists),
178 preloadedConfig: deviceConfigOf(device.preloadedConfig),
179 activeConfig: deviceConfigOf(device.activeConfig),
180 deviceMetadata: deviceMetadataOf(device.deviceMetadata),
181 state: device.state,
182 grants: deviceGrantsOf(device.grants),
183 };
184 };
185
186 export const CustomersDeploymentsDeviceProvider = () =>
187 Provider.succeed(CustomersDeploymentsDevice, {
188 stables: ["name", "deviceId", "parent", "project", "serialNumber", "fccId"],
189
190 diff: Effect.fn(function* ({ news, olds, output }) {
191 if (!isResolved(news)) return undefined;
192 return replaceOnIdentity({
193 previousParent: olds?.parent ?? output?.parent,
194 nextParent: expandPath(news.parent),
195 previousId: olds?.name ?? output?.name,
196 nextId: news.name,
197 extra:
198 (news.serialNumber !== undefined &&
199 output?.serialNumber !== undefined &&
200 news.serialNumber !== output.serialNumber) ||
201 (news.fccId !== undefined && output?.fccId !== undefined && news.fccId !== output.fccId),
202 });
203 }),
204
205 read: Effect.fn(function* ({ id, olds, output }) {
206 const env = yield* GcpEnvironment.current;
207 const parent = expandPath(olds?.parent ?? output?.parent ?? "");
208 const name = olds?.name ?? output?.name ?? "";
209 let existing = yield* getDeploymentDevice(name);
210 let locatedParent = existing ? parentOf(existing.name ?? "") || parent : parent;
211 if (existing === undefined) {
212 const found =
213 (yield* findOwnedCustomerDeploymentDevice(id, parent)) ??
214 (yield* scanOwnedCustomerDeploymentDevice(id, parent));
215 existing = found?.row;
216 locatedParent = found?.parent ?? locatedParent;
217 }
218 if (existing === undefined) return undefined;
219 const attrs = toAttrs(existing, locatedParent, env.project);
220 return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs);
221 }),
222
223 list: () =>
224 Effect.gen(function* () {
225 const env = yield* GcpEnvironment.current;
226 const parents = yield* walkCustomerDeployments();
227 const pages = yield* Effect.forEach(
228 parents,
229 (entry) => {
230 const parent = entry.deployment.name ?? "";
231 return parent.length === 0
232 ? Effect.succeed([])
233 : listCustomerDeploymentDevices(parent).pipe(
234 Effect.map((rows) =>
235 rows
236 .filter((row) => hasOwnershipMarker(row.displayName))
237 .map((row) => toAttrs(row, parent, env.project)),
238 ),
239 );
240 },
241 { concurrency: 4 },
242 );
243 return pages.flat();
244 }),
245
246 reconcile: Effect.fn(function* ({ id, news, output }) {
247 const env = yield* GcpEnvironment.current;
248 const parent = expandPath(news.parent);
249 const ownership = yield* ownershipLabels(id);
250 const displayName = encodeOwnershipLine(
251 ownership,
252 yield* toDisplayName(id, news.displayName, output?.displayName),
253 MAX_DISPLAY_NAME_LENGTH,
254 );
255 const serialNumber = yield* toSerialNumber(id, news.serialNumber, output?.serialNumber);
256 const desired = deviceBody({
257 displayName,
258 serialNumber,
259 fccId: news.fccId ?? output?.fccId,
260 grantRangeAllowlists: news.grantRangeAllowlists,
261 preloadedConfig: news.preloadedConfig,
262 deviceMetadata: news.deviceMetadata,
263 });
264
265 let current = yield* getDeploymentDevice(news.name ?? output?.name ?? "");
266 if (current === undefined) {
267 const found =
268 (yield* findOwnedCustomerDeploymentDevice(id, parent)) ??
269 (yield* scanOwnedCustomerDeploymentDevice(id, parent));
270 current = found?.row;
271 }
272
273 if (current === undefined) {
274 const created = yield* sasportal
275 .createCustomersDeploymentsDevices({
276 parent,
277 body: desired,
278 })
279 .pipe(
280 Effect.catchTag("Conflict", () =>
281 findOwnedCustomerDeploymentDevice(id, parent).pipe(Effect.map((found) => found?.row)),
282 ),
283 );
284 current = created ?? undefined;
285 }
286
287 if (current === undefined) {
288 return yield* new CustomersDeploymentsDeviceNotResolved({
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.patchDeploymentsDevices({
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.deleteDeploymentsDevices({ name: output.name })).pipe(
324 Effect.catchTag("NotFound", () => Effect.void),
325 );
326 yield* waitUntilGone(getDeploymentDevice(output.name));
327 }),
328 });