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

main
ts 394 lines 14.3 KB
Raw
1 import * as greengrassv2 from "@distilled.cloud/aws/greengrassv2";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import { AWSEnvironment } from "../Environment.ts";
13 import type { Providers } from "../Providers.ts";
14
15 /**
16 * A configuration update applied to a component when the deployment reaches
17 * a core device.
18 */
19 export interface DeploymentComponentConfigurationUpdate {
20 /**
21 * A JSON-serialized object that the deployment merges into the component's
22 * default configuration.
23 */
24 merge?: string;
25 /**
26 * Configuration paths to reset to their default values.
27 */
28 reset?: string[];
29 }
30
31 /**
32 * A component to include in a deployment, keyed by component name on the
33 * deployment's `components` map.
34 */
35 export interface DeploymentComponent {
36 /**
37 * The version of the component to deploy, e.g. `1.0.0`.
38 */
39 componentVersion: string;
40 /**
41 * Configuration update the deployment applies to the component.
42 */
43 configurationUpdate?: DeploymentComponentConfigurationUpdate;
44 }
45
46 export interface DeploymentProps {
47 /**
48 * The ARN of the target IoT thing or thing group. Each target has at most
49 * one deployment; creating a new deployment for a target supersedes the
50 * previous revision.
51 *
52 * Changing the target replaces the deployment.
53 */
54 targetArn: string;
55 /**
56 * A friendly name for the deployment.
57 * @default ${app}-${stage}-${id}
58 */
59 deploymentName?: string;
60 /**
61 * The components to deploy, keyed by component name. Updating this map
62 * creates a new deployment revision for the target.
63 */
64 components?: Record<string, DeploymentComponent>;
65 /**
66 * Tags to apply to the deployment. Merged with internal Alchemy tags.
67 */
68 tags?: Record<string, string>;
69 }
70
71 export interface Deployment extends Resource<
72 "AWS.GreengrassV2.Deployment",
73 DeploymentProps,
74 {
75 /** The unique ID of the deployment. */
76 deploymentId: string;
77 /** The ARN of the deployment. */
78 deploymentArn: string;
79 /** The ARN of the target core device or thing group. */
80 targetArn: string;
81 /** The revision of the deployment. */
82 revisionId?: string;
83 /** The current status of the deployment (`ACTIVE`, `COMPLETED`, ...). */
84 deploymentStatus?: string;
85 /** The ID of the IoT job that rolls the deployment out to core devices. */
86 iotJobId?: string;
87 /** The ARN of the IoT job that rolls the deployment out to core devices. */
88 iotJobArn?: string;
89 },
90 never,
91 Providers
92 > {}
93
94 /**
95 * An IoT Greengrass V2 continuous deployment that installs a set of component
96 * versions on a target IoT thing or thing group.
97 *
98 * Updating the deployment's components or name creates a new deployment
99 * revision for the target (the `deploymentId` attribute changes); the
100 * previous revision is canceled and deleted.
101 *
102 * ### Creating Deployments
103 * **Example:** Deploy a component to a thing
104 * ```typescript
105 * import * as GreengrassV2 from "@alchemy.run/aws/GreengrassV2";
106 * import * as IoT from "@alchemy.run/aws/IoT";
107 *
108 * const core = yield* IoT.Thing("Core", {});
109 * const component = yield* GreengrassV2.ComponentVersion("Hello", { recipe });
110 *
111 * const deployment = yield* GreengrassV2.Deployment("Rollout", {
112 * targetArn: core.thingArn,
113 * components: {
114 * [component.componentName]: {
115 * componentVersion: component.componentVersion,
116 * },
117 * },
118 * });
119 * ```
120 *
121 * **Example:** Deployment with a configuration update
122 * ```typescript
123 * const deployment = yield* GreengrassV2.Deployment("Rollout", {
124 * targetArn: core.thingArn,
125 * components: {
126 * "com.example.Hello": {
127 * componentVersion: "1.0.0",
128 * configurationUpdate: { merge: JSON.stringify({ interval: 30 }) },
129 * },
130 * },
131 * });
132 * ```
133 *
134 * @resource
135 */
136 export const Deployment = Resource<Deployment>("AWS.GreengrassV2.Deployment");
137
138 /**
139 * Raised when `createDeployment` returns without a deployment ID, which the
140 * provider needs to track the deployment revision.
141 */
142 export class GreengrassDeploymentMissingId extends Data.TaggedError(
143 "GreengrassDeploymentMissingId",
144 )<{ message: string }> {}
145
146 // Explicitly-typed pipeable retry helper (see EC2/VolumeAttachment.ts) —
147 // deleting a deployment right after cancellation can race the state change.
148 const retryWhileConflict = <A, E extends { readonly _tag: string }, R>(
149 self: Effect.Effect<A, E, R>,
150 ): Effect.Effect<A, E, R> =>
151 Effect.retry(self, {
152 while: (e) => e._tag === "ConflictException",
153 schedule: Schedule.max([Schedule.fixed(2000), Schedule.recurs(10)]),
154 });
155
156 const normalizeTags = (
157 tags: { [key: string]: string | undefined } | undefined,
158 ): Record<string, string> =>
159 Object.fromEntries(
160 Object.entries(tags ?? {}).filter((entry): entry is [string, string] => entry[1] !== undefined),
161 );
162
163 /**
164 * Canonicalizes a components map (ours or the wire's) for drift comparison:
165 * sorted keys, only defined fields.
166 */
167 interface ComparableComponentSpec {
168 componentVersion?: string;
169 configurationUpdate?: { merge?: string; reset?: readonly string[] };
170 }
171
172 const canonicalComponents = (
173 components: { [key: string]: ComparableComponentSpec | undefined } | undefined,
174 ): string =>
175 JSON.stringify(
176 Object.keys(components ?? {})
177 .sort()
178 .flatMap((name) => {
179 const spec = components?.[name];
180 return spec === undefined
181 ? []
182 : [
183 [
184 name,
185 {
186 componentVersion: spec.componentVersion,
187 merge: spec.configurationUpdate?.merge,
188 reset: spec.configurationUpdate?.reset?.slice().sort(),
189 },
190 ],
191 ];
192 }),
193 );
194
195 export const DeploymentProvider = () =>
196 Provider.effect(
197 Deployment,
198 Effect.gen(function* () {
199 const createDeploymentName = Effect.fn(function* (
200 id: string,
201 props: Pick<DeploymentProps, "deploymentName">,
202 ) {
203 return props.deploymentName ?? (yield* createPhysicalName({ id }));
204 });
205
206 const deploymentArn = Effect.fn(function* (deploymentId: string) {
207 const { accountId, region } = yield* AWSEnvironment.current;
208 return `arn:aws:greengrass:${region}:${accountId}:deployments:${deploymentId}`;
209 });
210
211 const observeDeployment = (deploymentId: string) =>
212 greengrassv2
213 .getDeployment({ deploymentId })
214 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
215
216 // The latest deployment revision for a target (cloud-authoritative).
217 const observeLatestForTarget = (targetArn: string) =>
218 Effect.gen(function* () {
219 const deployments = yield* greengrassv2.listDeployments
220 .items({ targetArn, historyFilter: "LATEST_ONLY" })
221 .pipe(Stream.runCollect);
222 const latest = Array.from(deployments)[0];
223 if (latest?.deploymentId === undefined) return undefined;
224 return yield* observeDeployment(latest.deploymentId);
225 });
226
227 const attributesOf = Effect.fn(function* (
228 live: greengrassv2.GetDeploymentResponse,
229 fallbackTargetArn: string,
230 ) {
231 const deploymentId = live.deploymentId;
232 if (deploymentId === undefined) {
233 return yield* new GreengrassDeploymentMissingId({
234 message: "getDeployment returned no deploymentId",
235 });
236 }
237 return {
238 deploymentId,
239 deploymentArn: yield* deploymentArn(deploymentId),
240 targetArn: live.targetArn ?? fallbackTargetArn,
241 revisionId: live.revisionId,
242 deploymentStatus: live.deploymentStatus,
243 iotJobId: live.iotJobId,
244 iotJobArn: live.iotJobArn,
245 };
246 });
247
248 // Cancel (if still active) and delete a superseded/destroyed revision.
249 const cancelAndDelete = (deploymentId: string) =>
250 Effect.gen(function* () {
251 yield* greengrassv2.cancelDeployment({ deploymentId }).pipe(
252 // Already completed/canceled/inactive revisions reject the
253 // cancellation — that is exactly the state we want.
254 Effect.catchTag(
255 ["ResourceNotFoundException", "ConflictException", "ValidationException"],
256 () => Effect.undefined,
257 ),
258 );
259 yield* greengrassv2.deleteDeployment({ deploymentId }).pipe(
260 retryWhileConflict,
261 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
262 );
263 });
264
265 return Deployment.Provider.of({
266 stables: ["targetArn"],
267 list: () =>
268 Effect.gen(function* () {
269 const deployments = yield* greengrassv2.listDeployments
270 .items({ historyFilter: "LATEST_ONLY" })
271 .pipe(Stream.runCollect);
272 const results: {
273 deploymentId: string;
274 deploymentArn: string;
275 targetArn: string;
276 revisionId?: string;
277 deploymentStatus?: string;
278 iotJobId?: string;
279 iotJobArn?: string;
280 }[] = [];
281 for (const deployment of deployments) {
282 if (deployment.deploymentId === undefined || deployment.targetArn === undefined) {
283 continue;
284 }
285 results.push({
286 deploymentId: deployment.deploymentId,
287 deploymentArn: yield* deploymentArn(deployment.deploymentId),
288 targetArn: deployment.targetArn,
289 revisionId: deployment.revisionId,
290 deploymentStatus: deployment.deploymentStatus,
291 });
292 }
293 return results;
294 }),
295 read: Effect.fn(function* ({ id, olds, output }) {
296 const live =
297 output?.deploymentId !== undefined
298 ? yield* observeDeployment(output.deploymentId)
299 : olds !== undefined
300 ? yield* observeLatestForTarget(olds.targetArn)
301 : undefined;
302 if (live?.deploymentId === undefined) return undefined;
303 const attrs = yield* attributesOf(live, output?.targetArn ?? olds?.targetArn ?? "");
304 return (yield* hasAlchemyTags(id, normalizeTags(live.tags))) ? attrs : Unowned(attrs);
305 }),
306 diff: Effect.fn(function* ({ news, olds }) {
307 if (!isResolved(news)) return undefined;
308 // A deployment belongs to exactly one target.
309 if (olds !== undefined && news.targetArn !== olds.targetArn) {
310 return { action: "replace" } as const;
311 }
312 // fall through: engine default update (new revision in reconcile)
313 }),
314 reconcile: Effect.fn(function* ({ id, news, output, session }) {
315 const deploymentName = yield* createDeploymentName(id, news);
316 const internalTags = yield* createInternalTags(id);
317 const desiredTags = { ...news.tags, ...internalTags };
318 const desiredComponents = canonicalComponents(news.components);
319
320 // 1. OBSERVE — the latest revision for the target is authoritative;
321 // output.deploymentId is only a cache of the revision we made.
322 let live = yield* observeLatestForTarget(news.targetArn);
323
324 // 2. ENSURE/SYNC — a deployment revision is immutable: when the
325 // observed latest revision drifts from the desired spec (or none
326 // exists), create a new revision that supersedes it.
327 const inSync =
328 live !== undefined &&
329 live.deploymentName === deploymentName &&
330 canonicalComponents(live.components) === desiredComponents;
331 if (!inSync) {
332 const created = yield* greengrassv2.createDeployment({
333 targetArn: news.targetArn,
334 deploymentName,
335 components: news.components ?? {},
336 tags: desiredTags,
337 });
338 if (created.deploymentId === undefined) {
339 return yield* new GreengrassDeploymentMissingId({
340 message: `createDeployment for ${news.targetArn} returned no deploymentId`,
341 });
342 }
343 // Clean up the revision we previously created, now superseded.
344 if (
345 output?.deploymentId !== undefined &&
346 output.deploymentId !== created.deploymentId
347 ) {
348 yield* cancelAndDelete(output.deploymentId);
349 }
350 live = yield* observeDeployment(created.deploymentId);
351 if (live === undefined) {
352 return yield* new GreengrassDeploymentMissingId({
353 message: `deployment ${created.deploymentId} disappeared after creation`,
354 });
355 }
356 }
357
358 // Post-ensure narrowing: `inSync` implies `live` was observed and
359 // the !inSync branch re-observed after create, but TS cannot track
360 // that through the reassignment — guard with a typed error.
361 if (live === undefined) {
362 return yield* new GreengrassDeploymentMissingId({
363 message: `no deployment observed for target ${news.targetArn} after reconcile`,
364 });
365 }
366
367 const attrs = yield* attributesOf(live, news.targetArn);
368
369 // 3. SYNC TAGS — diff against OBSERVED cloud tags so adoption and
370 // no-op updates converge (create-time tags only apply on create).
371 const observedTags = normalizeTags(live.tags);
372 const { upsert, removed } = diffTags(observedTags, desiredTags);
373 if (upsert.length > 0) {
374 yield* greengrassv2.tagResource({
375 resourceArn: attrs.deploymentArn,
376 tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
377 });
378 }
379 if (removed.length > 0) {
380 yield* greengrassv2.untagResource({
381 resourceArn: attrs.deploymentArn,
382 tagKeys: removed,
383 });
384 }
385
386 yield* session.note(attrs.deploymentId);
387 return attrs;
388 }),
389 delete: Effect.fn(function* ({ output }) {
390 yield* cancelAndDelete(output.deploymentId);
391 }),
392 });
393 }),
394 );