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

main
ts 292 lines 11.2 KB
Raw
1 import * as diagnostics from "@distilled.cloud/cloudflare/diagnostics";
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 Predicate from "effect/Predicate";
9 import * as Schedule from "effect/Schedule";
10 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
11 import type { Providers } from "../Providers.ts";
12
13 const TypeId = "Cloudflare.Diagnostics.EndpointHealthcheck" as const;
14 type TypeId = typeof TypeId;
15
16 export interface EndpointHealthcheckProps {
17 /**
18 * The IP address of the host to perform checks against. Must be an
19 * on-net (private) IP reachable through Magic Transit / Magic WAN, and
20 * unique among the account's endpoint healthchecks — Cloudflare rejects
21 * public or duplicate IPs with an "Invalid request" error (code 1002,
22 * surfaced as the typed `InvalidHealthcheckEndpoint`).
23 */
24 endpoint: string;
25 /**
26 * Type of check to perform. Only `"icmp"` is supported today.
27 * @default "icmp"
28 */
29 checkType?: "icmp";
30 /**
31 * Optional name associated with this check. Not unique on Cloudflare's
32 * side. If omitted, a unique name is generated from the app, stage, and
33 * logical ID.
34 *
35 * Cannot be changed after creation — Cloudflare's PUT endpoint echoes a
36 * new name back but never persists it — so updating this property
37 * triggers a replacement.
38 * @default ${app}-${stage}-${id}
39 */
40 name?: string;
41 }
42
43 export interface EndpointHealthcheckAttributes {
44 /** UUID of the endpoint healthcheck. Stable across updates. */
45 healthcheckId: string;
46 /** The Cloudflare account the healthcheck belongs to. */
47 accountId: string;
48 /** Type of check performed. */
49 checkType: "icmp" | (string & {});
50 /** The IP address of the host checks are performed against. */
51 endpoint: string;
52 /** Name associated with this check. */
53 name: string;
54 }
55
56 export type EndpointHealthcheck = Resource<
57 TypeId,
58 EndpointHealthcheckProps,
59 EndpointHealthcheckAttributes,
60 never,
61 Providers
62 >;
63
64 /**
65 * A Magic Transit / Magic WAN endpoint healthcheck — a continuous ICMP
66 * probe of an on-net IP address used to monitor reachability of hosts
67 * behind Magic tunnels.
68 *
69 * The `endpoint` must be a private (on-net) IP; Cloudflare rejects public
70 * IPs with the typed `InvalidHealthcheckEndpoint` error. The `endpoint` is
71 * mutable in place via PUT (the UUID is stable across updates), but `name`
72 * is create-only — changing it triggers a replacement.
73 * ### Creating an endpoint healthcheck
74 * **Example:** Probe an on-net host
75 * ```typescript
76 * const check = yield* Cloudflare.Diagnostics.EndpointHealthcheck("core-router", {
77 * endpoint: "10.0.0.1",
78 * });
79 * ```
80 *
81 * **Example:** With an explicit name
82 * ```typescript
83 * const check = yield* Cloudflare.Diagnostics.EndpointHealthcheck("core-router", {
84 * endpoint: "10.0.0.1",
85 * name: "core-router-probe",
86 * });
87 * ```
88 *
89 * ### Updating
90 * **Example:** Re-point the probe at a different host
91 * ```typescript
92 * // Changing `endpoint` updates the same healthcheck in place.
93 * const check = yield* Cloudflare.Diagnostics.EndpointHealthcheck("core-router", {
94 * endpoint: "10.0.0.2",
95 * });
96 * ```
97 *
98 * @see https://developers.cloudflare.com/magic-wan/
99 *
100 * @resource
101 * @product Diagnostics
102 * @category Observability & Analytics
103 */
104 export const EndpointHealthcheck = Resource<EndpointHealthcheck>(TypeId);
105
106 /**
107 * Returns true if the given value is an EndpointHealthcheck resource.
108 */
109 export const isEndpointHealthcheck = (value: unknown): value is EndpointHealthcheck =>
110 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
111
112 export const EndpointHealthcheckProvider = () =>
113 Provider.succeed(EndpointHealthcheck, {
114 stables: ["healthcheckId", "accountId"],
115
116 diff: Effect.fn(function* ({ id, news, output }) {
117 const { accountId } = yield* yield* CloudflareEnvironment;
118 if (!isResolved(news)) return undefined;
119 // Healthchecks live under an account; moving accounts is a replace.
120 if (output !== undefined && output.accountId !== accountId) {
121 return { action: "replace" } as const;
122 }
123 // The name is create-only: Cloudflare's PUT echoes a new name back
124 // but never persists it, so a name change forces a replacement.
125 // Auto-generated names are engine-owned: the deployed name stays
126 // authoritative even if the generator would name this id differently
127 // today. Only an explicit user-provided name can force a replace.
128 const desiredName =
129 news.name ?? output?.name ?? (yield* createHealthcheckName(id, news.name));
130 if (output !== undefined && output.name !== desiredName) {
131 return { action: "replace" } as const;
132 }
133 return undefined;
134 }),
135
136 read: Effect.fn(function* ({ id, output, olds }) {
137 const { accountId } = yield* yield* CloudflareEnvironment;
138 const acct = output?.accountId ?? accountId;
139
140 if (output?.healthcheckId) {
141 const observed = yield* getHealthcheck(acct, output.healthcheckId);
142 if (observed) return toAttributes(observed, acct);
143 return undefined;
144 }
145 // Cold read — recover from lost state by matching the deterministic
146 // physical name. Healthchecks carry no ownership markers, so report
147 // the match as Unowned and let the adopt policy gate takeover.
148 const name = yield* createHealthcheckName(id, olds?.name);
149 const match = yield* findByName(acct, name);
150 if (match) return Unowned(toAttributes(match, acct));
151 return undefined;
152 }),
153
154 reconcile: Effect.fn(function* ({ id, news, output }) {
155 const { accountId } = yield* yield* CloudflareEnvironment;
156 const name = yield* createHealthcheckName(id, news.name);
157 const desired = {
158 checkType: news.checkType ?? ("icmp" as const),
159 endpoint: news.endpoint,
160 name,
161 };
162
163 // Observe — the id cached on `output` is a hint, not a guarantee:
164 // a "No entry found" falls through to missing and we recreate.
165 // A GET right after a prior create can transiently 404 while the
166 // new healthcheck propagates; bounded-retry on the typed
167 // `EndpointHealthcheckNotFound` before concluding it is gone, so a
168 // propagation blip never leaks a duplicate (names are not unique).
169 const observed = output?.healthcheckId
170 ? yield* observeExisting(output.accountId ?? accountId, output.healthcheckId)
171 : undefined;
172
173 // Ensure — greenfield (or out-of-band delete): create with the full
174 // desired body. Names are not unique so there is no AlreadyExists
175 // race to tolerate.
176 if (!observed) {
177 const created = yield* diagnostics.createEndpointHealthcheck({
178 accountId,
179 ...desired,
180 });
181 return toAttributes(created, accountId);
182 }
183
184 // Sync — diff observed cloud state against desired; the update API
185 // is a PUT carrying the full body, so send everything, but skip the
186 // call entirely on a no-op. The name is create-only (a changed name
187 // is routed to replacement by `diff`; the PUT echoes a new name back
188 // without persisting it), so it never participates in the dirty
189 // check and the observed name is kept as the source of truth.
190 const dirty =
191 observed.endpoint !== desired.endpoint || observed.checkType !== desired.checkType;
192 if (!dirty) {
193 return toAttributes(observed, observed.accountId);
194 }
195
196 const updated = yield* diagnostics.updateEndpointHealthcheck({
197 accountId: observed.accountId,
198 id: observed.id ?? output!.healthcheckId,
199 ...desired,
200 name: observed.name ?? undefined,
201 });
202 // The PUT response echoes the request body; only `endpoint` is
203 // actually mutable, so overlay the persisted (observed) name.
204 return toAttributes({ ...updated, name: observed.name }, observed.accountId);
205 }),
206
207 list: Effect.fn(function* () {
208 const { accountId } = yield* yield* CloudflareEnvironment;
209 // Account-scoped, non-paginated list (the whole collection comes
210 // back in one response array). Skip accounts that lack the Magic
211 // Transit / WAN entitlement (typed `Forbidden`) with an empty list.
212 return yield* diagnostics.listEndpointHealthchecks({ accountId }).pipe(
213 Effect.map((checks) => checks.map((hc) => toAttributes(hc, accountId))),
214 Effect.catchTag("Forbidden", () => Effect.succeed([])),
215 );
216 }),
217
218 delete: Effect.fn(function* ({ output }) {
219 yield* diagnostics
220 .deleteEndpointHealthcheck({
221 accountId: output.accountId,
222 id: output.healthcheckId,
223 })
224 .pipe(Effect.catchTag("EndpointHealthcheckNotFound", () => Effect.void));
225 }),
226 });
227
228 type ObservedHealthcheck = diagnostics.GetEndpointHealthcheckResponse & {
229 accountId: string;
230 };
231
232 /**
233 * Read a healthcheck by id, mapping "gone" (`EndpointHealthcheckNotFound`,
234 * Cloudflare error code 1022) to `undefined`.
235 */
236 const getHealthcheck = (accountId: string, id: string) =>
237 diagnostics.getEndpointHealthcheck({ accountId, id }).pipe(
238 Effect.map((hc): ObservedHealthcheck => ({ ...hc, accountId })),
239 Effect.catchTag("EndpointHealthcheckNotFound", () => Effect.undefined),
240 );
241
242 /**
243 * Observe a healthcheck we believe exists (its id is cached on `output`).
244 * A GET issued right after a create can transiently 404 while the new
245 * state propagates, so bounded-retry on the typed
246 * `EndpointHealthcheckNotFound` before treating the resource as gone —
247 * this prevents a propagation blip from triggering a duplicate create.
248 */
249 const observeExisting = (accountId: string, id: string) =>
250 diagnostics.getEndpointHealthcheck({ accountId, id }).pipe(
251 Effect.map((hc): ObservedHealthcheck => ({ ...hc, accountId })),
252 Effect.retry({
253 while: (e) => e._tag === "EndpointHealthcheckNotFound",
254 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
255 }),
256 Effect.catchTag("EndpointHealthcheckNotFound", () => Effect.undefined),
257 );
258
259 /**
260 * Find a healthcheck by exact name. Names are not enforced unique on
261 * Cloudflare's side; pick deterministically by id.
262 */
263 const findByName = (accountId: string, name: string) =>
264 diagnostics.listEndpointHealthchecks({ accountId }).pipe(
265 Effect.map((list) =>
266 list
267 .filter((hc) => hc.name === name && typeof hc.id === "string")
268 .sort((a, b) => (a.id ?? "").localeCompare(b.id ?? ""))
269 .at(0),
270 ),
271 Effect.map((hc): ObservedHealthcheck | undefined => hc && { ...hc, accountId }),
272 );
273
274 const createHealthcheckName = (id: string, name: string | undefined) =>
275 Effect.gen(function* () {
276 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
277 });
278
279 const toAttributes = (
280 hc:
281 | ObservedHealthcheck
282 | diagnostics.CreateEndpointHealthcheckResponse
283 | diagnostics.UpdateEndpointHealthcheckResponse
284 | diagnostics.ListEndpointHealthchecksResponse[number],
285 accountId: string,
286 ): EndpointHealthcheckAttributes => ({
287 healthcheckId: hc.id ?? "",
288 accountId,
289 checkType: hc.checkType,
290 endpoint: hc.endpoint,
291 name: hc.name ?? "",
292 });