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:
Franklin G. Mendoza authored and GitHub committed 2026-09-12 11:31:20 -04:00
1 parent 606e7b966f
commit a985773611
18 files changed
+737 -2

No files matched your search

@@ -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),
@@ -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;
}
}
@@ -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) {}
}
@@ -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); }
}
@@ -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; }
}