@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, 07:15 UTC

main
ts 210 lines 7.85 KB
Raw
1 import * as IoTSiteWise from "@alchemy.run/aws/IoTSiteWise";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as Cause from "effect/Cause";
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 path from "pathe";
10
11 const main = path.resolve(import.meta.dirname, "handler.ts");
12
13 export class IoTSiteWiseTestFunction extends Lambda.Function<Lambda.Function>()(
14 "IoTSiteWiseTestFunction",
15 ) {}
16
17 export default IoTSiteWiseTestFunction.make(
18 {
19 main,
20 functionUrl: true,
21 timeout: Duration.seconds(30),
22 },
23 Effect.gen(function* () {
24 const model = yield* IoTSiteWise.AssetModel("BindingsPumpModel", {
25 assetModelDescription: "alchemy iotsitewise bindings fixture",
26 assetModelProperties: [
27 {
28 name: "Temperature",
29 dataType: "DOUBLE",
30 unit: "Celsius",
31 type: { measurement: {} },
32 },
33 ],
34 tags: { fixture: "iotsitewise-bindings" },
35 });
36 const asset = yield* IoTSiteWise.Asset("BindingsPump", {
37 assetModelId: model.assetModelId,
38 assetDescription: "alchemy iotsitewise bindings fixture asset",
39 tags: { fixture: "iotsitewise-bindings" },
40 });
41
42 const describeAsset = yield* IoTSiteWise.DescribeAsset(asset);
43 const listProperties = yield* IoTSiteWise.ListAssetProperties(asset);
44 const putValues = yield* IoTSiteWise.BatchPutAssetPropertyValue(asset);
45 const getValue = yield* IoTSiteWise.GetAssetPropertyValue(asset);
46 const getHistory = yield* IoTSiteWise.GetAssetPropertyValueHistory(asset);
47 const getAggregates = yield* IoTSiteWise.GetAssetPropertyAggregates(asset);
48 const getInterpolated = yield* IoTSiteWise.GetInterpolatedAssetPropertyValues(asset);
49 const executeQuery = yield* IoTSiteWise.ExecuteQuery();
50
51 // Resolve the service-assigned id of the Temperature property by name —
52 // exercises the DescribeAsset binding on every data-plane route.
53 const temperaturePropertyId = Effect.gen(function* () {
54 const described = yield* describeAsset();
55 const property = described.assetProperties.find((p) => p.name === "Temperature");
56 if (!property) {
57 return yield* Effect.fail(new Error("Temperature property not found on the bound asset"));
58 }
59 return property.id;
60 });
61
62 return {
63 fetch: Effect.gen(function* () {
64 const request = yield* HttpServerRequest;
65 const pathname = new URL(request.originalUrl).pathname;
66
67 // Cheap readiness route — no AWS call.
68 if (request.method === "GET" && pathname === "/ping") {
69 return yield* HttpServerResponse.json({ ok: true });
70 }
71
72 if (request.method === "POST" && pathname === "/describe") {
73 const described = yield* describeAsset();
74 return yield* HttpServerResponse.json({
75 assetId: described.assetId,
76 assetName: described.assetName,
77 propertyNames: described.assetProperties.map((p) => p.name),
78 });
79 }
80
81 if (request.method === "POST" && pathname === "/properties") {
82 const listed = yield* listProperties({ filter: "ALL" });
83 return yield* HttpServerResponse.json({
84 count: listed.assetPropertySummaries.length,
85 });
86 }
87
88 if (request.method === "POST" && pathname === "/put") {
89 const propertyId = yield* temperaturePropertyId;
90 // Fresh timestamp per call so retried requests never collide with
91 // an already-ingested TQV.
92 const now = yield* Effect.sync(() => Math.floor(Date.now() / 1000));
93 const result = yield* putValues({
94 entries: [
95 {
96 entryId: `temp-${now}`,
97 propertyId,
98 propertyValues: [
99 {
100 value: { doubleValue: 23.5 },
101 timestamp: { timeInSeconds: now },
102 quality: "GOOD",
103 },
104 ],
105 },
106 ],
107 });
108 return yield* HttpServerResponse.json({
109 errorCount: result.errorEntries.length,
110 errorCodes: result.errorEntries.flatMap((entry) =>
111 entry.errors.map((error) => error.errorCode),
112 ),
113 });
114 }
115
116 if (request.method === "POST" && pathname === "/value") {
117 const propertyId = yield* temperaturePropertyId;
118 const result = yield* getValue({ propertyId });
119 return yield* HttpServerResponse.json({
120 doubleValue: result.propertyValue?.value.doubleValue ?? null,
121 timeInSeconds: result.propertyValue?.timestamp.timeInSeconds ?? null,
122 });
123 }
124
125 if (request.method === "POST" && pathname === "/history") {
126 const propertyId = yield* temperaturePropertyId;
127 const now = yield* Effect.sync(() => Date.now());
128 const result = yield* getHistory({
129 propertyId,
130 startDate: new Date(now - 600_000),
131 endDate: new Date(now),
132 timeOrdering: "DESCENDING",
133 });
134 return yield* HttpServerResponse.json({
135 count: result.assetPropertyValueHistory.length,
136 });
137 }
138
139 if (request.method === "POST" && pathname === "/aggregates") {
140 const propertyId = yield* temperaturePropertyId;
141 const now = yield* Effect.sync(() => Date.now());
142 const result = yield* getAggregates({
143 propertyId,
144 aggregateTypes: ["AVERAGE"],
145 resolution: "1m",
146 startDate: new Date(now - 3_600_000),
147 endDate: new Date(now),
148 });
149 return yield* HttpServerResponse.json({
150 ok: true,
151 count: result.aggregatedValues.length,
152 });
153 }
154
155 if (request.method === "POST" && pathname === "/interpolated") {
156 const propertyId = yield* temperaturePropertyId;
157 const now = yield* Effect.sync(() => Math.floor(Date.now() / 1000));
158 const result = yield* getInterpolated({
159 propertyId,
160 startTimeInSeconds: now - 3600,
161 endTimeInSeconds: now,
162 intervalInSeconds: 60,
163 quality: "GOOD",
164 type: "LINEAR_INTERPOLATION",
165 });
166 return yield* HttpServerResponse.json({
167 ok: true,
168 count: result.interpolatedAssetPropertyValues.length,
169 });
170 }
171
172 if (request.method === "POST" && pathname === "/query") {
173 const described = yield* describeAsset();
174 const result = yield* executeQuery({
175 queryStatement: `SELECT asset_id, asset_name FROM asset WHERE asset_id = '${described.assetId}'`,
176 });
177 return yield* HttpServerResponse.json({
178 ok: true,
179 rowCount: result.rows?.length ?? 0,
180 });
181 }
182
183 return yield* HttpServerResponse.json(
184 { error: "Not found", method: request.method, pathname },
185 { status: 404 },
186 );
187 }).pipe(
188 // Surface the failure cause in the 500 body so the test's retry
189 // error carries the real diagnostic instead of an opaque
190 // "Internal Server Error".
191 Effect.catchCause((cause) =>
192 HttpServerResponse.json({ error: Cause.pretty(cause) }, { status: 500 }),
193 ),
194 ),
195 };
196 }).pipe(
197 Effect.provide(
198 Layer.mergeAll(
199 IoTSiteWise.DescribeAssetHttp,
200 IoTSiteWise.ListAssetPropertiesHttp,
201 IoTSiteWise.BatchPutAssetPropertyValueHttp,
202 IoTSiteWise.GetAssetPropertyValueHttp,
203 IoTSiteWise.GetAssetPropertyValueHistoryHttp,
204 IoTSiteWise.GetAssetPropertyAggregatesHttp,
205 IoTSiteWise.GetInterpolatedAssetPropertyValuesHttp,
206 IoTSiteWise.ExecuteQueryHttp,
207 ),
208 ),
209 ),
210 );