@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, 04:45 UTC

main
ts 582 lines 18.5 KB
Raw
1 import * as connectivity from "@distilled.cloud/cloudflare/connectivity";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Effect from "effect/Effect";
8 import * as Option from "effect/Option";
9 import * as Predicate from "effect/Predicate";
10 import * as Stream from "effect/Stream";
11 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
12 import type { Providers } from "../Providers.ts";
13
14 const TypeId = "Cloudflare.Connectivity.DirectoryService" as const;
15 type TypeId = typeof TypeId;
16
17 /**
18 * Protocol of a Connectivity Directory service.
19 */
20 export type DirectoryServiceType = "tcp" | "http";
21
22 /**
23 * Application protocol hint for `tcp` services.
24 */
25 export type DirectoryServiceAppProtocol = "postgresql" | "mysql" | (string & {});
26
27 export declare namespace DirectoryService {
28 /**
29 * Network a private IP host is reachable through — identified by the
30 * Cloudflare Tunnel that carries the traffic.
31 */
32 export interface Network {
33 /**
34 * UUID of the `cfd_tunnel` that provides connectivity to the host.
35 * Accepts a reference to a `Cloudflare.Tunnel.Tunnel` output.
36 */
37 tunnelId: string;
38 }
39
40 /**
41 * Network a private hostname is resolved and reached through.
42 */
43 export interface ResolverNetwork {
44 /**
45 * UUID of the `cfd_tunnel` that provides connectivity to the host.
46 * Accepts a reference to a `Cloudflare.Tunnel.Tunnel` output.
47 */
48 tunnelId: string;
49 /**
50 * IP addresses of the DNS resolvers used to resolve the hostname
51 * inside the private network.
52 */
53 resolverIps?: string[];
54 }
55
56 /**
57 * Private IPv4 host reached through a tunnel.
58 */
59 export interface Ipv4Host {
60 /** Private IPv4 address of the service. */
61 ipv4: string;
62 /** Tunnel-backed network the address lives in. */
63 network: Network;
64 }
65
66 /**
67 * Private IPv6 host reached through a tunnel.
68 */
69 export interface Ipv6Host {
70 /** Private IPv6 address of the service. */
71 ipv6: string;
72 /** Tunnel-backed network the address lives in. */
73 network: Network;
74 }
75
76 /**
77 * Dual-stack (IPv4 + IPv6) host reached through a tunnel.
78 */
79 export interface DualStackHost {
80 /** Private IPv4 address of the service. */
81 ipv4: string;
82 /** Private IPv6 address of the service. */
83 ipv6: string;
84 /** Tunnel-backed network the addresses live in. */
85 network: Network;
86 }
87
88 /**
89 * Private hostname resolved and reached through a tunnel.
90 */
91 export interface HostnameHost {
92 /** Private hostname of the service (e.g. `db.internal`). */
93 hostname: string;
94 /** Tunnel-backed resolver network used to resolve and reach the host. */
95 resolverNetwork: ResolverNetwork;
96 }
97
98 /**
99 * Host a directory service is reachable at — a private IPv4/IPv6
100 * address or a hostname, always reached through a Cloudflare Tunnel.
101 */
102 export type Host = Ipv4Host | Ipv6Host | DualStackHost | HostnameHost;
103
104 /**
105 * Fully-resolved host shape returned in Output Attributes (all tunnel
106 * references resolved to concrete UUID strings).
107 */
108 export type HostAttributes =
109 | { ipv4: string; network: { tunnelId: string } }
110 | { ipv6: string; network: { tunnelId: string } }
111 | { ipv4: string; ipv6: string; network: { tunnelId: string } }
112 | {
113 hostname: string;
114 resolverNetwork: { tunnelId: string; resolverIps?: string[] };
115 };
116 }
117
118 export type DirectoryServiceProps = {
119 /**
120 * Display name of the directory service. Must be unique within the
121 * account. If omitted, a unique name is generated from the app, stage,
122 * and logical ID.
123 * @default ${app}-${stage}-${id}
124 */
125 name?: string;
126 /**
127 * Service protocol: `tcp` (arbitrary TCP, e.g. a database) or `http`
128 * (plain HTTP/HTTPS origins).
129 */
130 type: DirectoryServiceType;
131 /**
132 * Host the service is reachable at — IPv4, IPv6, dual-stack, or
133 * hostname, reached through a Cloudflare Tunnel.
134 */
135 host: DirectoryService.Host;
136 /**
137 * Port the service listens on. Only valid for `type: "tcp"` services.
138 */
139 tcpPort?: number;
140 /**
141 * Port for plain HTTP traffic. Only valid for `type: "http"` services.
142 * @default 80
143 */
144 httpPort?: number;
145 /**
146 * Port for HTTPS traffic. Only valid for `type: "http"` services.
147 * @default 443
148 */
149 httpsPort?: number;
150 /**
151 * Application protocol hint for `tcp` services (e.g. `postgresql`).
152 */
153 appProtocol?: DirectoryServiceAppProtocol;
154 /**
155 * TLS settings used when connecting to the service.
156 * @default { certVerificationMode: "verify_full" }
157 */
158 tlsSettings?: {
159 /** Certificate verification mode (e.g. `verify_full`). */
160 certVerificationMode: string;
161 };
162 };
163
164 export type DirectoryServiceAttributes = {
165 /**
166 * Unique identifier of the directory service.
167 */
168 serviceId: string;
169 /**
170 * The Cloudflare account the service belongs to.
171 */
172 accountId: string;
173 /**
174 * Display name of the service.
175 */
176 name: string;
177 /**
178 * Service protocol (`tcp` or `http`).
179 */
180 type: DirectoryServiceType;
181 /**
182 * Host the service is reachable at, with tunnel references resolved.
183 */
184 host: DirectoryService.HostAttributes;
185 /**
186 * TCP port (only set for `tcp` services).
187 */
188 tcpPort: number | undefined;
189 /**
190 * HTTP port (only set for `http` services).
191 */
192 httpPort: number | undefined;
193 /**
194 * HTTPS port (only set for `http` services).
195 */
196 httpsPort: number | undefined;
197 /**
198 * Application protocol hint (only set for `tcp` services).
199 */
200 appProtocol: DirectoryServiceAppProtocol | undefined;
201 /**
202 * Certificate verification mode in effect.
203 */
204 certVerificationMode: string | undefined;
205 /**
206 * When the service was created.
207 */
208 createdAt: string | undefined;
209 /**
210 * When the service was last updated.
211 */
212 updatedAt: string | undefined;
213 };
214
215 export type DirectoryService = Resource<
216 TypeId,
217 DirectoryServiceProps,
218 DirectoryServiceAttributes,
219 never,
220 Providers
221 >;
222
223 /**
224 * A Cloudflare Connectivity Directory service — a named entry in the
225 * account's private-network service directory that maps a service name to
226 * a private host (IP or hostname) reachable through a Cloudflare Tunnel.
227 *
228 * Directory services are the registry behind Workers VPC and Zero Trust
229 * private-network connectivity: a `tcp` service describes a database-style
230 * origin (with an optional `appProtocol` hint), an `http` service describes
231 * an HTTP/HTTPS origin with explicit ports.
232 *
233 * Names are unique within the account. All properties — including the host
234 * and even the protocol type — are mutable in place via a full PUT; nothing
235 * forces a replacement except moving accounts.
236 * ### Creating a Directory Service
237 * **Example:** TCP database service through a tunnel
238 * ```typescript
239 * const tunnel = yield* Cloudflare.Tunnel.Tunnel("DbTunnel", {
240 * ingress: [{ service: "tcp://localhost:5432" }],
241 * });
242 * const db = yield* Cloudflare.Connectivity.DirectoryService("Postgres", {
243 * type: "tcp",
244 * tcpPort: 5432,
245 * appProtocol: "postgresql",
246 * host: { ipv4: "10.0.0.21", network: { tunnelId: tunnel.tunnelId } },
247 * });
248 * ```
249 *
250 * **Example:** HTTP service on a private hostname
251 * ```typescript
252 * const api = yield* Cloudflare.Connectivity.DirectoryService("InternalApi", {
253 * type: "http",
254 * httpPort: 8080,
255 * httpsPort: 8443,
256 * host: {
257 * hostname: "api.internal",
258 * resolverNetwork: { tunnelId: tunnel.tunnelId, resolverIps: ["10.0.0.53"] },
259 * },
260 * });
261 * ```
262 *
263 * ### Updating
264 * **Example:** Changing the host in place
265 * ```typescript
266 * // Host, ports, name, and TLS settings are all mutable — the service
267 * // keeps its serviceId across updates.
268 * const db = yield* Cloudflare.Connectivity.DirectoryService("Postgres", {
269 * type: "tcp",
270 * tcpPort: 5432,
271 * host: {
272 * hostname: "db.internal",
273 * resolverNetwork: { tunnelId: tunnel.tunnelId },
274 * },
275 * });
276 * ```
277 *
278 * @see https://developers.cloudflare.com/cloudflare-one/
279 *
280 * @resource
281 * @product Connectivity
282 * @category Cloudflare One (Zero Trust)
283 */
284 export const DirectoryService = Resource<DirectoryService>(TypeId);
285
286 /**
287 * Returns true if the given value is a DirectoryService resource.
288 */
289 export const isDirectoryService = (value: unknown): value is DirectoryService =>
290 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
291
292 export const DirectoryServiceProvider = () =>
293 Provider.succeed(DirectoryService, {
294 stables: ["serviceId", "accountId", "createdAt"],
295 diff: Effect.fn(function* ({ news, output }) {
296 const { accountId } = yield* yield* CloudflareEnvironment;
297 if (!isResolved(news)) return undefined;
298 // Directory services are account-scoped; moving accounts replaces.
299 if ((output?.accountId ?? accountId) !== accountId) {
300 return { action: "replace" } as const;
301 }
302 // Everything else (name, type, host, ports, appProtocol, TLS) is
303 // mutable via the full-body PUT — let the engine default to update.
304 return undefined;
305 }),
306 read: Effect.fn(function* ({ id, output, olds }) {
307 const { accountId } = yield* yield* CloudflareEnvironment;
308 const acct = output?.accountId ?? accountId;
309
310 // Owned path: refresh by the persisted service id.
311 if (output?.serviceId) {
312 const observed = yield* getService(acct, output.serviceId);
313 return observed ? toAttributes(observed, acct) : undefined;
314 }
315
316 // Cold read — recover from lost state by matching the deterministic
317 // physical name. Names are unique within the account (the API
318 // rejects duplicates), but the service carries no ownership markers,
319 // so brand the match `Unowned` and let the engine gate takeover
320 // behind the adopt policy.
321 const name = yield* createServiceName(id, olds?.name);
322 const match = yield* findByName(acct, name);
323 if (match) return Unowned(toAttributes(match, acct));
324 return undefined;
325 }),
326 reconcile: Effect.fn(function* ({ id, news, output }) {
327 const { accountId } = yield* yield* CloudflareEnvironment;
328 const acct = output?.accountId ?? accountId;
329 const name = yield* createServiceName(id, news.name);
330
331 // Observe — the serviceId cached on `output` is a hint, not a
332 // guarantee: a missing service falls through to a name scan
333 // (adoption / lost-state recovery) and then to create.
334 let observed = output?.serviceId ? yield* getService(acct, output.serviceId) : undefined;
335 if (!observed) {
336 observed = yield* findByName(acct, name);
337 }
338
339 // Ensure — create when missing. A concurrent create surfaces as
340 // the typed `VpcServiceNameAlreadyExists` (Cloudflare code 5101):
341 // converge by re-scanning for the service that won the race.
342 if (!observed) {
343 const created = yield* connectivity
344 .createDirectoryService({
345 accountId: acct,
346 name,
347 ...toRequestBody(news),
348 })
349 .pipe(
350 Effect.catchTag("VpcServiceNameAlreadyExists", (error) =>
351 findByName(acct, name).pipe(
352 Effect.flatMap((existing) =>
353 existing ? Effect.succeed(existing) : Effect.fail(error),
354 ),
355 ),
356 ),
357 );
358 observed = created;
359 }
360
361 // Sync — diff observed cloud state against desired. The update API
362 // is a full-body PUT, so send everything, but skip the call
363 // entirely on a no-op.
364 const current = toAttributes(observed, acct);
365 if (!isDirty(current, name, news)) {
366 return current;
367 }
368 const updated = yield* connectivity.updateDirectoryService({
369 accountId: acct,
370 serviceId: current.serviceId,
371 name,
372 ...toRequestBody(news),
373 });
374 return toAttributes(updated, acct);
375 }),
376 delete: Effect.fn(function* ({ output }) {
377 // Idempotent — an already-gone service surfaces as the typed
378 // `VpcServiceNotFound` (Cloudflare code 5104).
379 yield* connectivity
380 .deleteDirectoryService({
381 accountId: output.accountId,
382 serviceId: output.serviceId,
383 })
384 .pipe(Effect.catchTag("VpcServiceNotFound", () => Effect.void));
385 }),
386 // Account-scoped collection: enumerate every directory service in the
387 // account, exhaustively paginating the list API, and hydrate each into
388 // the same Attributes shape `read` returns.
389 list: Effect.fn(function* () {
390 const { accountId } = yield* yield* CloudflareEnvironment;
391 return yield* connectivity.listDirectoryServices.pages({ accountId }).pipe(
392 Stream.runCollect,
393 Effect.map((chunk) =>
394 Array.from(chunk).flatMap((page) =>
395 (page.result ?? []).map((service) => toAttributes(service, accountId)),
396 ),
397 ),
398 );
399 }),
400 });
401
402 type ObservedService = connectivity.GetDirectoryServiceResponse;
403
404 const createServiceName = (id: string, name: string | undefined) =>
405 Effect.gen(function* () {
406 if (name) return name;
407 return yield* createPhysicalName({ id, lowercase: true, maxLength: 63 });
408 });
409
410 /**
411 * Read a directory service by id, mapping "gone" (`VpcServiceNotFound`,
412 * Cloudflare error code 5104) to `undefined`.
413 */
414 const getService = (accountId: string, serviceId: string) =>
415 connectivity
416 .getDirectoryService({ accountId, serviceId })
417 .pipe(Effect.catchTag("VpcServiceNotFound", () => Effect.undefined));
418
419 /**
420 * Find a directory service by its (account-unique) name.
421 */
422 const findByName = (accountId: string, name: string) =>
423 connectivity.listDirectoryServices.items({ accountId }).pipe(
424 Stream.filter((s) => s.name === name),
425 Stream.runHead,
426 Effect.map(Option.getOrUndefined),
427 );
428
429 /**
430 * Build the shared create/update request body from desired props. Inputs
431 * (tunnel references) have been resolved to concrete strings by the Plan
432 * layer before reconcile runs.
433 */
434 const toRequestBody = (news: DirectoryServiceProps) => {
435 const host = news.host;
436 const requestHost =
437 "hostname" in host
438 ? {
439 hostname: host.hostname,
440 resolverNetwork: {
441 tunnelId: host.resolverNetwork.tunnelId,
442 resolverIps: host.resolverNetwork.resolverIps,
443 },
444 }
445 : "ipv4" in host && "ipv6" in host
446 ? {
447 ipv4: host.ipv4,
448 ipv6: host.ipv6,
449 network: { tunnelId: host.network.tunnelId },
450 }
451 : "ipv4" in host
452 ? { ipv4: host.ipv4, network: { tunnelId: host.network.tunnelId } }
453 : { ipv6: host.ipv6, network: { tunnelId: host.network.tunnelId } };
454 return {
455 type: news.type,
456 host: requestHost,
457 tcpPort: news.tcpPort,
458 httpPort: news.httpPort,
459 httpsPort: news.httpsPort,
460 appProtocol: news.appProtocol,
461 tlsSettings: news.tlsSettings,
462 };
463 };
464
465 /**
466 * Compare observed attributes against the desired props (with the resolved
467 * physical name) to decide whether the full-body PUT can be skipped.
468 */
469 const isDirty = (
470 current: DirectoryServiceAttributes,
471 name: string,
472 news: DirectoryServiceProps,
473 ): boolean => {
474 if (current.name !== name) return true;
475 if (current.type !== news.type) return true;
476 if (news.tcpPort !== undefined && current.tcpPort !== news.tcpPort) {
477 return true;
478 }
479 if (news.httpPort !== undefined && current.httpPort !== news.httpPort) {
480 return true;
481 }
482 if (news.httpsPort !== undefined && current.httpsPort !== news.httpsPort) {
483 return true;
484 }
485 if (news.appProtocol !== undefined && current.appProtocol !== news.appProtocol) {
486 return true;
487 }
488 if (
489 news.tlsSettings !== undefined &&
490 current.certVerificationMode !== news.tlsSettings.certVerificationMode
491 ) {
492 return true;
493 }
494 return !sameHost(current.host, news.host);
495 };
496
497 /**
498 * Structural host equality between the observed (resolved) host and the
499 * desired host props.
500 */
501 const sameHost = (
502 observed: DirectoryService.HostAttributes,
503 desired: DirectoryService.Host,
504 ): boolean => {
505 const canon = (h: {
506 hostname?: string;
507 ipv4?: string;
508 ipv6?: string;
509 tunnelId?: unknown;
510 resolverIps?: string[] | undefined;
511 }) => JSON.stringify([h.hostname, h.ipv4, h.ipv6, h.tunnelId, [...(h.resolverIps ?? [])].sort()]);
512 const flat = (h: DirectoryService.HostAttributes | DirectoryService.Host) =>
513 Predicate.hasProperty(h, "hostname")
514 ? {
515 hostname: h.hostname,
516 tunnelId: h.resolverNetwork.tunnelId,
517 resolverIps: h.resolverNetwork.resolverIps ?? undefined,
518 }
519 : {
520 ...(Predicate.hasProperty(h, "ipv4") ? { ipv4: h.ipv4 } : {}),
521 ...(Predicate.hasProperty(h, "ipv6") ? { ipv6: h.ipv6 } : {}),
522 tunnelId: h.network.tunnelId,
523 };
524 return canon(flat(observed)) === canon(flat(desired));
525 };
526
527 const toHostAttributes = (host: ObservedService["host"]): DirectoryService.HostAttributes => {
528 if ("hostname" in host) {
529 return {
530 hostname: host.hostname,
531 resolverNetwork: {
532 tunnelId: host.resolverNetwork.tunnelId,
533 ...(host.resolverNetwork.resolverIps
534 ? { resolverIps: [...host.resolverNetwork.resolverIps] }
535 : {}),
536 },
537 };
538 }
539 if ("ipv4" in host && "ipv6" in host) {
540 return {
541 ipv4: host.ipv4,
542 ipv6: host.ipv6,
543 network: { tunnelId: host.network.tunnelId },
544 };
545 }
546 if ("ipv4" in host) {
547 return { ipv4: host.ipv4, network: { tunnelId: host.network.tunnelId } };
548 }
549 return { ipv6: host.ipv6, network: { tunnelId: host.network.tunnelId } };
550 };
551
552 const toAttributes = (
553 service: {
554 serviceId?: string | null;
555 name: string;
556 // Distilled widens generated string enums to open unions (`string & {}`);
557 // the API only ever returns the known variants here.
558 type: string;
559 host: ObservedService["host"];
560 tcpPort?: number | null;
561 httpPort?: number | null;
562 httpsPort?: number | null;
563 appProtocol?: DirectoryServiceAppProtocol | null;
564 tlsSettings?: { certVerificationMode: string } | null;
565 createdAt?: string | null;
566 updatedAt?: string | null;
567 },
568 accountId: string,
569 ): DirectoryServiceAttributes => ({
570 serviceId: service.serviceId!,
571 accountId,
572 name: service.name,
573 type: service.type as DirectoryServiceType,
574 host: toHostAttributes(service.host),
575 tcpPort: service.tcpPort ?? undefined,
576 httpPort: service.httpPort ?? undefined,
577 httpsPort: service.httpsPort ?? undefined,
578 appProtocol: service.appProtocol ?? undefined,
579 certVerificationMode: service.tlsSettings?.certVerificationMode ?? undefined,
580 createdAt: service.createdAt ?? undefined,
581 updatedAt: service.updatedAt ?? undefined,
582 });