@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, 04:45 UTC

main
ts 197 lines 7.43 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
10 const TypeId = "Cloudflare.Logs.CmbConfig" as const;
11 type TypeId = typeof TypeId;
12
13 export type CmbConfigProps = {
14 /**
15 * The Cloudflare account whose Customer Metadata Boundary (CMB) log
16 * configuration is managed. The config is an account-level singleton, so
17 * the account is the resource's identity — changing it triggers a
18 * replacement.
19 * @default the account from the active Cloudflare profile
20 */
21 accountId?: string;
22 /**
23 * Name of the region log data is restricted to (e.g. `"eu"`).
24 *
25 * Changing the CMB region affects where ALL logs for the account are
26 * stored and processed — treat this as a destructive, account-wide
27 * setting.
28 */
29 regions?: string;
30 /**
31 * Whether log data may be accessed from outside the configured region.
32 * @default false
33 */
34 allowOutOfRegionAccess?: boolean;
35 };
36
37 export type CmbConfigAttributes = {
38 /** The Cloudflare account the CMB config belongs to. */
39 accountId: string;
40 /** Name of the region log data is restricted to. */
41 regions: string | undefined;
42 /** Whether log data may be accessed from outside the configured region. */
43 allowOutOfRegionAccess: boolean | undefined;
44 };
45
46 export type CmbConfig = Resource<TypeId, CmbConfigProps, CmbConfigAttributes, never, Providers>;
47
48 /**
49 * The account-level Customer Metadata Boundary (CMB) configuration for
50 * Cloudflare Logs (`/accounts/{account_id}/logs/control/cmb/config`).
51 *
52 * The CMB config is a true account singleton with PUT/DELETE semantics: the
53 * POST endpoint is a full upsert, and DELETE removes the configuration
54 * entirely (an account with no CMB config reads back as empty). Identity is
55 * the account itself.
56 *
57 * CMB is part of Cloudflare's Data Localization Suite and requires an
58 * Enterprise plan — on unentitled accounts every operation fails with the
59 * typed `LogsControlNotAuthorized` error.
60 *
61 * :::warning
62 * Changing the CMB region changes where ALL logs for the account are stored
63 * and processed, and deleting the config lifts the boundary. Handle with
64 * care in production accounts.
65 * :::
66 * ### Restricting logs to a region
67 * **Example:** Keep all account logs in the EU
68 * ```typescript
69 * const cmb = yield* Cloudflare.LogsControl.CmbConfig("EuLogs", {
70 * regions: "eu",
71 * });
72 * ```
73 *
74 * **Example:** Allow out-of-region access
75 * ```typescript
76 * const cmb = yield* Cloudflare.LogsControl.CmbConfig("EuLogs", {
77 * regions: "eu",
78 * allowOutOfRegionAccess: true,
79 * });
80 * ```
81 *
82 * @see https://developers.cloudflare.com/data-localization/metadata-boundary/
83 *
84 * @resource
85 * @product Logs
86 * @category Observability & Analytics
87 */
88 export const CmbConfig = Resource<CmbConfig>(TypeId);
89
90 /**
91 * Returns true if the given value is a CmbConfig resource.
92 */
93 export const isCmbConfig = (value: unknown): value is CmbConfig =>
94 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
95
96 export const CmbConfigProvider = () =>
97 Provider.succeed(CmbConfig, {
98 stables: ["accountId"],
99
100 diff: Effect.fn(function* ({ news, output }) {
101 if (!isResolved(news)) return undefined;
102 const { accountId } = yield* yield* CloudflareEnvironment;
103 const newAccountId = news.accountId ?? accountId;
104 // The account is the singleton's identity.
105 if (output !== undefined && output.accountId !== newAccountId) {
106 return { action: "replace" } as const;
107 }
108 return undefined;
109 }),
110
111 read: Effect.fn(function* ({ output, olds }) {
112 const { accountId: envAccountId } = yield* yield* CloudflareEnvironment;
113 const accountId =
114 output?.accountId ?? (typeof olds?.accountId === "string" ? olds.accountId : envAccountId);
115 const observed = yield* getCmbConfig(accountId);
116 // Unconfigured account — the singleton does not currently exist.
117 if (observed === undefined) return undefined;
118 // The config is an account singleton — there is no foreign instance
119 // to protect, so a cold read adopts freely.
120 return toAttributes(accountId, observed);
121 }),
122
123 // Account singleton: there is no account-wide collection API, only the
124 // single `/logs/control/cmb/config` GET. Mirror `read` exactly — return a
125 // one-element array when the config is set, `[]` when the account is
126 // unconfigured.
127 list: Effect.fn(function* () {
128 const { accountId } = yield* yield* CloudflareEnvironment;
129 const observed = yield* getCmbConfig(accountId);
130 return observed === undefined ? [] : [toAttributes(accountId, observed)];
131 }),
132
133 reconcile: Effect.fn(function* ({ news }) {
134 const { accountId: envAccountId } = yield* yield* CloudflareEnvironment;
135 // Inputs were resolved to concrete values by Plan.
136 const accountId = (news.accountId as string | undefined) ?? envAccountId;
137
138 // Observe — read the live config (undefined = unconfigured).
139 const observed = yield* getCmbConfig(accountId);
140
141 // Sync — POST is a full upsert; skip the call when the observed
142 // config already matches the desired one.
143 const desiredAllowOutOfRegionAccess = news.allowOutOfRegionAccess;
144 const inSync =
145 observed !== undefined &&
146 (observed.regions ?? undefined) === news.regions &&
147 (desiredAllowOutOfRegionAccess === undefined ||
148 (observed.allowOutOfRegionAccess ?? false) === desiredAllowOutOfRegionAccess);
149 if (inSync) {
150 return toAttributes(accountId, observed);
151 }
152
153 const created = yield* logs.createControlCmbConfig({
154 accountId,
155 regions: news.regions,
156 allowOutOfRegionAccess: news.allowOutOfRegionAccess,
157 });
158 return toAttributes(accountId, created);
159 }),
160
161 delete: Effect.fn(function* ({ output }) {
162 // Observe — already unconfigured (or gone with the account) means
163 // there is nothing to delete; re-delete after a crashed run is a
164 // no-op.
165 const observed = yield* getCmbConfig(output.accountId).pipe(
166 Effect.catchTag("InvalidRoute", () => Effect.undefined),
167 );
168 if (observed === undefined) return;
169 yield* logs
170 .deleteControlCmbConfig({ accountId: output.accountId })
171 .pipe(Effect.catchTag(["CmbConfigNotFound", "InvalidRoute"], () => Effect.void));
172 }),
173 });
174
175 /**
176 * Read the CMB config, normalizing "not configured" to `undefined`. An
177 * unconfigured account answers with `result: null` (decoded as an empty
178 * struct) or a 404 (`CmbConfigNotFound`).
179 */
180 const getCmbConfig = (accountId: string) =>
181 logs.getControlCmbConfig({ accountId }).pipe(
182 Effect.map((config) =>
183 config.regions === undefined || config.regions === null ? undefined : config,
184 ),
185 // Accounts without the Compliance/CMB entitlement get
186 // `LogsControlNotAuthorized` — treat as unconfigured (nothing to manage).
187 Effect.catchTag(["CmbConfigNotFound", "LogsControlNotAuthorized"], () => Effect.undefined),
188 );
189
190 const toAttributes = (
191 accountId: string,
192 config: logs.GetControlCmbConfigResponse | logs.CreateControlCmbConfigResponse,
193 ): CmbConfigAttributes => ({
194 accountId,
195 regions: config.regions ?? undefined,
196 allowOutOfRegionAccess: config.allowOutOfRegionAccess ?? undefined,
197 });