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

main
ts 194 lines 6.96 KB
Raw
1 import * as logs from "@distilled.cloud/cloudflare/logs";
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 { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
8 import type { Providers } from "../Providers.ts";
9 import { listAllZones } from "../Zone/lookup.ts";
10
11 const TypeId = "Cloudflare.Logs.RetentionFlag" as const;
12 type TypeId = typeof TypeId;
13
14 export type LogsRetentionFlagProps = {
15 /**
16 * Zone whose Logpull retention flag is managed. The flag is a zone-level
17 * singleton, so the zone is the resource's identity — changing it
18 * triggers a replacement (the old zone's flag is restored to the value
19 * it had before Alchemy managed it).
20 */
21 zoneId: string;
22 /**
23 * Whether Logpull log retention is enabled for the zone. Mutable —
24 * re-posted in place.
25 */
26 flag: boolean;
27 };
28
29 export type LogsRetentionFlagAttributes = {
30 /** Zone the retention flag belongs to. */
31 zoneId: string;
32 /** Whether Logpull log retention is enabled. */
33 flag: boolean;
34 /**
35 * The value the flag had before Alchemy first managed it. Restored on
36 * destroy, so deleting the resource puts the zone back the way it was
37 * found.
38 */
39 initialFlag: boolean;
40 };
41
42 export type LogsRetentionFlag = Resource<
43 TypeId,
44 LogsRetentionFlagProps,
45 LogsRetentionFlagAttributes,
46 never,
47 Providers
48 >;
49
50 /**
51 * The zone-level Logpull retention flag
52 * (`/zones/{zone_id}/logs/control/retention/flag`) pinned to a desired
53 * value.
54 *
55 * The flag is a singleton that always exists on every zone, so this
56 * resource never creates or deletes anything physical. Reconcile re-posts
57 * the flag when the observed value differs from the desired one; destroy
58 * restores the value the flag had before Alchemy first managed it
59 * (captured as `initialFlag`) — there is no DELETE endpoint.
60 *
61 * Logpull is an Enterprise feature — on unentitled zones every operation
62 * fails with the typed `LogsControlNotAuthorized` error.
63 * ### Managing log retention
64 * **Example:** Enable Logpull retention on a zone
65 * ```typescript
66 * const retention = yield* Cloudflare.LogsControl.LogsRetentionFlag("Retention", {
67 * zoneId: zone.zoneId,
68 * flag: true,
69 * });
70 * ```
71 *
72 * **Example:** Explicitly disable retention
73 * ```typescript
74 * yield* Cloudflare.LogsControl.LogsRetentionFlag("Retention", {
75 * zoneId: zone.zoneId,
76 * flag: false,
77 * });
78 * ```
79 *
80 * @see https://developers.cloudflare.com/logs/logpull/enabling-log-retention/
81 *
82 * @resource
83 * @product Logs
84 * @category Observability & Analytics
85 */
86 export const LogsRetentionFlag = Resource<LogsRetentionFlag>(TypeId);
87
88 /**
89 * Returns true if the given value is a LogsRetentionFlag resource.
90 */
91 export const isLogsRetentionFlag = (value: unknown): value is LogsRetentionFlag =>
92 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
93
94 export const LogsRetentionFlagProvider = () =>
95 Provider.succeed(LogsRetentionFlag, {
96 stables: ["zoneId", "initialFlag"],
97
98 list: Effect.fn(function* () {
99 const { accountId } = yield* yield* CloudflareEnvironment;
100 // No account-wide API for this zone singleton — enumerate every
101 // zone in the account and read its retention flag (every zone has
102 // one). The observed value at enumeration time is the zone's
103 // original, so it doubles as `initialFlag`.
104 const allZones = yield* listAllZones(accountId);
105 const rows = yield* Effect.forEach(
106 allZones.map((zone) => zone.id),
107 (zoneId) =>
108 getFlag(zoneId).pipe(
109 Effect.map((flag) =>
110 flag === undefined
111 ? undefined
112 : ({
113 zoneId,
114 flag,
115 initialFlag: flag,
116 } satisfies LogsRetentionFlagAttributes),
117 ),
118 // Logpull is Enterprise-only; unentitled zones reject with the
119 // typed error — skip them rather than fail the whole listing.
120 Effect.catchTag("LogsControlNotAuthorized", () => Effect.undefined),
121 ),
122 { concurrency: 10 },
123 );
124 return rows.filter((row): row is LogsRetentionFlagAttributes => row !== undefined);
125 }),
126
127 diff: Effect.fn(function* ({ news, output }) {
128 if (!isResolved(news)) return undefined;
129 // The zone is the singleton's identity.
130 if (output !== undefined && output.zoneId !== news.zoneId) {
131 return { action: "replace" } as const;
132 }
133 return undefined;
134 }),
135
136 read: Effect.fn(function* ({ output, olds }) {
137 const zoneId = output?.zoneId ?? (typeof olds?.zoneId === "string" ? olds.zoneId : undefined);
138 if (zoneId === undefined) return undefined;
139 const observed = yield* getFlag(zoneId);
140 // Zone deleted out-of-band — the flag is gone with it.
141 if (observed === undefined) return undefined;
142 // The flag is a zone singleton that always exists — there is nothing
143 // to "own", so a cold read adopts freely. The observed value at
144 // adoption time becomes the `initialFlag` restored on destroy.
145 const initialFlag = output?.initialFlag ?? observed;
146 return { zoneId, flag: observed, initialFlag };
147 }),
148
149 reconcile: Effect.fn(function* ({ news, output }) {
150 // Inputs were resolved to concrete strings by Plan.
151 const zoneId = news.zoneId as string;
152
153 // 1. Observe — the flag always exists; read its live value.
154 const observed = yield* logs
155 .getControlRetention({ zoneId })
156 .pipe(Effect.map((r) => r.flag ?? false));
157
158 // 2. Capture — the pre-management value, restored on destroy.
159 const initialFlag = output?.initialFlag ?? observed;
160
161 // 3. Sync — re-post only when the observed value differs.
162 if (observed === news.flag) {
163 return { zoneId, flag: observed, initialFlag };
164 }
165 const updated = yield* logs.createControlRetention({
166 zoneId,
167 flag: news.flag,
168 });
169 return { zoneId, flag: updated.flag ?? news.flag, initialFlag };
170 }),
171
172 delete: Effect.fn(function* ({ output }) {
173 const { zoneId, initialFlag } = output;
174 // Observe — if the zone itself is gone, so is the flag.
175 const observed = yield* getFlag(zoneId);
176 if (observed === undefined) return;
177 // Restore the pre-management value; skip the call when it already
178 // matches (idempotent re-delete after a crashed run).
179 if (observed === initialFlag) return;
180 yield* logs
181 .createControlRetention({ zoneId, flag: initialFlag })
182 .pipe(Effect.catchTag("InvalidRoute", () => Effect.void));
183 }),
184 });
185
186 /**
187 * Read the retention flag, normalizing a missing zone (`InvalidRoute`,
188 * Cloudflare error code 7003) to `undefined` and a null flag to `false`.
189 */
190 const getFlag = (zoneId: string) =>
191 logs.getControlRetention({ zoneId }).pipe(
192 Effect.map((r) => r.flag ?? false),
193 Effect.catchTag("InvalidRoute", () => Effect.undefined),
194 );