@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 490 lines 17.5 KB
Raw
1 import * as IAM from "@alchemy.run/aws/IAM";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as Location from "@alchemy.run/aws/Location";
4 import * as Duration from "effect/Duration";
5 import * as Effect from "effect/Effect";
6 import { HttpServerRequest } from "effect/http/HttpServerRequest";
7 import * as HttpServerResponse from "effect/http/HttpServerResponse";
8 import * as Layer from "effect/Layer";
9 import * as Result from "effect/Result";
10 import * as Stream from "effect/Stream";
11 import path from "pathe";
12
13 const main = path.resolve(import.meta.dirname, "handler.ts");
14
15 export class LocationTestFunction extends Lambda.Function<Lambda.Function>()(
16 "LocationTestFunction",
17 ) {}
18
19 // Downtown Seattle — near the Space Needle. [longitude, latitude]
20 const SEATTLE: [number, number] = [-122.3493, 47.6205];
21 const PIKE_PLACE: [number, number] = [-122.3421, 47.6091];
22
23 // A syntactically valid but nonexistent job id — the /jobs/get-missing and
24 // /jobs/cancel-missing probe routes assert the typed ResourceNotFoundException.
25 const MISSING_JOB_ID = "00000000-0000-4000-8000-000000000000";
26
27 export default LocationTestFunction.make(
28 {
29 main,
30 functionUrl: true,
31 // Place-index and route-calculator calls fan out to upstream data
32 // providers and can exceed Lambda's 3s default.
33 timeout: Duration.seconds(30),
34 },
35 Effect.gen(function* () {
36 const tracker = yield* Location.Tracker("BindingsTracker", {});
37 const collection = yield* Location.GeofenceCollection("BindingsCollection", {});
38 // HERE (not Esri): SearchPlaceIndexForText only returns PlaceId — needed
39 // by the /places/get-place route — for HERE and Grab data providers.
40 const index = yield* Location.PlaceIndex("BindingsIndex", {
41 dataSource: "Here",
42 });
43 const calculator = yield* Location.RouteCalculator("BindingsCalculator", {
44 dataSource: "Esri",
45 });
46 const map = yield* Location.Map("BindingsMap", {
47 configuration: { style: "VectorEsriNavigation" },
48 });
49
50 // A role for the StartJob binding — only used to exercise the binding's
51 // deploy-time wiring (geo:StartJob + iam:PassRole grants); no job is ever
52 // started, so the trust policy just needs a principal IAM accepts
53 // ("location.amazonaws.com" is not a recognized service principal).
54 const jobsRole = yield* IAM.Role("LocationJobsRole", {
55 assumeRolePolicyDocument: {
56 Version: "2012-10-17",
57 Statement: [
58 {
59 Effect: "Allow",
60 Principal: { Service: "lambda.amazonaws.com" },
61 Action: ["sts:AssumeRole"],
62 },
63 ],
64 },
65 });
66
67 // Event source: subscribe the host to Location geofence events. The
68 // deploy proves the EventBridge rule + invoke permission wiring.
69 yield* Location.consumeTrackerEvents(
70 { kinds: ["geofence-event", "device-position-event"] },
71 (events) =>
72 Stream.runForEach(events, (event) =>
73 Effect.log(`location event: ${event.detail.DeviceId} ${event.detail.EventType}`),
74 ),
75 );
76
77 // Tracker data plane
78 const updatePositions = yield* Location.BatchUpdateDevicePosition(tracker);
79 const getPosition = yield* Location.GetDevicePosition(tracker);
80 const getHistory = yield* Location.GetDevicePositionHistory(tracker);
81 const listPositions = yield* Location.ListDevicePositions(tracker);
82 const batchGetPositions = yield* Location.BatchGetDevicePosition(tracker);
83 const verifyPosition = yield* Location.VerifyDevicePosition(tracker);
84 const deleteHistory = yield* Location.BatchDeleteDevicePositionHistory(tracker);
85
86 // Geofence data plane
87 const putGeofence = yield* Location.PutGeofence(collection);
88 const getGeofence = yield* Location.GetGeofence(collection);
89 const listGeofences = yield* Location.ListGeofences(collection);
90 const batchPutGeofence = yield* Location.BatchPutGeofence(collection);
91 const batchDeleteGeofence = yield* Location.BatchDeleteGeofence(collection);
92 const evaluateGeofences = yield* Location.BatchEvaluateGeofences(collection);
93 const forecastEvents = yield* Location.ForecastGeofenceEvents(collection);
94
95 // Places
96 const searchText = yield* Location.SearchPlaceIndexForText(index);
97 const searchPosition = yield* Location.SearchPlaceIndexForPosition(index);
98 const suggest = yield* Location.SearchPlaceIndexForSuggestions(index);
99 const getPlace = yield* Location.GetPlace(index);
100
101 // Routes
102 const calculateRoute = yield* Location.CalculateRoute(calculator);
103 const calculateMatrix = yield* Location.CalculateRouteMatrix(calculator);
104
105 // Map assets
106 const getStyle = yield* Location.GetMapStyleDescriptor(map);
107 const getGlyphs = yield* Location.GetMapGlyphs(map);
108 const getSprites = yield* Location.GetMapSprites(map);
109 const getTile = yield* Location.GetMapTile(map);
110
111 // Batch metadata jobs
112 const listJobs = yield* Location.ListJobs();
113 const getJob = yield* Location.GetJob();
114 const cancelJob = yield* Location.CancelJob();
115 // Bound for its deploy-time wiring (geo:StartJob + iam:PassRole); starting
116 // a real batch job needs S3 input/output data.
117 yield* Location.StartJob(jobsRole);
118
119 return {
120 fetch: Effect.gen(function* () {
121 const request = yield* HttpServerRequest;
122 const pathname = new URL(request.originalUrl).pathname;
123
124 // Cheap readiness route — no AWS call.
125 if (pathname === "/ping") {
126 return yield* HttpServerResponse.json({ ok: true });
127 }
128
129 if (pathname === "/tracker/update") {
130 const result = yield* updatePositions({
131 Updates: [
132 {
133 DeviceId: "device-1",
134 Position: SEATTLE,
135 SampleTime: new Date(),
136 },
137 ],
138 });
139 return yield* HttpServerResponse.json({
140 errors: result.Errors.length,
141 });
142 }
143
144 if (pathname === "/tracker/latest") {
145 const latest = yield* getPosition({ DeviceId: "device-1" });
146 return yield* HttpServerResponse.json({
147 deviceId: latest.DeviceId,
148 position: latest.Position,
149 });
150 }
151
152 if (pathname === "/tracker/batch-get") {
153 const result = yield* batchGetPositions({
154 DeviceIds: ["device-1"],
155 });
156 return yield* HttpServerResponse.json({
157 found: result.DevicePositions.length,
158 errors: result.Errors.length,
159 });
160 }
161
162 if (pathname === "/tracker/history") {
163 const history = yield* getHistory({ DeviceId: "device-1" });
164 return yield* HttpServerResponse.json({
165 count: history.DevicePositions.length,
166 });
167 }
168
169 if (pathname === "/tracker/list") {
170 const page = yield* listPositions();
171 return yield* HttpServerResponse.json({
172 count: page.Entries.length,
173 deviceIds: page.Entries.map((entry) => entry.DeviceId),
174 });
175 }
176
177 if (pathname === "/tracker/verify") {
178 const result = yield* verifyPosition({
179 DeviceState: {
180 DeviceId: "device-1",
181 SampleTime: new Date(),
182 Position: SEATTLE,
183 WiFiAccessPoints: [{ MacAddress: "A0:EC:F9:1E:32:C1", Rss: -66 }],
184 },
185 }).pipe(
186 Effect.map((verdict) => ({
187 inferredState: verdict.InferredState !== undefined,
188 deviceId: verdict.DeviceId,
189 })),
190 // Position verification needs real cell/Wi-Fi signal data; a
191 // typed ValidationException still proves IAM + wiring.
192 Effect.catchTag("ValidationException", (e) =>
193 Effect.succeed({ validationError: e.message }),
194 ),
195 );
196 return yield* HttpServerResponse.json(result);
197 }
198
199 if (pathname === "/tracker/delete-history") {
200 const result = yield* deleteHistory({ DeviceIds: ["device-1"] });
201 return yield* HttpServerResponse.json({
202 errors: result.Errors.length,
203 });
204 }
205
206 if (pathname === "/geofence/put") {
207 const result = yield* putGeofence({
208 GeofenceId: "fence-1",
209 Geometry: { Circle: { Center: SEATTLE, Radius: 200 } },
210 });
211 return yield* HttpServerResponse.json({
212 geofenceId: result.GeofenceId,
213 });
214 }
215
216 if (pathname === "/geofence/get") {
217 const fence = yield* getGeofence({ GeofenceId: "fence-1" });
218 return yield* HttpServerResponse.json({
219 geofenceId: fence.GeofenceId,
220 status: fence.Status,
221 });
222 }
223
224 if (pathname === "/geofence/list") {
225 // Also serves as the test setup's IAM canary — always responds 200
226 // and surfaces the typed failure tag so setup can wait for geo:*
227 // authorization (or diagnose schema gaps) without blind 500s.
228 const page = yield* Effect.result(listGeofences());
229 return yield* HttpServerResponse.json(
230 Result.isSuccess(page)
231 ? { ok: true, count: (page.success.Entries ?? []).length }
232 : {
233 ok: false,
234 tag: page.failure._tag,
235 message: String(page.failure),
236 },
237 );
238 }
239
240 if (pathname === "/geofence/batch-put") {
241 const result = yield* batchPutGeofence({
242 Entries: [
243 {
244 GeofenceId: "fence-2",
245 Geometry: { Circle: { Center: PIKE_PLACE, Radius: 100 } },
246 },
247 ],
248 });
249 return yield* HttpServerResponse.json({
250 successes: result.Successes.length,
251 errors: result.Errors.length,
252 });
253 }
254
255 if (pathname === "/geofence/evaluate") {
256 const result = yield* Effect.result(
257 evaluateGeofences({
258 DevicePositionUpdates: [
259 {
260 DeviceId: "device-1",
261 Position: SEATTLE,
262 SampleTime: new Date(),
263 },
264 ],
265 }),
266 );
267 return yield* HttpServerResponse.json(
268 Result.isSuccess(result)
269 ? // Errors is omitted from the wire response when every update
270 // evaluated cleanly (patched optional in distilled).
271 { ok: true, errors: (result.success.Errors ?? []).length }
272 : {
273 ok: false,
274 tag: result.failure._tag,
275 message: String(result.failure),
276 },
277 );
278 }
279
280 if (pathname === "/geofence/forecast") {
281 const result = yield* forecastEvents({
282 DeviceState: { Position: SEATTLE, Speed: 15 },
283 TimeHorizonMinutes: 30,
284 });
285 return yield* HttpServerResponse.json({
286 forecasted: result.ForecastedEvents.length,
287 distanceUnit: result.DistanceUnit,
288 });
289 }
290
291 if (pathname === "/geofence/batch-delete") {
292 const result = yield* batchDeleteGeofence({
293 GeofenceIds: ["fence-2"],
294 });
295 return yield* HttpServerResponse.json({
296 errors: result.Errors.length,
297 });
298 }
299
300 if (pathname === "/places/search-text") {
301 const result = yield* searchText({
302 Text: "Space Needle, Seattle, WA",
303 BiasPosition: SEATTLE,
304 MaxResults: 3,
305 });
306 return yield* HttpServerResponse.json({
307 count: (result.Results ?? []).length,
308 firstLabel: result.Results?.[0]?.Place?.Label,
309 });
310 }
311
312 if (pathname === "/places/search-position") {
313 const result = yield* searchPosition({
314 Position: SEATTLE,
315 MaxResults: 1,
316 });
317 return yield* HttpServerResponse.json({
318 count: (result.Results ?? []).length,
319 firstLabel: result.Results?.[0]?.Place?.Label,
320 });
321 }
322
323 if (pathname === "/places/suggestions") {
324 const result = yield* suggest({
325 Text: "coffee",
326 BiasPosition: SEATTLE,
327 MaxResults: 5,
328 });
329 return yield* HttpServerResponse.json({
330 count: (result.Results ?? []).length,
331 firstText: result.Results?.[0]?.Text,
332 });
333 }
334
335 if (pathname === "/places/get-place") {
336 // GetPlace needs a PlaceId — resolve one via SearchText first.
337 const searched = yield* searchText({
338 Text: "Space Needle, Seattle, WA",
339 BiasPosition: SEATTLE,
340 MaxResults: 1,
341 });
342 const placeId = searched.Results?.[0]?.PlaceId;
343 if (placeId === undefined) {
344 return yield* HttpServerResponse.json({
345 ok: false,
346 tag: "NoPlaceId",
347 message: "search returned no PlaceId",
348 });
349 }
350 const place = yield* Effect.result(getPlace({ PlaceId: placeId }));
351 return yield* HttpServerResponse.json(
352 Result.isSuccess(place)
353 ? {
354 ok: true,
355 label: place.success.Place?.Label,
356 point: place.success.Place?.Geometry?.Point,
357 }
358 : {
359 ok: false,
360 tag: place.failure._tag,
361 message: String(place.failure),
362 },
363 );
364 }
365
366 if (pathname === "/routes/calculate") {
367 const route = yield* calculateRoute({
368 DeparturePosition: SEATTLE,
369 DestinationPosition: PIKE_PLACE,
370 });
371 return yield* HttpServerResponse.json({
372 distance: route.Summary?.Distance,
373 duration: route.Summary?.DurationSeconds,
374 });
375 }
376
377 if (pathname === "/routes/matrix") {
378 const matrix = yield* calculateMatrix({
379 DeparturePositions: [SEATTLE],
380 DestinationPositions: [PIKE_PLACE],
381 });
382 return yield* HttpServerResponse.json({
383 rows: (matrix.RouteMatrix ?? []).length,
384 distance: matrix.RouteMatrix?.[0]?.[0]?.Distance,
385 });
386 }
387
388 if (pathname === "/map/style") {
389 const style = yield* getStyle();
390 return yield* HttpServerResponse.json({
391 bytes: style.Blob?.length ?? 0,
392 contentType: style.ContentType,
393 });
394 }
395
396 if (pathname === "/map/glyphs") {
397 const glyphs = yield* getGlyphs({
398 FontStack: "Arial Regular",
399 FontUnicodeRange: "0-255.pbf",
400 });
401 return yield* HttpServerResponse.json({
402 bytes: glyphs.Blob?.length ?? 0,
403 });
404 }
405
406 if (pathname === "/map/sprites") {
407 const sprites = yield* getSprites({ FileName: "sprites.json" });
408 return yield* HttpServerResponse.json({
409 bytes: sprites.Blob?.length ?? 0,
410 });
411 }
412
413 if (pathname === "/map/tile") {
414 const tile = yield* getTile({ Z: "0", X: "0", Y: "0" });
415 return yield* HttpServerResponse.json({
416 bytes: tile.Blob?.length ?? 0,
417 contentType: tile.ContentType,
418 });
419 }
420
421 if (pathname === "/jobs/list") {
422 const page = yield* listJobs();
423 return yield* HttpServerResponse.json({
424 count: page.Entries.length,
425 });
426 }
427
428 if (pathname === "/jobs/get-missing") {
429 const result = yield* Effect.result(getJob({ JobId: MISSING_JOB_ID }));
430 return yield* HttpServerResponse.json(
431 Result.isSuccess(result)
432 ? { tag: "found" }
433 : {
434 tag: result.failure._tag,
435 message: String(result.failure),
436 },
437 );
438 }
439
440 if (pathname === "/jobs/cancel-missing") {
441 const result = yield* Effect.result(cancelJob({ JobId: MISSING_JOB_ID }));
442 return yield* HttpServerResponse.json(
443 Result.isSuccess(result)
444 ? { tag: "cancelled" }
445 : {
446 tag: result.failure._tag,
447 message: String(result.failure),
448 },
449 );
450 }
451
452 return yield* HttpServerResponse.json({ error: "Not found", pathname }, { status: 404 });
453 }).pipe(Effect.orDie),
454 };
455 }).pipe(
456 Effect.provide(
457 Layer.mergeAll(
458 Lambda.EventSource,
459 Location.BatchUpdateDevicePositionHttp,
460 Location.GetDevicePositionHttp,
461 Location.GetDevicePositionHistoryHttp,
462 Location.ListDevicePositionsHttp,
463 Location.BatchGetDevicePositionHttp,
464 Location.VerifyDevicePositionHttp,
465 Location.BatchDeleteDevicePositionHistoryHttp,
466 Location.PutGeofenceHttp,
467 Location.GetGeofenceHttp,
468 Location.ListGeofencesHttp,
469 Location.BatchPutGeofenceHttp,
470 Location.BatchDeleteGeofenceHttp,
471 Location.BatchEvaluateGeofencesHttp,
472 Location.ForecastGeofenceEventsHttp,
473 Location.SearchPlaceIndexForTextHttp,
474 Location.SearchPlaceIndexForPositionHttp,
475 Location.SearchPlaceIndexForSuggestionsHttp,
476 Location.GetPlaceHttp,
477 Location.CalculateRouteHttp,
478 Location.CalculateRouteMatrixHttp,
479 Location.GetMapStyleDescriptorHttp,
480 Location.GetMapGlyphsHttp,
481 Location.GetMapSpritesHttp,
482 Location.GetMapTileHttp,
483 Location.ListJobsHttp,
484 Location.GetJobHttp,
485 Location.CancelJobHttp,
486 Location.StartJobHttp,
487 ),
488 ),
489 ),
490 );