@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 225 lines 7.76 KB
Raw
1 import * as location from "@distilled.cloud/aws/location";
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, type Tags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as EffectStream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import { toTagRecord } from "./internal.ts";
13
14 export class PlaceIndexUnexpectedResponse extends Data.TaggedError("PlaceIndexUnexpectedResponse")<{
15 readonly message: string;
16 readonly cause?: unknown;
17 }> {}
18
19 export interface PlaceIndexProps {
20 /**
21 * Name of the place index. Immutable — changing it replaces the index.
22 * @default ${app}-${stage}-${id}
23 */
24 indexName?: string;
25 /**
26 * Data provider for geocoding/search. Immutable — changing it replaces the
27 * index. One of `Esri`, `Grab`, or `Here`.
28 */
29 dataSource: string;
30 /**
31 * How results of the operations that use this index will be stored.
32 * `SingleUse` results can't be stored; `Storage` results can be cached.
33 * @default "SingleUse"
34 */
35 intendedUse?: string;
36 /**
37 * Optional description of the place index resource.
38 */
39 description?: string;
40 /**
41 * Tags to associate with the place index.
42 */
43 tags?: Record<string, string>;
44 }
45
46 export interface PlaceIndex extends Resource<
47 "AWS.Location.PlaceIndex",
48 PlaceIndexProps,
49 {
50 /** Physical name of the place index. */
51 indexName: string;
52 /** ARN of the place index. */
53 indexArn: string;
54 /** Data provider backing the index. */
55 dataSource: string;
56 /** Intended use of the index results. */
57 intendedUse: string | undefined;
58 /** Description of the place index. */
59 description: string | undefined;
60 /** Tags currently associated with the index. */
61 tags: Record<string, string>;
62 },
63 never,
64 Providers
65 > {}
66
67 /**
68 * An Amazon Location Service place index. A place index geocodes text and
69 * positions against a chosen data provider. The data source is immutable;
70 * the intended use and description can be updated in place.
71 *
72 * ### Creating Place Indexes
73 * **Example:** Basic Place Index
74 * ```typescript
75 * import * as Location from "@alchemy.run/aws/Location";
76 *
77 * const index = yield* Location.PlaceIndex("Places", {
78 * dataSource: "Esri",
79 * });
80 * ```
81 *
82 * **Example:** Storage-Intent Place Index
83 * ```typescript
84 * const index = yield* Location.PlaceIndex("Geocoder", {
85 * dataSource: "Here",
86 * intendedUse: "Storage",
87 * description: "Cacheable geocoding index",
88 * });
89 * ```
90 *
91 * @resource
92 */
93 export const PlaceIndex = Resource<PlaceIndex>("AWS.Location.PlaceIndex");
94
95 const createIndexName = (id: string, props: { indexName?: string | undefined }) =>
96 Effect.gen(function* () {
97 if (props.indexName) return props.indexName;
98 return yield* createPhysicalName({ id, maxLength: 100 });
99 });
100
101 const readIndex = Effect.fn(function* (indexName: string) {
102 const found = yield* location
103 .describePlaceIndex({ IndexName: indexName })
104 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
105 if (!found) return undefined;
106 return {
107 indexName: found.IndexName,
108 indexArn: found.IndexArn,
109 dataSource: found.DataSource,
110 intendedUse: found.DataSourceConfiguration?.IntendedUse,
111 description: found.Description ? found.Description : undefined,
112 tags: toTagRecord(found.Tags),
113 } satisfies PlaceIndex["Attributes"];
114 });
115
116 export const PlaceIndexProvider = () =>
117 Provider.effect(
118 PlaceIndex,
119 Effect.gen(function* () {
120 return {
121 stables: ["indexName", "indexArn"],
122 list: () =>
123 Effect.gen(function* () {
124 const names = yield* location.listPlaceIndexes.pages({}).pipe(
125 EffectStream.runCollect,
126 Effect.map((chunk) =>
127 Array.from(chunk).flatMap((page) =>
128 (page.Entries ?? []).map((entry) => entry.IndexName),
129 ),
130 ),
131 );
132 const hydrated = yield* Effect.forEach(names, (name) => readIndex(name), {
133 concurrency: 10,
134 });
135 return hydrated.filter(
136 (attrs): attrs is PlaceIndex["Attributes"] => attrs !== undefined,
137 );
138 }),
139 read: Effect.fn(function* ({ id, olds, output }) {
140 const indexName = output?.indexName ?? (yield* createIndexName(id, olds ?? {}));
141 const state = yield* readIndex(indexName);
142 if (!state) return undefined;
143 return (yield* hasAlchemyTags(id, state.tags as Tags)) ? state : Unowned(state);
144 }),
145 diff: Effect.fn(function* ({ id, news, olds }) {
146 if (!isResolved(news)) return;
147 const oldName = yield* createIndexName(id, olds);
148 const newName = yield* createIndexName(id, news);
149 // Name and data source are immutable — either change forces a replace.
150 if (oldName !== newName || olds.dataSource !== news.dataSource) {
151 return { action: "replace" } as const;
152 }
153 }),
154 reconcile: Effect.fn(function* ({ id, news, output, session }) {
155 const indexName = output?.indexName ?? (yield* createIndexName(id, news));
156 const internalTags = yield* createInternalTags(id);
157 const desiredTags = { ...internalTags, ...news.tags };
158
159 let state = yield* readIndex(indexName);
160
161 if (state === undefined) {
162 yield* location
163 .createPlaceIndex({
164 IndexName: indexName,
165 DataSource: news.dataSource,
166 Description: news.description,
167 DataSourceConfiguration: news.intendedUse
168 ? { IntendedUse: news.intendedUse }
169 : undefined,
170 Tags: desiredTags,
171 })
172 .pipe(Effect.catchTag("ConflictException", () => Effect.void));
173 state = yield* readIndex(indexName);
174 if (state === undefined) {
175 return yield* new PlaceIndexUnexpectedResponse({
176 message: `failed to read created place index ${indexName}`,
177 });
178 }
179 }
180
181 if (
182 state.description !== (news.description ?? undefined) ||
183 (news.intendedUse !== undefined && state.intendedUse !== news.intendedUse)
184 ) {
185 yield* location.updatePlaceIndex({
186 IndexName: indexName,
187 Description: news.description,
188 DataSourceConfiguration: news.intendedUse
189 ? { IntendedUse: news.intendedUse }
190 : undefined,
191 });
192 }
193
194 const { removed, upsert } = diffTags(state.tags, desiredTags);
195 if (removed.length > 0) {
196 yield* location.untagResource({
197 ResourceArn: state.indexArn,
198 TagKeys: removed,
199 });
200 }
201 if (upsert.length > 0) {
202 yield* location.tagResource({
203 ResourceArn: state.indexArn,
204 Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
205 });
206 }
207
208 yield* session.note(state.indexArn);
209
210 const final = yield* readIndex(indexName);
211 if (!final) {
212 return yield* new PlaceIndexUnexpectedResponse({
213 message: `failed to read reconciled place index ${indexName}`,
214 });
215 }
216 return final;
217 }),
218 delete: Effect.fn(function* ({ output }) {
219 yield* location
220 .deletePlaceIndex({ IndexName: output.indexName })
221 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
222 }),
223 };
224 }),
225 );