@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 259 lines 9.52 KB
Raw
1 import * as personalize from "@distilled.cloud/aws/personalize";
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, 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 type { Providers } from "../Providers.ts";
13 import { readPersonalizeTags, syncPersonalizeTags } from "./internal.ts";
14
15 export class EventTrackerNotReady extends Data.TaggedError("EventTrackerNotReady")<{
16 readonly message: string;
17 readonly cause?: unknown;
18 }> {}
19
20 export interface EventTrackerProps {
21 /**
22 * Name of the event tracker. If omitted, a unique name is generated from
23 * the app, stage, and logical ID. Changing the name replaces the tracker.
24 */
25 name?: string;
26 /**
27 * ARN of the dataset group the event tracker records events for. The
28 * dataset group should contain an Interactions dataset (events are recorded
29 * into it). Only one event tracker can exist per dataset group. Immutable —
30 * changing it replaces the tracker.
31 */
32 datasetGroupArn: string;
33 /**
34 * User-defined tags for the event tracker.
35 */
36 tags?: Record<string, string>;
37 }
38
39 export interface EventTracker extends Resource<
40 "AWS.Personalize.EventTracker",
41 EventTrackerProps,
42 {
43 /**
44 * ARN of the event tracker.
45 */
46 eventTrackerArn: string;
47 /**
48 * The tracking ID passed as `trackingId` to the PutEvents /
49 * PutActionInteractions data-plane operations.
50 */
51 trackingId: string;
52 /**
53 * Name of the event tracker.
54 */
55 name: string;
56 /**
57 * Event tracker status (e.g. `ACTIVE`, `CREATE PENDING`).
58 */
59 status: string;
60 /**
61 * ARN of the dataset group the tracker records events for.
62 */
63 datasetGroupArn: string;
64 },
65 never,
66 Providers
67 > {}
68
69 /**
70 * An Amazon Personalize event tracker — the ingestion endpoint for streaming
71 * interaction events into a dataset group's Interactions dataset. Creating a
72 * tracker yields a `trackingId` that the {@link PutEvents} data-plane binding
73 * uses to record events in real time.
74 *
75 * ### Creating an Event Tracker
76 * **Example:** Track Events for a Dataset Group
77 * ```typescript
78 * const tracker = yield* Personalize.EventTracker("Tracker", {
79 * datasetGroupArn: group.datasetGroupArn,
80 * });
81 * ```
82 *
83 * ### Streaming Events
84 * **Example:** Record Click Events from a Lambda
85 * ```typescript
86 * // init
87 * const putEvents = yield* Personalize.PutEvents(tracker);
88 *
89 * // runtime
90 * yield* putEvents({
91 * sessionId: "session-1",
92 * userId: "user-1",
93 * eventList: [{ eventType: "click", itemId: "item-42", sentAt: new Date() }],
94 * });
95 * ```
96 *
97 * @resource
98 */
99 export const EventTracker = Resource<EventTracker>("AWS.Personalize.EventTracker");
100
101 export const EventTrackerProvider = () =>
102 Provider.effect(
103 EventTracker,
104 Effect.gen(function* () {
105 const createName = Effect.fn(function* (id: string, props: EventTrackerProps) {
106 return props.name ?? (yield* createPhysicalName({ id, maxLength: 63 }));
107 });
108
109 const describe = Effect.fn(function* (eventTrackerArn: string) {
110 const response = yield* personalize
111 .describeEventTracker({ eventTrackerArn })
112 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
113 return response?.eventTracker;
114 });
115
116 /** Poll until the tracker reaches ACTIVE; fail fast on CREATE FAILED. */
117 const waitActive = Effect.fn(function* (eventTrackerArn: string) {
118 const tracker = yield* describe(eventTrackerArn).pipe(
119 Effect.repeat({
120 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(40)]),
121 until: (t) => t?.status === "ACTIVE" || (t?.status ?? "").includes("FAILED"),
122 }),
123 );
124 if (tracker?.status !== "ACTIVE") {
125 return yield* new EventTrackerNotReady({
126 message: `Personalize event tracker ${eventTrackerArn} did not become ACTIVE (status: ${tracker?.status})`,
127 });
128 }
129 return tracker;
130 });
131
132 /** Find an existing tracker's ARN by name within its dataset group. */
133 const findArnByName = Effect.fn(function* (name: string, datasetGroupArn: string) {
134 const pages = yield* personalize.listEventTrackers
135 .pages({ datasetGroupArn })
136 .pipe(Stream.runCollect);
137 return Array.from(pages)
138 .flatMap((page) => page.eventTrackers ?? [])
139 .find((summary) => summary.name === name)?.eventTrackerArn;
140 });
141
142 const toAttrs = (tracker: personalize.EventTracker) => ({
143 eventTrackerArn: tracker.eventTrackerArn!,
144 trackingId: tracker.trackingId!,
145 name: tracker.name!,
146 status: tracker.status!,
147 datasetGroupArn: tracker.datasetGroupArn!,
148 });
149
150 return {
151 stables: ["eventTrackerArn", "trackingId", "name"],
152
153 diff: Effect.fn(function* ({ id, olds, news }) {
154 if (!isResolved(news)) return undefined;
155 const oldName = yield* createName(id, olds);
156 const newName = yield* createName(id, news);
157 if (
158 oldName !== newName ||
159 (olds.datasetGroupArn ?? undefined) !== (news.datasetGroupArn ?? undefined)
160 ) {
161 return { action: "replace" } as const;
162 }
163 }),
164
165 read: Effect.fn(function* ({ id, output }) {
166 if (!output?.eventTrackerArn) return undefined;
167 const tracker = yield* describe(output.eventTrackerArn);
168 if (tracker === undefined) return undefined;
169 const attrs = toAttrs(tracker);
170 const tags = yield* readPersonalizeTags(tracker.eventTrackerArn!);
171 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
172 }),
173
174 reconcile: Effect.fn(function* ({ id, news, output, session }) {
175 const name = yield* createName(id, news);
176 const internalTags = yield* createInternalTags(id);
177 const desiredTags = { ...internalTags, ...news.tags };
178
179 // 1. Observe — cloud state is authoritative; output is an ARN cache.
180 let tracker =
181 output?.eventTrackerArn !== undefined
182 ? yield* describe(output.eventTrackerArn)
183 : undefined;
184
185 // 2. Ensure — create if missing, then wait for ACTIVE. A crashed
186 // prior run may have left a same-named tracker behind with no
187 // persisted state — adopt it by name and converge.
188 if (tracker === undefined) {
189 const arn = yield* personalize
190 .createEventTracker({
191 name,
192 datasetGroupArn: news.datasetGroupArn,
193 tags: Object.entries(desiredTags).map(([tagKey, tagValue]) => ({
194 tagKey,
195 tagValue,
196 })),
197 })
198 .pipe(
199 Effect.map((created) => created.eventTrackerArn!),
200 Effect.catchTag("ResourceAlreadyExistsException", (error) =>
201 findArnByName(name, news.datasetGroupArn).pipe(
202 Effect.flatMap((existing) =>
203 existing === undefined ? Effect.fail(error) : Effect.succeed(existing),
204 ),
205 ),
206 ),
207 );
208 tracker = yield* waitActive(arn);
209 }
210
211 // 3. Sync tags — diff against OBSERVED cloud tags (no-op after a
212 // fresh create; converges an adopted leftover).
213 yield* syncPersonalizeTags(tracker.eventTrackerArn!, desiredTags);
214
215 yield* session.note(tracker.eventTrackerArn!);
216 return toAttrs(tracker);
217 }),
218
219 delete: Effect.fn(function* ({ output }) {
220 yield* personalize.deleteEventTracker({ eventTrackerArn: output.eventTrackerArn }).pipe(
221 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
222 Effect.retry({
223 while: (e) => e._tag === "ResourceInUseException",
224 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(20)]),
225 }),
226 );
227 // Deletion is asynchronous — wait until the tracker is actually gone
228 // so its dataset group can delete without ResourceInUse churn.
229 const remaining = yield* describe(output.eventTrackerArn).pipe(
230 Effect.repeat({
231 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(40)]),
232 until: (tracker): boolean => tracker === undefined,
233 }),
234 );
235 if (remaining !== undefined) {
236 return yield* new EventTrackerNotReady({
237 message: `Personalize event tracker ${output.eventTrackerArn} was not deleted (status: ${remaining.status})`,
238 });
239 }
240 }),
241
242 list: () =>
243 personalize.listEventTrackers.pages({}).pipe(
244 Stream.runCollect,
245 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.eventTrackers ?? [])),
246 Effect.flatMap(
247 Effect.forEach(
248 (summary) =>
249 describe(summary.eventTrackerArn!).pipe(
250 Effect.map((t) => (t ? toAttrs(t) : undefined)),
251 ),
252 { concurrency: 4 },
253 ),
254 ),
255 Effect.map((items) => items.filter((item) => item !== undefined)),
256 ),
257 };
258 }),
259 );