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

main
ts 178 lines 7.12 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as aisearch from "@distilled.cloud/cloudflare/aisearch";
6 import * as Effect from "effect/Effect";
7 import * as HttpClient from "effect/http/HttpClient";
8 import { MinimumLogLevel } from "effect/References";
9 import * as Schedule from "effect/Schedule";
10 import AiSearchCrawlTargetWorker from "./fixtures/crawl-target-worker.ts";
11
12 const { test } = Test.make({ providers: Cloudflare.providers() });
13
14 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
15
16 // Type-level coverage: the `AiSearch` construct result *is* an
17 // `AiSearchInstance`, so it can be passed anywhere one is expected. These
18 // assertions fail to compile the moment the construct stops being
19 // substitutable for an instance. The two binding styles are also exercised at
20 // runtime by the `bindings-stack` fixtures (Effect Worker `bind(...)` +
21 // async Worker `env`).
22 declare const _search: Cloudflare.AI.Search;
23 // 1. Assignable to an `AiSearchInstance` (and thus to
24 // `Cloudflare.AI.Search.Search(...)`, which is how an Effect Worker attaches
25 // the `ai_search` binding). These
26 // assertions live inside a never-invoked closure so the type checks compile
27 // without executing the `declare`d binding (which has no runtime value).
28 void (() => {
29 const _asInstance: Cloudflare.AI.Search = _search;
30 void _asInstance;
31 void Cloudflare.AI.QuerySearch(_search);
32 });
33 // 2. As a Worker `env` binding, `InferEnv` resolves it to the same runtime
34 // handle (`AiSearchInstance`) it would for a plain `AiSearchInstance`.
35 type _EnvSearch = Cloudflare.InferEnv<{
36 SEARCH: Cloudflare.AI.Search;
37 }>["SEARCH"];
38 type _EnvInstance = Cloudflare.InferEnv<{
39 SEARCH: Cloudflare.AI.Search;
40 }>["SEARCH"];
41 const _envSame: _EnvSearch extends _EnvInstance ? true : never = true;
42 void _envSame;
43
44 const getInstance = (accountId: string, id: string, namespace = "default") =>
45 aisearch.readNamespaceInstance({ accountId, namespace, id }).pipe(
46 Effect.retry({
47 while: (e) => e._tag === "Forbidden",
48 schedule: Schedule.exponential("500 millis"),
49 times: 8,
50 }),
51 );
52
53 const expectGone = (accountId: string, id: string, namespace = "default") =>
54 getInstance(accountId, id, namespace).pipe(
55 Effect.flatMap(() => Effect.fail({ _tag: "InstanceNotDeleted" } as const)),
56 Effect.catchTag(["AiSearchInstanceNotFound", "NamespaceNotFound"], () => Effect.void),
57 Effect.retry({
58 while: (e) => e._tag === "InstanceNotDeleted",
59 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(10)]),
60 }),
61 );
62
63 // The `AiSearch` construct composes an R2 bucket, a managed service token
64 // (AccountApiToken + AiSearchToken children), and the instance — a single
65 // `yield*` wires the whole pipeline together.
66 const program = () =>
67 Effect.gen(function* () {
68 const bucket = yield* Cloudflare.R2.Bucket("AiSearchSource", {
69 forceDestroy: true,
70 });
71 const search = yield* Cloudflare.AI.Search("Search", {
72 source: bucket,
73 });
74 return { bucket, search, serviceToken: search.serviceToken };
75 });
76
77 test.provider(
78 "construct auto-creates a managed token and wires it into the instance",
79 (stack) =>
80 Effect.gen(function* () {
81 const { accountId } = yield* yield* CloudflareEnvironment;
82
83 yield* stack.destroy();
84
85 const deployed = yield* stack.deploy(program());
86
87 const { search, serviceToken } = deployed;
88 expect(search.instanceId).toBeTruthy();
89 // The managed service token was minted as a child and wired in.
90 expect(serviceToken).toBeDefined();
91 expect(search.tokenId).toEqual(serviceToken!.id);
92
93 // Cloudflare's read projection hides the token association
94 // (`tokenId` comes back `null`), so verify the instance exists rather
95 // than re-asserting the token id off the read path.
96 const live = yield* getInstance(accountId, search.instanceId);
97 expect(live.id).toEqual(search.instanceId);
98
99 yield* stack.destroy();
100
101 yield* expectGone(accountId, search.instanceId);
102 }).pipe(logLevel),
103 {
104 tags: ["provider:cloudflare", "provider:cloudflare:ai", "provider:cloudflare:r2", "live"],
105 timeout: 300_000,
106 },
107 );
108
109 // A web-crawler source crawls a seed URL and needs no service token, so the
110 // construct must NOT mint an AccountApiToken / AiSearchToken — `token` comes
111 // back undefined. Cloudflare only crawls a domain the account owns, so the
112 // crawl is seeded at a Worker we deploy (its `workers.dev` URL is owned by
113 // the account); the fixture serves a sitemap so `parseType: "discover"`
114 // always finds content.
115 const crawlerProgram = () =>
116 Effect.gen(function* () {
117 const target = yield* AiSearchCrawlTargetWorker;
118 // Exercise the flattened source group end-to-end: `parse` (parseType +
119 // parse options) must translate into the distilled
120 // `sourceParams.webCrawler.{parseType,parseOptions}`.
121 const search = yield* Cloudflare.AI.Search("Search", {
122 source: target.url.as<string>(),
123 // Cloudflare renamed the `crawl` parse type to `discover` and removed
124 // crawl options from the API. The fixture serves a sitemap, so
125 // discovery always finds content.
126 parse: { type: "discover", useBrowserRendering: false },
127 });
128 return { target, search, serviceToken: search.serviceToken };
129 });
130
131 test.provider(
132 "web-crawler source skips token minting",
133 (stack) =>
134 Effect.gen(function* () {
135 const { accountId } = yield* yield* CloudflareEnvironment;
136
137 yield* stack.destroy();
138
139 // Deploy the crawl target first and wait until its `workers.dev` URL is
140 // actually serving. AI Search fetches the seed synchronously when it
141 // validates a web-crawler at create time; against a URL that isn't live
142 // yet it finds no content and rejects with `missing_sitemap`.
143 const warmed = yield* stack.deploy(
144 Effect.gen(function* () {
145 return yield* AiSearchCrawlTargetWorker;
146 }),
147 );
148 const client = yield* HttpClient.HttpClient;
149 const targetUrl = warmed.url;
150 expect(targetUrl).toBeTypeOf("string");
151 yield* client.get(targetUrl as string).pipe(
152 Effect.flatMap((res) =>
153 res.status === 200
154 ? Effect.succeed(res)
155 : Effect.fail(new Error(`crawl target not ready: ${res.status}`)),
156 ),
157 Effect.retry({ schedule: Schedule.spaced("3 seconds"), times: 20 }),
158 );
159
160 const deployed = yield* stack.deploy(crawlerProgram());
161
162 const { search, serviceToken } = deployed;
163 // No service token is minted for a web crawler.
164 expect(serviceToken).toBeUndefined();
165 expect(search.type).toEqual("web-crawler");
166
167 const live = yield* getInstance(accountId, search.instanceId);
168 expect(live.type).toEqual("web-crawler");
169
170 yield* stack.destroy();
171
172 yield* expectGone(accountId, search.instanceId);
173 }).pipe(logLevel),
174 {
175 tags: ["provider:cloudflare", "provider:cloudflare:ai", "provider:cloudflare:worker", "live"],
176 timeout: 300_000,
177 },
178 );