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

main
ts 277 lines 9.21 KB
Raw
1 import * as loadBalancers from "@distilled.cloud/cloudflare/load-balancers";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Predicate from "effect/Predicate";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
11 import type { Providers } from "../Providers.ts";
12
13 const TypeId = "Cloudflare.LoadBalancer.MonitorGroup" as const;
14 type TypeId = typeof TypeId;
15
16 /**
17 * A monitor membership within a monitor group.
18 */
19 export interface MonitorGroupMember {
20 /**
21 * The ID of the {@link Monitor} to include in the group.
22 */
23 monitorId: string;
24 /**
25 * Whether this member's health check is active.
26 * @default true
27 */
28 enabled?: boolean;
29 /**
30 * If true, the member's results are recorded but do not affect the
31 * group's aggregate health.
32 * @default false
33 */
34 monitoringOnly?: boolean;
35 /**
36 * Whether this member must report healthy for the group to be healthy.
37 * @default true
38 */
39 mustBeHealthy?: boolean;
40 }
41
42 export interface MonitorGroupProps {
43 /**
44 * A short description of the monitor group. Monitor groups have no name
45 * field, so the description doubles as the group's identity for state
46 * recovery — if omitted, a unique name is generated from the app, stage,
47 * and logical ID.
48 * @default ${app}-${stage}-${id}
49 */
50 description?: string;
51 /**
52 * List of monitors in this group.
53 */
54 members: ReadonlyArray<MonitorGroupMember>;
55 }
56
57 export interface MonitorGroupAttributes {
58 /** Cloudflare-assigned monitor group identifier. */
59 monitorGroupId: string;
60 /** The Cloudflare account the monitor group belongs to. */
61 accountId: string;
62 /** Monitor group description (carries the physical name when generated). */
63 description: string;
64 /** ISO8601 creation timestamp. */
65 createdOn: string | undefined;
66 /** ISO8601 last-modified timestamp. */
67 modifiedOn: string | undefined;
68 }
69
70 export type MonitorGroup = Resource<
71 TypeId,
72 MonitorGroupProps,
73 MonitorGroupAttributes,
74 never,
75 Providers
76 >;
77
78 /**
79 * A Cloudflare Load Balancing monitor group — aggregates several
80 * {@link Monitor}s into one health signal that a
81 * {@link Pool} can reference via `monitorGroup` (mutually
82 * exclusive with `monitor`).
83 *
84 * Monitor groups are an Enterprise-only feature; on non-entitled accounts
85 * creation fails with the typed `MonitorGroupsNotEnabled` error.
86 * ### Creating a Monitor Group
87 * **Example:** Group of two monitors
88 * ```typescript
89 * const group = yield* Cloudflare.LoadBalancer.MonitorGroup("ApiChecks", {
90 * members: [
91 * { monitorId: httpsMonitor.monitorId },
92 * { monitorId: tcpMonitor.monitorId, mustBeHealthy: false },
93 * ],
94 * });
95 * ```
96 *
97 * ### Using with a Pool
98 * **Example:** Attach the group to a pool
99 * ```typescript
100 * yield* Cloudflare.LoadBalancer.Pool("ApiPool", {
101 * origins: [{ name: "origin-1", address: "203.0.113.10" }],
102 * monitorGroup: group.monitorGroupId,
103 * });
104 * ```
105 *
106 * @see https://developers.cloudflare.com/load-balancing/monitors/
107 *
108 * @resource
109 * @product Load Balancers
110 * @category Performance & Reliability
111 */
112 export const MonitorGroup = Resource<MonitorGroup>(TypeId);
113
114 /**
115 * Returns true if the given value is a MonitorGroup resource.
116 */
117 export const isMonitorGroup = (value: unknown): value is MonitorGroup =>
118 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
119
120 export const MonitorGroupProvider = () =>
121 Provider.succeed(MonitorGroup, {
122 stables: ["monitorGroupId", "accountId", "createdOn"],
123
124 diff: Effect.fn(function* ({ output }) {
125 const { accountId } = yield* yield* CloudflareEnvironment;
126 if ((output?.accountId ?? accountId) !== accountId) {
127 return { action: "replace" } as const;
128 }
129 return undefined;
130 }),
131
132 // Monitor groups are an account-scoped collection — paginate the
133 // account-wide list and hydrate each into the exact `read` Attributes
134 // shape (pattern (b) in processes/list-support.md).
135 list: Effect.fn(function* () {
136 const { accountId } = yield* yield* CloudflareEnvironment;
137 return yield* loadBalancers.listMonitorGroups.pages({ accountId }).pipe(
138 Stream.runCollect,
139 Effect.map((chunk) =>
140 Array.from(chunk).flatMap((page) =>
141 (page.result ?? []).map((g) => toAttributes(g, accountId)),
142 ),
143 ),
144 );
145 }),
146
147 read: Effect.fn(function* ({ id, output, olds }) {
148 const { accountId } = yield* yield* CloudflareEnvironment;
149 const acct = output?.accountId ?? accountId;
150
151 if (output?.monitorGroupId) {
152 const observed = yield* getMonitorGroup(acct, output.monitorGroupId);
153 return observed ? toAttributes(observed, acct) : undefined;
154 }
155 // Cold read — recover from lost state by matching the deterministic
156 // description (our physical name). Monitor groups carry no ownership
157 // marker, so report the match as Unowned.
158 const description = yield* createDescription(id, olds?.description);
159 const match = yield* findByDescription(acct, description);
160 if (match) return Unowned(toAttributes(match, acct));
161 return undefined;
162 }),
163
164 reconcile: Effect.fn(function* ({ id, news, output }) {
165 const { accountId } = yield* yield* CloudflareEnvironment;
166 const description = yield* createDescription(id, news.description);
167 const members = buildMembers(news);
168
169 // 1. Observe — output.monitorGroupId is a cache hint.
170 const observed = output?.monitorGroupId
171 ? yield* getMonitorGroup(output.accountId ?? accountId, output.monitorGroupId)
172 : undefined;
173
174 // 2. Ensure — missing: create with the full desired body.
175 if (!observed) {
176 const created = yield* loadBalancers.createMonitorGroup({
177 accountId,
178 description,
179 members,
180 });
181 return toAttributes(created, accountId);
182 }
183
184 // 3. Sync — PUT the full desired body when anything drifts; skip
185 // the call on a no-op.
186 const dirty =
187 observed.description !== description ||
188 JSON.stringify(
189 observed.members.map((m) => ({
190 monitorId: m.monitorId,
191 enabled: m.enabled,
192 monitoringOnly: m.monitoringOnly,
193 mustBeHealthy: m.mustBeHealthy,
194 })),
195 ) !== JSON.stringify(members);
196 if (!dirty) {
197 return toAttributes(observed, accountId);
198 }
199 const updated = yield* loadBalancers.updateMonitorGroup({
200 accountId,
201 monitorGroupId: observed.id,
202 description,
203 members,
204 });
205 return toAttributes(updated, accountId);
206 }),
207
208 delete: Effect.fn(function* ({ output }) {
209 // A group still referenced by a pool cannot be deleted — retry the
210 // typed MonitorGroupInUse tag with bounded backoff while the engine
211 // tears down dependents.
212 yield* loadBalancers
213 .deleteMonitorGroup({
214 accountId: output.accountId,
215 monitorGroupId: output.monitorGroupId,
216 })
217 .pipe(
218 Effect.retry({
219 while: (e) => e._tag === "MonitorGroupInUse",
220 schedule: Schedule.max([Schedule.exponential("1 second"), Schedule.recurs(6)]),
221 }),
222 Effect.catchTag("MonitorGroupNotFound", () => Effect.void),
223 );
224 }),
225 });
226
227 type ObservedMonitorGroup =
228 | loadBalancers.GetMonitorGroupResponse
229 | loadBalancers.CreateMonitorGroupResponse
230 | loadBalancers.UpdateMonitorGroupResponse
231 | loadBalancers.ListMonitorGroupsResponse["result"][number];
232
233 /**
234 * Read a monitor group by id, mapping "gone" (`MonitorGroupNotFound`,
235 * HTTP 404 code 1001) to `undefined`.
236 */
237 const getMonitorGroup = (accountId: string, monitorGroupId: string) =>
238 loadBalancers
239 .getMonitorGroup({ accountId, monitorGroupId })
240 .pipe(Effect.catchTag("MonitorGroupNotFound", () => Effect.undefined));
241
242 /**
243 * Find a monitor group by exact description. If several carry the same
244 * description, pick the oldest for determinism.
245 */
246 const findByDescription = (accountId: string, description: string) =>
247 loadBalancers.listMonitorGroups.items({ accountId }).pipe(
248 Stream.filter((g) => g.description === description),
249 Stream.runCollect,
250 Effect.map((chunk) =>
251 Array.from(chunk)
252 .sort((a, b) => (a.createdOn ?? "").localeCompare(b.createdOn ?? ""))
253 .at(0),
254 ),
255 );
256
257 const createDescription = (id: string, description: string | undefined) =>
258 Effect.gen(function* () {
259 return description ?? (yield* createPhysicalName({ id, lowercase: true }));
260 });
261
262 const buildMembers = (news: MonitorGroupProps) =>
263 news.members.map((m) => ({
264 // Inputs are resolved to concrete strings by Plan.
265 monitorId: m.monitorId as string,
266 enabled: m.enabled ?? true,
267 monitoringOnly: m.monitoringOnly ?? false,
268 mustBeHealthy: m.mustBeHealthy ?? true,
269 }));
270
271 const toAttributes = (group: ObservedMonitorGroup, accountId: string): MonitorGroupAttributes => ({
272 monitorGroupId: group.id,
273 accountId,
274 description: group.description,
275 createdOn: group.createdOn ?? undefined,
276 modifiedOn: group.modifiedOn ?? undefined,
277 });