@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 122 lines 4.94 KB
Raw
1 import { layerRuntime } from "@alchemy.run/cloudflare-runtime/core";
2 import { AlchemyContext } from "alchemy/AlchemyContext";
3 import * as RpcProvider from "alchemy/Local/RpcProvider";
4 import { LOCAL_ID_PREFIX } from "alchemy/ProviderMode";
5 import { moduleExtension } from "alchemy/Util/Node";
6 import * as Context from "effect/Context";
7 import * as Effect from "effect/Effect";
8 import * as Layer from "effect/Layer";
9 import * as MutableHashMap from "effect/MutableHashMap";
10 import * as Path from "effect/Path";
11 import { CloudflareEnvironment } from "./CloudflareEnvironment.ts";
12 import type { Consumer } from "./Queues/Consumer.ts";
13 import type { Queue } from "./Queues/Queue.ts";
14 import { LocalEdgeLive } from "./Workers/LocalEdge.ts";
15
16 /**
17 * The Cloudflare provider group module ([Local.ts](./Local.ts)) every
18 * Cloudflare local provider is registered in; the dev sidecar imports it on
19 * first use (see `Local/Sidecar.ts`).
20 */
21 export const LOCAL_PROVIDERS_URL = import.meta.resolve(
22 // `import.meta.resolve(<string>)` is a runtime API — TypeScript's
23 // `rewriteRelativeImportExtensions` does NOT touch the string literal, so
24 // we have to pick the right extension ourselves. `import.meta.url` reflects
25 // the actual on-disk extension of *this* file (`.ts` when loaded from
26 // `src/` under Bun or vitest, `.js` when loaded from the compiled `lib/`
27 // under Node), which is exactly the signal we need.
28 `./Local${moduleExtension(import.meta.url)}`,
29 import.meta.url,
30 );
31
32 export class LocalRuntimeState extends Context.Service<
33 LocalRuntimeState,
34 {
35 readonly queues: MutableHashMap.MutableHashMap<
36 Queue["Attributes"]["queueId"],
37 Queue["Attributes"]
38 >;
39 readonly queueConsumers: MutableHashMap.MutableHashMap<
40 Consumer["Attributes"]["consumerId"],
41 Consumer["Attributes"]
42 >;
43 /**
44 * Restart hooks for locally running Workers, keyed by script name.
45 *
46 * A local workerd instance bakes its queue-consumer wiring in at start
47 * time (`runtime.start({ queueConsumers })`), but the `Consumer`
48 * resource that populates {@link queueConsumers} reconciles as a
49 * *sibling* of the Worker — the engine may start workerd before the
50 * consumer registers. Providers that mutate a worker's runtime wiring
51 * (e.g. `ConsumerProviderLocal`) invoke the script's hook after
52 * updating state so the running instance is reconfigured; the hook is
53 * a no-op until the worker has served at least once.
54 */
55 readonly workerRestarts: MutableHashMap.MutableHashMap<string, Effect.Effect<void>>;
56 }
57 >()("alchemy/cloudflare/LocalRuntimeState") {}
58
59 const LocalRuntimeStateLive = Layer.succeed(
60 LocalRuntimeState,
61 LocalRuntimeState.of({
62 queues: MutableHashMap.empty(),
63 queueConsumers: MutableHashMap.empty(),
64 workerRestarts: MutableHashMap.empty(),
65 }),
66 );
67
68 /**
69 * Directory under `.alchemy` holding local-provider persistent state
70 * (workerd storage). Shared so every consumer — the local runtime layer and
71 * Vite child processes — points at the same storage.
72 */
73 export const localStorageDirectory = Effect.gen(function* () {
74 const { dotAlchemy } = yield* AlchemyContext;
75 const path = yield* Path.Path;
76 return path.join(dotAlchemy, "local");
77 });
78
79 const makeLocalRuntimeServices = () =>
80 RpcProvider.providerServicesEffect(
81 Effect.gen(function* () {
82 const getEnv = yield* CloudflareEnvironment;
83 return Layer.merge(
84 LocalRuntimeStateLive,
85 LocalEdgeLive.pipe(
86 Layer.provideMerge(
87 layerRuntime({
88 api: {
89 accountId: getEnv.pipe(Effect.map((env) => env.accountId)),
90 },
91 storage: {
92 directory: yield* localStorageDirectory,
93 },
94 }),
95 ),
96 ),
97 );
98 }),
99 );
100
101 let _localRuntimeServices: ReturnType<typeof makeLocalRuntimeServices> | undefined;
102
103 /**
104 * The shared local-runtime dependency layer (workerd `Runtime`,
105 * `WorkerProxy`, {@link LocalRuntimeState}, the zone-routing `LocalEdge`) used by every Cloudflare local
106 * provider.
107 *
108 * Returns a **module-memoized layer reference**: local providers register
109 * via `ProviderLayer.dual`, which builds each provider's local variant
110 * lazily against the stack build's shared `Layer.MemoMap` — memoization is
111 * keyed by layer identity, so Worker/Queue/Consumer/Container composing
112 * this exact reference into their local thunks share one runtime instance
113 * per stack build (a fresh build gets a fresh instance via its own memo
114 * map; the layer blueprint itself is immutable).
115 */
116 export const localRuntimeServices = () => (_localRuntimeServices ??= makeLocalRuntimeServices());
117
118 export const isLocalId = (id: string | undefined): id is string =>
119 typeof id === "string" && id.startsWith(LOCAL_ID_PREFIX);
120 export const isLiveId = (id: string | undefined): id is string =>
121 typeof id === "string" && !id.startsWith(LOCAL_ID_PREFIX);
122 export const generateLocalId = (): string => `${LOCAL_ID_PREFIX}${crypto.randomUUID()}`;