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

main
ts 153 lines 5.04 KB
Raw
1 import * as iotfleetwise from "@distilled.cloud/aws/iotfleetwise";
2 import { Region, type RegionName } from "@distilled.cloud/aws/Region";
3 import { diffTags } from "alchemy/Tags";
4 import * as Effect from "effect/Effect";
5 import * as Schedule from "effect/Schedule";
6
7 /**
8 * AWS IoT FleetWise is offered only in `us-east-1` and `eu-central-1`
9 * (there is no `iotfleetwise.{region}.amazonaws.com` endpoint anywhere
10 * else). The providers follow the ambient region when it is one of the
11 * supported two and pin `us-east-1` otherwise, mirroring how WAFv2
12 * CLOUDFRONT-scoped resources pin their home region.
13 *
14 * @internal
15 */
16 const FLEETWISE_REGIONS: ReadonlySet<string> = new Set(["us-east-1", "eu-central-1"]);
17
18 /** @internal */
19 export const FLEETWISE_HOME_REGION: RegionName = "us-east-1";
20
21 /**
22 * Run a distilled IoT FleetWise effect in a supported region: the ambient
23 * region when FleetWise is offered there, otherwise `us-east-1`.
24 *
25 * `Region`'s service value is an `Effect<RegionName>` (see
26 * `@distilled.cloud/aws/Region`), so it is provided as an effect, not a
27 * bare string.
28 *
29 * @internal
30 */
31 export const inFleetWiseRegion = <A, E, R>(
32 effect: Effect.Effect<A, E, R>,
33 ): Effect.Effect<A, E, R | Region> =>
34 Effect.gen(function* () {
35 // No region configured falls back to the home region. This runs when a
36 // binding captures its client, which cannot fail, so a ConfigProvider
37 // that cannot read its source stays a defect here.
38 const ambient = yield* (yield* Region).pipe(
39 Effect.catchTag("Alchemy::AWS::MissingRegion", () => Effect.undefined),
40 Effect.orDie,
41 );
42 return ambient !== undefined && FLEETWISE_REGIONS.has(ambient)
43 ? yield* effect
44 : yield* effect.pipe(Effect.provideService(Region, Effect.succeed(FLEETWISE_HOME_REGION)));
45 });
46
47 /**
48 * Read the observed tags of an IoT FleetWise resource as a plain record.
49 * Tag-read failures degrade to an empty record so tag drift never blocks
50 * reads of the resource itself.
51 *
52 * @internal
53 */
54 export const readFleetWiseTags = Effect.fn(function* (arn: string) {
55 const response = yield* iotfleetwise.listTagsForResource({ ResourceARN: arn }).pipe(
56 inFleetWiseRegion,
57 Effect.orElseSucceed(
58 () =>
59 ({
60 Tags: [],
61 }) as iotfleetwise.ListTagsForResourceResponse,
62 ),
63 );
64 return Object.fromEntries((response.Tags ?? []).map((tag) => [tag.Key, tag.Value])) as Record<
65 string,
66 string
67 >;
68 });
69
70 /**
71 * Convert a tag record to the FleetWise wire shape.
72 *
73 * @internal
74 */
75 export const toFleetWiseTagList = (tags: Record<string, string>): iotfleetwise.Tag[] =>
76 Object.entries(tags).map(([Key, Value]) => ({ Key, Value }));
77
78 /**
79 * Converge an IoT FleetWise resource's tags on the desired record, diffing
80 * against OBSERVED cloud tags (never `olds`/`output`).
81 *
82 * @internal
83 */
84 export const syncFleetWiseTags = Effect.fn(function* (
85 arn: string,
86 desired: Record<string, string>,
87 ) {
88 const observed = yield* readFleetWiseTags(arn);
89 const { upsert, removed } = diffTags(observed, desired);
90 if (upsert.length > 0) {
91 yield* iotfleetwise.tagResource({ ResourceARN: arn, Tags: upsert }).pipe(inFleetWiseRegion);
92 }
93 if (removed.length > 0) {
94 yield* iotfleetwise
95 .untagResource({ ResourceARN: arn, TagKeys: removed })
96 .pipe(inFleetWiseRegion);
97 }
98 });
99
100 /**
101 * Retry an effect through FleetWise `ConflictException` windows (e.g. a
102 * signal catalog whose model manifests are still deleting, or a decoder
103 * manifest with vehicles detaching). Bounded: ~30s total.
104 *
105 * Explicitly typed: inlining `Effect.retry` with options in provider
106 * lifecycle code widens the provider layer to `unknown` in declaration
107 * emit.
108 *
109 * @internal
110 */
111 export const retryWhileConflict = <A, E extends { readonly _tag: string }, R>(
112 self: Effect.Effect<A, E, R>,
113 ): Effect.Effect<A, E, R> =>
114 Effect.retry(self, {
115 while: (e) => e._tag === "ConflictException",
116 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]),
117 });
118
119 /**
120 * Bounded eventual-consistency retry for observe-after-write reads
121 * (~20s total).
122 *
123 * @internal
124 */
125 export const retryObservation = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
126 Effect.retry(self, {
127 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(10)]),
128 });
129
130 /**
131 * Order-insensitive deep equality over plain JSON-ish values (props and
132 * observed FleetWise structures). Object keys are sorted; arrays stay
133 * positional.
134 *
135 * @internal
136 */
137 export const stableEquals = (left: unknown, right: unknown): boolean =>
138 stableStringify(left) === stableStringify(right);
139
140 const stableStringify = (value: unknown): string => JSON.stringify(normalize(value));
141
142 const normalize = (value: unknown): unknown => {
143 if (Array.isArray(value)) return value.map(normalize);
144 if (value !== null && typeof value === "object") {
145 return Object.fromEntries(
146 Object.entries(value as Record<string, unknown>)
147 .filter(([, v]) => v !== undefined)
148 .sort(([l], [r]) => l.localeCompare(r))
149 .map(([k, v]) => [k, normalize(v)]),
150 );
151 }
152 return value;
153 };