@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 244 lines 8.24 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 Stream from "effect/Stream";
8 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
9 import type { Providers } from "../Providers.ts";
10
11 const TypeId = "Cloudflare.Addressing.PrefixDelegation" as const;
12 type TypeId = typeof TypeId;
13
14 export interface PrefixDelegationProps {
15 /**
16 * Identifier of the parent BYOIP prefix being delegated from. Changing it
17 * forces a replacement.
18 */
19 prefixId: string;
20 /**
21 * IP Prefix in Classless Inter-Domain Routing format to delegate. Must be
22 * contained in the parent prefix. Changing it forces a replacement.
23 */
24 cidr: string;
25 /**
26 * Identifier of the Cloudflare account the prefix is delegated to.
27 * Changing it forces a replacement.
28 */
29 delegatedAccountId: string;
30 }
31
32 export interface PrefixDelegationAttributes {
33 /** Cloudflare-assigned identifier of the delegation. */
34 delegationId: string;
35 /** Identifier of the parent BYOIP prefix. */
36 prefixId: string;
37 /** The Cloudflare account that owns the parent prefix. */
38 accountId: string;
39 /** Delegated IP Prefix in CIDR format. */
40 cidr: string;
41 /** The account the prefix portion is delegated to. */
42 delegatedAccountId: string;
43 /** ISO8601 creation timestamp. */
44 createdAt: string | undefined;
45 }
46
47 export type PrefixDelegation = Resource<
48 TypeId,
49 PrefixDelegationProps,
50 PrefixDelegationAttributes,
51 never,
52 Providers
53 >;
54
55 /**
56 * Delegates part of a BYOIP prefix to another Cloudflare account, allowing
57 * that account to use the delegated CIDR (e.g. for its own service
58 * bindings).
59 *
60 * Delegations are create/delete only — every prop change forces a
61 * replacement.
62 * ### Delegating a Prefix
63 * **Example:** Delegate a /26 to another account
64 * ```typescript
65 * const delegation = yield* Cloudflare.Addressing.PrefixDelegation("share", {
66 * prefixId: prefix.prefixId,
67 * cidr: "192.0.2.0/26",
68 * delegatedAccountId: "023e105f4ecef8ad9ca31a8372d0c353",
69 * });
70 * ```
71 *
72 * @see https://developers.cloudflare.com/byoip/
73 *
74 * @resource
75 * @product Addressing
76 * @category Network
77 */
78 export const PrefixDelegation = Resource<PrefixDelegation>(TypeId);
79
80 /**
81 * Returns true if the given value is an PrefixDelegation resource.
82 */
83 export const isPrefixDelegation = (value: unknown): value is PrefixDelegation =>
84 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
85
86 export const PrefixDelegationProvider = () =>
87 Provider.succeed(PrefixDelegation, {
88 stables: ["delegationId", "prefixId", "accountId", "cidr", "delegatedAccountId", "createdAt"],
89
90 diff: Effect.fn(function* ({ olds, news, output }) {
91 if (olds === undefined) return undefined;
92 if (!isResolved(news) || !isResolved(olds)) return undefined;
93 // Create/delete only — any change forces a replacement.
94 const oldPrefixId = output?.prefixId ?? olds.prefixId;
95 if (
96 typeof oldPrefixId === "string" &&
97 typeof news.prefixId === "string" &&
98 news.prefixId !== oldPrefixId
99 ) {
100 return { action: "replace" } as const;
101 }
102 if (news.cidr !== (output?.cidr ?? olds.cidr)) {
103 return { action: "replace" } as const;
104 }
105 const oldDelegated = output?.delegatedAccountId ?? olds.delegatedAccountId;
106 if (
107 typeof oldDelegated === "string" &&
108 typeof news.delegatedAccountId === "string" &&
109 news.delegatedAccountId !== oldDelegated
110 ) {
111 return { action: "replace" } as const;
112 }
113 return undefined;
114 }),
115
116 read: Effect.fn(function* ({ output, olds }) {
117 const { accountId } = yield* yield* CloudflareEnvironment;
118 const acct = output?.accountId ?? accountId;
119 const prefixId =
120 output?.prefixId ?? (typeof olds?.prefixId === "string" ? olds.prefixId : undefined);
121 if (!prefixId) return undefined;
122
123 // There is no get-by-id op — list and filter. Cold reads match on
124 // (cidr, delegatedAccountId), which identify a delegation uniquely.
125 const delegations = yield* listDelegations(acct, prefixId);
126 const match = output?.delegationId
127 ? delegations.find((d) => d.id === output.delegationId)
128 : delegations.find(
129 (d) =>
130 d.cidr === (output?.cidr ?? olds?.cidr) &&
131 d.delegatedAccountId ===
132 (output?.delegatedAccountId ??
133 (typeof olds?.delegatedAccountId === "string"
134 ? olds.delegatedAccountId
135 : undefined)),
136 );
137 return match ? toAttributes(match, prefixId, acct) : undefined;
138 }),
139
140 reconcile: Effect.fn(function* ({ news, output }) {
141 const { accountId } = yield* yield* CloudflareEnvironment;
142 const acct = output?.accountId ?? accountId;
143 const prefixId = news.prefixId as string;
144 const delegatedAccountId = news.delegatedAccountId as string;
145
146 // 1. Observe — find an existing delegation with the same identity.
147 const delegations = yield* listDelegations(acct, prefixId);
148 const observed =
149 (output?.delegationId
150 ? delegations.find((d) => d.id === output.delegationId)
151 : undefined) ??
152 delegations.find(
153 (d) => d.cidr === news.cidr && d.delegatedAccountId === delegatedAccountId,
154 );
155 if (observed) {
156 // Nothing is mutable — converged.
157 return toAttributes(observed, prefixId, acct);
158 }
159
160 // 2. Ensure — create the delegation.
161 const created = yield* addressing.createPrefixDelegation({
162 accountId: acct,
163 prefixId,
164 cidr: news.cidr,
165 delegatedAccountId,
166 });
167 return toAttributes(created, prefixId, acct);
168 }),
169
170 delete: Effect.fn(function* ({ output }) {
171 yield* addressing
172 .deletePrefixDelegation({
173 accountId: output.accountId,
174 prefixId: output.prefixId,
175 delegationId: output.delegationId,
176 })
177 .pipe(Effect.catchTag("DelegationNotFound", () => Effect.void));
178 }),
179
180 // Delegations are children of BYOIP prefixes and have no account-wide
181 // enumeration API. Fan out: list every account prefix, then list the
182 // delegations on each prefix (bounded concurrency). A prefix that has
183 // gone away between the two calls reads as an empty list (typed
184 // `PrefixNotFound`, handled in `listDelegations`).
185 list: Effect.fn(function* () {
186 const { accountId } = yield* yield* CloudflareEnvironment;
187
188 const prefixIds = yield* addressing.listPrefixes.pages({ accountId }).pipe(
189 Stream.runCollect,
190 Effect.map((chunk) =>
191 Array.from(chunk).flatMap((page) =>
192 (page.result ?? [])
193 .map((p) => p.id)
194 .filter((id): id is string => typeof id === "string"),
195 ),
196 ),
197 );
198
199 const rows = yield* Effect.forEach(
200 prefixIds,
201 (prefixId) =>
202 listDelegations(accountId, prefixId).pipe(
203 Effect.map((delegations) =>
204 delegations.map((d) => toAttributes(d, prefixId, accountId)),
205 ),
206 ),
207 { concurrency: 10 },
208 );
209
210 return rows.flat();
211 }),
212 });
213
214 interface ObservedDelegation {
215 readonly id?: string | null;
216 readonly cidr?: string | null;
217 readonly createdAt?: string | null;
218 readonly delegatedAccountId?: string | null;
219 readonly parentPrefixId?: string | null;
220 }
221
222 /**
223 * List all delegations on a prefix. A missing parent prefix reads as an
224 * empty list.
225 */
226 const listDelegations = (accountId: string, prefixId: string) =>
227 addressing.listPrefixDelegations.items({ accountId, prefixId }).pipe(
228 Stream.runCollect,
229 Effect.map((chunk) => Array.from(chunk) as ObservedDelegation[]),
230 Effect.catchTag("PrefixNotFound", () => Effect.succeed([] as ObservedDelegation[])),
231 );
232
233 const toAttributes = (
234 delegation: ObservedDelegation,
235 prefixId: string,
236 accountId: string,
237 ): PrefixDelegationAttributes => ({
238 delegationId: delegation.id ?? "",
239 prefixId,
240 accountId,
241 cidr: delegation.cidr ?? "",
242 delegatedAccountId: delegation.delegatedAccountId ?? "",
243 createdAt: delegation.createdAt ?? undefined,
244 });