@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, 06:00 UTC

main
ts 1,403 lines 46.9 KB
Raw
1 import { Unowned } from "alchemy/AdoptPolicy";
2 import { AlchemyContext } from "alchemy/AlchemyContext";
3 import { Artifacts } from "alchemy/Artifacts";
4 import * as Binding from "alchemy/Binding";
5 import { isResolved } from "alchemy/Diff";
6 import * as ProviderLayer from "alchemy/Local/ProviderLayer";
7 import { Platform, type Main, type PlatformProps } from "alchemy/Platform";
8 import * as Provider from "alchemy/Provider";
9 import { LOCAL_ID_PREFIX, type ProviderMode } from "alchemy/ProviderMode";
10 import { Resource, type ResourceBinding } from "alchemy/Resource";
11 import {
12 createHostRuntimeContext,
13 type HostRuntimeContext,
14 type ServerHost,
15 } from "alchemy/Runtime/Process";
16 import { unpackEnvValue } from "alchemy/RuntimeContext";
17 import { Stack } from "alchemy/Stack";
18 import * as State from "alchemy/State";
19 import { isUnknown } from "alchemy/Util/unknown";
20 import { Data } from "effect";
21 import * as Config from "effect/Config";
22 import * as ConfigProvider from "effect/ConfigProvider";
23 import * as Context from "effect/Context";
24 import * as Duration from "effect/Duration";
25 import * as Effect from "effect/Effect";
26 import * as HttpServerResponse from "effect/http/HttpServerResponse";
27 import * as Layer from "effect/Layer";
28 import * as Option from "effect/Option";
29 import * as Redacted from "effect/Redacted";
30
31 // Bucket
32 export type BucketProps = {
33 name?: string;
34 };
35
36 export interface Bucket extends Resource<
37 "Test.Bucket",
38 BucketProps,
39 {
40 name: string;
41 bucketArn: string;
42 }
43 > {}
44
45 export const Bucket = Resource<Bucket>("Test.Bucket");
46
47 const bucketProvider = () =>
48 Provider.succeed(Bucket, {
49 list: () => Effect.succeed([]),
50 diff: Effect.fn(function* ({ id, news, output }) {
51 if (!isResolved(news)) return undefined;
52 }),
53 reconcile: Effect.fn(function* ({ id, news = {}, output }) {
54 if (output !== undefined) return output;
55 return {
56 name: news.name ?? id,
57 bucketArn: `arn:test:bucket:us-east-1:123456789:${id}`,
58 };
59 }),
60 delete: Effect.fn(function* ({ output }) {
61 return;
62 }),
63 });
64
65 // Queue
66 export type Props = {
67 name?: string;
68 };
69
70 export interface Queue extends Resource<
71 "Test.Queue",
72 Props,
73 {
74 name: string;
75 queueUrl: string;
76 }
77 > {}
78
79 export const Queue = Resource<Queue>("Test.Queue");
80
81 export const queueProvider = () =>
82 Provider.succeed(Queue, {
83 list: () => Effect.succeed([]),
84 diff: Effect.fn(function* ({ id, news = {}, output }) {
85 if (!isResolved(news)) return undefined;
86 }),
87 reconcile: Effect.fn(function* ({ id, news = {} }) {
88 const name = news.name ?? id;
89 return {
90 name,
91 queueUrl: `https://test.queue.com/${name}`,
92 };
93 }),
94 delete: Effect.fn(function* ({ output }) {}),
95 });
96
97 export type FunctionProps = {
98 name?: string;
99 env?: Record<string, string>;
100 };
101
102 export interface Function extends Resource<
103 "Test.Function",
104 FunctionProps,
105 {
106 name: string;
107 env: Record<string, string>;
108 functionArn: string;
109 }
110 > {}
111
112 export const Function = Resource<Function>("Test.Function");
113
114 export const functionProvider = () =>
115 Provider.succeed(Function, {
116 list: () => Effect.succeed([]),
117 diff: Effect.fn(function* ({ id, news, output }) {
118 if (!isResolved(news)) return undefined;
119 }),
120 reconcile: Effect.fn(function* ({ id, news = {} }) {
121 return {
122 name: news.name ?? id,
123 env: news.env ?? {},
124 functionArn: `arn:aws:lambda:us-west-2:084828582823:function:${id}`,
125 };
126 }),
127 delete: Effect.fn(function* ({ output }) {}),
128 });
129
130 export type BindingTargetProps = {
131 name?: string;
132 string?: string;
133 replaceString?: string;
134 };
135
136 export interface BindingTarget extends Resource<
137 "Test.BindingTarget",
138 BindingTargetProps,
139 {
140 name: string;
141 string: string;
142 env: Record<string, string>;
143 replaceString: BindingTargetProps["replaceString"];
144 },
145 {
146 env?: Record<string, string>;
147 }
148 > {}
149
150 export const BindingTarget = Resource<BindingTarget>("Test.BindingTarget");
151
152 export const bindingTargetProvider = () =>
153 Provider.effect(
154 BindingTarget,
155 Effect.gen(function* () {
156 return {
157 list: () => Effect.succeed([]),
158 diff: Effect.fn(function* ({ id, news = {}, olds = {}, newBindings }) {
159 if (!isResolved(news)) return undefined;
160 const hooks = Option.getOrUndefined(yield* Effect.serviceOption(TestResourceHooks));
161 if (hooks?.diff && isResolved(newBindings)) {
162 yield* hooks.diff(id, newBindings as ResourceBinding[]);
163 }
164 const n = news as BindingTargetProps;
165 const o = olds as BindingTargetProps;
166 if (n.replaceString !== o.replaceString) {
167 return {
168 action: "replace",
169 };
170 }
171 if (n.name !== o.name || n.string !== o.string) {
172 return {
173 action: "update",
174 };
175 }
176 return undefined;
177 }),
178 precreate: Effect.fn(function* ({ id, news = {} }) {
179 return {
180 name: news.name ?? id,
181 string: news.string ?? id,
182 env: {},
183 replaceString: news.replaceString,
184 };
185 }),
186 reconcile: Effect.fn(function* ({ id, news = {}, olds, bindings }) {
187 // The hook routing tracks the engine's create-vs-update intent.
188 // `olds === undefined` covers greenfield AND replacement-create
189 // (engine resets olds when minting a new instance), which is
190 // exactly when the test wants `failOn("X", "create")` to fire.
191 // `output === undefined` would miss replacements with `precreate`
192 // because precreate populates `output` before reconcile runs.
193 const hooks = Option.getOrUndefined(yield* Effect.serviceOption(TestResourceHooks));
194 if (olds === undefined) {
195 if (hooks?.create) {
196 yield* hooks.create(id, news as TestResourceProps);
197 }
198 } else {
199 if (hooks?.update) {
200 yield* hooks.update(id, news as TestResourceProps);
201 }
202 }
203 return {
204 name: news.name ?? id,
205 string: news.string ?? id,
206 env: Object.assign(
207 {},
208 ...bindings.map((binding: any) => binding.env ?? binding.data?.env ?? {}),
209 ),
210 replaceString: news.replaceString,
211 };
212 }),
213 delete: Effect.fn(function* ({ id }) {
214 const hooks = Option.getOrUndefined(yield* Effect.serviceOption(TestResourceHooks));
215 if (hooks?.delete) {
216 yield* hooks.delete(id);
217 }
218 return;
219 }),
220 };
221 }),
222 );
223
224 export type DeletedBindingRegressionProps = {
225 name?: string;
226 };
227
228 export interface DeletedBindingRegressionTarget extends Resource<
229 "Test.DeletedBindingRegressionTarget",
230 DeletedBindingRegressionProps,
231 {
232 name: string;
233 env: Record<string, string>;
234 },
235 {
236 env?: Record<string, string>;
237 }
238 > {}
239
240 export const DeletedBindingRegressionTarget = Resource<DeletedBindingRegressionTarget>(
241 "Test.DeletedBindingRegressionTarget",
242 );
243
244 export const deletedBindingRegressionProvider = () =>
245 Provider.succeed(DeletedBindingRegressionTarget, {
246 list: () => Effect.succeed([]),
247 diff: Effect.fn(function* () {}),
248 precreate: Effect.fn(function* ({ id, news = {} }) {
249 return {
250 name: news.name ?? id,
251 env: {},
252 };
253 }),
254 reconcile: Effect.fn(function* ({ id, news = {}, bindings }) {
255 return {
256 name: news.name ?? id,
257 env: Object.assign(
258 {},
259 ...bindings.map((binding: any) => binding.env ?? binding.data?.env ?? {}),
260 ),
261 };
262 }),
263 delete: Effect.fn(function* () {}),
264 });
265
266 export type ArtifactProbeProps = {
267 value: string;
268 };
269
270 export interface ArtifactProbe extends Resource<
271 "Test.ArtifactProbe",
272 ArtifactProbeProps,
273 {
274 value: string;
275 artifactValue: string | undefined;
276 }
277 > {}
278
279 export const ArtifactProbe = Resource<ArtifactProbe>("Test.ArtifactProbe");
280
281 export const artifactProbeProvider = () =>
282 Provider.succeed(ArtifactProbe, {
283 list: () => Effect.succeed([]),
284 diff: Effect.fn(function* ({ news, olds }) {
285 const next = news as ArtifactProbeProps;
286 const prev = olds as ArtifactProbeProps | undefined;
287 const artifacts = yield* Artifacts;
288 const previous = yield* artifacts.get<string>("memo");
289 if (previous !== undefined && previous !== next.value && previous !== prev?.value) {
290 return { action: "replace" as const };
291 }
292 yield* artifacts.set("memo", next.value);
293 return next.value !== prev?.value ? { action: "update" as const } : undefined;
294 }),
295 reconcile: Effect.fn(function* ({ news }) {
296 const props = news as ArtifactProbeProps;
297 const artifacts = yield* Artifacts;
298 return {
299 value: props.value,
300 artifactValue: yield* artifacts.get<string>("memo"),
301 };
302 }),
303 delete: Effect.fn(function* () {}),
304 });
305
306 // TestResource
307
308 export type TestResourceProps = {
309 string?: string;
310 stringArray?: string[];
311 object?: {
312 string: string;
313 };
314 replaceString?: string;
315 redacted?: Redacted.Redacted<string>;
316 redactedArray?: Redacted.Redacted<string>[];
317 };
318
319 export interface TestResource extends Resource<
320 "Test.TestResource",
321 TestResourceProps,
322 {
323 string: string;
324 stringArray: string[];
325 stableString: string;
326 stableArray: string[];
327 replaceString: TestResourceProps["replaceString"];
328 redacted: Redacted.Redacted<string> | undefined;
329 redactedArray: Redacted.Redacted<string>[] | undefined;
330 }
331 > {}
332
333 export class TestResourceHooks extends Context.Service<
334 TestResourceHooks,
335 {
336 create?: (id: string, props: TestResourceProps) => Effect.Effect<void, any>;
337 update?: (id: string, props: TestResourceProps) => Effect.Effect<void, any>;
338 delete?: (id: string) => Effect.Effect<void, any>;
339 /**
340 * If provided, invoked from a binding-aware provider's `diff` with the
341 * exact `newBindings` array the engine handed it. Lets a test assert what
342 * the plan stage observes (e.g. that duplicates were collapsed by sid).
343 */
344 diff?: (id: string, newBindings: ResourceBinding[]) => Effect.Effect<void, any>;
345 /**
346 * If provided, the read hook is invoked for the resource's `read` lifecycle
347 * operation. Return:
348 * - attrs (any object) to simulate an existing cloud resource that is
349 * adoptable
350 * - `undefined` to simulate a resource that does not exist
351 * - fail with `OwnedBySomeoneElse` to reject adoption
352 */
353 read?: (id: string) => Effect.Effect<TestResource["Attributes"] | undefined, any>;
354 }
355 >()("TestResourceHooks") {}
356
357 export const TestResource = Resource<TestResource>("Test.TestResource");
358
359 export const testResourceProvider = () =>
360 Provider.effect(
361 TestResource,
362 Effect.gen(function* () {
363 return {
364 list: () => Effect.succeed([]),
365 read: Effect.fn(function* ({ id, output }) {
366 const hooks = Option.getOrUndefined(yield* Effect.serviceOption(TestResourceHooks));
367 if (hooks?.read) {
368 return (yield* hooks.read(id)) as any;
369 }
370 return output;
371 }),
372 diff: Effect.fn(function* ({ id, news = {}, olds = {} }) {
373 if (!isResolved(news)) return undefined;
374 const n = news as TestResourceProps;
375 const o = olds as TestResourceProps;
376 if (n.replaceString !== o.replaceString) {
377 return {
378 action: "replace",
379 };
380 }
381 const redactedValue = (r: Redacted.Redacted<string> | undefined): string | undefined =>
382 r && Redacted.isRedacted(r) ? Redacted.value(r) : undefined;
383 const redactedArrayValues = (
384 arr: Redacted.Redacted<string>[] | undefined,
385 ): string[] | undefined => arr?.map((r) => Redacted.value(r));
386 const oldRedactedArr = redactedArrayValues(o.redactedArray);
387 const newRedactedArr = redactedArrayValues(n.redactedArray);
388 return isUnknown(n.string) ||
389 isUnknown(n.stringArray) ||
390 n.string !== o.string ||
391 n.stringArray?.length !== o.stringArray?.length ||
392 !!n.stringArray !== !!o.stringArray ||
393 n.stringArray?.some(isUnknown) ||
394 n.stringArray?.some((s, i) => s !== o.stringArray?.[i]) ||
395 redactedValue(n.redacted) !== redactedValue(o.redacted) ||
396 oldRedactedArr?.length !== newRedactedArr?.length ||
397 !!oldRedactedArr !== !!newRedactedArr ||
398 newRedactedArr?.some((s, i) => s !== oldRedactedArr?.[i])
399 ? {
400 action: "update",
401 stables: ["stableString", "stableArray"],
402 }
403 : undefined;
404 }),
405 reconcile: Effect.fn(function* ({ id, news = {}, olds }) {
406 const hooks = Option.getOrUndefined(yield* Effect.serviceOption(TestResourceHooks));
407 // Branch on `olds` (engine's create-vs-update intent), not
408 // `output` — replacements arrive with a precreate stub in
409 // `output` but `olds === undefined`.
410 if (olds === undefined) {
411 if (hooks?.create) {
412 yield* hooks.create(id, news);
413 }
414 } else {
415 if (hooks?.update) {
416 yield* hooks.update(id, news);
417 }
418 }
419 return {
420 string: news.string ?? id,
421 stringArray: news.stringArray ?? [],
422 stableString: id,
423 stableArray: [id],
424 replaceString: news.replaceString,
425 redacted: news.redacted,
426 redactedArray: news.redactedArray,
427 };
428 }),
429 delete: Effect.fn(function* ({ id }) {
430 const hooks = Option.getOrUndefined(yield* Effect.serviceOption(TestResourceHooks));
431 if (hooks?.delete) {
432 yield* hooks.delete(id);
433 }
434 return;
435 }),
436 };
437 }),
438 );
439
440 // StaticStablesResource - A test resource that has static stables on the provider
441 // This simulates resources like VPC, Subnet, etc. where certain properties (e.g., vpcId, subnetId)
442 // are always stable and defined on the provider itself, not returned dynamically by diff()
443
444 export type StaticStablesResourceProps = {
445 string?: string;
446 tags?: Record<string, string>;
447 replaceString?: string;
448 };
449
450 export interface StaticStablesResource extends Resource<
451 "Test.StaticStablesResource",
452 StaticStablesResourceProps,
453 {
454 string: string;
455 tags: Record<string, string>;
456 stableId: string;
457 stableArn: string;
458 replaceString: StaticStablesResourceProps["replaceString"];
459 }
460 > {}
461
462 export class StaticStablesResourceHooks extends Context.Service<
463 StaticStablesResourceHooks,
464 {
465 create?: (id: string, props: StaticStablesResourceProps) => Effect.Effect<void, any>;
466 update?: (id: string, props: StaticStablesResourceProps) => Effect.Effect<void, any>;
467 delete?: (id: string) => Effect.Effect<void, any>;
468 }
469 >()("StaticStablesResourceHooks") {}
470
471 export const StaticStablesResource = Resource<StaticStablesResource>("Test.StaticStablesResource");
472
473 export const staticStablesResourceProvider = () =>
474 Provider.succeed(StaticStablesResource, {
475 list: () => Effect.succeed([]),
476 // KEY DIFFERENCE: Static stables defined on the provider itself
477 // These are always stable regardless of what diff() returns
478 stables: ["stableId", "stableArn"],
479 diff: Effect.fn(function* ({ id, news = {}, olds = {} }) {
480 if (!isResolved(news)) return undefined;
481 const n = news as StaticStablesResourceProps;
482 const o = olds as StaticStablesResourceProps;
483 // Replace when replaceString changes
484 if (n.replaceString !== o.replaceString) {
485 return { action: "replace" };
486 }
487 // For string changes, return update action
488 if (n.string !== o.string) {
489 return { action: "update" };
490 }
491 // For tag-only changes, return undefined (no action)
492 // This simulates the VPC bug: tags changed, arePropsChanged returns true,
493 // but diff() returns undefined because provider doesn't explicitly handle tags
494 return undefined;
495 }),
496 reconcile: Effect.fn(function* ({ id, news = {}, olds, output }) {
497 const hooks = Option.getOrUndefined(yield* Effect.serviceOption(StaticStablesResourceHooks));
498 // Branch on `olds` (engine create vs update intent). Replacements
499 // pass `output` from the previous generation if any, but engine
500 // resets `olds` to `undefined` for the new instance.
501 if (olds === undefined) {
502 if (hooks?.create) {
503 yield* hooks.create(id, news);
504 }
505 return {
506 string: news.string ?? id,
507 tags: news.tags ?? {},
508 stableId: output?.stableId ?? `stable-${id}`,
509 stableArn: output?.stableArn ?? (`arn:test:resource:us-east-1:123456789:${id}` as const),
510 replaceString: news.replaceString,
511 };
512 }
513 if (hooks?.update) {
514 yield* hooks.update(id, news);
515 }
516 return {
517 string: news.string ?? id,
518 tags: news.tags ?? {},
519 stableId: output?.stableId ?? `stable-${id}`,
520 stableArn: output?.stableArn ?? (`arn:test:resource:us-east-1:123456789:${id}` as const),
521 replaceString: news.replaceString,
522 };
523 }),
524 delete: Effect.fn(function* ({ id, output }) {
525 yield* Effect.logDebug(output.string);
526 const hooks = Option.getOrUndefined(yield* Effect.serviceOption(StaticStablesResourceHooks));
527 if (hooks?.delete) {
528 yield* hooks.delete(id);
529 }
530 return;
531 }),
532 });
533
534 // KindStablesResource - reproduces providers whose stable output attributes
535 // include a `kind` field, such as PlanetScale databases.
536
537 export type KindStablesResourceProps = {
538 value: string;
539 upstream?: KindStablesResource;
540 };
541
542 export interface KindStablesResource extends Resource<
543 "Test.KindStablesResource",
544 KindStablesResourceProps,
545 {
546 kind: "postgresql";
547 value: string;
548 upstreamKind: "postgresql" | undefined;
549 }
550 > {}
551
552 export const KindStablesResource = Resource<KindStablesResource>("Test.KindStablesResource");
553
554 export const kindStablesResourceProvider = () =>
555 Provider.succeed(KindStablesResource, {
556 list: () => Effect.succeed([]),
557 stables: ["kind"],
558 diff: Effect.fn(function* ({ news, olds }) {
559 if (!isResolved(news)) return undefined;
560 if (news.value !== olds?.value) {
561 return { action: "update" };
562 }
563 return undefined;
564 }),
565 reconcile: Effect.fn(function* ({ news }) {
566 const upstream = news.upstream as KindStablesResource["Attributes"] | undefined;
567 return {
568 kind: "postgresql",
569 value: news.value,
570 upstreamKind: upstream?.kind,
571 };
572 }),
573 delete: Effect.fn(function* () {}),
574 });
575
576 // OverrideStablesResource — declares BOTH a provider-level `stables` list AND
577 // a `diff` that returns its own `stables` list that DISAGREES with it. Used to
578 // assert that a present `diff.stables` OVERRIDES `provider.stables` during plan
579 // (rather than being merged with it):
580 // - `providerStable` is only in `provider.stables` (omitted by `diff.stables`)
581 // - `diffStable` is only in `diff.stables` (omitted by `provider.stables`)
582 // - `sharedStable` is in both
583 // Under override semantics, on a `string` change `providerStable` must be
584 // treated as CHANGED (downstream re-plans) while `diffStable`/`sharedStable`
585 // stay stable. Under the old merge, `providerStable` would wrongly stay stable.
586 // When `string` is unchanged the diff returns a noop that still carries its
587 // `stables`, which a `--force` deploy must honor (#1832).
588
589 export type OverrideStablesResourceProps = {
590 string?: string;
591 };
592
593 export interface OverrideStablesResource extends Resource<
594 "Test.OverrideStablesResource",
595 OverrideStablesResourceProps,
596 {
597 string: string;
598 providerStable: string;
599 diffStable: string;
600 sharedStable: string;
601 }
602 > {}
603
604 export const OverrideStablesResource = Resource<OverrideStablesResource>(
605 "Test.OverrideStablesResource",
606 );
607
608 export const overrideStablesResourceProvider = () =>
609 Provider.succeed(OverrideStablesResource, {
610 list: () => Effect.succeed([]),
611 stables: ["providerStable", "sharedStable"],
612 diff: Effect.fn(function* ({ news = {}, olds = {} }) {
613 if (!isResolved(news)) return undefined;
614 const n = news as OverrideStablesResourceProps;
615 const o = olds as OverrideStablesResourceProps;
616 if (n.string !== o.string) {
617 return {
618 action: "update",
619 stables: ["diffStable", "sharedStable"],
620 } as const;
621 }
622 // Unchanged: still advertise the diff-level stables so a `--force`
623 // deploy (which upgrades this noop to an update) keeps them (#1832).
624 return { action: "noop", stables: ["diffStable", "sharedStable"] } as const;
625 }),
626 reconcile: Effect.fn(function* ({ id, news = {} }) {
627 return {
628 string: news.string ?? id,
629 providerStable: `provider-${id}`,
630 diffStable: `diff-${id}`,
631 sharedStable: `shared-${id}`,
632 };
633 }),
634 delete: Effect.fn(function* () {}),
635 });
636
637 export type PhasedTargetProps = {
638 desired: string;
639 replaceKey?: string;
640 };
641
642 export interface PhasedTarget extends Resource<
643 "Test.PhasedTarget",
644 PhasedTargetProps,
645 {
646 stableId: string;
647 value: string;
648 env: Record<string, string>;
649 replaceKey: string | undefined;
650 },
651 {
652 env?: Record<string, string>;
653 }
654 > {}
655
656 export const PhasedTarget = Resource<PhasedTarget>("Test.PhasedTarget");
657
658 const phasedStableId = (replaceKey?: string) => `stable:${replaceKey ?? "default"}`;
659
660 const mergeBindingEnv = (bindings: Array<any>) =>
661 Object.assign({}, ...bindings.map((binding) => binding.env ?? binding.data?.env ?? {}));
662
663 export const phasedTargetProvider = () =>
664 Provider.effect(
665 PhasedTarget,
666 Effect.gen(function* () {
667 return {
668 list: () => Effect.succeed([]),
669 diff: Effect.fn(function* ({ news, olds }) {
670 if (!isResolved(news)) return undefined;
671 const n = news as PhasedTargetProps;
672 const o = olds as PhasedTargetProps;
673 if (n.replaceKey !== o.replaceKey) {
674 return { action: "replace" } as const;
675 }
676 if (n.desired !== o.desired) {
677 return { action: "update" } as const;
678 }
679 }),
680 precreate: Effect.fn(function* ({ news }) {
681 return {
682 stableId: phasedStableId(news.replaceKey),
683 value: `pre:${news.desired}`,
684 env: {},
685 replaceKey: news.replaceKey,
686 };
687 }),
688 reconcile: Effect.fn(function* ({ id, news, olds, bindings }) {
689 const hooks = Option.getOrUndefined(yield* Effect.serviceOption(TestResourceHooks));
690 // Branch on `olds` not `output`: replacement-create has
691 // precreate-populated `output` but engine-cleared `olds`.
692 if (olds === undefined) {
693 if (hooks?.create) {
694 yield* hooks.create(id, {
695 string: news.desired,
696 replaceString: news.replaceKey,
697 });
698 }
699 } else {
700 if (hooks?.update) {
701 yield* hooks.update(id, {
702 string: news.desired,
703 replaceString: news.replaceKey,
704 });
705 }
706 }
707 return {
708 stableId: phasedStableId(news.replaceKey),
709 value: news.desired,
710 env: mergeBindingEnv(bindings),
711 replaceKey: news.replaceKey,
712 };
713 }),
714 delete: Effect.fn(function* ({ id }) {
715 const hooks = Option.getOrUndefined(yield* Effect.serviceOption(TestResourceHooks));
716 if (hooks?.delete) {
717 yield* hooks.delete(id);
718 }
719 }),
720 };
721 }),
722 );
723
724 // NoPrecreateBindingTarget - like BindingTarget but without precreate,
725 // used to test cycle detection for resources that cannot break cycles.
726
727 export type NoPrecreateBindingTargetProps = {
728 string?: string;
729 };
730
731 export interface NoPrecreateBindingTarget extends Resource<
732 "Test.NoPrecreateBindingTarget",
733 NoPrecreateBindingTargetProps,
734 {
735 string: string;
736 env: Record<string, string>;
737 },
738 {
739 env?: Record<string, string>;
740 }
741 > {}
742
743 export const NoPrecreateBindingTarget = Resource<NoPrecreateBindingTarget>(
744 "Test.NoPrecreateBindingTarget",
745 );
746
747 export const noPrecreateBindingTargetProvider = () =>
748 Provider.succeed(NoPrecreateBindingTarget, {
749 list: () => Effect.succeed([]),
750 diff: Effect.fn(function* () {}),
751 reconcile: Effect.fn(function* ({ id, news = {}, bindings }) {
752 return {
753 string: news.string ?? id,
754 env: Object.assign(
755 {},
756 ...bindings.map((binding: any) => binding.env ?? binding.data?.env ?? {}),
757 ),
758 };
759 }),
760 delete: Effect.fn(function* () {}),
761 });
762
763 // DurationResource — exercises Duration round-tripping through state.
764 // Input Duration must arrive at reconcile as a real Duration object (so the
765 // resolver doesn't shred its prototype); output Duration must re-hydrate from
766 // state on a subsequent deploy as a real Duration object too.
767
768 export type DurationResourceProps = {
769 timeout: Duration.Duration;
770 };
771
772 export interface DurationResource extends Resource<
773 "Test.DurationResource",
774 DurationResourceProps,
775 {
776 /** Echoes the input Duration so we can assert what reconcile observed. */
777 observedTimeout: Duration.Duration;
778 /** Authoritative Duration the provider produces; persisted to state. */
779 computedTimeout: Duration.Duration;
780 }
781 > {}
782
783 export const DurationResource = Resource<DurationResource>("Test.DurationResource");
784
785 export const durationResourceProvider = () =>
786 Provider.succeed(DurationResource, {
787 list: () => Effect.succeed([]),
788 diff: Effect.fn(function* ({ news }) {
789 if (!isResolved(news)) return undefined;
790 return undefined;
791 }),
792 reconcile: Effect.fn(function* ({ news }) {
793 // If `news.timeout` was shredded by the resolver into a plain object,
794 // these calls would throw or produce nonsense. The test asserts the
795 // numeric output so a regression surfaces as a failed assertion.
796 const observed = news.timeout;
797 const computed = Duration.millis(Duration.toMillis(observed) + 1_000);
798 return {
799 observedTimeout: observed,
800 computedTimeout: computed,
801 };
802 }),
803 delete: Effect.fn(function* () {}),
804 });
805
806 // DeleteFirstResource — exercises `{ action: "replace", deleteFirst: true }`.
807 //
808 // Models a resource whose replacement cannot coexist with the original (a
809 // fixed physical name / singleton). When `replaceString` changes it asks the
810 // engine to tear the old generation down BEFORE creating the new one.
811 //
812 // Two test affordances:
813 // - create/update/delete route through `TestResourceHooks` so a test can
814 // record the order the engine invokes them in.
815 // - if a `CollisionRegistry` is in context, create fails when an instance
816 // with the same physical `name` is still live. Under create-first ordering
817 // a same-name replacement would collide here (reproducing the real Docker
818 // "network already exists" / no-op `volume create` bug); under delete-first
819 // it succeeds.
820
821 export class CollisionRegistry extends Context.Service<
822 CollisionRegistry,
823 { readonly live: Set<string> }
824 >()("CollisionRegistry") {}
825
826 export class CollisionError extends Data.TaggedError("CollisionError")<{
827 name: string;
828 }> {}
829
830 export type DeleteFirstResourceProps = {
831 string?: string;
832 replaceString?: string;
833 name?: string;
834 };
835
836 export interface DeleteFirstResource extends Resource<
837 "Test.DeleteFirstResource",
838 DeleteFirstResourceProps,
839 {
840 name: string;
841 string: string;
842 replaceString: DeleteFirstResourceProps["replaceString"];
843 }
844 > {}
845
846 export const DeleteFirstResource = Resource<DeleteFirstResource>("Test.DeleteFirstResource");
847
848 export const deleteFirstResourceProvider = () =>
849 Provider.succeed(DeleteFirstResource, {
850 list: () => Effect.succeed([]),
851 diff: Effect.fn(function* ({ news = {}, olds = {} }) {
852 if (!isResolved(news)) return undefined;
853 const n = news as DeleteFirstResourceProps;
854 const o = olds as DeleteFirstResourceProps;
855 if (n.replaceString !== o.replaceString) {
856 return { action: "replace", deleteFirst: true } as const;
857 }
858 if (n.string !== o.string) {
859 return { action: "update" } as const;
860 }
861 return undefined;
862 }),
863 reconcile: Effect.fn(function* ({ id, news = {}, olds }) {
864 const name = news.name ?? id;
865 const hooks = Option.getOrUndefined(yield* Effect.serviceOption(TestResourceHooks));
866 const registry = Option.getOrUndefined(yield* Effect.serviceOption(CollisionRegistry));
867 // `olds === undefined` ⇒ create (greenfield OR replacement-create); the
868 // engine clears `olds` when minting the new replacement generation.
869 if (olds === undefined) {
870 if (registry?.live.has(name)) {
871 return yield* Effect.fail(new CollisionError({ name }));
872 }
873 registry?.live.add(name);
874 if (hooks?.create) {
875 yield* hooks.create(id, {
876 string: news.string,
877 replaceString: news.replaceString,
878 });
879 }
880 } else if (hooks?.update) {
881 yield* hooks.update(id, {
882 string: news.string,
883 replaceString: news.replaceString,
884 });
885 }
886 return {
887 name,
888 string: news.string ?? id,
889 replaceString: news.replaceString,
890 };
891 }),
892 delete: Effect.fn(function* ({ id, output }) {
893 const hooks = Option.getOrUndefined(yield* Effect.serviceOption(TestResourceHooks));
894 const registry = Option.getOrUndefined(yield* Effect.serviceOption(CollisionRegistry));
895 registry?.live.delete(output.name);
896 if (hooks?.delete) {
897 yield* hooks.delete(id);
898 }
899 }),
900 });
901
902 // ── DriftResource — exercises `alchemy drift --repair`.
903 //
904 // Models a cloud with an inspectable, mutable backing store (`TestCloud`):
905 // `reconcile` upserts the resource into the cloud map, `read` observes it,
906 // `delete` removes it. Tests mutate the map out-of-band to simulate drift
907 // (or delete entries to simulate out-of-band deletion) and assert that
908 // `sync` converges the cloud back to the last-deployed desired state.
909 //
910 // The map stores deep copies — the in-memory state store keeps references,
911 // so aliasing the persisted `attr` would make out-of-band mutations
912 // invisible to drift detection.
913
914 export interface TestCloudService {
915 /** Live cloud state keyed by logical id. Mutate/delete to simulate drift. */
916 readonly resources: Map<string, Record<string, any>>;
917 /** Ids whose `read` result is branded {@link Unowned} (foreign tags). */
918 readonly unowned: Set<string>;
919 /** Lifecycle invocations, in order. Clear between phases to scope asserts. */
920 readonly calls: { op: "read" | "reconcile" | "delete"; id: string }[];
921 }
922
923 export class TestCloud extends Context.Service<TestCloud, TestCloudService>()("TestCloud") {}
924
925 export const makeTestCloud = (): TestCloudService => ({
926 resources: new Map(),
927 unowned: new Set(),
928 calls: [],
929 });
930
931 export type DriftResourceProps = {
932 value?: string;
933 tags?: Record<string, string>;
934 };
935
936 export interface DriftResource extends Resource<
937 "Test.DriftResource",
938 DriftResourceProps,
939 {
940 id: string;
941 value: string;
942 tags: Record<string, string>;
943 env: Record<string, string>;
944 },
945 {
946 env?: Record<string, string>;
947 }
948 > {}
949
950 export const DriftResource = Resource<DriftResource>("Test.DriftResource");
951
952 export const driftResourceProvider = () =>
953 Provider.effect(
954 DriftResource,
955 Effect.gen(function* () {
956 const cloudOf = Effect.serviceOption(TestCloud).pipe(Effect.map(Option.getOrUndefined));
957 const copy = (attrs: Record<string, any>) =>
958 JSON.parse(JSON.stringify(attrs)) as DriftResource["Attributes"];
959 return {
960 list: () => Effect.succeed([]),
961 read: Effect.fn(function* ({ id, output }) {
962 const cloud = yield* cloudOf;
963 // Without a TestCloud in context the resource behaves like
964 // TestResource: read reflects the persisted output back.
965 if (!cloud) return output;
966 cloud.calls.push({ op: "read", id });
967 const live = cloud.resources.get(id);
968 if (live === undefined) return undefined;
969 const attrs = copy(live);
970 return cloud.unowned.has(id) ? Unowned(attrs) : attrs;
971 }),
972 reconcile: Effect.fn(function* ({ id, news = {}, olds, bindings }) {
973 const cloud = yield* cloudOf;
974 cloud?.calls.push({ op: "reconcile", id });
975 const hooks = Option.getOrUndefined(yield* Effect.serviceOption(TestResourceHooks));
976 if (olds === undefined) {
977 if (hooks?.create) {
978 yield* hooks.create(id, { string: news.value });
979 }
980 } else if (hooks?.update) {
981 yield* hooks.update(id, { string: news.value });
982 }
983 const attrs = {
984 id,
985 value: news.value ?? id,
986 tags: news.tags ?? {},
987 env: Object.assign(
988 {},
989 ...bindings.map((binding: any) => binding.env ?? binding.data?.env ?? {}),
990 ),
991 };
992 cloud?.resources.set(id, copy(attrs));
993 return attrs;
994 }),
995 delete: Effect.fn(function* ({ id }) {
996 const cloud = yield* cloudOf;
997 cloud?.calls.push({ op: "delete", id });
998 cloud?.resources.delete(id);
999 }),
1000 };
1001 }),
1002 );
1003
1004 // AliasedWidget — a resource whose type was "renamed" from `Test.Widget` to
1005 // `Test.Widgets.Widget`. The legacy name is carried as an alias so state
1006 // persisted under the old type still resolves to this provider. Its provider
1007 // is intentionally NOT part of `TestLayers` — alias tests provide it as a
1008 // bare layer or wrapped in a `ProviderCollection` to exercise both lookup
1009 // paths in isolation.
1010 export interface AliasedWidget extends Resource<
1011 "Test.Widgets.Widget",
1012 { name?: string },
1013 {
1014 name: string;
1015 }
1016 > {}
1017
1018 export const AliasedWidget = Resource<AliasedWidget>("Test.Widgets.Widget", {
1019 aliases: ["Test.Widget"],
1020 });
1021
1022 /** Logical IDs whose provider `delete` ran — proves deletion went through the provider. */
1023 export const aliasedWidgetDeletes: string[] = [];
1024
1025 export const aliasedWidgetProvider = () =>
1026 Provider.succeed(AliasedWidget, {
1027 list: () => Effect.succeed([]),
1028 reconcile: Effect.fn(function* ({ id, news }) {
1029 return { name: news?.name ?? id };
1030 }),
1031 delete: Effect.fn(function* ({ id }) {
1032 aliasedWidgetDeletes.push(id);
1033 }),
1034 });
1035
1036 // FqnProbe — echoes the identity the engine threads into each handler input
1037 // (`id` and `fqn`) back out as attributes. Lets a test assert that the engine
1038 // passes the resource's real fully-qualified name — namespace path + logical
1039 // id — which differs from the bare logical `id` for namespaced resources.
1040
1041 export interface FqnProbe extends Resource<
1042 "Test.FqnProbe",
1043 {},
1044 {
1045 id: string;
1046 fqn: string;
1047 }
1048 > {}
1049
1050 export const FqnProbe = Resource<FqnProbe>("Test.FqnProbe");
1051
1052 export const fqnProbeProvider = () =>
1053 Provider.succeed(FqnProbe, {
1054 list: () => Effect.succeed([]),
1055 diff: Effect.fn(function* ({ news }) {
1056 if (!isResolved(news)) return undefined;
1057 return undefined;
1058 }),
1059 reconcile: Effect.fn(function* ({ id, fqn }) {
1060 return { id, fqn };
1061 }),
1062 delete: Effect.fn(function* () {}),
1063 });
1064
1065 /**
1066 * Run `eff` as if under `alchemy dev`: overrides `AlchemyContext.dev` so
1067 * plans and applies inside resolve the LOCAL provider mode by default —
1068 * exactly what the `alchemy dev` command does for a whole run.
1069 */
1070 export const inDev = <A, E, R>(
1071 eff: Effect.Effect<A, E, R>,
1072 ): Effect.Effect<A, E, R | AlchemyContext> =>
1073 AlchemyContext.pipe(
1074 Effect.flatMap((ctx) => eff.pipe(Effect.provideService(AlchemyContext, { ...ctx, dev: true }))),
1075 );
1076
1077 // ModalResource — a resource registered via `ProviderLayer.dual` with
1078 // distinct live and local implementations. Used by provider-mode tests to
1079 // assert: mode stamping in state, replace-on-mode-switch, mode-correct
1080 // deletes of old generations/orphans, and lazy non-default-variant builds.
1081 //
1082 // Both recorders are module-level (like `aliasedWidgetDeletes`) and tag
1083 // every entry with the scratch stack name so concurrent tests in the same
1084 // file can filter to their own activity.
1085
1086 export type ModalResourceProps = {
1087 value?: string;
1088 /**
1089 * Changing this forces an ordinary (same-mode) replacement — used to
1090 * assert that `providerMode` survives provider-diff replacements and
1091 * that old generations are deleted with their own stamped mode.
1092 */
1093 replaceValue?: string;
1094 /**
1095 * Changing this forces a `deleteFirst` replacement — used to assert that
1096 * `deleteOldGenerations` (the pre-create teardown) resolves each old
1097 * generation's provider by ITS stamped mode.
1098 */
1099 deleteFirstValue?: string;
1100 };
1101
1102 export interface ModalResource extends Resource<
1103 "Test.ModalResource",
1104 ModalResourceProps,
1105 {
1106 value: string;
1107 /** Which provider variant reconciled this instance. */
1108 runtime: ProviderMode;
1109 /**
1110 * Physical identity marker, mirroring real local providers: the local
1111 * variant fabricates a `dev:`-prefixed id, the live variant a plain
1112 * one. Legacy-row tests rely on this to exercise the marker-inferred
1113 * mode fallback for unstamped rows.
1114 */
1115 instance: string;
1116 /**
1117 * Local dev URL — returned by the LOCAL variant only, mirroring how a
1118 * local Worker's attrs carry its dev-proxy URL. Apply announces it as
1119 * a `ready at <url>` note on local-mode rows.
1120 */
1121 url?: string;
1122 }
1123 > {}
1124
1125 export const ModalResource = Resource<ModalResource>("Test.ModalResource");
1126
1127 /** Variant layer constructions, in order. */
1128 export const modalBuilds: { stack: string; mode: ProviderMode }[] = [];
1129 /** Lifecycle calls dispatched to each variant, in order. */
1130 export const modalCalls: {
1131 stack: string;
1132 mode: ProviderMode;
1133 op: "reconcile" | "delete";
1134 id: string;
1135 }[] = [];
1136
1137 // Some plan-level test harnesses build `TestLayers()` without a `Stack`
1138 // service in context, so the discriminator is resolved as an option with a
1139 // fallback rather than required at layer build.
1140 const modalStackName = Effect.serviceOption(Stack).pipe(
1141 Effect.map(Option.match({ onNone: () => "unknown", onSome: (s) => s.name })),
1142 );
1143
1144 const modalVariant = (mode: ProviderMode) =>
1145 Provider.effect(
1146 ModalResource,
1147 Effect.gen(function* () {
1148 modalBuilds.push({ stack: yield* modalStackName, mode });
1149 return {
1150 list: () => Effect.succeed([]),
1151 read: Effect.fn(function* ({ output }) {
1152 // Echo persisted attrs (the TestResource default): no cloud to
1153 // observe, and a cold-start probe (output undefined) finds nothing.
1154 return output;
1155 }),
1156 diff: Effect.fn(function* ({ news, olds }) {
1157 if (!isResolved(news)) return undefined;
1158 const n = news as ModalResourceProps;
1159 const o = olds as ModalResourceProps | undefined;
1160 if (n.deleteFirstValue !== o?.deleteFirstValue) {
1161 return { action: "replace", deleteFirst: true } as const;
1162 }
1163 if (n.replaceValue !== o?.replaceValue) {
1164 return { action: "replace" } as const;
1165 }
1166 return n.value !== o?.value
1167 ? ({ action: "update" } as const)
1168 : ({ action: "noop" } as const);
1169 }),
1170 reconcile: Effect.fn(function* ({ id, news = {}, olds }) {
1171 // Failure injection via the shared TestResourceHooks (same pattern
1172 // as bindingTargetProvider): `olds === undefined` is the engine's
1173 // create intent — greenfield or replacement-create.
1174 const hooks = Option.getOrUndefined(yield* Effect.serviceOption(TestResourceHooks));
1175 if (olds === undefined) {
1176 if (hooks?.create) {
1177 yield* hooks.create(id, {
1178 string: (news as ModalResourceProps).value,
1179 });
1180 }
1181 } else if (hooks?.update) {
1182 yield* hooks.update(id, {
1183 string: (news as ModalResourceProps).value,
1184 });
1185 }
1186 modalCalls.push({
1187 stack: yield* modalStackName,
1188 mode,
1189 op: "reconcile",
1190 id,
1191 });
1192 return {
1193 value: (news as ModalResourceProps).value ?? id,
1194 runtime: mode,
1195 instance: mode === "local" ? `${LOCAL_ID_PREFIX}${id}` : id,
1196 ...(mode === "local" ? { url: "http://localhost:1337" } : {}),
1197 };
1198 }),
1199 delete: Effect.fn(function* ({ id }) {
1200 const hooks = Option.getOrUndefined(yield* Effect.serviceOption(TestResourceHooks));
1201 if (hooks?.delete) {
1202 yield* hooks.delete(id);
1203 }
1204 modalCalls.push({
1205 stack: yield* modalStackName,
1206 mode,
1207 op: "delete",
1208 id,
1209 });
1210 }),
1211 };
1212 }),
1213 );
1214
1215 export const modalResourceProvider = () =>
1216 ProviderLayer.dual(ModalResource, {
1217 live: () => modalVariant("live"),
1218 local: () => modalVariant("local"),
1219 dataPlane: () => modalLocalDataPlane,
1220 liveDataPlane: () => modalLiveDataPlane,
1221 });
1222
1223 /**
1224 * Which data-plane override a deploy-time binding client ran under.
1225 * The local/live layers below stamp this; ambient (no wrap) is `"ambient"`.
1226 */
1227 export class DataPlaneTag extends Context.Service<DataPlaneTag, "local" | "live">()(
1228 "Test.DataPlaneTag",
1229 ) {}
1230
1231 export const modalLocalDataPlane = Layer.succeed(DataPlaneTag, "local");
1232 export const modalLiveDataPlane = Layer.succeed(DataPlaneTag, "live");
1233
1234 /**
1235 * Deploy-time binding used to pin Binding client routing: the returned
1236 * client reads {@link DataPlaneTag}, which is only in context when the wrap
1237 * provided the matching plane layer closest.
1238 */
1239 export interface ProbeBinding extends Binding.Service<
1240 ProbeBinding,
1241 "Test.ProbeBinding",
1242 (
1243 resource: ModalResource | readonly ModalResource[],
1244 ) => Effect.Effect<() => Effect.Effect<"local" | "live" | "ambient">>
1245 > {}
1246 export const ProbeBinding = Binding.Service<ProbeBinding>("Test.ProbeBinding");
1247
1248 export const ProbeBindingLive = Layer.succeed(
1249 ProbeBinding,
1250 Effect.fn(function* (_resource: ModalResource | readonly ModalResource[]) {
1251 return () =>
1252 Effect.serviceOption(DataPlaneTag).pipe(
1253 Effect.map((opt) => (Option.isSome(opt) ? opt.value : "ambient")),
1254 );
1255 }),
1256 );
1257
1258 // CapturedConfigHost - a Platform whose Init reads `Config.String("CAPTURED_MODE")`.
1259 // Its provider's diff always returns `noop` without comparing `env`, so only
1260 // the engine's comparison of Init-captured values can plan an update (#1831).
1261 // `reconcile` echoes the delivered value as the `mode` attribute.
1262 export interface CapturedConfigHostProps extends PlatformProps {
1263 main?: string;
1264 env?: Record<string, unknown>;
1265 }
1266
1267 export interface CapturedConfigHost extends Resource<
1268 "Test.CapturedConfigHost",
1269 CapturedConfigHostProps,
1270 { mode: unknown }
1271 > {}
1272
1273 export const CapturedConfigHost: Platform<
1274 CapturedConfigHost,
1275 ServerHost,
1276 Main<ServerHost>,
1277 HostRuntimeContext
1278 > = Platform("Test.CapturedConfigHost", {
1279 createRuntimeContext: createHostRuntimeContext("Test.CapturedConfigHost"),
1280 });
1281
1282 export const capturedConfigHostProvider = () =>
1283 Provider.succeed(CapturedConfigHost, {
1284 list: () => Effect.succeed([]),
1285 diff: () => Effect.succeed({ action: "noop" as const }),
1286 reconcile: Effect.fn(function* ({ news }) {
1287 const mode = unpackEnvValue(news.env?.CAPTURED_MODE as string);
1288 return { mode: Redacted.isRedacted(mode) ? Redacted.value(mode) : mode };
1289 }),
1290 delete: Effect.fn(function* () {}),
1291 });
1292
1293 /** Declare the host with `mode` served to its Init's `Config` reads. */
1294 export const capturedConfigHost = (mode: string) =>
1295 Effect.gen(function* () {
1296 const ambient = yield* ConfigProvider.ConfigProvider;
1297 return yield* CapturedConfigHost(
1298 "Host",
1299 { main: "index.ts" },
1300 Effect.gen(function* () {
1301 const value = yield* Config.String("CAPTURED_MODE");
1302 return { fetch: Effect.succeed(HttpServerResponse.text(value)) };
1303 }),
1304 ).pipe(
1305 Effect.provideService(
1306 ConfigProvider.ConfigProvider,
1307 ConfigProvider.orElse(ConfigProvider.fromUnknown({ CAPTURED_MODE: mode }), ambient),
1308 ),
1309 );
1310 });
1311
1312 // Layers
1313 export const TestLayers = () =>
1314 Layer.mergeAll(
1315 bucketProvider(),
1316 fqnProbeProvider(),
1317 queueProvider(),
1318 functionProvider(),
1319 bindingTargetProvider(),
1320 deletedBindingRegressionProvider(),
1321 artifactProbeProvider(),
1322 testResourceProvider(),
1323 staticStablesResourceProvider(),
1324 kindStablesResourceProvider(),
1325 overrideStablesResourceProvider(),
1326 phasedTargetProvider(),
1327 noPrecreateBindingTargetProvider(),
1328 durationResourceProvider(),
1329 deleteFirstResourceProvider(),
1330 driftResourceProvider(),
1331 modalResourceProvider(),
1332 capturedConfigHostProvider(),
1333 ProbeBindingLive,
1334 );
1335
1336 export const InMemoryTestLayers = () => Layer.mergeAll(TestLayers(), State.inMemoryState());
1337
1338 // ── Failure injection helpers ──────────────────────────────────────────────
1339 //
1340 // These helpers produce TestResourceHooks records that can be passed to the
1341 // `hook(...)` test combinator to inject failures or defects into specific
1342 // resource lifecycle methods. `failOn` produces typed failures, while
1343 // `dieOn` and `throwOn` produce defects (uncaught/thrown errors).
1344
1345 export class ResourceFailure extends Data.TaggedError("ResourceFailure")<{
1346 message: string;
1347 }> {
1348 constructor(message = "Failed to create") {
1349 super({ message });
1350 }
1351 }
1352
1353 type LifecycleHook = "create" | "update" | "delete";
1354
1355 export type LifecycleHooks = {
1356 create?: (id: string, props: TestResourceProps) => Effect.Effect<void, any>;
1357 update?: (id: string, props: TestResourceProps) => Effect.Effect<void, any>;
1358 delete?: (id: string) => Effect.Effect<void, any>;
1359 };
1360
1361 export const failOn = (resourceId: string, hook: LifecycleHook): LifecycleHooks => ({
1362 [hook]: (id: string) =>
1363 id === resourceId ? Effect.fail(new ResourceFailure()) : Effect.succeed(undefined),
1364 });
1365
1366 export const failOnMultiple = (
1367 failures: Array<{ id: string; hook: LifecycleHook }>,
1368 ): LifecycleHooks => {
1369 const idsFor = (hook: LifecycleHook) => failures.filter((f) => f.hook === hook).map((f) => f.id);
1370 const createFailures = idsFor("create");
1371 const updateFailures = idsFor("update");
1372 const deleteFailures = idsFor("delete");
1373 return {
1374 create: (id: string) =>
1375 createFailures.includes(id) ? Effect.fail(new ResourceFailure()) : Effect.succeed(undefined),
1376 update: (id: string) =>
1377 updateFailures.includes(id) ? Effect.fail(new ResourceFailure()) : Effect.succeed(undefined),
1378 delete: (id: string) =>
1379 deleteFailures.includes(id) ? Effect.fail(new ResourceFailure()) : Effect.succeed(undefined),
1380 };
1381 };
1382
1383 export const dieOn = (
1384 resourceId: string,
1385 hook: LifecycleHook,
1386 message = `dieOn:${resourceId}:${hook}`,
1387 ): LifecycleHooks => ({
1388 [hook]: (id: string) =>
1389 id === resourceId ? Effect.die(new Error(message)) : Effect.succeed(undefined),
1390 });
1391
1392 export const throwOn = (
1393 resourceId: string,
1394 hook: LifecycleHook,
1395 message = `throwOn:${resourceId}:${hook}`,
1396 ): LifecycleHooks => ({
1397 [hook]: (id: string) =>
1398 Effect.sync(() => {
1399 if (id === resourceId) {
1400 throw new Error(message);
1401 }
1402 }),
1403 });