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

main
ts 313 lines 11.4 KB
Raw
1 import * as addressing from "@distilled.cloud/cloudflare/addressing";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Predicate from "effect/Predicate";
7 import * as Schedule from "effect/Schedule";
8 import * as Stream from "effect/Stream";
9 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
10 import type { Providers } from "../Providers.ts";
11
12 const TypeId = "Cloudflare.Addressing.BgpPrefix" as const;
13 type TypeId = typeof TypeId;
14
15 export interface BgpPrefixProps {
16 /**
17 * Identifier of the parent BYOIP prefix the BGP prefix belongs to.
18 * Changing it forces a replacement.
19 */
20 prefixId: string;
21 /**
22 * IP Prefix in Classless Inter-Domain Routing format. Must be contained
23 * in the parent prefix. Changing it forces a replacement.
24 */
25 cidr: string;
26 /**
27 * Whether the BGP prefix is advertised to the internet (maps to
28 * `on_demand.advertised`). Mutable — patched in place; BGP propagation
29 * is eventually consistent (minutes).
30 * @default false
31 */
32 advertised?: boolean;
33 /**
34 * Number of times to prepend the Cloudflare ASN to the BGP AS-Path
35 * attribute. Mutable.
36 */
37 asnPrependCount?: number;
38 /**
39 * If `true`, Cloudflare advertises the prefix only while a matching BGP
40 * prefix exists in the Magic routing table, automatically withdrawing it
41 * otherwise. Mutable.
42 */
43 autoAdvertiseWithdraw?: boolean;
44 }
45
46 export interface BgpPrefixAttributes {
47 /** Cloudflare-assigned identifier of the BGP prefix. */
48 bgpPrefixId: string;
49 /** Identifier of the parent BYOIP prefix. */
50 prefixId: string;
51 /** The Cloudflare account the prefix belongs to. */
52 accountId: string;
53 /** IP Prefix in CIDR format. */
54 cidr: string;
55 /** ASN the prefix is advertised under. */
56 asn: number | undefined;
57 /** Number of Cloudflare ASN prepends on the AS-Path attribute. */
58 asnPrependCount: number | undefined;
59 /** Whether Cloudflare auto-withdraws the prefix without a Magic route. */
60 autoAdvertiseWithdraw: boolean | undefined;
61 /** On-demand advertisement state for the BGP prefix. */
62 onDemand: {
63 /** Whether the prefix is currently advertised. */
64 advertised: boolean;
65 /** When the advertisement state last changed. */
66 advertisedModifiedAt: string | undefined;
67 /** Whether on-demand advertisement is enabled for the prefix. */
68 onDemandEnabled: boolean;
69 /** `true` while an advertisement change is propagating. */
70 onDemandLocked: boolean;
71 };
72 /** ISO8601 creation timestamp. */
73 createdAt: string | undefined;
74 /** ISO8601 last-modified timestamp. */
75 modifiedAt: string | undefined;
76 }
77
78 export type BgpPrefix = Resource<TypeId, BgpPrefixProps, BgpPrefixAttributes, never, Providers>;
79
80 /**
81 * A BGP prefix controlling on-demand advertisement of a BYOIP prefix (or a
82 * subnet of it) to the internet.
83 *
84 * Cloudflare automatically creates BGP prefixes during BYOIP onboarding, so
85 * reconcile adopts an existing BGP prefix matching the CIDR before creating
86 * a new one. There is **no delete API** — destroying this resource only
87 * withdraws the advertisement (`advertised: false`) and drops the state.
88 * ### Advertising a Prefix
89 * **Example:** Advertise the whole BYOIP prefix
90 * ```typescript
91 * const bgp = yield* Cloudflare.Addressing.BgpPrefix("advertise", {
92 * prefixId: prefix.prefixId,
93 * cidr: prefix.cidr,
94 * advertised: true,
95 * });
96 * ```
97 *
98 * **Example:** Withdraw with AS-Path prepending configured
99 * ```typescript
100 * const bgp = yield* Cloudflare.Addressing.BgpPrefix("advertise", {
101 * prefixId: prefix.prefixId,
102 * cidr: prefix.cidr,
103 * advertised: false,
104 * asnPrependCount: 2,
105 * });
106 * ```
107 *
108 * @see https://developers.cloudflare.com/byoip/concepts/bgp-prefixes/
109 *
110 * @resource
111 * @product Addressing
112 * @category Network
113 */
114 export const BgpPrefix = Resource<BgpPrefix>(TypeId);
115
116 /**
117 * Returns true if the given value is an BgpPrefix resource.
118 */
119 export const isBgpPrefix = (value: unknown): value is BgpPrefix =>
120 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
121
122 export const BgpPrefixProvider = () =>
123 Provider.succeed(BgpPrefix, {
124 stables: ["bgpPrefixId", "prefixId", "accountId", "cidr", "createdAt"],
125
126 diff: Effect.fn(function* ({ olds, news, output }) {
127 if (olds === undefined) return undefined;
128 if (!isResolved(news) || !isResolved(olds)) return undefined;
129 // prefixId is Input<string>; by diff time both sides are concrete.
130 const oldPrefixId = output?.prefixId ?? olds.prefixId;
131 if (
132 typeof oldPrefixId === "string" &&
133 typeof news.prefixId === "string" &&
134 news.prefixId !== oldPrefixId
135 ) {
136 return { action: "replace" } as const;
137 }
138 if (news.cidr !== (output?.cidr ?? olds.cidr)) {
139 return { action: "replace" } as const;
140 }
141 return undefined;
142 }),
143
144 read: Effect.fn(function* ({ output, olds }) {
145 const { accountId } = yield* yield* CloudflareEnvironment;
146 const acct = output?.accountId ?? accountId;
147 const prefixId =
148 output?.prefixId ?? (typeof olds?.prefixId === "string" ? olds.prefixId : undefined);
149 if (!prefixId) return undefined;
150
151 if (output?.bgpPrefixId) {
152 const observed = yield* getBgpPrefix(acct, prefixId, output.bgpPrefixId);
153 return observed ? toAttributes(observed, prefixId, acct) : undefined;
154 }
155 // Cold read — match on CIDR, which is unique within the parent prefix.
156 const cidr = output?.cidr ?? olds?.cidr;
157 if (typeof cidr !== "string") return undefined;
158 const match = yield* findByCidr(acct, prefixId, cidr);
159 return match ? toAttributes(match, prefixId, acct) : undefined;
160 }),
161
162 // BGP prefixes are children of BYOIP IP prefixes, which have no single
163 // account-wide enumeration endpoint. Fan out: list every account IP
164 // prefix, then exhaustively page the BGP prefixes under each. Accounts
165 // without BYOIP simply have no parent prefixes, so the result is
166 // naturally empty.
167 list: Effect.fn(function* () {
168 const { accountId } = yield* yield* CloudflareEnvironment;
169
170 const prefixIds = yield* addressing.listPrefixes.items({ accountId }).pipe(
171 Stream.runCollect,
172 Effect.map((chunk) =>
173 Array.from(chunk)
174 .map((p) => p.id)
175 .filter((id): id is string => typeof id === "string"),
176 ),
177 );
178
179 const rows = yield* Effect.forEach(
180 prefixIds,
181 (prefixId) =>
182 addressing.listPrefixBgpPrefixes.items({ accountId, prefixId }).pipe(
183 Stream.runCollect,
184 Effect.map((chunk) =>
185 Array.from(chunk).map((bgp) => toAttributes(bgp, prefixId, accountId)),
186 ),
187 // Parent prefix removed mid-enumeration — skip it.
188 Effect.catchTag("PrefixNotFound", () => Effect.succeed([] as BgpPrefixAttributes[])),
189 ),
190 { concurrency: 10 },
191 );
192 return rows.flat();
193 }),
194
195 reconcile: Effect.fn(function* ({ news, output }) {
196 const { accountId } = yield* yield* CloudflareEnvironment;
197 const acct = output?.accountId ?? accountId;
198 const prefixId = news.prefixId as string;
199
200 // 1. Observe — by cached id first, then by CIDR: Cloudflare creates
201 // BGP prefixes itself during onboarding, so an existing one with
202 // our CIDR is adopted rather than duplicated.
203 let observed = output?.bgpPrefixId
204 ? yield* getBgpPrefix(acct, prefixId, output.bgpPrefixId)
205 : undefined;
206 if (!observed) {
207 observed = yield* findByCidr(acct, prefixId, news.cidr);
208 }
209
210 // 2. Ensure — create if genuinely missing.
211 if (!observed) {
212 observed = yield* addressing.createPrefixBgpPrefix({
213 accountId: acct,
214 prefixId,
215 cidr: news.cidr,
216 });
217 }
218 const bgpPrefixId = observed.id ?? "";
219
220 // 3. Sync — diff observed advertisement settings against desired and
221 // patch only the delta. `onDemandLocked` means a change is already
222 // propagating; retry (bounded) while locked.
223 const desiredAdvertised = news.advertised ?? false;
224 const dirty =
225 (news.advertised !== undefined &&
226 (observed.onDemand?.advertised ?? false) !== desiredAdvertised) ||
227 (news.asnPrependCount !== undefined &&
228 (observed.asnPrependCount ?? 0) !== news.asnPrependCount) ||
229 (news.autoAdvertiseWithdraw !== undefined &&
230 (observed.autoAdvertiseWithdraw ?? false) !== news.autoAdvertiseWithdraw);
231 if (dirty) {
232 const patched = yield* addressing
233 .patchPrefixBgpPrefix({
234 accountId: acct,
235 prefixId,
236 bgpPrefixId,
237 asnPrependCount: news.asnPrependCount,
238 autoAdvertiseWithdraw: news.autoAdvertiseWithdraw,
239 onDemand: news.advertised !== undefined ? { advertised: news.advertised } : undefined,
240 })
241 .pipe(
242 Effect.retry({
243 while: (e) => e._tag === "BgpPrefixNotFound",
244 schedule: Schedule.exponential("2 seconds"),
245 times: 5,
246 }),
247 );
248 return toAttributes(patched, prefixId, acct);
249 }
250
251 return toAttributes(observed, prefixId, acct);
252 }),
253
254 delete: Effect.fn(function* ({ output }) {
255 // No delete API exists — BGP prefixes live as long as the parent
256 // BYOIP prefix. Withdraw the advertisement (best effort) and drop
257 // the state.
258 if (output.onDemand.advertised) {
259 yield* addressing
260 .patchPrefixBgpPrefix({
261 accountId: output.accountId,
262 prefixId: output.prefixId,
263 bgpPrefixId: output.bgpPrefixId,
264 onDemand: { advertised: false },
265 })
266 .pipe(Effect.catchTag(["BgpPrefixNotFound", "PrefixNotFound"], () => Effect.void));
267 }
268 }),
269 });
270
271 type ObservedBgpPrefix = addressing.GetPrefixBgpPrefixResponse;
272
273 /**
274 * Read a BGP prefix by id, mapping "gone" (`BgpPrefixNotFound` /
275 * `PrefixNotFound`) to `undefined`.
276 */
277 const getBgpPrefix = (accountId: string, prefixId: string, bgpPrefixId: string) =>
278 addressing
279 .getPrefixBgpPrefix({ accountId, prefixId, bgpPrefixId })
280 .pipe(Effect.catchTag(["BgpPrefixNotFound", "PrefixNotFound"], () => Effect.undefined));
281
282 /**
283 * Find a BGP prefix by exact CIDR — unique within a parent prefix. The
284 * parent prefix being gone reads as "no match".
285 */
286 const findByCidr = (accountId: string, prefixId: string, cidr: string) =>
287 addressing.listPrefixBgpPrefixes.items({ accountId, prefixId }).pipe(
288 Stream.runCollect,
289 Effect.map((chunk) => Array.from(chunk).find((p) => p.cidr === cidr)),
290 Effect.catchTag("PrefixNotFound", () => Effect.undefined),
291 );
292
293 const toAttributes = (
294 bgp: ObservedBgpPrefix,
295 prefixId: string,
296 accountId: string,
297 ): BgpPrefixAttributes => ({
298 bgpPrefixId: bgp.id ?? "",
299 prefixId,
300 accountId,
301 cidr: bgp.cidr ?? "",
302 asn: bgp.asn ?? undefined,
303 asnPrependCount: bgp.asnPrependCount ?? undefined,
304 autoAdvertiseWithdraw: bgp.autoAdvertiseWithdraw ?? undefined,
305 onDemand: {
306 advertised: bgp.onDemand?.advertised ?? false,
307 advertisedModifiedAt: bgp.onDemand?.advertisedModifiedAt ?? undefined,
308 onDemandEnabled: bgp.onDemand?.onDemandEnabled ?? false,
309 onDemandLocked: bgp.onDemand?.onDemandLocked ?? false,
310 },
311 createdAt: bgp.createdAt ?? undefined,
312 modifiedAt: bgp.modifiedAt ?? undefined,
313 });