@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, 03:37 UTC

main
ts 156 lines 6.92 KB
Raw
1 /** @effect-diagnostics anyUnknownInErrorContext:off */
2
3 import * as Context from "effect/Context";
4 import * as Effect from "effect/Effect";
5 import * as Layer from "effect/Layer";
6 import { AlchemyContext } from "../AlchemyContext.ts";
7 import type { Platform } from "../Platform.ts";
8 import { Provider, type ProviderService } from "../Provider.ts";
9 import { defaultProviderMode, type ProviderMode } from "../ProviderMode.ts";
10 import type { ResourceClassLike, ResourceLike } from "../Resource.ts";
11
12 /**
13 * Registers a resource provider with both a **live** and a **local**
14 * implementation, making provider mode a first-class, per-run *and*
15 * per-resource concern:
16 *
17 * - The `Provider(type)` service placed in context delegates to the
18 * variant for the run's default mode (`AlchemyContext.dev ? "local" :
19 * "live"`). `findProvider` resolves the concrete variant, including its
20 * optional lifecycle methods and metadata.
21 * - Both variants are exposed via {@link ProviderService.modes} as lazy,
22 * memoized builders. NEITHER is constructed at registration: a variant
23 * (and the mode-specific dependency layers composed inside its thunk) is
24 * built the first time something demands it — planning a resource of
25 * this type, deleting a state row stamped with its mode, a nuke scan. A
26 * dual provider whose resources never appear in a run costs nothing, and
27 * in dev the sidecar process a local variant spawns only starts once a
28 * resource of its type is actually planned.
29 *
30 * Laziness mechanics: the layer is a {@link Layer.fromBuildMemo}, so the
31 * build itself is memoized by layer identity (one provider instance — and
32 * one instance registry for local providers — per memo-map ancestry, i.e.
33 * shared across every stack build that forks the same root, exactly like
34 * ordinary layers). The build receives its `MemoMap` and `Scope`; variant
35 * layers are built with `Layer.buildWithMemoMap` against that same memo
36 * map and scope, which means:
37 *
38 * - dependency layers shared between different providers' local variants
39 * (e.g. Cloudflare's `localRuntimeServices()`) are constructed exactly
40 * once, provided the thunks share the layer *reference*;
41 * - lazily-built services live until the memoized entry's scope closes
42 * (when every borrowing scope has closed), like any eagerly-built
43 * provider.
44 *
45 * @example
46 * ```ts
47 * export const WorkerProvider = () =>
48 * ProviderLayer.dual(Worker, {
49 * live: () => LiveWorkerProvider(),
50 * local: () =>
51 * LocalWorkerProvider().pipe(Layer.provide(localRuntimeServices())),
52 * });
53 * ```
54 */
55 export const dual = <
56 R extends ResourceLike,
57 LayerLive extends Layer.Layer<any, any, any>,
58 LayerLocal extends Layer.Layer<any, any, any>,
59 >(
60 // Only the resource type string is needed — a ResourceClass, a Platform,
61 // or a bare `{ Type }` (useful when importing the class would create a
62 // module cycle) all satisfy this.
63 cls: ResourceClassLike<R> | Platform<R, any, any, any, any> | { Type: R["Type"] },
64 input: {
65 live: () => LayerLive;
66 local: () => LayerLocal;
67 /**
68 * Data-plane override context for the local mode — the layer of cloud
69 * environment services (endpoint, credentials, region) the local
70 * lifecycle variant runs under (e.g. AWS's `flociServices()`). Stamped
71 * onto the registered service as
72 * {@link ProviderService.localDataPlane} so `Binding.Service` clients
73 * can route deploy-time data-plane calls (Action bodies, plan-time
74 * `execute`) to the emulator when the bound resource resolves local.
75 * Pass a module-memoized layer reference.
76 */
77 dataPlane?: () => Layer.Layer<any, any, never>;
78 /**
79 * Data-plane override for **live** mode — the inverse of
80 * {@link dataPlane}. Stamped as {@link ProviderService.liveDataPlane} so
81 * `Alchemy.remote()` binding clients in a `dev` run provide the live
82 * chain closest (ambient is the emulator). Pass a module-memoized
83 * layer reference. AWS duals also get this from
84 * `pinCollectionEnvironment`.
85 */
86 liveDataPlane?: () => Layer.Layer<any, any, never>;
87 },
88 ): Layer.Layer<
89 Layer.Success<LayerLive | LayerLocal>,
90 Layer.Error<LayerLive | LayerLocal>,
91 Layer.Services<LayerLive | LayerLocal> | AlchemyContext
92 > =>
93 Layer.fromBuildMemo((memoMap, scope) =>
94 Effect.gen(function* () {
95 // The layer-build context contains everything provided to the
96 // provider stack (API clients, environments, ...). Captured here so
97 // lazily-built variants see the same services as an eager build.
98 const context = yield* Effect.context<never>();
99 const defaultMode = yield* defaultProviderMode;
100
101 const buildVariant = (mode: ProviderMode) =>
102 Layer.buildWithMemoMap(
103 (mode === "live" ? input.live() : input.local()).pipe(
104 Layer.provide(Layer.succeedContext(context)),
105 ) as Layer.Layer<any, any, never>,
106 memoMap,
107 scope,
108 ).pipe(
109 Effect.map((built): ProviderService<R> => ({
110 ...(built.mapUnsafe.get(cls.Type) as ProviderService<R>),
111 mode,
112 })),
113 );
114
115 // Memoized so each variant is constructed at most once per stack
116 // build, no matter how many resources/deletes resolve it.
117 const cached = {
118 live: yield* Effect.cached(buildVariant("live")),
119 local: yield* Effect.cached(buildVariant("local")),
120 };
121
122 // Lazy accessors die on construction failure: a provider layer that
123 // cannot be built is fatal (Providers.ts pipes `Layer.orDie` around
124 // the eager path for the same reason).
125 const modes: {
126 readonly [M in ProviderMode]: Effect.Effect<ProviderService<R>>;
127 } = {
128 live: Effect.orDie(cached.live),
129 local: Effect.orDie(cached.local),
130 };
131
132 // Every engine path resolves a concrete variant through
133 // `providerForMode` and reads optional-method presence (`read`,
134 // `precreate`, `tail`, `logs`), `version`, `stables` and `nuke`
135 // there. The registered service therefore only needs the required
136 // lifecycle methods for structural provider checks and direct
137 // registration access — each forwarding to the default
138 // variant, built on first call.
139 const variant = modes[defaultMode];
140
141 return Context.make(Provider(cls.Type) as any, {
142 aliases: "Aliases" in cls ? cls.Aliases : undefined,
143 diff: (input) =>
144 Effect.flatMap(variant, (service) =>
145 service.diff === undefined ? Effect.void : service.diff(input),
146 ),
147 reconcile: (input) => Effect.flatMap(variant, (service) => service.reconcile(input)),
148 delete: (input) => Effect.flatMap(variant, (service) => service.delete(input)),
149 list: (...args) => Effect.flatMap(variant, (service) => service.list(...args)),
150 mode: defaultMode,
151 modes,
152 localDataPlane: input.dataPlane,
153 liveDataPlane: input.liveDataPlane,
154 } satisfies ProviderService<R>);
155 }),
156 ) as any;