mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(bcm-pricing-calculator): emulate workload estimates (#3441)
* feat(bcm-pricing-calculator): emulate workload estimates * fix(bcm-pricing-calculator): serialize timestamps as epoch seconds * fix(bcm-pricing-calculator): align idempotency and errors
This commit is contained in:
1 parent
606e7b966f
commit
a985773611
18 files changed
+737
-2
No files matched your search
@@ -239,7 +239,7 @@ Floci supports local emulation for application services, data services, eventing
|
||||
| Databases and caching | RDS, RDS Data API, Neptune, DocumentDB, MemoryDB, ElastiCache |
|
||||
| Messaging and transfer | SES, Kinesis, MSK, Amazon MQ, Transfer Family, DataSync, IoT Core, Amazon Connect, Amazon AppIntegrations |
|
||||
| Security and governance | AWS Network Firewall, AWS RAM, Service Quotas, WAF v2, GuardDuty, Amazon Inspector, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations, AWS Account Management, IAM Access Analyzer, IAM Identity Center (SSO Admin, OIDC, Access Portal, SCIM), Identity Store, Amazon Macie, Amazon Detective, Security Hub, Amazon Verified Permissions, Control Catalog, Control Tower, Service Catalog, AWS Marketplace |
|
||||
| Cost and billing | AWS Budgets, Pricing, Cost Explorer, Cost and Usage Reports, BCM Data Exports |
|
||||
| Cost and billing | AWS Budgets, Pricing, Cost Explorer, Cost and Usage Reports, BCM Pricing Calculator, BCM Data Exports |
|
||||
| Resilience, backup, and config | AWS FIS, AWS Backup, AWS Config, AppConfig, AppConfigData, CloudFormation, Cloud Control API |
|
||||
|
||||
For operation-level compatibility, see the [Services Overview](https://floci.io/floci/services/).
|
||||
@@ -328,6 +328,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/
|
||||
| Pricing | In-process with static snapshot | Product discovery, attributes, price list files, pagination |
|
||||
| Cost Explorer | In-process | Cost synthesized from Floci resource state and pricing snapshots |
|
||||
| Cost and Usage Reports | In-process with floci-duck sidecar | CUR 2.0 and FOCUS 1.2 columns, account-scoped storage, Parquet emission |
|
||||
| BCM Pricing Calculator | In-process | Workload estimate create, usage pricing, read, and delete lifecycle |
|
||||
| BCM Data Exports | In-process | Export lifecycle, executions, update and delete operations |
|
||||
|
||||
</details>
|
||||
|
||||
@@ -517,6 +517,11 @@
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>oam</artifactId>
|
||||
</dependency>
|
||||
<!-- BCM Pricing Calculator client -->
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>bcmpricingcalculator</artifactId>
|
||||
</dependency>
|
||||
<!-- SSO credential support (needed for FLOCI_TARGET=aws with SSO profiles) -->
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
|
||||
@@ -39,6 +39,7 @@ import software.amazon.awssdk.services.ssoadmin.SsoAdminClient;
|
||||
import software.amazon.awssdk.services.ssooidc.SsoOidcClient;
|
||||
import software.amazon.awssdk.services.identitystore.IdentitystoreClient;
|
||||
import software.amazon.awssdk.services.budgets.BudgetsClient;
|
||||
import software.amazon.awssdk.services.bcmpricingcalculator.BcmPricingCalculatorClient;
|
||||
import software.amazon.awssdk.services.macie2.Macie2Client;
|
||||
import software.amazon.awssdk.services.controlcatalog.ControlCatalogClient;
|
||||
import software.amazon.awssdk.services.marketplacecatalog.MarketplaceCatalogClient;
|
||||
@@ -1303,6 +1304,14 @@ public final class TestFixtures {
|
||||
.build();
|
||||
}
|
||||
|
||||
public static BcmPricingCalculatorClient bcmPricingCalculatorClient() {
|
||||
return BcmPricingCalculatorClient.builder()
|
||||
.endpointOverride(ENDPOINT)
|
||||
.region(REGION)
|
||||
.credentialsProvider(CREDENTIALS)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static ResourceExplorer2Client resourceExplorer2Client() {
|
||||
return resourceExplorer2Client(REGION);
|
||||
}
|
||||
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.services.bcmpricingcalculator.BcmPricingCalculatorClient;
|
||||
import software.amazon.awssdk.services.bcmpricingcalculator.model.BatchCreateWorkloadEstimateUsageEntry;
|
||||
import software.amazon.awssdk.services.bcmpricingcalculator.model.BatchCreateWorkloadEstimateUsageRequest;
|
||||
import software.amazon.awssdk.services.bcmpricingcalculator.model.CreateWorkloadEstimateRequest;
|
||||
import software.amazon.awssdk.services.bcmpricingcalculator.model.DeleteWorkloadEstimateRequest;
|
||||
import software.amazon.awssdk.services.bcmpricingcalculator.model.GetWorkloadEstimateRequest;
|
||||
import software.amazon.awssdk.services.bcmpricingcalculator.model.WorkloadEstimateRateType;
|
||||
import software.amazon.awssdk.services.bcmpricingcalculator.model.WorkloadEstimateStatus;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class BcmPricingCalculatorTest {
|
||||
@Test
|
||||
void workloadEstimateLifecycle() {
|
||||
try (BcmPricingCalculatorClient client = TestFixtures.bcmPricingCalculatorClient()) {
|
||||
var created = client.createWorkloadEstimate(CreateWorkloadEstimateRequest.builder()
|
||||
.name("sdk-estimate")
|
||||
.clientToken("sdk-estimate-token")
|
||||
.rateType(WorkloadEstimateRateType.BEFORE_DISCOUNTS)
|
||||
.build());
|
||||
assertNotNull(created.id());
|
||||
|
||||
var batch = client.batchCreateWorkloadEstimateUsage(BatchCreateWorkloadEstimateUsageRequest.builder()
|
||||
.workloadEstimateId(created.id())
|
||||
.clientToken("sdk-usage-token")
|
||||
.usage(List.of(BatchCreateWorkloadEstimateUsageEntry.builder()
|
||||
.serviceCode("AmazonEC2")
|
||||
.usageType("BoxUsage:t3.micro")
|
||||
.operation("")
|
||||
.key("sdk1")
|
||||
.usageAccountId("000000000000")
|
||||
.group("compute")
|
||||
.amount(730d)
|
||||
.build()))
|
||||
.build());
|
||||
assertTrue(batch.errors().isEmpty());
|
||||
assertEquals(1, batch.items().size());
|
||||
|
||||
var estimate = client.getWorkloadEstimate(GetWorkloadEstimateRequest.builder()
|
||||
.identifier(created.id()).build());
|
||||
assertEquals(WorkloadEstimateStatus.VALID, estimate.status());
|
||||
assertEquals(7.592d, estimate.totalCost(), 0.000001d);
|
||||
|
||||
client.deleteWorkloadEstimate(DeleteWorkloadEstimateRequest.builder()
|
||||
.identifier(created.id()).build());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
# BCM Pricing Calculator (`bcm-pricing-calculator:*`)
|
||||
|
||||
**Protocol:** AWS JSON 1.0
|
||||
**Header:** `X-Amz-Target: AWSBCMPricingCalculator.<Action>`
|
||||
**Endpoint prefix:** `bcm-pricing-calculator`
|
||||
|
||||
Floci emulates the workload-estimate path of the in-console AWS Pricing Calculator. Usage lines are priced from Floci's bundled AWS Pricing snapshots, so estimates stay deterministic and require no external network access.
|
||||
|
||||
## Supported operations
|
||||
|
||||
| Operation | Notes |
|
||||
|---|---|
|
||||
| `CreateWorkloadEstimate` | Creates an account-scoped workload estimate and honors `clientToken` idempotency |
|
||||
| `BatchCreateWorkloadEstimateUsage` | Adds 1 to 25 usage lines and recalculates the estimate total |
|
||||
| `GetWorkloadEstimate` | Returns the estimate status, rate metadata, currency, and total cost |
|
||||
| `DeleteWorkloadEstimate` | Idempotent; also removes the estimate's usage lines |
|
||||
|
||||
## Pricing behavior
|
||||
|
||||
`BatchCreateWorkloadEstimateUsage` resolves each usage line by `serviceCode`, `usageType`, and, when supplied, `operation`. The matching On-Demand price dimension from the Pricing service snapshot determines the unit and USD rate. The usage amount is multiplied by that rate and the estimate total is recalculated synchronously.
|
||||
|
||||
Floci currently models `BEFORE_DISCOUNTS` with the bundled public On-Demand rates. The AWS API also accepts `AFTER_DISCOUNTS` and `AFTER_DISCOUNTS_AND_COMMITMENTS`; these values are preserved on the estimate, but Floci does not have account-specific negotiated rates or purchase commitments to alter the calculated amount.
|
||||
|
||||
## Validation and lifecycle
|
||||
|
||||
- Workload estimate names use AWS's `[a-zA-Z0-9-]+` shape and are limited to 64 characters.
|
||||
- Estimate identifiers use the AWS 36-character lowercase UUID shape.
|
||||
- `clientToken` supports AWS idempotency semantics. Reusing a token with conflicting create parameters returns `ConflictException`.
|
||||
- Batch requests accept 1 to 25 entries.
|
||||
- Usage keys are at most 10 alphanumeric characters and `usageAccountId` is exactly 12 digits.
|
||||
- A successful local calculation is stored as `VALID`; Floci performs the calculation synchronously rather than exposing a temporary `UPDATING` state.
|
||||
- Currency is `USD`.
|
||||
- Deleting an already-absent valid identifier succeeds, matching the idempotent delete contract.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Variable | Default | Description |
|
||||
|---|---|---|
|
||||
| `FLOCI_SERVICES_BCM_PRICING_CALCULATOR_ENABLED` | `true` | Enable or disable the service |
|
||||
|
||||
## Example
|
||||
|
||||
```bash
|
||||
export AWS_ENDPOINT_URL=http://localhost:4566
|
||||
export AWS_DEFAULT_REGION=us-east-1
|
||||
export AWS_ACCESS_KEY_ID=test
|
||||
export AWS_SECRET_ACCESS_KEY=test
|
||||
|
||||
estimate_id=$(aws bcm-pricing-calculator create-workload-estimate \
|
||||
--name example-estimate \
|
||||
--rate-type BEFORE_DISCOUNTS \
|
||||
--client-token example-create \
|
||||
--query id --output text)
|
||||
|
||||
aws bcm-pricing-calculator batch-create-workload-estimate-usage \
|
||||
--workload-estimate-id "$estimate_id" \
|
||||
--client-token example-usage \
|
||||
--usage '[{"serviceCode":"AmazonEC2","usageType":"BoxUsage:t3.micro","operation":"","key":"ec2a","usageAccountId":"000000000000","amount":730}]'
|
||||
|
||||
aws bcm-pricing-calculator get-workload-estimate --identifier "$estimate_id"
|
||||
aws bcm-pricing-calculator delete-workload-estimate --identifier "$estimate_id"
|
||||
```
|
||||
@@ -131,6 +131,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
|
||||
| [Pricing](pricing.md) | `POST /` + `X-Amz-Target: AWSPriceListService.*` | JSON 1.1 | 5 |
|
||||
| [Cost Explorer](ce.md) | `POST /` + `X-Amz-Target: AWSInsightsIndexService.*` | JSON 1.1 | 9 |
|
||||
| [Cost and Usage Reports](cur.md) | `POST /` + `X-Amz-Target: AWSOrigamiServiceGatewayService.*` | JSON 1.1 | 6 |
|
||||
| [BCM Pricing Calculator](bcm-pricing-calculator.md) | `POST /` + `X-Amz-Target: AWSBCMPricingCalculator.*` | JSON 1.0 | 4 |
|
||||
| [BCM Data Exports](bcm-data-exports.md) | `POST /` + `X-Amz-Target: AWSBillingAndCostManagementDataExports.*` | JSON 1.1 | 7 |
|
||||
| [Transfer Family](transfer.md) | `POST /` + `X-Amz-Target: TransferService.*` | JSON 1.1 | 17 |
|
||||
| [DataSync](datasync.md) | `POST /` + `X-Amz-Target: FmrsService.*` | JSON 1.1 | 48 |
|
||||
|
||||
@@ -210,6 +210,7 @@ nav:
|
||||
- Pricing: services/pricing.md
|
||||
- Cost Explorer: services/ce.md
|
||||
- Cost and Usage Reports: services/cur.md
|
||||
- BCM Pricing Calculator: services/bcm-pricing-calculator.md
|
||||
- BCM Data Exports: services/bcm-data-exports.md
|
||||
- Testcontainers:
|
||||
- Overview: testcontainers/index.md
|
||||
|
||||
@@ -704,6 +704,7 @@ public interface EmulatorConfig {
|
||||
CurServiceConfig cur();
|
||||
BcmDataExportsServiceConfig bcmDataExports();
|
||||
OamServiceConfig oam();
|
||||
BcmPricingCalculatorServiceConfig bcmPricingCalculator();
|
||||
ConfigServiceConfig configservice();
|
||||
CloudTrailServiceConfig cloudtrail();
|
||||
CloudControlServiceConfig cloudcontrol();
|
||||
@@ -1928,6 +1929,11 @@ public interface EmulatorConfig {
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface BcmPricingCalculatorServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface BcmDataExportsServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.ObjectReader;
|
||||
import io.github.hectorvent.floci.services.cloudcontrol.CloudControlJsonHandler;
|
||||
import io.github.hectorvent.floci.services.bcmpricingcalculator.BcmPricingCalculatorJsonHandler;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsJsonHandler;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbResponses;
|
||||
@@ -53,6 +54,7 @@ public class AwsJsonController {
|
||||
private final NetworkFirewallJsonHandler networkFirewallJsonHandler;
|
||||
private final MarketplaceJsonHandler marketplaceJsonHandler;
|
||||
private final VerifiedPermissionsJsonHandler verifiedPermissionsJsonHandler;
|
||||
private final BcmPricingCalculatorJsonHandler bcmPricingCalculatorJsonHandler;
|
||||
|
||||
@Inject
|
||||
public AwsJsonController(ObjectMapper objectMapper, ResolvedServiceCatalog catalog,
|
||||
@@ -66,7 +68,8 @@ public class AwsJsonController {
|
||||
SwfJsonHandler swfJsonHandler,
|
||||
NetworkFirewallJsonHandler networkFirewallJsonHandler,
|
||||
MarketplaceJsonHandler marketplaceJsonHandler,
|
||||
VerifiedPermissionsJsonHandler verifiedPermissionsJsonHandler) {
|
||||
VerifiedPermissionsJsonHandler verifiedPermissionsJsonHandler,
|
||||
BcmPricingCalculatorJsonHandler bcmPricingCalculatorJsonHandler) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.strictBodyReader = objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
|
||||
this.catalog = catalog;
|
||||
@@ -82,6 +85,7 @@ public class AwsJsonController {
|
||||
this.networkFirewallJsonHandler = networkFirewallJsonHandler;
|
||||
this.marketplaceJsonHandler = marketplaceJsonHandler;
|
||||
this.verifiedPermissionsJsonHandler = verifiedPermissionsJsonHandler;
|
||||
this.bcmPricingCalculatorJsonHandler = bcmPricingCalculatorJsonHandler;
|
||||
}
|
||||
|
||||
@POST
|
||||
@@ -134,6 +138,7 @@ public class AwsJsonController {
|
||||
action, request, region, regionResolver.getAccountId());
|
||||
case "marketplace" -> marketplaceJsonHandler.handle(action, request, region);
|
||||
case "verifiedpermissions" -> verifiedPermissionsJsonHandler.handle(action, request, region);
|
||||
case "bcm-pricing-calculator" -> bcmPricingCalculatorJsonHandler.handle(action, request, region);
|
||||
default -> null;
|
||||
};
|
||||
// catalog.matchTarget is protocol-agnostic: a JSON 1.1 target
|
||||
|
||||
@@ -555,6 +555,11 @@ public class ResolvedServiceCatalog {
|
||||
"cur", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
|
||||
protocols(ServiceProtocol.JSON),
|
||||
Set.of("AWSOrigamiServiceGatewayService."), Set.of("cur"), Set.of(), Set.of()),
|
||||
descriptor("bcm-pricing-calculator", "bcmpricingcalculator",
|
||||
config.services().bcmPricingCalculator().enabled(), true,
|
||||
"bcmpricingcalculator", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
|
||||
protocols(ServiceProtocol.JSON),
|
||||
Set.of("AWSBCMPricingCalculator."), Set.of("bcm-pricing-calculator"), Set.of(), Set.of()),
|
||||
descriptor("bcm-data-exports", "bcmdataexports", config.services().bcmDataExports().enabled(), true,
|
||||
"bcmdataexports", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
|
||||
protocols(ServiceProtocol.JSON),
|
||||
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
package io.github.hectorvent.floci.services.bcmpricingcalculator;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.bcmpricingcalculator.model.WorkloadEstimate;
|
||||
import io.github.hectorvent.floci.services.bcmpricingcalculator.model.WorkloadEstimateUsage;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@ApplicationScoped
|
||||
public class BcmPricingCalculatorJsonHandler {
|
||||
private final BcmPricingCalculatorService service;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public BcmPricingCalculatorJsonHandler(BcmPricingCalculatorService service, ObjectMapper objectMapper) {
|
||||
this.service = service;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public Response handle(String action, JsonNode request, String region) {
|
||||
try {
|
||||
return switch (action) {
|
||||
case "CreateWorkloadEstimate" -> create(request);
|
||||
case "BatchCreateWorkloadEstimateUsage" -> batchCreateUsage(request);
|
||||
case "GetWorkloadEstimate" -> get(request);
|
||||
case "DeleteWorkloadEstimate" -> delete(request);
|
||||
default -> Response.status(400).entity(new AwsErrorResponse(
|
||||
"UnknownOperationException", "Unknown operation: AWSBCMPricingCalculator." + action)).build();
|
||||
};
|
||||
} catch (AwsException e) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private Response create(JsonNode request) {
|
||||
WorkloadEstimate estimate = service.create(text(request, "name"), text(request, "clientToken"),
|
||||
text(request, "rateType"), stringMap(request.path("tags")));
|
||||
return Response.ok(estimateNode(estimate)).build();
|
||||
}
|
||||
|
||||
private Response batchCreateUsage(JsonNode request) {
|
||||
List<BcmPricingCalculatorService.UsageInput> entries = new ArrayList<>();
|
||||
JsonNode usage = request.path("usage");
|
||||
if (usage.isArray()) {
|
||||
for (JsonNode item : usage) {
|
||||
entries.add(new BcmPricingCalculatorService.UsageInput(
|
||||
text(item, "serviceCode"), text(item, "usageType"), text(item, "operation"),
|
||||
text(item, "key"), text(item, "usageAccountId"), text(item, "group"),
|
||||
item.path("amount").isNumber() ? item.path("amount").asDouble() : Double.NaN));
|
||||
}
|
||||
}
|
||||
BcmPricingCalculatorService.UsageBatchResult result = service.batchCreateUsage(
|
||||
text(request, "workloadEstimateId"), entries, text(request, "clientToken"));
|
||||
ObjectNode out = objectMapper.createObjectNode();
|
||||
ArrayNode items = out.putArray("items");
|
||||
result.items().forEach(item -> items.add(usageNode(item)));
|
||||
ArrayNode errors = out.putArray("errors");
|
||||
result.errors().forEach(error -> {
|
||||
ObjectNode node = errors.addObject();
|
||||
if (error.key() != null) node.put("key", error.key());
|
||||
node.put("errorCode", error.errorCode());
|
||||
node.put("errorMessage", error.errorMessage());
|
||||
});
|
||||
return Response.ok(out).build();
|
||||
}
|
||||
|
||||
private Response get(JsonNode request) {
|
||||
return Response.ok(estimateNode(service.get(text(request, "identifier")))).build();
|
||||
}
|
||||
|
||||
private Response delete(JsonNode request) {
|
||||
service.delete(text(request, "identifier"));
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private ObjectNode estimateNode(WorkloadEstimate e) {
|
||||
ObjectNode out = objectMapper.createObjectNode();
|
||||
out.put("id", e.getId());
|
||||
out.put("name", e.getName());
|
||||
out.put("createdAt", epochSeconds(e.getCreatedAt()));
|
||||
out.put("expiresAt", epochSeconds(e.getExpiresAt()));
|
||||
out.put("rateType", e.getRateType());
|
||||
out.put("rateTimestamp", epochSeconds(e.getRateTimestamp()));
|
||||
out.put("status", e.getStatus());
|
||||
out.put("totalCost", e.getTotalCost());
|
||||
out.put("costCurrency", e.getCostCurrency());
|
||||
return out;
|
||||
}
|
||||
|
||||
private ObjectNode usageNode(WorkloadEstimateUsage u) {
|
||||
ObjectNode out = objectMapper.createObjectNode();
|
||||
out.put("serviceCode", u.getServiceCode());
|
||||
out.put("usageType", u.getUsageType());
|
||||
out.put("operation", u.getOperation());
|
||||
if (u.getLocation() != null) out.put("location", u.getLocation());
|
||||
out.put("id", u.getId());
|
||||
out.put("usageAccountId", u.getUsageAccountId());
|
||||
if (u.getGroup() != null) out.put("group", u.getGroup());
|
||||
ObjectNode quantity = out.putObject("quantity");
|
||||
quantity.put("unit", u.getUnit());
|
||||
quantity.put("amount", u.getAmount());
|
||||
out.put("cost", u.getCost());
|
||||
out.put("currency", u.getCurrency());
|
||||
out.put("status", u.getStatus());
|
||||
out.put("key", u.getKey());
|
||||
return out;
|
||||
}
|
||||
|
||||
private static double epochSeconds(java.time.Instant instant) {
|
||||
return instant.getEpochSecond() + instant.getNano() / 1_000_000_000.0;
|
||||
}
|
||||
|
||||
private static String text(JsonNode node, String field) {
|
||||
JsonNode value = node == null ? null : node.get(field);
|
||||
return value == null || value.isNull() ? null : value.asText();
|
||||
}
|
||||
|
||||
private static Map<String, String> stringMap(JsonNode node) {
|
||||
if (node == null || !node.isObject()) return null;
|
||||
Map<String, String> out = new LinkedHashMap<>();
|
||||
node.fields().forEachRemaining(entry -> out.put(entry.getKey(), entry.getValue().asText()));
|
||||
return out;
|
||||
}
|
||||
}
|
||||
+228
@@ -0,0 +1,228 @@
|
||||
package io.github.hectorvent.floci.services.bcmpricingcalculator;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.bcmpricingcalculator.model.WorkloadEstimate;
|
||||
import io.github.hectorvent.floci.services.bcmpricingcalculator.model.WorkloadEstimateUsage;
|
||||
import io.github.hectorvent.floci.services.pricing.PricingService;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ApplicationScoped
|
||||
public class BcmPricingCalculatorService {
|
||||
private static final Pattern NAME = Pattern.compile("[a-zA-Z0-9-]+");
|
||||
private static final Pattern ACCOUNT = Pattern.compile("\\d{12}");
|
||||
private static final List<String> RATE_TYPES = List.of(
|
||||
"BEFORE_DISCOUNTS", "AFTER_DISCOUNTS", "AFTER_DISCOUNTS_AND_COMMITMENTS");
|
||||
|
||||
public record UsageInput(String serviceCode, String usageType, String operation, String key,
|
||||
String usageAccountId, String group, double amount) {}
|
||||
public record UsageError(String key, String errorCode, String errorMessage) {}
|
||||
public record UsageBatchResult(List<WorkloadEstimateUsage> items, List<UsageError> errors) {}
|
||||
|
||||
private final StorageBackend<String, WorkloadEstimate> estimates;
|
||||
private final StorageBackend<String, WorkloadEstimateUsage> usages;
|
||||
private final RegionResolver regionResolver;
|
||||
private final PricingService pricingService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public BcmPricingCalculatorService(StorageFactory storageFactory, RegionResolver regionResolver,
|
||||
PricingService pricingService, ObjectMapper objectMapper) {
|
||||
this(storageFactory.create("bcmpricingcalculator", "workload-estimates.json",
|
||||
new TypeReference<Map<String, WorkloadEstimate>>() {}),
|
||||
storageFactory.create("bcmpricingcalculator", "workload-estimate-usages.json",
|
||||
new TypeReference<Map<String, WorkloadEstimateUsage>>() {}),
|
||||
regionResolver, pricingService, objectMapper);
|
||||
}
|
||||
|
||||
BcmPricingCalculatorService(StorageBackend<String, WorkloadEstimate> estimates,
|
||||
StorageBackend<String, WorkloadEstimateUsage> usages,
|
||||
RegionResolver regionResolver, PricingService pricingService,
|
||||
ObjectMapper objectMapper) {
|
||||
this.estimates = estimates;
|
||||
this.usages = usages;
|
||||
this.regionResolver = regionResolver;
|
||||
this.pricingService = pricingService;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public synchronized WorkloadEstimate create(String name, String clientToken, String rateType, Map<String, String> tags) {
|
||||
if (name == null) throw validation("name is required.");
|
||||
if (name.length() > 64 || !NAME.matcher(name).matches()) throw validation("name is invalid.");
|
||||
validateToken(clientToken);
|
||||
String effectiveRate = rateType == null || rateType.isBlank() ? "BEFORE_DISCOUNTS" : rateType;
|
||||
if (!RATE_TYPES.contains(effectiveRate)) throw validation("rateType is invalid.");
|
||||
if (tags != null && tags.size() > 200) throw validation("tags exceeds the maximum size of 200.");
|
||||
|
||||
if (clientToken != null) {
|
||||
WorkloadEstimate replay = estimates.scan(_ -> true).stream()
|
||||
.filter(e -> clientToken.equals(e.getClientToken())).findFirst().orElse(null);
|
||||
if (replay != null) {
|
||||
if (!replay.getName().equals(name) || !replay.getRateType().equals(effectiveRate)) {
|
||||
throw new AwsException("ConflictException", "The idempotency token was reused with different parameters.", 400,
|
||||
Map.of("resourceId", replay.getId(), "resourceType", "WorkloadEstimate"));
|
||||
}
|
||||
return replay;
|
||||
}
|
||||
}
|
||||
|
||||
Instant now = Instant.now();
|
||||
WorkloadEstimate estimate = new WorkloadEstimate();
|
||||
estimate.setId(UUID.randomUUID().toString());
|
||||
estimate.setName(name);
|
||||
estimate.setOwnerAccountId(regionResolver.getAccountId());
|
||||
estimate.setRateType(effectiveRate);
|
||||
estimate.setStatus("VALID");
|
||||
estimate.setTotalCost(0.0);
|
||||
estimate.setCostCurrency("USD");
|
||||
estimate.setCreatedAt(now);
|
||||
estimate.setRateTimestamp(now);
|
||||
estimate.setExpiresAt(now.plus(30, ChronoUnit.DAYS));
|
||||
estimate.setClientToken(clientToken);
|
||||
estimate.setTags(tags);
|
||||
estimates.put(estimate.getId(), estimate);
|
||||
return estimate;
|
||||
}
|
||||
|
||||
public WorkloadEstimate get(String id) {
|
||||
validateId(id);
|
||||
return estimates.get(id).orElseThrow(() -> notFound(id));
|
||||
}
|
||||
|
||||
public void delete(String id) {
|
||||
validateId(id);
|
||||
if (estimates.get(id).isEmpty()) return;
|
||||
estimates.delete(id);
|
||||
usages.keys().stream().filter(k -> k.startsWith(id + "/")).toList().forEach(usages::delete);
|
||||
}
|
||||
|
||||
public synchronized UsageBatchResult batchCreateUsage(String estimateId, List<UsageInput> entries, String clientToken) {
|
||||
WorkloadEstimate estimate = get(estimateId);
|
||||
validateToken(clientToken);
|
||||
if (entries == null || entries.isEmpty() || entries.size() > 25) {
|
||||
throw validation("usage must contain between 1 and 25 entries.");
|
||||
}
|
||||
List<WorkloadEstimateUsage> items = new ArrayList<>();
|
||||
List<UsageError> errors = new ArrayList<>();
|
||||
for (UsageInput input : entries) {
|
||||
try {
|
||||
validateUsage(input);
|
||||
String key = estimateId + "/" + input.key();
|
||||
if (usages.get(key).isPresent()) {
|
||||
errors.add(new UsageError(input.key(), "CONFLICT", "A usage entry with this key already exists."));
|
||||
continue;
|
||||
}
|
||||
PricingMatch match = resolvePrice(input);
|
||||
WorkloadEstimateUsage usage = new WorkloadEstimateUsage();
|
||||
usage.setId(UUID.randomUUID().toString());
|
||||
usage.setWorkloadEstimateId(estimateId);
|
||||
usage.setKey(input.key());
|
||||
usage.setServiceCode(input.serviceCode());
|
||||
usage.setUsageType(input.usageType());
|
||||
usage.setOperation(input.operation());
|
||||
usage.setUsageAccountId(input.usageAccountId());
|
||||
usage.setGroup(input.group());
|
||||
usage.setAmount(input.amount());
|
||||
usage.setUnit(match.unit());
|
||||
usage.setCost(roundMoney(input.amount() * match.rate()));
|
||||
usage.setCurrency("USD");
|
||||
usage.setStatus("VALID");
|
||||
usage.setLocation(match.location());
|
||||
usages.put(key, usage);
|
||||
items.add(usage);
|
||||
} catch (AwsException e) {
|
||||
errors.add(new UsageError(input == null ? null : input.key(), "BAD_REQUEST", e.getMessage()));
|
||||
}
|
||||
}
|
||||
recompute(estimate);
|
||||
return new UsageBatchResult(items, errors);
|
||||
}
|
||||
|
||||
public List<WorkloadEstimateUsage> listUsage(String estimateId) {
|
||||
get(estimateId);
|
||||
return usages.scan(k -> k.startsWith(estimateId + "/")).stream()
|
||||
.sorted(java.util.Comparator.comparing(WorkloadEstimateUsage::getKey)).toList();
|
||||
}
|
||||
|
||||
private void recompute(WorkloadEstimate estimate) {
|
||||
double total = listUsageWithoutLookup(estimate.getId()).stream().mapToDouble(WorkloadEstimateUsage::getCost).sum();
|
||||
estimate.setTotalCost(roundMoney(total));
|
||||
estimate.setStatus("VALID");
|
||||
estimate.setRateTimestamp(Instant.now());
|
||||
estimates.put(estimate.getId(), estimate);
|
||||
}
|
||||
|
||||
private List<WorkloadEstimateUsage> listUsageWithoutLookup(String estimateId) {
|
||||
return usages.scan(k -> k.startsWith(estimateId + "/"));
|
||||
}
|
||||
|
||||
private PricingMatch resolvePrice(UsageInput input) {
|
||||
List<PricingService.FilterSpec> filters = new ArrayList<>();
|
||||
filters.add(new PricingService.FilterSpec("TERM_MATCH", "usagetype", input.usageType()));
|
||||
if (input.operation() != null && !input.operation().isBlank()) {
|
||||
filters.add(new PricingService.FilterSpec("TERM_MATCH", "operation", input.operation()));
|
||||
}
|
||||
ObjectNode response = pricingService.getProducts(input.serviceCode(), filters, null, null, 10);
|
||||
JsonNode prices = response.path("PriceList");
|
||||
if (!prices.isArray() || prices.size() != 1) {
|
||||
throw validation("Pricing data is unavailable for the supplied serviceCode, usageType, and operation.");
|
||||
}
|
||||
try {
|
||||
JsonNode product = objectMapper.readTree(prices.get(0).asText());
|
||||
JsonNode attrs = product.path("product").path("attributes");
|
||||
String location = attrs.path("location").asText(null);
|
||||
JsonNode onDemand = product.path("terms").path("OnDemand");
|
||||
JsonNode term = onDemand.elements().hasNext() ? onDemand.elements().next() : null;
|
||||
JsonNode dimensions = term == null ? null : term.path("priceDimensions");
|
||||
JsonNode dimension = dimensions != null && dimensions.elements().hasNext() ? dimensions.elements().next() : null;
|
||||
if (dimension == null) throw new IllegalArgumentException();
|
||||
double rate = Double.parseDouble(dimension.path("pricePerUnit").path("USD").asText());
|
||||
return new PricingMatch(rate, dimension.path("unit").asText("Usage"), location);
|
||||
} catch (Exception e) {
|
||||
throw validation("Pricing data is unavailable for the supplied usage.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateUsage(UsageInput input) {
|
||||
if (input == null) throw validation("usage entry is required.");
|
||||
if (input.serviceCode() == null || input.usageType() == null || input.operation() == null
|
||||
|| input.key() == null || input.usageAccountId() == null) throw validation("usage entry is missing a required field.");
|
||||
if (input.key().length() > 10 || !input.key().matches("[A-Za-z0-9]*")) throw validation("key is invalid.");
|
||||
if (!ACCOUNT.matcher(input.usageAccountId()).matches()) throw validation("usageAccountId is invalid.");
|
||||
if (!Double.isFinite(input.amount()) || input.amount() < 0) throw validation("amount is invalid.");
|
||||
}
|
||||
|
||||
private static void validateToken(String token) {
|
||||
if (token != null && (token.isEmpty() || token.length() > 64 || !token.matches("[\\u0021-\\u007E]+"))) {
|
||||
throw validation("clientToken is invalid.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateId(String id) {
|
||||
if (id == null || !id.matches("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}")) {
|
||||
throw validation("identifier is invalid.");
|
||||
}
|
||||
}
|
||||
|
||||
private static double roundMoney(double value) { return Math.round(value * 100_000_000d) / 100_000_000d; }
|
||||
private static AwsException validation(String message) { return new AwsException("ValidationException", message, 400); }
|
||||
private static AwsException notFound(String id) { return new AwsException("ResourceNotFoundException", "Workload estimate " + id + " was not found.", 400,
|
||||
Map.of("resourceId", id, "resourceType", "WorkloadEstimate")); }
|
||||
private record PricingMatch(double rate, String unit, String location) {}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package io.github.hectorvent.floci.services.bcmpricingcalculator.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
public class WorkloadEstimate {
|
||||
private String id;
|
||||
private String name;
|
||||
private String ownerAccountId;
|
||||
private String rateType;
|
||||
private String status;
|
||||
private double totalCost;
|
||||
private String costCurrency;
|
||||
private Instant createdAt;
|
||||
private Instant expiresAt;
|
||||
private Instant rateTimestamp;
|
||||
private String clientToken;
|
||||
private Map<String, String> tags = new LinkedHashMap<>();
|
||||
|
||||
public WorkloadEstimate() {}
|
||||
public String getId() { return id; }
|
||||
public void setId(String id) { this.id = id; }
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
public String getOwnerAccountId() { return ownerAccountId; }
|
||||
public void setOwnerAccountId(String ownerAccountId) { this.ownerAccountId = ownerAccountId; }
|
||||
public String getRateType() { return rateType; }
|
||||
public void setRateType(String rateType) { this.rateType = rateType; }
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
public double getTotalCost() { return totalCost; }
|
||||
public void setTotalCost(double totalCost) { this.totalCost = totalCost; }
|
||||
public String getCostCurrency() { return costCurrency; }
|
||||
public void setCostCurrency(String costCurrency) { this.costCurrency = costCurrency; }
|
||||
public Instant getCreatedAt() { return createdAt; }
|
||||
public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
|
||||
public Instant getExpiresAt() { return expiresAt; }
|
||||
public void setExpiresAt(Instant expiresAt) { this.expiresAt = expiresAt; }
|
||||
public Instant getRateTimestamp() { return rateTimestamp; }
|
||||
public void setRateTimestamp(Instant rateTimestamp) { this.rateTimestamp = rateTimestamp; }
|
||||
public String getClientToken() { return clientToken; }
|
||||
public void setClientToken(String clientToken) { this.clientToken = clientToken; }
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags == null ? new LinkedHashMap<>() : new LinkedHashMap<>(tags); }
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package io.github.hectorvent.floci.services.bcmpricingcalculator.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
public class WorkloadEstimateUsage {
|
||||
private String id;
|
||||
private String workloadEstimateId;
|
||||
private String key;
|
||||
private String serviceCode;
|
||||
private String usageType;
|
||||
private String operation;
|
||||
private String usageAccountId;
|
||||
private String group;
|
||||
private double amount;
|
||||
private String unit;
|
||||
private double cost;
|
||||
private String currency;
|
||||
private String status;
|
||||
private String location;
|
||||
|
||||
public WorkloadEstimateUsage() {}
|
||||
public String getId() { return id; }
|
||||
public void setId(String id) { this.id = id; }
|
||||
public String getWorkloadEstimateId() { return workloadEstimateId; }
|
||||
public void setWorkloadEstimateId(String workloadEstimateId) { this.workloadEstimateId = workloadEstimateId; }
|
||||
public String getKey() { return key; }
|
||||
public void setKey(String key) { this.key = key; }
|
||||
public String getServiceCode() { return serviceCode; }
|
||||
public void setServiceCode(String serviceCode) { this.serviceCode = serviceCode; }
|
||||
public String getUsageType() { return usageType; }
|
||||
public void setUsageType(String usageType) { this.usageType = usageType; }
|
||||
public String getOperation() { return operation; }
|
||||
public void setOperation(String operation) { this.operation = operation; }
|
||||
public String getUsageAccountId() { return usageAccountId; }
|
||||
public void setUsageAccountId(String usageAccountId) { this.usageAccountId = usageAccountId; }
|
||||
public String getGroup() { return group; }
|
||||
public void setGroup(String group) { this.group = group; }
|
||||
public double getAmount() { return amount; }
|
||||
public void setAmount(double amount) { this.amount = amount; }
|
||||
public String getUnit() { return unit; }
|
||||
public void setUnit(String unit) { this.unit = unit; }
|
||||
public double getCost() { return cost; }
|
||||
public void setCost(double cost) { this.cost = cost; }
|
||||
public String getCurrency() { return currency; }
|
||||
public void setCurrency(String currency) { this.currency = currency; }
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
public String getLocation() { return location; }
|
||||
public void setLocation(String location) { this.location = location; }
|
||||
}
|
||||
@@ -602,6 +602,8 @@ floci:
|
||||
enabled: true
|
||||
emit-mode: synchronous
|
||||
staging-bucket: floci-cur-staging
|
||||
bcm-pricing-calculator:
|
||||
enabled: true
|
||||
bcm-data-exports:
|
||||
enabled: true
|
||||
emit-mode: synchronous
|
||||
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
package io.github.hectorvent.floci.services.bcmpricingcalculator;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
|
||||
@QuarkusTest
|
||||
class BcmPricingCalculatorIntegrationTest {
|
||||
private static final String CONTENT_TYPE = "application/x-amz-json-1.0";
|
||||
private static final String TARGET = "AWSBCMPricingCalculator.";
|
||||
|
||||
@BeforeAll
|
||||
static void setup() { RestAssuredJsonUtils.configureAwsContentTypes(); }
|
||||
|
||||
@Test
|
||||
void workloadEstimateLifecyclePricesUsage() {
|
||||
String id = given().contentType(CONTENT_TYPE).header("X-Amz-Target", TARGET + "CreateWorkloadEstimate")
|
||||
.body("""
|
||||
{"name":"estimate-one","clientToken":"estimate-token-1","rateType":"BEFORE_DISCOUNTS"}
|
||||
""")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("status", equalTo("VALID"))
|
||||
.body("createdAt", instanceOf(Number.class))
|
||||
.body("expiresAt", instanceOf(Number.class))
|
||||
.body("rateTimestamp", instanceOf(Number.class))
|
||||
.body("costCurrency", equalTo("USD"))
|
||||
.extract().path("id");
|
||||
|
||||
given().contentType(CONTENT_TYPE).header("X-Amz-Target", TARGET + "BatchCreateWorkloadEstimateUsage")
|
||||
.body("""
|
||||
{"workloadEstimateId":"%s","clientToken":"usage-token-1","usage":[{
|
||||
"serviceCode":"AmazonEC2","usageType":"BoxUsage:t3.micro","operation":"",
|
||||
"key":"ec2a","usageAccountId":"000000000000","group":"compute","amount":730
|
||||
}]}
|
||||
""".formatted(id))
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("errors", empty())
|
||||
.body("items.size()", equalTo(1))
|
||||
.body("items[0].status", equalTo("VALID"))
|
||||
.body("items[0].cost", equalTo(7.592f));
|
||||
|
||||
given().contentType(CONTENT_TYPE).header("X-Amz-Target", TARGET + "GetWorkloadEstimate")
|
||||
.body("{\"identifier\":\"" + id + "\"}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("status", equalTo("VALID"))
|
||||
.body("totalCost", equalTo(7.592f));
|
||||
|
||||
given().contentType(CONTENT_TYPE).header("X-Amz-Target", TARGET + "DeleteWorkloadEstimate")
|
||||
.body("{\"identifier\":\"" + id + "\"}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createIsIdempotentByClientToken() {
|
||||
String body = "{\"name\":\"idem-estimate\",\"clientToken\":\"same-token\"}";
|
||||
String first = given().contentType(CONTENT_TYPE).header("X-Amz-Target", TARGET + "CreateWorkloadEstimate")
|
||||
.body(body).when().post("/").then().statusCode(200).extract().path("id");
|
||||
String second = given().contentType(CONTENT_TYPE).header("X-Amz-Target", TARGET + "CreateWorkloadEstimate")
|
||||
.body(body).when().post("/").then().statusCode(200).extract().path("id");
|
||||
org.junit.jupiter.api.Assertions.assertEquals(first, second);
|
||||
}
|
||||
@Test
|
||||
void tokenConflictAndIdempotentDeleteMatchAwsContract() {
|
||||
String firstBody = "{\"name\":\"token-one\",\"clientToken\":\"conflict-token\"}";
|
||||
String id = given().contentType(CONTENT_TYPE).header("X-Amz-Target", TARGET + "CreateWorkloadEstimate")
|
||||
.body(firstBody).when().post("/").then().statusCode(200).extract().path("id");
|
||||
|
||||
given().contentType(CONTENT_TYPE).header("X-Amz-Target", TARGET + "CreateWorkloadEstimate")
|
||||
.body("{\"name\":\"token-two\",\"clientToken\":\"conflict-token\"}")
|
||||
.when().post("/").then().statusCode(400).body("__type", containsString("ConflictException"));
|
||||
|
||||
String deleteBody = "{\"identifier\":\"" + id + "\"}";
|
||||
given().contentType(CONTENT_TYPE).header("X-Amz-Target", TARGET + "DeleteWorkloadEstimate")
|
||||
.body(deleteBody).when().post("/").then().statusCode(200);
|
||||
given().contentType(CONTENT_TYPE).header("X-Amz-Target", TARGET + "DeleteWorkloadEstimate")
|
||||
.body(deleteBody).when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void estimatesAreAccountIsolated() {
|
||||
String accountA = "AWS4-HMAC-SHA256 Credential=111111111111/20260911/us-east-1/bcm-pricing-calculator/aws4_request";
|
||||
String accountB = "AWS4-HMAC-SHA256 Credential=222222222222/20260911/us-east-1/bcm-pricing-calculator/aws4_request";
|
||||
String id = given().contentType(CONTENT_TYPE).header("Authorization", accountA)
|
||||
.header("X-Amz-Target", TARGET + "CreateWorkloadEstimate")
|
||||
.body("{\"name\":\"account-a\"}")
|
||||
.when().post("/").then().statusCode(200).extract().path("id");
|
||||
|
||||
given().contentType(CONTENT_TYPE).header("Authorization", accountB)
|
||||
.header("X-Amz-Target", TARGET + "GetWorkloadEstimate")
|
||||
.body("{\"identifier\":\"" + id + "\"}")
|
||||
.when().post("/").then().statusCode(400).body("__type", containsString("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createAcceptsUpToTwoHundredTagsAndRejectsMore() {
|
||||
java.util.Map<String, String> tags = new java.util.LinkedHashMap<>();
|
||||
for (int i = 0; i < 200; i++) {
|
||||
tags.put("tag" + i, "value");
|
||||
}
|
||||
given().contentType(CONTENT_TYPE).header("X-Amz-Target", TARGET + "CreateWorkloadEstimate")
|
||||
.body(java.util.Map.of("name", "two-hundred-tags", "tags", tags))
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
tags.put("tag200", "value");
|
||||
given().contentType(CONTENT_TYPE).header("X-Amz-Target", TARGET + "CreateWorkloadEstimate")
|
||||
.body(java.util.Map.of("name", "too-many-tags", "tags", tags))
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body("__type", containsString("ValidationException"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -339,6 +339,8 @@ floci:
|
||||
cur:
|
||||
enabled: true
|
||||
emit-mode: off
|
||||
bcm-pricing-calculator:
|
||||
enabled: true
|
||||
bcm-data-exports:
|
||||
enabled: true
|
||||
emit-mode: off
|
||||
|
||||
@@ -375,6 +375,7 @@ deferred_handlers:
|
||||
- { path: src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandler.java } # non-tabular doc (grouped/inline)
|
||||
- { path: src/main/java/io/github/hectorvent/floci/services/applicationautoscaling/ScalingPolicyAlarmActionHandler.java } # not a JSON/Query action dispatcher — its `case "X" ->` arms are the StepScaling AdjustmentType switch, not AWS actions
|
||||
- { path: src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandler.java } # non-tabular doc (grouped/inline)
|
||||
- { path: src/main/java/io/github/hectorvent/floci/services/bcmpricingcalculator/BcmPricingCalculatorJsonHandler.java } # focused workload-estimate surface
|
||||
- { path: src/main/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsJsonHandler.java } # no standalone action table yet
|
||||
- { path: src/main/java/io/github/hectorvent/floci/services/ce/CostExplorerJsonHandler.java } # no standalone action table yet
|
||||
- { path: src/main/java/io/github/hectorvent/floci/services/cloudcontrol/CloudControlJsonHandler.java } # no standalone action table yet
|
||||
|
||||
Reference in new issue
Block a user