Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Stack.ts

372 lines10.8 KB

1import type { ConfigError } from "effect/Config";
2import { ConfigProvider } from "effect/ConfigProvider";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import { FileSystem } from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Logger from "effect/Logger";
8import * as Option from "effect/Option";
9import { Path } from "effect/Path";
10import * as Scope from "effect/Scope";
11import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient";
12import type { HttpClient } from "effect/unstable/http/HttpClient";
13import type { ChildProcessSpawner } from "effect/unstable/process/ChildProcessSpawner";
14import type { ActionLike } from "./Action.ts";
15import { AlchemyContext, AlchemyContextLive } from "./AlchemyContext.ts";
16import { type ArtifactStore, provideFreshArtifactStore } from "./Artifacts.ts";
17import { AuthProviders } from "./Auth/AuthProvider.ts";
18import { CredentialsStore, CredentialsStoreLive } from "./Auth/Credentials.ts";
19import { AlchemyProfile, ProfileLive } from "./Auth/Profile.ts";
20import { Cli } from "./Cli/Cli.ts";
21import type { Input, InputProps } from "./Input.ts";
22import * as Output from "./Output.ts";
23import type { Provider, ProviderCollectionLike } from "./Provider.ts";
24import type { ResourceBinding, ResourceLike } from "./Resource.ts";
25import { Stage } from "./Stage.ts";
26import type { State } from "./State/State.ts";
27import { loadConfigProvider } from "./Util/ConfigProvider.ts";
28import { effectClass, taggedFunction } from "./Util/effect.ts";
29import { fileLogger } from "./Util/FileLogger.ts";
30import { PlatformServices } from "./Util/PlatformServices.ts";
31​
32export type StackServices =
33 | Stack
34 | Stage
35 | Scope.Scope
36 | FileSystem
37 | Path
38 | AlchemyContext
39 | HttpClient
40 | ChildProcessSpawner
41 | AuthProviders
42 | AlchemyProfile
43 | ArtifactStore
44 | CredentialsStore
45 | Cli;
46​
47export type ProviderServices =
48 | ProviderCollectionLike
49 | Provider<any>
50 | EnvironmentLike
51 | CredentialsLike
52 | DockerLike;
53​
54// tagged type to allow types like AWSEnvironment/AWS Region to bubble through
55export interface EnvironmentLike {
56 readonly kind: "Environment";
58​
59// tagged type to allow types like AWS Credentials to bubble through
60export interface CredentialsLike {
61 readonly kind: "Credentials";
63​
64export interface DockerLike {
65 readonly key: "@alchemy/Docker";
67​
68export type StackEffect<A, Err = never, Req = never> = Effect.Effect<
69 A,
70 Err,
71 | PlatformServices
72 | HttpClient
73 | Scope.Scope
74 | AuthProviders
75 | AlchemyContext
76 | Cli
77 | AlchemyProfile
78 | CredentialsStore
79 | ArtifactStore
80 | State
81 | Req
82>;
83​
84export type Stack = Context.ServiceClass.Shape<
85 "Stack",
86 Omit<StackSpec, "output">
87>;
88​
89export interface StackProps<Req> {
90 providers: Layer.Layer<Extract<Req, ProviderServices>, never, StackServices>;
91 state: Layer.Layer<State, never, StackServices>;
93​
94export const Stack: Context.ServiceClass<
95 Stack,
96 "Stack",
97 Omit<StackSpec, "output">
98> & {
99 make<A, Req>(
100 stack: {
101 Shape: A;
102 },
103 effect: Effect.Effect<
104 NoInfer<A extends object ? InputProps<A> : Input<A>>,
105 ConfigError,
106 Req
107 >,
108 ): Effect.Effect<CompiledStack<A>, ConfigError>;
109 <Self>(): {
110 <A, Req>(
111 stackName: string,
112 options: StackProps<NoInfer<Req>>,
113 eff: Effect.Effect<A, ConfigError, Req>,
114 ): Effect.Effect<Self, ConfigError> & {
115 new (_: never): A extends object ? A : {};
116 stage: {
117 [stage: string]: Effect.Effect<Self>;
118 };
119 };
120 };
121 <Self, Shape>(): {
122 (stackName: string): Effect.Effect<Self> & {
123 new (_: never): Output.ToOutput<Shape>;
124 make: <A, Req>(
125 options: StackProps<NoInfer<Req>>,
126 effect: Effect.Effect<A, ConfigError, Req>,
127 ) => Effect.Effect<CompiledStack<A>, ConfigError>;
128 stage: {
129 [stage: string]: Effect.Effect<Self>;
130 };
131 };
132 };
133 <A, Req extends StackServices | ProviderServices = never>(
134 stackName: string,
135 options: StackProps<NoInfer<Req>>,
136 eff: Effect.Effect<A, ConfigError, Req>,
137 ): Effect.Effect<CompiledStack<A>, ConfigError>;
138} = Object.assign(
139 taggedFunction(
140 Context.Service<Stack, Omit<StackSpec, "output">>()("Stack"),
141 <A, Req>(
142 stackName?: string,
143 options?: StackProps<NoInfer<Req>>,
144 eff?: Effect.Effect<A, ConfigError, Req>,
145 ) => {
146 if (!stackName) {
147 return (stackName: string) =>
148 Object.assign(
149 // by default, reference the stack at the "current" stage of the importer
150 Output.stackRef<A>(stackName).pipe(effectClass),
151 {
152 stackName,
153 stage: createStageProxy(stackName),
154 state: options?.state,
155 providers: options?.providers,
156 make: <Req = never>(
157 options: StackProps<NoInfer<Req>>,
158 eff: Effect.Effect<A, ConfigError, Req>,
159 ) =>
160 // @ts-expect-error
161 Stack(stackName, options, eff),
162 },
163 );
164 }
165 return eff!.pipe(
166 // @ts-expect-error
167 make({
168 name: stackName,
169 ...options!,
170 }),
171 (eff) =>
172 Object.assign(eff, {
173 stackName,
174 stage: createStageProxy(stackName),
175 state: options?.state,
176 providers: options?.providers,
177 }),
178 );
179 },
180 ),
181) as any;
182​
183const createStageProxy = (stackName: string) =>
184 new Proxy(
185 {},
186 {
187 get: (_, stage: string) => Output.stackRef(stackName, { stage }),
188 },
189 );
190​
191export interface StackSpec<Output = any> {
192 name: string;
193 stage: string;
194 // @internal
195 resources: {
196 [logicalId: string]: ResourceLike;
197 };
198 bindings: {
199 [logicalId: string]: ResourceBinding[];
200 };
201 /** Tasks registered on the stack, keyed by FQN. */
202 actions: {
203 [logicalId: string]: ActionLike;
204 };
205 output: Output;
207​
208export interface CompiledStack<
209 Output = any,
210 Services = any,
211> extends StackSpec<Output> {
212 services: Context.Context<Services>;
214​
215export const StackName = Stack.use((stack) => Effect.succeed(stack.name));
216​
217export interface MakeStackProps<ROut = never> {
218 name: string;
219 providers: Layer.Layer<ROut, never, StackServices>;
220 state: Layer.Layer<State, never, StackServices>;
221 /** @internal */
222 stack?: StackSpec;
224​
225export const make =
226 <ROut = never>(options: MakeStackProps<ROut>) =>
227 <A, Err = never, Req extends ROut | StackServices = never>(
228 effect: Effect.Effect<A, Err, Req>,
229 ) =>
230 Effect.scope.pipe(
231 Effect.flatMap((scope) => {
232 if (options.state == null) {
233 return Effect.die(
234 new Error(
235 `Stack "${options.name}" is missing a state store. ` +
236 `Add a \`state\` layer to the stack options, e.g.:\n` +
237 ` Alchemy.Stack("${options.name}", {\n` +
238 ` providers: Cloudflare.providers(),\n` +
239 ` state: Cloudflare.state(), // <-- required\n` +
240 ` }, ...)\n` +
241 `See https://alchemy.run/state-store for available state stores.`,
242 ),
243 );
244 }
245 if (options.providers == null) {
246 return Effect.die(
247 new Error(
248 `Stack "${options.name}" is missing a providers layer. ` +
249 `Add a \`providers\` layer to the stack options, e.g.:\n` +
250 ` Alchemy.Stack("${options.name}", {\n` +
251 ` providers: Cloudflare.providers(), // <-- required\n` +
252 ` state: Cloudflare.state(),\n` +
253 ` }, ...)`,
254 ),
255 );
256 }
257 return options.providers.pipe(
258 Layer.provideMerge(options.state),
259 Layer.provideMerge(
260 Layer.effect(
261 Stack,
262 Stage.pipe(
263 Effect.map(
264 (stage) =>
265 options.stack ?? {
266 name: options.name,
267 stage,
268 resources: {},
269 bindings: {},
270 actions: {},
271 },
272 ),
273 ),
274 ),
275 ),
276 Layer.buildWithScope(scope),
277 );
278 }),
279 Effect.flatMap((context) =>
280 Effect.all([
281 effect,
282 Stack,
283 Effect.context<ROut | StackServices>(),
284 ]).pipe(
285 Effect.map(
286 ([output, stack, services]): CompiledStack<
287 A,
288 ROut | StackServices
289 > => ({
290 ...stack,
291 output,
292 services: Context.merge(services, context),
293 }),
294 ),
295 Effect.provideContext(context),
296 ),
297 ),
298 );
299​
300export const CurrentStack = Effect.serviceOption(Stack)
301​
302 .pipe(Effect.map(Option.getOrUndefined));
303​
304const platform = Layer.mergeAll(
305 PlatformServices,
306 FetchHttpClient.layer,
307 Logger.layer([fileLogger("out")], { mergeWithExisting: true }),
308 Layer.provide(ProfileLive, PlatformServices),
309 Layer.provide(CredentialsStoreLive, PlatformServices),
310);
311// override alchemy state store, CLI/reporting, state, and Config
312const alchemy = (overrides?: { dev?: boolean }) =>
313 Layer.mergeAll(
314 // CLI.inkCLI(),
315 // optional
316 overrides?.dev
317 ? Layer.provide(
318 Layer.effect(
319 AlchemyContext,
320 AlchemyContext.useSync((ctx) => ({ ...ctx, dev: overrides.dev! })),
321 ),
322 AlchemyContextLive,
323 )
324 : AlchemyContextLive,
325 );
326​
327export const evalStack = <A, B, StackErr, Err, Req>(
328 effect: StackEffect<CompiledStack<A>, StackErr, Stage | AlchemyContext>,
329 fn: (stack: CompiledStack<A>) => Effect.Effect<B, Err, Req>,
330 options: {
331 stage: string;
332 dev?: boolean;
333 /**
334 * Optional caller-supplied scope. When provided, scoped resources
335 * (e.g. the dev sidecar process) live until the caller closes this
336 * scope instead of being torn down when `evalStack` resolves. Used
337 * by the test harness so the sidecar survives across `beforeAll`,
338 * tests, and `afterAll`. When omitted, behaves as before with a
339 * private scope closed on completion.
340 */
341 scope?: Scope.Scope;
342 },
343) => {
344 const body = Effect.gen(function* () {
345 const stack = yield* effect;
346 const configProvider = yield* loadConfigProvider(Option.none());
347​
348 return yield* fn(stack).pipe(
349 provideFreshArtifactStore,
350 Effect.provide(stack.services),
351 Effect.provide(Layer.succeed(ConfigProvider, configProvider)),
352 );
353 }).pipe(
354 Effect.provide(
355 Layer.effect(
356 AuthProviders,
357 Effect.serviceOption(AuthProviders).pipe(
358 Effect.map(Option.getOrElse(() => ({}))),
359 ),
360 ).pipe(
361 Layer.provideMerge(Layer.succeed(Stage, options.stage)),
362 Layer.provideMerge(
363 Layer.provideMerge(alchemy({ dev: options.dev }), platform),
364 ),
365 ),
366 ),
367 );
368​
369 return options.scope === undefined
370 ? Effect.scoped(body)
371 : Scope.provide(body, options.scope);
372};