@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, 04:45 UTC

main
ts 226 lines 7.94 KB
Raw
1 import * as sfn from "@distilled.cloud/aws/sfn";
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 Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import { AWSEnvironment } from "../Environment.ts";
11 import type { Providers } from "../Providers.ts";
12
13 export interface ActivityProps {
14 /**
15 * Name of the activity (1-80 characters; letters, digits, dashes and
16 * underscores). If omitted, a deterministic physical name is generated
17 * from the app, stage, and logical ID. Changing the name triggers a
18 * replacement.
19 */
20 activityName?: string;
21 /**
22 * Tags to apply to the activity. Merged with internal Alchemy tags.
23 */
24 tags?: Record<string, string>;
25 }
26
27 export interface Activity extends Resource<
28 "AWS.StepFunctions.Activity",
29 ActivityProps,
30 {
31 /**
32 * Physical name of the activity.
33 */
34 activityName: string;
35 /**
36 * ARN of the activity — reference it from a state machine Task state's
37 * `Resource` field.
38 */
39 activityArn: string;
40 },
41 never,
42 Providers
43 > {}
44
45 /**
46 * An AWS Step Functions activity — a named endpoint that external workers
47 * poll for tasks (`GetActivityTask`) and complete with the `SendTask*`
48 * callback operations.
49 *
50 * Activities support worker-hosted task processing outside Lambda. For
51 * most callback flows the `.waitForTaskToken` service-integration pattern
52 * on a {@link StateMachine} Task state is preferred.
53 * ### Creating Activities
54 * **Example:** Basic Activity
55 * ```typescript
56 * import * as StepFunctions from "@alchemy.run/aws/StepFunctions";
57 *
58 * const activity = yield* StepFunctions.Activity("ApprovalActivity");
59 * ```
60 *
61 * **Example:** Reference an Activity from a State Machine
62 * ```typescript
63 * const machine = yield* StepFunctions.StateMachine("ApprovalFlow", {
64 * definition: {
65 * StartAt: "WaitForWorker",
66 * States: {
67 * WaitForWorker: {
68 * Type: "Task",
69 * Resource: activity.activityArn,
70 * End: true,
71 * },
72 * },
73 * },
74 * });
75 * ```
76 *
77 * ### Completing Tasks at Runtime
78 * **Example:** Send a task result scoped to the activity
79 * ```typescript
80 * // init
81 * const sendTaskSuccess = yield* StepFunctions.SendTaskSuccess(activity);
82 *
83 * // runtime
84 * yield* sendTaskSuccess({
85 * taskToken: token,
86 * output: JSON.stringify({ approved: true }),
87 * });
88 * ```
89 *
90 * @resource
91 */
92 export const Activity = Resource<Activity>("AWS.StepFunctions.Activity");
93
94 const toSfnTags = (tags: Record<string, string>): sfn.Tag[] =>
95 Object.entries(tags).map(([key, value]) => ({ key, value }));
96
97 const fromSfnTags = (tags: ReadonlyArray<sfn.Tag> | undefined): Record<string, string> =>
98 Object.fromEntries(
99 (tags ?? [])
100 .filter(
101 (tag): tag is { key: string; value: string } =>
102 typeof tag.key === "string" && typeof tag.value === "string",
103 )
104 .map((tag) => [tag.key, tag.value]),
105 );
106
107 export const ActivityProvider = () =>
108 Provider.effect(
109 Activity,
110 Effect.gen(function* () {
111 const createName = Effect.fn(function* (
112 id: string,
113 props: Pick<ActivityProps, "activityName">,
114 ) {
115 return props.activityName ?? (yield* createPhysicalName({ id, maxLength: 80 }));
116 });
117
118 const activityArnOf = (region: string, accountId: string, name: string) =>
119 `arn:aws:states:${region}:${accountId}:activity:${name}`;
120
121 const describeOrUndefined = Effect.fn(function* (activityArn: string) {
122 return yield* sfn
123 .describeActivity({ activityArn })
124 .pipe(Effect.catchTag("ActivityDoesNotExist", () => Effect.undefined));
125 });
126
127 const fetchObservedTags = Effect.fn(function* (resourceArn: string) {
128 return yield* sfn.listTagsForResource({ resourceArn }).pipe(
129 Effect.map((r) => fromSfnTags(r.tags)),
130 Effect.catchTag("ResourceNotFound", () => Effect.succeed({} as Record<string, string>)),
131 );
132 });
133
134 return Activity.Provider.of({
135 stables: ["activityName", "activityArn"],
136
137 list: () =>
138 Effect.gen(function* () {
139 const pages = yield* sfn.listActivities.pages({}).pipe(Stream.runCollect);
140 return Array.from(pages)
141 .flatMap((page) => page.activities ?? [])
142 .map((activity) => ({
143 activityName: activity.name,
144 activityArn: activity.activityArn,
145 }));
146 }),
147
148 read: Effect.fn(function* ({ id, olds, output }) {
149 const { accountId, region } = yield* AWSEnvironment.current;
150 const name = output?.activityName ?? (yield* createName(id, olds ?? {}));
151 const activityArn = output?.activityArn ?? activityArnOf(region, accountId, name);
152 const found = yield* describeOrUndefined(activityArn);
153 if (!found) return undefined;
154 const attrs = {
155 activityName: found.name,
156 activityArn: found.activityArn,
157 };
158 const tags = yield* fetchObservedTags(activityArn);
159 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
160 }),
161
162 diff: Effect.fn(function* ({ id, news, olds }) {
163 if (!isResolved(news)) return undefined;
164 const oldName = yield* createName(id, olds ?? {});
165 const newName = yield* createName(id, news ?? {});
166 if (oldName !== newName) {
167 return { action: "replace" } as const;
168 }
169 // tags converge via update
170 }),
171
172 reconcile: Effect.fn(function* ({ id, news, output, session }) {
173 const { accountId, region } = yield* AWSEnvironment.current;
174 // `news` is undefined when the resource is declared without a
175 // props argument (`Activity("id")`).
176 const props = news ?? {};
177 const name = output?.activityName ?? (yield* createName(id, props));
178 const activityArn = activityArnOf(region, accountId, name);
179 const internalTags = yield* createInternalTags(id);
180 const desiredTags = { ...props.tags, ...internalTags };
181
182 // 1. OBSERVE — cloud state is authoritative.
183 const observed = yield* describeOrUndefined(activityArn);
184
185 // 2. ENSURE — createActivity is idempotent for an identical
186 // configuration; ActivityAlreadyExists only fires when the
187 // existing activity differs (encryption config), in which case
188 // we keep the existing one (the ARN is deterministic).
189 if (observed === undefined) {
190 yield* sfn
191 .createActivity({ name, tags: toSfnTags(desiredTags) })
192 .pipe(Effect.catchTag("ActivityAlreadyExists", () => Effect.void));
193 }
194
195 // 3. SYNC TAGS — against OBSERVED cloud tags (create-time tags
196 // only apply on first create; adoption may carry foreign tags).
197 const observedTags = yield* fetchObservedTags(activityArn);
198 const { upsert, removed } = diffTags(observedTags, desiredTags);
199 if (upsert.length > 0) {
200 yield* sfn.tagResource({
201 resourceArn: activityArn,
202 tags: upsert.map(({ Key, Value }) => ({
203 key: Key,
204 value: Value,
205 })),
206 });
207 }
208 if (removed.length > 0) {
209 yield* sfn.untagResource({
210 resourceArn: activityArn,
211 tagKeys: removed,
212 });
213 }
214
215 yield* session.note(activityArn);
216 return { activityName: name, activityArn };
217 }),
218
219 delete: Effect.fn(function* ({ output }) {
220 // deleteActivity is idempotent — deleting a non-existent activity
221 // succeeds.
222 yield* sfn.deleteActivity({ activityArn: output.activityArn });
223 }),
224 });
225 }),
226 );