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

main
ts 355 lines 12.1 KB
Raw
1 import * as resourceSharing from "@distilled.cloud/cloudflare/resource-sharing";
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 import type { ShareableResourceType, ShareStatus } from "./Share.ts";
11
12 const TypeId = "Cloudflare.ResourceSharing.ShareResource" as const;
13 type TypeId = typeof TypeId;
14
15 export type ShareResourceProps = {
16 /**
17 * The share this resource belongs to. Changing the share triggers a
18 * replacement.
19 */
20 shareId: string;
21 /**
22 * Type of the shared resource (e.g. `gateway-policy`). Changing the type
23 * triggers a replacement.
24 */
25 resourceType: ShareableResourceType;
26 /**
27 * Identifier of the resource being shared (e.g. the gateway policy id).
28 * Changing it triggers a replacement.
29 */
30 resourceId: string;
31 /**
32 * Account that owns the resource being shared. Changing it triggers a
33 * replacement.
34 * @default the current account
35 */
36 resourceAccountId?: string;
37 /**
38 * Resource metadata forwarded to the share API. The only mutable field.
39 * @default {}
40 */
41 meta?: unknown;
42 };
43
44 export type ShareResourceAttributes = {
45 /**
46 * Server-assigned share-resource identifier — distinct from the shared
47 * `resourceId`. Stable across updates.
48 */
49 shareResourceId: string;
50 /**
51 * The Cloudflare account that owns the share.
52 */
53 accountId: string;
54 /**
55 * The share this resource belongs to.
56 */
57 shareId: string;
58 /**
59 * Type of the shared resource.
60 */
61 resourceType: ShareableResourceType;
62 /**
63 * Identifier of the resource being shared.
64 */
65 resourceId: string;
66 /**
67 * Account that owns the resource being shared.
68 */
69 resourceAccountId: string;
70 /**
71 * Resource metadata.
72 */
73 meta: unknown;
74 /**
75 * Version of the shared resource.
76 */
77 resourceVersion: number;
78 /**
79 * Lifecycle status of the share resource.
80 */
81 status: ShareStatus;
82 /**
83 * When the share resource was created.
84 */
85 created: string;
86 /**
87 * When the share resource was last modified.
88 */
89 modified: string;
90 };
91
92 export type ShareResource = Resource<
93 TypeId,
94 ShareResourceProps,
95 ShareResourceAttributes,
96 never,
97 Providers
98 >;
99
100 /**
101 * A resource entry on an existing Cloudflare share — adds a shareable
102 * resource (gateway policy, custom ruleset, …) to a `Share` incrementally.
103 *
104 * Only `meta` is mutable in place; changing the share, type, id, or owning
105 * account triggers a replacement. A share must always retain at least one
106 * resource — the last entry cannot be deleted (delete the `Share` instead).
107 * Do not manage the same entry both inline on `Share.resources` and through
108 * this resource.
109 * ### Adding a Resource to a Share
110 * **Example:** Share an additional gateway policy
111 * ```typescript
112 * const entry = yield* Cloudflare.ResourceSharing.ShareResource("ExtraPolicy", {
113 * shareId: share.shareId,
114 * resourceType: "gateway-policy",
115 * resourceId: policy.ruleId,
116 * });
117 * ```
118 *
119 * ### Updating Metadata
120 * **Example:** Update `meta` in place
121 * ```typescript
122 * const entry = yield* Cloudflare.ResourceSharing.ShareResource("ExtraPolicy", {
123 * shareId: share.shareId,
124 * resourceType: "gateway-policy",
125 * resourceId: policy.ruleId,
126 * meta: { note: "rotated" },
127 * });
128 * ```
129 *
130 * @see https://developers.cloudflare.com/fundamentals/manage-account-resources/
131 *
132 * @resource
133 * @product Resource Sharing
134 * @category Account & Identity
135 */
136 export const ShareResource = Resource<ShareResource>(TypeId);
137
138 /**
139 * Returns true if the given value is a ShareResource resource.
140 */
141 export const isShareResource = (value: unknown): value is ShareResource =>
142 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
143
144 export const ShareResourceProvider = () =>
145 Provider.succeed(ShareResource, {
146 stables: [
147 "shareResourceId",
148 "accountId",
149 "shareId",
150 "resourceType",
151 "resourceId",
152 "resourceAccountId",
153 "created",
154 ],
155 diff: Effect.fn(function* ({ olds, news, output }) {
156 if (!isResolved(news)) return undefined;
157 const { accountId } = yield* yield* CloudflareEnvironment;
158 if ((output?.accountId ?? accountId) !== accountId) {
159 return { action: "replace" } as const;
160 }
161 // The share is a path parameter — an entry cannot move between
162 // shares in place. By diff time both sides are resolved strings.
163 const oldShareId = output?.shareId ?? olds?.shareId;
164 if (
165 typeof oldShareId === "string" &&
166 typeof news.shareId === "string" &&
167 oldShareId !== news.shareId
168 ) {
169 return { action: "replace" } as const;
170 }
171 const oldType = output?.resourceType ?? olds?.resourceType;
172 if (oldType !== undefined && oldType !== news.resourceType) {
173 return { action: "replace" } as const;
174 }
175 const oldResourceId = output?.resourceId ?? olds?.resourceId;
176 if (
177 typeof oldResourceId === "string" &&
178 typeof news.resourceId === "string" &&
179 oldResourceId !== news.resourceId
180 ) {
181 return { action: "replace" } as const;
182 }
183 const oldOwner = output?.resourceAccountId ?? olds?.resourceAccountId;
184 const newOwner = news.resourceAccountId ?? accountId;
185 if (typeof oldOwner === "string" && typeof newOwner === "string" && oldOwner !== newOwner) {
186 return { action: "replace" } as const;
187 }
188 return undefined;
189 }),
190 read: Effect.fn(function* ({ olds, output }) {
191 const { accountId } = yield* yield* CloudflareEnvironment;
192 const acct = output?.accountId ?? accountId;
193 const shareId = output?.shareId ?? (olds?.shareId as string | undefined);
194 if (shareId === undefined) return undefined;
195
196 if (output?.shareResourceId) {
197 const observed = yield* getEntry(acct, shareId, output.shareResourceId);
198 return observed ? toAttributes(observed, acct, shareId) : undefined;
199 }
200 // Cold read — recover from lost state by matching the natural key
201 // (resourceType, resourceId) among the share's live entries.
202 const resourceType = olds?.resourceType as ShareableResourceType | undefined;
203 const resourceId = olds?.resourceId as string | undefined;
204 if (resourceType === undefined || resourceId === undefined) {
205 return undefined;
206 }
207 const match = yield* findEntry(acct, shareId, resourceType, resourceId);
208 return match ? toAttributes(match, acct, shareId) : undefined;
209 }),
210 reconcile: Effect.fn(function* ({ news, output }) {
211 const { accountId } = yield* yield* CloudflareEnvironment;
212 const acct = output?.accountId ?? accountId;
213 const shareId = news.shareId as string;
214 const resourceId = news.resourceId as string;
215 const desiredMeta = news.meta ?? {};
216
217 // Observe — the id cached on `output` is a hint; fall through to a
218 // natural-key lookup so an AlreadyExists race converges instead of
219 // failing, then to create.
220 const observed =
221 (output?.shareResourceId
222 ? yield* getEntry(acct, shareId, output.shareResourceId)
223 : undefined) ?? (yield* findEntry(acct, shareId, news.resourceType, resourceId));
224
225 if (!observed) {
226 // Ensure — greenfield (or out-of-band delete).
227 const created = yield* resourceSharing.createResource({
228 accountId: acct,
229 shareId,
230 resourceType: news.resourceType,
231 resourceId,
232 resourceAccountId: (news.resourceAccountId as string) ?? acct,
233 meta: desiredMeta,
234 });
235 return toAttributes(created, acct, shareId);
236 }
237
238 // Sync — `meta` is the only mutable field; skip the PUT on a no-op.
239 if (JSON.stringify(observed.meta ?? {}) !== JSON.stringify(desiredMeta)) {
240 const updated = yield* resourceSharing.updateResource({
241 accountId: acct,
242 shareId,
243 shareResourceId: observed.id,
244 meta: desiredMeta,
245 });
246 return toAttributes(updated, acct, shareId);
247 }
248 return toAttributes(observed, acct, shareId);
249 }),
250 delete: Effect.fn(function* ({ output }) {
251 // Deletion is asynchronous (`status: deleting`); the DELETE call is
252 // idempotent against a missing entry. Deleting the last resource of
253 // a share is a genuine dependency violation and propagates.
254 yield* resourceSharing
255 .deleteResource({
256 accountId: output.accountId,
257 shareId: output.shareId,
258 shareResourceId: output.shareResourceId,
259 })
260 .pipe(Effect.catchTag("ShareResourceNotFound", () => Effect.void));
261 }),
262 list: Effect.fn(function* () {
263 const { accountId } = yield* yield* CloudflareEnvironment;
264 // Parent fan-out: a ShareResource is a sub-resource of a Share with
265 // no account-wide enumeration of its own. Enumerate every share we
266 // send (account-scoped), then list each share's resource entries
267 // with bounded concurrency, paginating both levels exhaustively.
268 const shares = yield* resourceSharing.listResourceSharings
269 .pages({ accountId, kind: "sent" })
270 .pipe(
271 Stream.runCollect,
272 Effect.map((chunk) =>
273 Array.from(chunk).flatMap((page) =>
274 (page.result ?? []).filter((s) => s.status !== "deleted"),
275 ),
276 ),
277 );
278 const rows = yield* Effect.forEach(
279 shares,
280 (share) =>
281 resourceSharing.listResources.pages({ accountId, shareId: share.id }).pipe(
282 Stream.runCollect,
283 Effect.map((chunk) =>
284 Array.from(chunk).flatMap((page) =>
285 (page.result ?? [])
286 .filter((r) => r.status !== "deleted" && r.status !== "deleting")
287 .map((entry) => toAttributes(entry, accountId, share.id)),
288 ),
289 ),
290 // A share removed out-of-band between enumeration and the
291 // per-share list surfaces as ShareNotFound — skip it.
292 Effect.catchTag("ShareNotFound", () => Effect.succeed([] as ShareResourceAttributes[])),
293 ),
294 { concurrency: 10 },
295 );
296 return rows.flat();
297 }),
298 });
299
300 type ObservedEntry = resourceSharing.GetResourceResponse;
301
302 /**
303 * Read a share-resource entry by id, mapping "gone"
304 * (`ShareResourceNotFound`, HTTP 404) and the terminal `deleted` status to
305 * `undefined`.
306 */
307 const getEntry = (accountId: string, shareId: string, shareResourceId: string) =>
308 resourceSharing.getResource({ accountId, shareId, shareResourceId }).pipe(
309 Effect.map((entry): ObservedEntry | undefined =>
310 entry.status === "deleted" ? undefined : entry,
311 ),
312 Effect.catchTag("ShareResourceNotFound", () => Effect.undefined),
313 );
314
315 /**
316 * Find a live entry by its natural key (resourceType, resourceId). A missing
317 * share surfaces as `ShareNotFound` — treat it as "no entry".
318 */
319 const findEntry = (
320 accountId: string,
321 shareId: string,
322 resourceType: ShareableResourceType,
323 resourceId: string,
324 ) =>
325 resourceSharing.listResources({ accountId, shareId, resourceType, perPage: 50 }).pipe(
326 Effect.map((list) =>
327 list.result.find(
328 (r) => r.resourceId === resourceId && r.status !== "deleted" && r.status !== "deleting",
329 ),
330 ),
331 Effect.catchTag("ShareNotFound", () => Effect.undefined),
332 );
333
334 const toAttributes = (
335 entry:
336 | ObservedEntry
337 | resourceSharing.CreateResourceResponse
338 | resourceSharing.UpdateResourceResponse
339 | resourceSharing.ListResourcesResponse["result"][number],
340 accountId: string,
341 shareId: string,
342 ): ShareResourceAttributes => ({
343 shareResourceId: entry.id,
344 accountId,
345 shareId,
346 // Distilled widens generated string enums to open unions (`string & {}`).
347 resourceType: entry.resourceType as ShareableResourceType,
348 resourceId: entry.resourceId,
349 resourceAccountId: entry.resourceAccountId,
350 meta: entry.meta,
351 resourceVersion: entry.resourceVersion,
352 status: entry.status as ShareStatus,
353 created: entry.created,
354 modified: entry.modified,
355 });