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
| 1 | import * as CostExplorer from "@alchemy.run/aws/CostExplorer"; |
| 2 | import * as Lambda from "@alchemy.run/aws/Lambda"; |
| 3 | import * as Duration from "effect/Duration"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import { HttpServerRequest } from "effect/http/HttpServerRequest"; |
| 6 | import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 7 | import * as Layer from "effect/Layer"; |
| 8 | import * as Stream from "effect/Stream"; |
| 9 | import path from "pathe"; |
| 10 | |
| 11 | const main = path.resolve(import.meta.dirname, "handler.ts"); |
| 12 | |
| 13 | // A well-formed-but-nonexistent anomaly id — drives the typed error path for |
| 14 | // ProvideAnomalyFeedback (proving the monitor-scoped grant reaches the API). |
| 15 | const NONEXISTENT_ANOMALY_ID = "00000000-0000-0000-0000-000000000000"; |
| 16 | |
| 17 | /** |
| 18 | * First day of the month `offset` months from now (UTC), as `yyyy-MM-dd`. |
| 19 | * Cost Explorer time periods are half-open `[Start, End)` date intervals. |
| 20 | */ |
| 21 | const monthStart = (offset: number) => |
| 22 | Effect.sync(() => { |
| 23 | const now = new Date(); |
| 24 | return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + offset, 1)) |
| 25 | .toISOString() |
| 26 | .slice(0, 10); |
| 27 | }); |
| 28 | |
| 29 | export class CostExplorerTestFunction extends Lambda.Function<Lambda.Function>()( |
| 30 | "CostExplorerTestFunction", |
| 31 | ) {} |
| 32 | |
| 33 | export default CostExplorerTestFunction.make( |
| 34 | { |
| 35 | main, |
| 36 | functionUrl: true, |
| 37 | // Cost Explorer queries routinely take several seconds; the AWS default |
| 38 | // 3s Lambda timeout is too tight. |
| 39 | timeout: Duration.seconds(30), |
| 40 | }, |
| 41 | Effect.gen(function* () { |
| 42 | // A CUSTOM monitor (the account allows only one DIMENSIONAL/SERVICE |
| 43 | // monitor, which AnomalyMonitor.test.ts may own). |
| 44 | const monitor = yield* CostExplorer.AnomalyMonitor("BindingsMonitor", { |
| 45 | monitorType: "CUSTOM", |
| 46 | monitorSpecification: { |
| 47 | Tags: { Key: "alchemy-ce-bindings", Values: ["fixture"] }, |
| 48 | }, |
| 49 | }); |
| 50 | |
| 51 | const category = yield* CostExplorer.CostCategory("BindingsCategory", { |
| 52 | rules: [ |
| 53 | { |
| 54 | Value: "fixture", |
| 55 | Type: "REGULAR", |
| 56 | Rule: { |
| 57 | Tags: { |
| 58 | Key: "alchemy-ce-bindings", |
| 59 | Values: ["fixture"], |
| 60 | MatchOptions: ["EQUALS"], |
| 61 | }, |
| 62 | }, |
| 63 | }, |
| 64 | ], |
| 65 | defaultValue: "other", |
| 66 | }); |
| 67 | |
| 68 | // --- account-level bindings --- |
| 69 | const getCostAndUsage = yield* CostExplorer.GetCostAndUsage(); |
| 70 | const getCostAndUsageComparisons = yield* CostExplorer.GetCostAndUsageComparisons(); |
| 71 | const getCostAndUsageWithResources = yield* CostExplorer.GetCostAndUsageWithResources(); |
| 72 | const getCostComparisonDrivers = yield* CostExplorer.GetCostComparisonDrivers(); |
| 73 | const getApproximateUsageRecords = yield* CostExplorer.GetApproximateUsageRecords(); |
| 74 | const getCostForecast = yield* CostExplorer.GetCostForecast(); |
| 75 | const getUsageForecast = yield* CostExplorer.GetUsageForecast(); |
| 76 | const getDimensionValues = yield* CostExplorer.GetDimensionValues(); |
| 77 | const getTags = yield* CostExplorer.GetTags(); |
| 78 | const getCostCategories = yield* CostExplorer.GetCostCategories(); |
| 79 | const getReservationCoverage = yield* CostExplorer.GetReservationCoverage(); |
| 80 | const getReservationPurchaseRecommendation = |
| 81 | yield* CostExplorer.GetReservationPurchaseRecommendation(); |
| 82 | const getReservationUtilization = yield* CostExplorer.GetReservationUtilization(); |
| 83 | const getRightsizingRecommendation = yield* CostExplorer.GetRightsizingRecommendation(); |
| 84 | const getSavingsPlansCoverage = yield* CostExplorer.GetSavingsPlansCoverage(); |
| 85 | const getSavingsPlansPurchaseRecommendation = |
| 86 | yield* CostExplorer.GetSavingsPlansPurchaseRecommendation(); |
| 87 | const getSavingsPlanPurchaseRecommendationDetails = |
| 88 | yield* CostExplorer.GetSavingsPlanPurchaseRecommendationDetails(); |
| 89 | const getSavingsPlansUtilization = yield* CostExplorer.GetSavingsPlansUtilization(); |
| 90 | const getSavingsPlansUtilizationDetails = |
| 91 | yield* CostExplorer.GetSavingsPlansUtilizationDetails(); |
| 92 | const startSavingsPlansPurchaseRecommendationGeneration = |
| 93 | yield* CostExplorer.StartSavingsPlansPurchaseRecommendationGeneration(); |
| 94 | const listSavingsPlansPurchaseRecommendationGeneration = |
| 95 | yield* CostExplorer.ListSavingsPlansPurchaseRecommendationGeneration(); |
| 96 | const startCommitmentPurchaseAnalysis = yield* CostExplorer.StartCommitmentPurchaseAnalysis(); |
| 97 | const getCommitmentPurchaseAnalysis = yield* CostExplorer.GetCommitmentPurchaseAnalysis(); |
| 98 | const listCommitmentPurchaseAnalyses = yield* CostExplorer.ListCommitmentPurchaseAnalyses(); |
| 99 | const listCostAllocationTags = yield* CostExplorer.ListCostAllocationTags(); |
| 100 | const updateCostAllocationTagsStatus = yield* CostExplorer.UpdateCostAllocationTagsStatus(); |
| 101 | const startCostAllocationTagBackfill = yield* CostExplorer.StartCostAllocationTagBackfill(); |
| 102 | const listCostAllocationTagBackfillHistory = |
| 103 | yield* CostExplorer.ListCostAllocationTagBackfillHistory(); |
| 104 | const provideAnomalyFeedback = yield* CostExplorer.ProvideAnomalyFeedback(); |
| 105 | |
| 106 | // --- monitor-scoped bindings --- |
| 107 | const getAnomalies = yield* CostExplorer.GetAnomalies(monitor); |
| 108 | |
| 109 | // --- cost-category-scoped bindings --- |
| 110 | const listCostCategoryResourceAssociations = |
| 111 | yield* CostExplorer.ListCostCategoryResourceAssociations(category); |
| 112 | |
| 113 | // --- anomaly event source --- |
| 114 | // Anomalies cannot be forced in a test (they require days of real spend |
| 115 | // data), so this exercises the deploy-time wiring: the EventBridge rule |
| 116 | // on `aws.ce` / `Anomaly Detected` plus the Lambda invoke permission. |
| 117 | yield* CostExplorer.consumeAnomalyEvents({}, (events) => |
| 118 | Stream.runForEach(events, (event) => |
| 119 | Effect.log(`cost anomaly ${event.detail.anomalyId} on ${event.detail.dimensionValue}`), |
| 120 | ), |
| 121 | ); |
| 122 | |
| 123 | const bound = { |
| 124 | getCostAndUsage, |
| 125 | getCostAndUsageComparisons, |
| 126 | getCostAndUsageWithResources, |
| 127 | getCostComparisonDrivers, |
| 128 | getApproximateUsageRecords, |
| 129 | getCostForecast, |
| 130 | getUsageForecast, |
| 131 | getDimensionValues, |
| 132 | getTags, |
| 133 | getCostCategories, |
| 134 | getReservationCoverage, |
| 135 | getReservationPurchaseRecommendation, |
| 136 | getReservationUtilization, |
| 137 | getRightsizingRecommendation, |
| 138 | getSavingsPlansCoverage, |
| 139 | getSavingsPlansPurchaseRecommendation, |
| 140 | getSavingsPlanPurchaseRecommendationDetails, |
| 141 | getSavingsPlansUtilization, |
| 142 | getSavingsPlansUtilizationDetails, |
| 143 | startSavingsPlansPurchaseRecommendationGeneration, |
| 144 | listSavingsPlansPurchaseRecommendationGeneration, |
| 145 | startCommitmentPurchaseAnalysis, |
| 146 | getCommitmentPurchaseAnalysis, |
| 147 | listCommitmentPurchaseAnalyses, |
| 148 | listCostAllocationTags, |
| 149 | updateCostAllocationTagsStatus, |
| 150 | startCostAllocationTagBackfill, |
| 151 | listCostAllocationTagBackfillHistory, |
| 152 | getAnomalies, |
| 153 | provideAnomalyFeedback, |
| 154 | listCostCategoryResourceAssociations, |
| 155 | }; |
| 156 | |
| 157 | return { |
| 158 | fetch: Effect.gen(function* () { |
| 159 | const request = yield* HttpServerRequest; |
| 160 | const url = new URL(request.originalUrl); |
| 161 | const pathname = url.pathname; |
| 162 | |
| 163 | if (request.method === "GET" && pathname === "/bindings") { |
| 164 | return yield* HttpServerResponse.json({ |
| 165 | bound: Object.keys(bound), |
| 166 | }); |
| 167 | } |
| 168 | |
| 169 | if (request.method === "GET" && pathname === "/cost-and-usage") { |
| 170 | const Start = yield* monthStart(-1); |
| 171 | const End = yield* monthStart(0); |
| 172 | const result = yield* getCostAndUsage({ |
| 173 | TimePeriod: { Start, End }, |
| 174 | Granularity: "MONTHLY", |
| 175 | Metrics: ["UnblendedCost"], |
| 176 | }).pipe( |
| 177 | Effect.map((r) => ({ |
| 178 | tag: "Ok", |
| 179 | results: (r.ResultsByTime ?? []).length, |
| 180 | amount: r.ResultsByTime?.[0]?.Total?.UnblendedCost?.Amount ?? null, |
| 181 | })), |
| 182 | Effect.catchTag("DataUnavailableException", (e) => |
| 183 | Effect.succeed({ tag: e._tag, results: 0, amount: null }), |
| 184 | ), |
| 185 | ); |
| 186 | return yield* HttpServerResponse.json(result); |
| 187 | } |
| 188 | |
| 189 | if (request.method === "GET" && pathname === "/dimension-values") { |
| 190 | const Start = yield* monthStart(-1); |
| 191 | const End = yield* monthStart(0); |
| 192 | const result = yield* getDimensionValues({ |
| 193 | TimePeriod: { Start, End }, |
| 194 | Dimension: "SERVICE", |
| 195 | }).pipe( |
| 196 | Effect.map((r) => ({ |
| 197 | tag: "Ok", |
| 198 | count: (r.DimensionValues ?? []).length, |
| 199 | })), |
| 200 | Effect.catchTag("DataUnavailableException", (e) => |
| 201 | Effect.succeed({ tag: e._tag, count: 0 }), |
| 202 | ), |
| 203 | ); |
| 204 | return yield* HttpServerResponse.json(result); |
| 205 | } |
| 206 | |
| 207 | if (request.method === "GET" && pathname === "/tag-keys") { |
| 208 | const Start = yield* monthStart(-1); |
| 209 | const End = yield* monthStart(0); |
| 210 | const result = yield* getTags({ TimePeriod: { Start, End } }).pipe( |
| 211 | Effect.map((r) => ({ tag: "Ok", count: (r.Tags ?? []).length })), |
| 212 | Effect.catchTag("DataUnavailableException", (e) => |
| 213 | Effect.succeed({ tag: e._tag, count: 0 }), |
| 214 | ), |
| 215 | ); |
| 216 | return yield* HttpServerResponse.json(result); |
| 217 | } |
| 218 | |
| 219 | if (request.method === "GET" && pathname === "/cost-categories") { |
| 220 | const Start = yield* monthStart(-1); |
| 221 | const End = yield* monthStart(0); |
| 222 | const result = yield* getCostCategories({ |
| 223 | TimePeriod: { Start, End }, |
| 224 | }).pipe( |
| 225 | Effect.map((r) => ({ |
| 226 | tag: "Ok", |
| 227 | names: r.CostCategoryNames ?? [], |
| 228 | })), |
| 229 | Effect.catchTag("DataUnavailableException", (e) => |
| 230 | Effect.succeed({ tag: e._tag, names: [] as string[] }), |
| 231 | ), |
| 232 | ); |
| 233 | return yield* HttpServerResponse.json(result); |
| 234 | } |
| 235 | |
| 236 | if (request.method === "GET" && pathname === "/forecast") { |
| 237 | const Start = yield* monthStart(1); |
| 238 | const End = yield* monthStart(2); |
| 239 | const result = yield* getCostForecast({ |
| 240 | TimePeriod: { Start, End }, |
| 241 | Metric: "UNBLENDED_COST", |
| 242 | Granularity: "MONTHLY", |
| 243 | }).pipe( |
| 244 | Effect.map((r) => ({ tag: "Ok", amount: r.Total?.Amount ?? null })), |
| 245 | Effect.catchTag("DataUnavailableException", (e) => |
| 246 | Effect.succeed({ tag: e._tag, amount: null }), |
| 247 | ), |
| 248 | ); |
| 249 | return yield* HttpServerResponse.json(result); |
| 250 | } |
| 251 | |
| 252 | if (request.method === "GET" && pathname === "/approximate-usage") { |
| 253 | // SERVICE-dimension estimates only support HOURLY granularity — |
| 254 | // DAILY is resource-level only and fails with ValidationException |
| 255 | // ("The estimation data cannot be generated for your input |
| 256 | // combination", verified by probe). |
| 257 | const result = yield* getApproximateUsageRecords({ |
| 258 | Granularity: "HOURLY", |
| 259 | ApproximationDimension: "SERVICE", |
| 260 | }).pipe( |
| 261 | Effect.map((r) => ({ tag: "Ok", total: r.TotalRecords ?? 0 })), |
| 262 | Effect.catchTag("DataUnavailableException", (e) => |
| 263 | Effect.succeed({ tag: e._tag, total: 0 }), |
| 264 | ), |
| 265 | ); |
| 266 | return yield* HttpServerResponse.json(result); |
| 267 | } |
| 268 | |
| 269 | if (request.method === "GET" && pathname === "/rightsizing") { |
| 270 | // Rightsizing recommendations are an opt-in Cost Explorer |
| 271 | // preference on the payer account. An account without the opt-in |
| 272 | // rejects with RightsizingRecommendationNotEnabled — the |
| 273 | // AccessDeniedException "opt-in only feature" rejection (verified |
| 274 | // by probe) patched into distilled as a specific typed tag. A |
| 275 | // genuine IAM gap still surfaces as AccessDeniedException and |
| 276 | // fails the route. |
| 277 | const result = yield* getRightsizingRecommendation({ |
| 278 | Service: "AmazonEC2", |
| 279 | }).pipe( |
| 280 | Effect.map((r) => ({ |
| 281 | tag: "Ok", |
| 282 | count: (r.RightsizingRecommendations ?? []).length, |
| 283 | })), |
| 284 | Effect.catchTag("RightsizingRecommendationNotEnabled", (e) => |
| 285 | Effect.succeed({ tag: e._tag, count: 0 }), |
| 286 | ), |
| 287 | ); |
| 288 | return yield* HttpServerResponse.json(result); |
| 289 | } |
| 290 | |
| 291 | if (request.method === "GET" && pathname === "/reservation-recommendation") { |
| 292 | const result = yield* getReservationPurchaseRecommendation({ |
| 293 | Service: "Amazon Elastic Compute Cloud - Compute", |
| 294 | }).pipe( |
| 295 | Effect.map((r) => ({ |
| 296 | tag: "Ok", |
| 297 | count: (r.Recommendations ?? []).length, |
| 298 | })), |
| 299 | Effect.catchTag("DataUnavailableException", (e) => |
| 300 | Effect.succeed({ tag: e._tag, count: 0 }), |
| 301 | ), |
| 302 | ); |
| 303 | return yield* HttpServerResponse.json(result); |
| 304 | } |
| 305 | |
| 306 | if (request.method === "GET" && pathname === "/savings-plans-utilization") { |
| 307 | const Start = yield* monthStart(-1); |
| 308 | const End = yield* monthStart(0); |
| 309 | const result = yield* getSavingsPlansUtilization({ |
| 310 | TimePeriod: { Start, End }, |
| 311 | }).pipe( |
| 312 | Effect.map((r) => ({ |
| 313 | tag: "Ok", |
| 314 | utilization: r.Total?.Utilization?.UtilizationPercentage ?? null, |
| 315 | })), |
| 316 | Effect.catchTag("DataUnavailableException", (e) => |
| 317 | Effect.succeed({ tag: e._tag, utilization: null }), |
| 318 | ), |
| 319 | ); |
| 320 | return yield* HttpServerResponse.json(result); |
| 321 | } |
| 322 | |
| 323 | if (request.method === "GET" && pathname === "/recommendation-generations") { |
| 324 | const result = yield* listSavingsPlansPurchaseRecommendationGeneration().pipe( |
| 325 | Effect.map((r) => ({ |
| 326 | tag: "Ok", |
| 327 | count: (r.GenerationSummaryList ?? []).length, |
| 328 | })), |
| 329 | Effect.catchTag("DataUnavailableException", (e) => |
| 330 | Effect.succeed({ tag: e._tag, count: 0 }), |
| 331 | ), |
| 332 | ); |
| 333 | return yield* HttpServerResponse.json(result); |
| 334 | } |
| 335 | |
| 336 | if (request.method === "GET" && pathname === "/commitment-analyses") { |
| 337 | const result = yield* listCommitmentPurchaseAnalyses().pipe( |
| 338 | Effect.map((r) => ({ |
| 339 | tag: "Ok", |
| 340 | count: (r.AnalysisSummaryList ?? []).length, |
| 341 | })), |
| 342 | Effect.catchTag("DataUnavailableException", (e) => |
| 343 | Effect.succeed({ tag: e._tag, count: 0 }), |
| 344 | ), |
| 345 | ); |
| 346 | return yield* HttpServerResponse.json(result); |
| 347 | } |
| 348 | |
| 349 | if (request.method === "GET" && pathname === "/allocation-tags") { |
| 350 | const result = yield* listCostAllocationTags({ MaxResults: 100 }); |
| 351 | return yield* HttpServerResponse.json({ |
| 352 | count: (result.CostAllocationTags ?? []).length, |
| 353 | }); |
| 354 | } |
| 355 | |
| 356 | if (request.method === "GET" && pathname === "/backfill-history") { |
| 357 | const result = yield* listCostAllocationTagBackfillHistory(); |
| 358 | return yield* HttpServerResponse.json({ |
| 359 | count: (result.BackfillRequests ?? []).length, |
| 360 | }); |
| 361 | } |
| 362 | |
| 363 | if (request.method === "GET" && pathname === "/anomalies") { |
| 364 | // GetAnomalies only accepts a start date within the last 90 days; |
| 365 | // two months back exceeds that at some month ends. |
| 366 | const Start = yield* monthStart(-1); |
| 367 | const result = yield* getAnomalies({ |
| 368 | DateInterval: { StartDate: Start }, |
| 369 | }); |
| 370 | return yield* HttpServerResponse.json({ |
| 371 | count: (result.Anomalies ?? []).length, |
| 372 | }); |
| 373 | } |
| 374 | |
| 375 | if (request.method === "GET" && pathname === "/anomaly-feedback-invalid") { |
| 376 | // Exercises the account-level grant + the typed error path — the |
| 377 | // nonexistent anomaly id must surface the typed ValidationException |
| 378 | // ("Feedback is submitted for an invalid anomaly", verified by |
| 379 | // probe). An IAM gap would surface AccessDeniedException and 500 |
| 380 | // this route instead. |
| 381 | const result = yield* provideAnomalyFeedback({ |
| 382 | AnomalyId: NONEXISTENT_ANOMALY_ID, |
| 383 | Feedback: "PLANNED_ACTIVITY", |
| 384 | }).pipe( |
| 385 | Effect.map(() => "Provided"), |
| 386 | Effect.catchTag("ValidationException", (e) => Effect.succeed(e._tag)), |
| 387 | ); |
| 388 | return yield* HttpServerResponse.json({ tag: result }); |
| 389 | } |
| 390 | |
| 391 | if (request.method === "GET" && pathname === "/category-associations") { |
| 392 | const result = yield* listCostCategoryResourceAssociations(); |
| 393 | return yield* HttpServerResponse.json({ |
| 394 | count: (result.CostCategoryResourceAssociations ?? []).length, |
| 395 | }); |
| 396 | } |
| 397 | |
| 398 | return yield* HttpServerResponse.json( |
| 399 | { error: "Not found", method: request.method, pathname }, |
| 400 | { status: 404 }, |
| 401 | ); |
| 402 | }).pipe(Effect.orDie), |
| 403 | }; |
| 404 | }).pipe( |
| 405 | Effect.provide( |
| 406 | Layer.mergeAll( |
| 407 | Lambda.EventSource, |
| 408 | CostExplorer.GetCostAndUsageHttp, |
| 409 | CostExplorer.GetCostAndUsageComparisonsHttp, |
| 410 | CostExplorer.GetCostAndUsageWithResourcesHttp, |
| 411 | CostExplorer.GetCostComparisonDriversHttp, |
| 412 | CostExplorer.GetApproximateUsageRecordsHttp, |
| 413 | CostExplorer.GetCostForecastHttp, |
| 414 | CostExplorer.GetUsageForecastHttp, |
| 415 | CostExplorer.GetDimensionValuesHttp, |
| 416 | CostExplorer.GetTagsHttp, |
| 417 | CostExplorer.GetCostCategoriesHttp, |
| 418 | CostExplorer.GetReservationCoverageHttp, |
| 419 | CostExplorer.GetReservationPurchaseRecommendationHttp, |
| 420 | CostExplorer.GetReservationUtilizationHttp, |
| 421 | CostExplorer.GetRightsizingRecommendationHttp, |
| 422 | CostExplorer.GetSavingsPlansCoverageHttp, |
| 423 | CostExplorer.GetSavingsPlansPurchaseRecommendationHttp, |
| 424 | CostExplorer.GetSavingsPlanPurchaseRecommendationDetailsHttp, |
| 425 | CostExplorer.GetSavingsPlansUtilizationHttp, |
| 426 | CostExplorer.GetSavingsPlansUtilizationDetailsHttp, |
| 427 | CostExplorer.StartSavingsPlansPurchaseRecommendationGenerationHttp, |
| 428 | CostExplorer.ListSavingsPlansPurchaseRecommendationGenerationHttp, |
| 429 | CostExplorer.StartCommitmentPurchaseAnalysisHttp, |
| 430 | CostExplorer.GetCommitmentPurchaseAnalysisHttp, |
| 431 | CostExplorer.ListCommitmentPurchaseAnalysesHttp, |
| 432 | CostExplorer.ListCostAllocationTagsHttp, |
| 433 | CostExplorer.UpdateCostAllocationTagsStatusHttp, |
| 434 | CostExplorer.StartCostAllocationTagBackfillHttp, |
| 435 | CostExplorer.ListCostAllocationTagBackfillHistoryHttp, |
| 436 | CostExplorer.GetAnomaliesHttp, |
| 437 | CostExplorer.ProvideAnomalyFeedbackHttp, |
| 438 | CostExplorer.ListCostCategoryResourceAssociationsHttp, |
| 439 | ), |
| 440 | ), |
| 441 | ), |
| 442 | ); |