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

main
ts 343 lines 11.2 KB
Raw
1 import * as connectivity from "@distilled.cloud/cloudflare/connectivity";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { isResourceOfType, Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Option from "effect/Option";
8 import * as Stream from "effect/Stream";
9 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
10 import type { Providers } from "../Providers.ts";
11
12 export type VpcServiceProps = {
13 /**
14 * Display name for the VPC service. If omitted, a unique name is generated.
15 *
16 * @default ${app}-${stage}-${id}
17 */
18 name?: string;
19 /**
20 * Service protocol. Currently only `"http"` is supported.
21 *
22 * @default "http"
23 */
24 serviceType?: "http";
25 /**
26 * Port that Workers should reach for plain HTTP traffic.
27 */
28 httpPort?: number;
29 /**
30 * Port that Workers should reach for HTTPS traffic.
31 */
32 httpsPort?: number;
33 /**
34 * Host the service is reachable at -- IPv4, IPv6, dual stack, or hostname.
35 */
36 host: VpcService.Host;
37 /**
38 * Whether to adopt an existing VPC service with the same name when create
39 * fails because of a name conflict.
40 *
41 * @default false
42 */
43 adopt?: boolean;
44 };
45
46 export declare namespace VpcService {
47 /**
48 * Host the VPC service is reachable at.
49 */
50 export type Host = IPv4Host | IPv6Host | DualStackHost | HostnameHost;
51 export interface IPv4Host {
52 ipv4: string;
53 network: Network;
54 }
55 export interface IPv6Host {
56 ipv6: string;
57 network: Network;
58 }
59 export interface DualStackHost {
60 ipv4: string;
61 ipv6: string;
62 network: Network;
63 }
64 export interface HostnameHost {
65 hostname: string;
66 resolverNetwork: ResolverNetwork;
67 }
68 export interface Network {
69 tunnelId: string;
70 }
71 export interface ResolverNetwork extends Network {
72 resolverIps?: string[];
73 }
74 }
75
76 export type Attributes = {
77 serviceId: string;
78 serviceName: string;
79 serviceType: "http" | "tcp";
80 httpPort: number | undefined;
81 httpsPort: number | undefined;
82 host: VpcService.Host;
83 accountId: string;
84 createdAt: number | undefined;
85 updatedAt: number | undefined;
86 };
87
88 export type VpcService = Resource<
89 "Cloudflare.VpcService.VpcService",
90 VpcServiceProps,
91 Attributes,
92 never,
93 Providers
94 >;
95
96 /**
97 * A Cloudflare VPC service that exposes a private host (IP or hostname)
98 * reachable through a Cloudflare Tunnel for Workers VPC.
99 *
100 * `VpcService` creates HTTP services. For a TCP service — e.g. a private
101 * database that Hyperdrive connects to — use
102 * `Cloudflare.Connectivity.DirectoryService` with `type: "tcp"`.
103 * ### Creating a VPC Service
104 * **Example:** Hostname through a tunnel
105 * ```typescript
106 * const tunnel = yield* Cloudflare.Tunnel.Tunnel("MyTunnel");
107 * const service = yield* Cloudflare.VpcService.VpcService("Internal", {
108 * host: {
109 * hostname: "internal.example.com",
110 * resolverNetwork: { tunnelId: tunnel.tunnelId, resolverIps: ["10.0.0.53"] },
111 * },
112 * });
113 * ```
114 *
115 * **Example:** IPv4 with explicit ports
116 * ```typescript
117 * const service = yield* Cloudflare.VpcService.VpcService("DevServer", {
118 * httpPort: 5173,
119 * host: { ipv4: "192.168.1.100", network: { tunnelId: tunnel.tunnelId } },
120 * });
121 * ```
122 *
123 * @resource
124 * @product Workers VPC
125 * @category Network
126 */
127 export const VpcService = Resource<VpcService>("Cloudflare.VpcService.VpcService", {
128 aliases: ["Cloudflare.VpcService"],
129 });
130
131 export const isVpcService = (value: unknown): value is VpcService =>
132 isResourceOfType(value, "Cloudflare.VpcService.VpcService");
133
134 const createServiceName = (id: string, name: string | undefined) =>
135 Effect.gen(function* () {
136 if (name) return name;
137 return yield* createPhysicalName({
138 id,
139 lowercase: true,
140 maxLength: 63,
141 });
142 });
143
144 const findServiceByName = Effect.fn(function* (name: string) {
145 const { accountId } = yield* yield* CloudflareEnvironment;
146 return yield* connectivity.listDirectoryServices.items({ accountId }).pipe(
147 Stream.filter((s) => s.name === name),
148 Stream.runHead,
149 Effect.map(Option.getOrUndefined),
150 );
151 });
152
153 export const VpcServiceProvider = () =>
154 Provider.succeed(VpcService, {
155 stables: ["serviceId", "accountId"],
156 list: Effect.fn(function* () {
157 const { accountId } = yield* yield* CloudflareEnvironment;
158 return yield* connectivity.listDirectoryServices.pages({ accountId }).pipe(
159 Stream.runCollect,
160 Effect.map((chunk) =>
161 Array.from(chunk).flatMap((page) =>
162 (page.result ?? [])
163 .filter((s): s is typeof s & { serviceId: string } => s.serviceId != null)
164 .map((s) => formatVpcService(s, accountId)),
165 ),
166 ),
167 // VPC/Workers connectivity is plan-gated; an un-entitled
168 // account rejects the list route. Treat as nothing to enumerate.
169 Effect.catchTag("Forbidden", () => Effect.succeed([])),
170 );
171 }),
172 diff: Effect.fn(function* ({ id, olds, news, output }) {
173 const { accountId } = yield* yield* CloudflareEnvironment;
174 if (!isResolved(news)) return undefined;
175 if ((output?.accountId ?? accountId) !== accountId) {
176 return { action: "replace" } as const;
177 }
178 const oldName = output?.serviceName ?? (yield* createServiceName(id, olds?.name));
179 // Auto-generated names are engine-owned: the deployed name stays
180 // authoritative even if the generator would name this id differently
181 // today. Only an explicit user-provided name can force a rename.
182 const name = news.name ?? oldName;
183 if (name !== oldName) {
184 return { action: "update" } as const;
185 }
186 }),
187 reconcile: Effect.fn(function* ({ id, news, output }) {
188 const { accountId } = yield* yield* CloudflareEnvironment;
189 // Prefer the deployed name: regenerating would rename the deployed
190 // service if the generator's output for this id ever drifts. An
191 // explicit user-provided name still wins (renames apply in place).
192 const name = news.name ?? output?.serviceName ?? (yield* createServiceName(id, news.name));
193 const acct = output?.accountId ?? accountId;
194
195 // Observe — re-fetch the cached service; fall back to a name
196 // scan so we recover from out-of-band deletes or partial state
197 // persistence failures.
198 let observed: connectivity.GetDirectoryServiceResponse | undefined;
199 if (output?.serviceId) {
200 observed = yield* connectivity
201 .getDirectoryService({
202 accountId: acct,
203 serviceId: output.serviceId,
204 })
205 .pipe(Effect.orElseSucceed(() => undefined));
206 }
207 if (!observed) {
208 const match = yield* findServiceByName(name);
209 observed = match as connectivity.GetDirectoryServiceResponse | undefined;
210 }
211
212 // Ensure — create if missing. Cloudflare rejects a duplicate
213 // name with a generic error; tolerate by adopting the existing
214 // service (when the caller opted in) and re-applying the
215 // desired configuration.
216 if (!observed || !observed.serviceId) {
217 const result = yield* connectivity
218 .createDirectoryService({
219 accountId: acct,
220 name,
221 type: news.serviceType ?? "http",
222 httpPort: news.httpPort,
223 httpsPort: news.httpsPort,
224 host: news.host,
225 })
226 .pipe(
227 Effect.catch((err: unknown) =>
228 Effect.gen(function* () {
229 if (!news.adopt) return yield* Effect.fail(err as never);
230 const existing = yield* findServiceByName(name);
231 if (!existing || !existing.serviceId) {
232 return yield* Effect.fail(err as never);
233 }
234 return yield* connectivity.updateDirectoryService({
235 accountId: acct,
236 serviceId: existing.serviceId,
237 name,
238 type: news.serviceType ?? "http",
239 httpPort: news.httpPort,
240 httpsPort: news.httpsPort,
241 host: news.host,
242 });
243 }),
244 ),
245 );
246 return formatVpcService(result, acct);
247 }
248
249 // Sync — the Cloudflare update API replaces all mutable fields
250 // (name, ports, host) atomically, so always issue it so
251 // adoption and routine updates converge.
252 const result = yield* connectivity.updateDirectoryService({
253 accountId: acct,
254 serviceId: observed.serviceId,
255 name,
256 type: news.serviceType ?? observed.type ?? "http",
257 httpPort: news.httpPort,
258 httpsPort: news.httpsPort,
259 host: news.host,
260 });
261 return formatVpcService(result, acct);
262 }),
263 delete: Effect.fn(function* ({ output }) {
264 yield* connectivity
265 .deleteDirectoryService({
266 accountId: output.accountId,
267 serviceId: output.serviceId,
268 })
269 .pipe(Effect.catch(() => Effect.void));
270 }),
271 read: Effect.fn(function* ({ id, output, olds }) {
272 const { accountId } = yield* yield* CloudflareEnvironment;
273 if (output?.serviceId) {
274 return yield* connectivity
275 .getDirectoryService({
276 accountId: output.accountId,
277 serviceId: output.serviceId,
278 })
279 .pipe(
280 Effect.map((s) => formatVpcService(s, output.accountId)),
281 Effect.orElseSucceed(() => undefined),
282 );
283 }
284 const name = yield* createServiceName(id, olds?.name);
285 const existing = yield* findServiceByName(name);
286 if (!existing || !existing.serviceId) return undefined;
287 return formatVpcService(existing, accountId);
288 }),
289 });
290
291 export const formatVpcService = (
292 service: {
293 serviceId?: string | null;
294 name: string;
295 // Distilled widened generated string enums to open unions (`string & {}`);
296 // the API only ever returns the known variants here.
297 type: string;
298 createdAt?: string | null;
299 updatedAt?: string | null;
300 httpPort?: number | null;
301 httpsPort?: number | null;
302 host: connectivity.GetDirectoryServiceResponse["host"];
303 },
304 accountId: string,
305 ): Attributes => {
306 let host: VpcService.Host;
307 if ("hostname" in service.host) {
308 host = {
309 hostname: service.host.hostname,
310 resolverNetwork: {
311 tunnelId: service.host.resolverNetwork.tunnelId,
312 resolverIps: service.host.resolverNetwork.resolverIps ?? undefined,
313 },
314 };
315 } else if ("ipv4" in service.host && "ipv6" in service.host) {
316 host = {
317 ipv4: service.host.ipv4,
318 ipv6: service.host.ipv6,
319 network: { tunnelId: service.host.network.tunnelId },
320 };
321 } else if ("ipv4" in service.host) {
322 host = {
323 ipv4: service.host.ipv4,
324 network: { tunnelId: service.host.network.tunnelId },
325 };
326 } else {
327 host = {
328 ipv6: service.host.ipv6,
329 network: { tunnelId: service.host.network.tunnelId },
330 };
331 }
332 return {
333 serviceId: service.serviceId!,
334 serviceName: service.name,
335 serviceType: service.type as "http" | "tcp",
336 httpPort: service.httpPort ?? undefined,
337 httpsPort: service.httpsPort ?? undefined,
338 host,
339 accountId,
340 createdAt: service.createdAt ? new Date(service.createdAt).getTime() : undefined,
341 updatedAt: service.updatedAt ? new Date(service.updatedAt).getTime() : undefined,
342 };
343 };