feat(ce): add Cost Explorer service (#832)

Implements the `AWSInsightsIndexService.*` JSON 1.1 surface backed by
synthesizing cost and usage from Floci's existing resource state
multiplied by the bundled AWS Pricing snapshot (#821). Covers the nine
Cost Explorer operations the FinOps tooling ecosystem most commonly
exercises:

- `GetCostAndUsage` / `GetCostAndUsageWithResources` — full
  `TimePeriod`, `Granularity` (DAILY / MONTHLY / HOURLY),
  `Metrics` (UnblendedCost / BlendedCost / AmortizedCost /
  NetUnblendedCost / NetAmortizedCost / UsageQuantity /
  NormalizedUsageAmount), `GroupBy` (DIMENSION / TAG /
  COST_CATEGORY), and the recursive `Filter` expression tree
  (`And` / `Or` / `Not` / `Dimensions` / `Tags` / `CostCategories`).
- `GetDimensionValues` — returns the dimension values present in the
  synthesized data; honors filters and search strings.
- `GetTags` — returns tag keys / values across enumerated resources.
- `GetReservationCoverage` / `GetReservationUtilization` — zero-totalled
  stubs so callers that hit these endpoints during smoke tests don't
  fail on `UnknownOperationException`.
- `GetSavingsPlansCoverage` / `GetSavingsPlansUtilization` — same
  stubbed shape.
- `GetCostCategories` — empty list (cost-category management is
  out-of-scope for this PR).

`GROUP_BY=RECORD_TYPE` distinguishes `Usage`, `Credit`, `Tax`,
`Refund`, `DiscountedUsage`, and the four `SavingsPlan*` variants.
`Tax` / `Refund` / `DiscountedUsage` / `SavingsPlan*` are reserved for
follow-up PRs; `Credit` is emitted when
`FLOCI_SERVICES_CE_CREDIT_USD_MONTHLY > 0`, capped at the synthesized
monthly usage so net cost never goes below zero.

## Architecture

A new SPI lives in `core/common/`:

    public interface ResourceUsageEnumerator {
        Stream<UsageLine> enumerate(Instant start, Instant end, String region);
    }

CDI auto-discovers all `@ApplicationScoped` beans implementing it.
Cost Explorer iterates `Instance<ResourceUsageEnumerator>` per request,
so adding a new Floci service with cost data is a matter of dropping a
new enumerator bean next to the service — zero changes to
`CostExplorerService`. The same enumerators will feed the upcoming CUR
and BCM Data Exports Parquet writer (#823) without duplication.

The bundled enumerators are:

- `Ec2UsageEnumerator` — `BoxUsage:<instanceType>` * hours per running
  instance, priced from the Pricing snapshot.
- `S3UsageEnumerator` — `TimedStorage-ByteHrs` * GB-month per bucket,
  priced from the snapshot.
- `LambdaUsageEnumerator` — catalog-only line per function (zero
  quantity until invocation tracking lands in a follow-up).
- `UnpricedServicesEnumerator` — emits zero-quantity catalog rows for
  the remaining ~30 Floci services so they appear in
  `GetDimensionValues SERVICE` without contributing billed cost.

Each priced enumerator additionally emits a zero-quantity catalog
line so the service shows up in `GetDimensionValues SERVICE` even
when no resources exist.

## Tests

`CostExplorerIntegrationTest` covers all nine operations via
RestAssured wire-format assertions: granularity bucketing,
filter-expression evaluation, group-by combinations, dimension and
tag listings, RI / SP stubs, validation errors. 20 tests, all green.

The full Floci test suite stays green with the additions
(4030 tests run, 0 failures, 0 errors, excluding the pre-existing
local-env flakes documented during PR #821).

Refs: https://github.com/orgs/floci-io/discussions/791
Refs: https://github.com/floci-io/floci/issues/822
This commit is contained in:
Shubham Srivastava authored and GitHub committed 2026-05-14 20:29:37 -05:00
1 parent e4666dfa7a
commit 6acbf1f2c2
28 files changed
+2471 -7

No files matched your search

@@ -302,6 +302,7 @@ public interface EmulatorConfig {
TextractServiceConfig textract();
PricingServiceConfig pricing();
TranscribeServiceConfig transcribe();
CostExplorerServiceConfig ce();
}
interface TransferServiceConfig {
@@ -660,6 +661,20 @@ public interface EmulatorConfig {
boolean enabled();
}
interface CostExplorerServiceConfig {
@WithDefault("true")
boolean enabled();
/**
* Synthetic monthly USD credit applied as a {@code Credit} {@code RECORD_TYPE}
* row in {@code GetCostAndUsage} responses. The emitted credit is capped at
* the synthesized monthly usage so net cost never goes below zero.
* Defaults to zero (no credit emitted).
*/
@WithDefault("0.0")
double creditUsdMonthly();
}
interface EcrServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.ecs.EcsJsonHandler;
import io.github.hectorvent.floci.services.firehose.FirehoseJsonHandler;
import io.github.hectorvent.floci.services.glue.GlueJsonHandler;
import io.github.hectorvent.floci.services.resourcegroupstagging.ResourceGroupsTaggingJsonHandler;
import io.github.hectorvent.floci.services.ce.CostExplorerJsonHandler;
import io.github.hectorvent.floci.services.pricing.PricingJsonHandler;
import io.github.hectorvent.floci.services.textract.TextractJsonHandler;
import io.github.hectorvent.floci.services.transcribe.TranscribeJsonHandler;
@@ -70,6 +71,7 @@ public class AwsJson11Controller {
private final TextractJsonHandler textractJsonHandler;
private final PricingJsonHandler pricingJsonHandler;
private final TranscribeJsonHandler transcribeJsonHandler;
private final CostExplorerJsonHandler costExplorerJsonHandler;
@Inject
public AwsJson11Controller(ObjectMapper objectMapper, ResolvedServiceCatalog catalog,
@@ -91,7 +93,8 @@ public class AwsJson11Controller {
TransferHandler transferHandler,
TextractJsonHandler textractJsonHandler,
PricingJsonHandler pricingJsonHandler,
TranscribeJsonHandler transcribeJsonHandler) {
TranscribeJsonHandler transcribeJsonHandler,
CostExplorerJsonHandler costExplorerJsonHandler) {
this.objectMapper = objectMapper;
this.catalog = catalog;
this.regionResolver = regionResolver;
@@ -117,6 +120,7 @@ public class AwsJson11Controller {
this.textractJsonHandler = textractJsonHandler;
this.pricingJsonHandler = pricingJsonHandler;
this.transcribeJsonHandler = transcribeJsonHandler;
this.costExplorerJsonHandler = costExplorerJsonHandler;
}
@POST
@@ -167,6 +171,7 @@ public class AwsJson11Controller {
case "textract" -> textractJsonHandler.handle(action, request, region);
case "pricing" -> pricingJsonHandler.handle(action, request, region);
case "transcribe" -> transcribeJsonHandler.handle(action, request, region);
case "ce" -> costExplorerJsonHandler.handle(action, request, region);
default -> null;
};
// catalog.matchTarget is protocol-agnostic: a JSON 1.0 target
@@ -251,7 +251,11 @@ public class ResolvedServiceCatalog {
descriptor("transcribe", "transcribe", config.services().transcribe().enabled(), true,
null, null, 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
Set.of("Transcribe."), Set.of("transcribe"), Set.of(), Set.of())
Set.of("Transcribe."), Set.of("transcribe"), Set.of(), Set.of()),
descriptor("ce", "ce", config.services().ce().enabled(), true,
null, null, 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
Set.of("AWSInsightsIndexService."), Set.of("ce"), Set.of(), Set.of())
));
}
@@ -0,0 +1,48 @@
package io.github.hectorvent.floci.core.common;
import java.time.Instant;
import java.util.stream.Stream;
/**
* SPI for any Floci service that wants to participate in Cost Explorer / CUR
* cost-and-usage reporting.
* <p>
* Implementations are discovered by CDI. Drop a class annotated
* {@code @ApplicationScoped} that implements this interface anywhere on the
* classpath; Cost Explorer auto-injects it via {@code Instance<>}. There is no
* central registration step.
*
* <p>An implementation enumerates the resource state held by its service and
* emits one {@link UsageLine} per (resource, region, usage-type, day) cell that
* was active during the requested period. Lines for unpriced services should
* still be emitted with {@code quantity = 0} — that keeps the service visible
* in {@code GetDimensionValues}({@code SERVICE}) responses without contributing
* to billed cost.
*
* <p>Implementations should be cheap to call repeatedly: Cost Explorer invokes
* {@link #enumerate} per request and does not cache across calls. Implementations
* are responsible for honoring {@code region} themselves; the caller does not
* pre-filter.
*
* <p><b>Usage-type contract:</b> future enumerators should emit AWS-native usage
* types (e.g. {@code BoxUsage:t3.micro}, {@code TimedStorage-Standard},
* {@code AWS-Lambda-Requests}) that match the {@code usagetype} attribute carried
* on the corresponding product offer in the Pricing snapshot. The fallback
* synthesis path in {@code PricingRateLookup} is compatibility-only for
* incomplete external snapshots supplied via
* {@code FLOCI_SERVICES_PRICING_SNAPSHOT_PATH} that omit {@code usagetype}; new
* code should not rely on it.
*/
public interface ResourceUsageEnumerator {
/**
* Returns the usage rows for {@code [periodStart, periodEnd)} in {@code region}.
* The boundaries are half-open: {@code periodStart} inclusive, {@code periodEnd}
* exclusive. Both are UTC instants aligned to a day boundary by the caller.
*
* <p>The stream is consumed eagerly by Cost Explorer; implementations may
* return a closed stream once exhausted. Empty stream is valid (and is the
* default for services with no resources in {@code region}).
*/
Stream<UsageLine> enumerate(Instant periodStart, Instant periodEnd, String region);
}
@@ -0,0 +1,57 @@
package io.github.hectorvent.floci.core.common;
import java.time.Instant;
import java.util.Map;
/**
* One synthesized cost-and-usage row, before Cost Explorer pricing or grouping.
* <p>
* Each Floci service that wants to participate in cost reporting emits these via
* an {@link ResourceUsageEnumerator} bean. Cost Explorer ({@code services/ce})
* and CUR / BCM Data Exports consume the same stream.
* <p>
* Fields map to the AWS CE / CUR dimensions:
* <ul>
* <li>{@link #service()} — {@code Dimension.SERVICE} (e.g. {@code AmazonEC2})</li>
* <li>{@link #region()} — {@code Dimension.REGION}</li>
* <li>{@link #usageType()} — {@code Dimension.USAGE_TYPE}</li>
* <li>{@link #recordType()} — {@code Dimension.RECORD_TYPE}
* (one of {@code Usage}, {@code Credit}, {@code Tax}, {@code Refund},
* {@code DiscountedUsage},
* {@code SavingsPlanCoveredUsage}, {@code SavingsPlanNegation},
* {@code SavingsPlanUpfrontFee}, {@code SavingsPlanRecurringFee})</li>
* <li>{@link #operation()} — {@code Dimension.OPERATION}</li>
* <li>{@link #linkedAccountId()} — {@code Dimension.LINKED_ACCOUNT}</li>
* <li>{@link #resourceId()} — populated when the request asks for resource-level data</li>
* <li>{@link #tags()} — resource tags surfaced into the {@code TAG} group key namespace</li>
* <li>{@link #quantity()} — usage quantity in {@link #usageUnit()} (e.g. {@code Hrs}, {@code GB-Mo})</li>
* <li>{@link #periodStart()} / {@link #periodEnd()} — half-open day window</li>
* </ul>
*
* <p>This is a wire-neutral model. The Cost Explorer service maps it to
* {@code GetCostAndUsage} responses; the CUR service maps it to Parquet rows.
*/
public record UsageLine(
Instant periodStart,
Instant periodEnd,
String service,
String region,
String usageType,
String operation,
String recordType,
String linkedAccountId,
String resourceId,
Map<String, String> tags,
double quantity,
String usageUnit) {
public static final String RECORD_TYPE_USAGE = "Usage";
public static final String RECORD_TYPE_CREDIT = "Credit";
public static final String RECORD_TYPE_TAX = "Tax";
public static final String RECORD_TYPE_REFUND = "Refund";
public static final String RECORD_TYPE_DISCOUNTED_USAGE = "DiscountedUsage";
public static final String RECORD_TYPE_SP_COVERED_USAGE = "SavingsPlanCoveredUsage";
public static final String RECORD_TYPE_SP_NEGATION = "SavingsPlanNegation";
public static final String RECORD_TYPE_SP_UPFRONT_FEE = "SavingsPlanUpfrontFee";
public static final String RECORD_TYPE_SP_RECURRING_FEE = "SavingsPlanRecurringFee";
}
@@ -0,0 +1,47 @@
package io.github.hectorvent.floci.services.ce;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
/**
* JSON 1.1 handler for AWS Cost Explorer operations.
* Dispatches {@code X-Amz-Target: AWSInsightsIndexService.*} actions to
* {@link CostExplorerService}.
*
* @see <a href="https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_Operations_AWS_Cost_Explorer_Service.html">AWS Cost Explorer API</a>
*/
@ApplicationScoped
public class CostExplorerJsonHandler {
private static final Logger LOG = Logger.getLogger(CostExplorerJsonHandler.class);
private final CostExplorerService service;
@Inject
public CostExplorerJsonHandler(CostExplorerService service) {
this.service = service;
}
public Response handle(String action, JsonNode request, String region) {
LOG.debugv("CostExplorer action: {0}", action);
return switch (action) {
case "GetCostAndUsage" -> Response.ok(service.getCostAndUsage(request, region)).build();
case "GetCostAndUsageWithResources" -> Response.ok(service.getCostAndUsageWithResources(request, region)).build();
case "GetDimensionValues" -> Response.ok(service.getDimensionValues(request, region)).build();
case "GetTags" -> Response.ok(service.getTags(request, region)).build();
case "GetReservationCoverage" -> Response.ok(service.getReservationCoverage()).build();
case "GetReservationUtilization" -> Response.ok(service.getReservationUtilization()).build();
case "GetSavingsPlansCoverage" -> Response.ok(service.getSavingsPlansCoverage()).build();
case "GetSavingsPlansUtilization" -> Response.ok(service.getSavingsPlansUtilization()).build();
case "GetCostCategories" -> Response.ok(service.getCostCategories(request)).build();
default -> Response.status(400)
.entity(new AwsErrorResponse("UnknownOperationException",
"Unknown operation: AWSInsightsIndexService." + action))
.build();
};
}
}
@@ -0,0 +1,318 @@
package io.github.hectorvent.floci.services.ce;
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.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.ResourceUsageEnumerator;
import io.github.hectorvent.floci.core.common.UsageLine;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
/**
* AWS Cost Explorer (`ce:*`) emulation.
* <p>
* Synthesizes cost and usage from Floci's own resource state, multiplied by
* the AWS Pricing snapshot served by {@code services/pricing}. Discovery of
* which services contribute to cost is handled by CDI: every
* {@code @ApplicationScoped} bean implementing
* {@link ResourceUsageEnumerator} is auto-injected here, so adding a new
* Floci service with cost reporting needs no change to this class.
*
* @see <a href="https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_Operations_AWS_Cost_Explorer_Service.html">AWS Cost Explorer API</a>
*/
@ApplicationScoped
public class CostExplorerService {
private static final Logger LOG = Logger.getLogger(CostExplorerService.class);
private final ObjectMapper objectMapper;
private final Instance<ResourceUsageEnumerator> enumerators;
private final PricingRateLookup rateLookup;
private final GroupAggregator aggregator;
private final double monthlyCreditUsd;
@Inject
public CostExplorerService(ObjectMapper objectMapper,
Instance<ResourceUsageEnumerator> enumerators,
PricingRateLookup rateLookup,
EmulatorConfig config) {
this(objectMapper, enumerators, rateLookup, config.services().ce().creditUsdMonthly());
}
CostExplorerService(ObjectMapper objectMapper,
Instance<ResourceUsageEnumerator> enumerators,
PricingRateLookup rateLookup,
double monthlyCreditUsd) {
this.objectMapper = objectMapper;
this.enumerators = enumerators;
this.rateLookup = rateLookup;
this.aggregator = new GroupAggregator(objectMapper);
this.monthlyCreditUsd = monthlyCreditUsd;
}
public ObjectNode getCostAndUsage(JsonNode request, String defaultRegion) {
return runCostAndUsage(request, defaultRegion);
}
/**
* Returns the same shape as {@link #getCostAndUsage} for now. Floci's
* resource-level data is already surfaced through the {@code RESOURCE_ID}
* dimension, so a caller that wants resource breakdown can issue
* {@code GetCostAndUsage} with {@code GroupBy=[{Type:DIMENSION,Key:RESOURCE_ID}]}.
* A separate emit path that returns inline resource attributions can land
* later if a consumer needs it.
*/
public ObjectNode getCostAndUsageWithResources(JsonNode request, String defaultRegion) {
return runCostAndUsage(request, defaultRegion);
}
private ObjectNode runCostAndUsage(JsonNode request, String defaultRegion) {
TimeWindow window = parseTimeWindow(request);
TimeBucketing.Granularity granularity = TimeBucketing.parseGranularity(
request.path("Granularity").asText(null));
Set<String> metrics = GroupAggregator.parseMetrics(request.path("Metrics"));
if (metrics.isEmpty()) {
throw new AwsException("ValidationException",
"1 validation error detected: Value at 'Metrics' failed to satisfy constraint: Member must contain at least 1 element.", 400);
}
List<GroupAggregator.GroupBy> groupBys = GroupAggregator.parseGroupBy(request.path("GroupBy"));
JsonNode filter = request.has("Filter") ? request.get("Filter") : null;
List<UsageLine> all = collectLines(window.start(), window.end(), defaultRegion);
// Apply filter once across the full window so the same set is reused
// per bucket (lines are emitted per request scope, no cross-bucket leakage).
List<UsageLine> filtered = new ArrayList<>();
for (UsageLine line : all) {
if (FilterExpressionEvaluator.matches(filter, line)) {
filtered.add(line);
}
}
CostSynthesizer synthesizer = new CostSynthesizer(rateLookup);
if (monthlyCreditUsd > 0) {
CreditLineEmitter creditEmitter = new CreditLineEmitter(monthlyCreditUsd);
List<UsageLine> credits = creditEmitter.emit(filtered.stream(), synthesizer).toList();
for (UsageLine credit : credits) {
if (FilterExpressionEvaluator.matches(filter, credit)) {
filtered.add(credit);
}
}
}
ObjectNode response = objectMapper.createObjectNode();
ArrayNode resultsByTime = response.putArray("ResultsByTime");
for (TimeBucketing.Bucket bucket : TimeBucketing.split(window.start(), window.end(), granularity)) {
List<UsageLine> bucketLines = new ArrayList<>();
for (UsageLine line : filtered) {
if (overlaps(line, bucket)) {
bucketLines.add(scaleToBucket(line, bucket));
}
}
resultsByTime.add(aggregator.buildResultByTime(bucket.start(), bucket.end(),
bucketLines, groupBys, metrics, synthesizer));
}
ArrayNode groupDefinitions = response.putArray("GroupDefinitions");
for (GroupAggregator.GroupBy gb : groupBys) {
ObjectNode def = groupDefinitions.addObject();
def.put("Type", gb.type());
def.put("Key", gb.key());
}
response.putArray("DimensionValueAttributes");
return response;
}
public ObjectNode getDimensionValues(JsonNode request, String defaultRegion) {
TimeWindow window = parseTimeWindow(request);
String dimension = request.path("Dimension").asText(null);
if (dimension == null || dimension.isEmpty()) {
throw new AwsException("ValidationException",
"1 validation error detected: Value at 'Dimension' failed to satisfy constraint: Member must not be null.", 400);
}
String search = request.path("SearchString").asText(null);
JsonNode filter = request.has("Filter") ? request.get("Filter") : null;
Set<String> values = new TreeSet<>();
for (UsageLine line : collectLines(window.start(), window.end(), defaultRegion)) {
if (!FilterExpressionEvaluator.matches(filter, line)) {
continue;
}
String v = FilterExpressionEvaluator.dimensionValue(dimension, line);
if (v != null && !v.isEmpty() && (search == null || v.contains(search))) {
values.add(v);
}
}
ObjectNode response = objectMapper.createObjectNode();
ArrayNode arr = response.putArray("DimensionValues");
for (String v : values) {
ObjectNode entry = arr.addObject();
entry.put("Value", v);
}
response.put("ReturnSize", values.size());
response.put("TotalSize", values.size());
return response;
}
public ObjectNode getTags(JsonNode request, String defaultRegion) {
TimeWindow window = parseTimeWindow(request);
String tagKey = request.path("TagKey").asText(null);
String search = request.path("SearchString").asText(null);
JsonNode filter = request.has("Filter") ? request.get("Filter") : null;
Set<String> values = new TreeSet<>();
Set<String> keys = new TreeSet<>();
for (UsageLine line : collectLines(window.start(), window.end(), defaultRegion)) {
if (!FilterExpressionEvaluator.matches(filter, line)) {
continue;
}
if (line.tags() == null) {
continue;
}
for (Map.Entry<String, String> tag : line.tags().entrySet()) {
keys.add(tag.getKey());
if (tagKey != null && !tagKey.isEmpty()) {
if (tagKey.equals(tag.getKey())
&& (search == null || tag.getValue().contains(search))) {
values.add(tag.getValue());
}
}
}
}
ObjectNode response = objectMapper.createObjectNode();
ArrayNode arr = response.putArray("Tags");
Set<String> emit = (tagKey == null || tagKey.isEmpty()) ? keys : values;
for (String v : emit) {
arr.add(v);
}
response.put("ReturnSize", emit.size());
response.put("TotalSize", emit.size());
return response;
}
public ObjectNode getReservationCoverage() {
ObjectNode response = objectMapper.createObjectNode();
response.putArray("CoveragesByTime");
ObjectNode total = response.putObject("Total");
ObjectNode coverageHours = total.putObject("CoverageHours");
coverageHours.put("OnDemandHours", "0");
coverageHours.put("ReservedHours", "0");
coverageHours.put("TotalRunningHours", "0");
coverageHours.put("CoverageHoursPercentage", "0");
return response;
}
public ObjectNode getReservationUtilization() {
ObjectNode response = objectMapper.createObjectNode();
response.putArray("UtilizationsByTime");
ObjectNode total = response.putObject("Total");
total.put("UtilizationPercentage", "0");
total.put("UtilizationPercentageInUnits", "0");
total.put("PurchasedHours", "0");
total.put("PurchasedUnits", "0");
total.put("TotalActualHours", "0");
total.put("TotalActualUnits", "0");
total.put("UnusedHours", "0");
total.put("UnusedUnits", "0");
total.put("OnDemandCostOfRIHoursUsed", "0");
total.put("NetRISavings", "0");
total.put("TotalPotentialRISavings", "0");
total.put("AmortizedUpfrontFee", "0");
total.put("AmortizedRecurringFee", "0");
total.put("TotalAmortizedFee", "0");
total.put("RICostForUnusedHours", "0");
total.put("RealizedSavings", "0");
total.put("UnrealizedSavings", "0");
return response;
}
public ObjectNode getSavingsPlansCoverage() {
ObjectNode response = objectMapper.createObjectNode();
response.putArray("SavingsPlansCoverages");
return response;
}
public ObjectNode getSavingsPlansUtilization() {
ObjectNode response = objectMapper.createObjectNode();
response.putArray("SavingsPlansUtilizationsByTime");
ObjectNode total = response.putObject("Total");
ObjectNode utilization = total.putObject("Utilization");
utilization.put("TotalCommitment", "0");
utilization.put("UsedCommitment", "0");
utilization.put("UnusedCommitment", "0");
utilization.put("UtilizationPercentage", "0");
return response;
}
public ObjectNode getCostCategories(JsonNode request) {
ObjectNode response = objectMapper.createObjectNode();
response.putArray("CostCategoryNames");
response.putArray("CostCategoryValues");
response.put("ReturnSize", 0);
response.put("TotalSize", 0);
return response;
}
private List<UsageLine> collectLines(Instant start, Instant end, String region) {
List<UsageLine> all = new ArrayList<>();
for (ResourceUsageEnumerator enumerator : enumerators) {
try {
enumerator.enumerate(start, end, region).forEach(all::add);
} catch (Exception e) {
LOG.warnv(e, "Enumerator {0} failed", enumerator.getClass().getSimpleName());
}
}
return all;
}
private TimeWindow parseTimeWindow(JsonNode request) {
JsonNode tp = request.path("TimePeriod");
if (!tp.isObject() || tp.isEmpty()) {
throw new AwsException("ValidationException",
"1 validation error detected: Value at 'TimePeriod' failed to satisfy constraint: Member must not be null.", 400);
}
Instant start = TimeBucketing.parseDate(tp.path("Start").asText(null), "TimePeriod.Start");
Instant end = TimeBucketing.parseDate(tp.path("End").asText(null), "TimePeriod.End");
return new TimeWindow(start, end);
}
private static boolean overlaps(UsageLine line, TimeBucketing.Bucket bucket) {
return line.periodStart().isBefore(bucket.end()) && line.periodEnd().isAfter(bucket.start());
}
/**
* Returns a copy of {@code line} with quantity scaled to the fraction of the
* line's window that falls inside {@code bucket}. Keeps daily/hourly outputs
* proportional when the request window doesn't align to the line's day.
*/
private static UsageLine scaleToBucket(UsageLine line, TimeBucketing.Bucket bucket) {
Instant overlapStart = line.periodStart().isAfter(bucket.start()) ? line.periodStart() : bucket.start();
Instant overlapEnd = line.periodEnd().isBefore(bucket.end()) ? line.periodEnd() : bucket.end();
long lineSeconds = Math.max(1, line.periodEnd().getEpochSecond() - line.periodStart().getEpochSecond());
long overlapSeconds = Math.max(0, overlapEnd.getEpochSecond() - overlapStart.getEpochSecond());
double factor = overlapSeconds / (double) lineSeconds;
return new UsageLine(
bucket.start(), bucket.end(),
line.service(), line.region(), line.usageType(), line.operation(),
line.recordType(), line.linkedAccountId(), line.resourceId(),
line.tags(),
line.quantity() * factor,
line.usageUnit());
}
private record TimeWindow(Instant start, Instant end) {}
}
@@ -0,0 +1,76 @@
package io.github.hectorvent.floci.services.ce;
import io.github.hectorvent.floci.core.common.UsageLine;
import java.util.HashMap;
import java.util.Map;
/**
* Multiplies a {@link UsageLine} by the matching unit price from
* {@link PricingRateLookup} to produce per-metric cost amounts.
* <p>
* AWS exposes five cost metrics — {@code UnblendedCost}, {@code BlendedCost},
* {@code AmortizedCost}, {@code NetUnblendedCost}, {@code NetAmortizedCost} —
* plus {@code UsageQuantity} and {@code NormalizedUsageAmount}. Floci has no
* commitment math, so all five cost metrics return the same value.
*/
class CostSynthesizer {
private final PricingRateLookup rates;
private final Map<String, Map<String, Double>> rateCache = new HashMap<>();
CostSynthesizer(PricingRateLookup rates) {
this.rates = rates;
}
/** Returns a metric-name -> {amount, unit} map for the given line. */
Map<String, MetricValue> compute(UsageLine line) {
double cost;
double quantity;
String quantityUnit;
if (isUsdDenominated(line)) {
// Credit / Refund / SavingsPlan upfront and recurring fees arrive
// already denominated in USD. Treat the line quantity as the cost
// amount directly; do not multiply by a per-unit rate. UsageQuantity
// is reported as zero because AWS does not surface a separate usage
// unit for these record types.
cost = line.quantity();
quantity = 0.0;
quantityUnit = line.usageUnit() == null ? "USD" : line.usageUnit();
} else {
cost = line.quantity() * lookupRate(line);
quantity = line.quantity();
quantityUnit = line.usageUnit();
}
Map<String, MetricValue> metrics = new HashMap<>();
metrics.put("UnblendedCost", new MetricValue(cost, "USD"));
metrics.put("BlendedCost", new MetricValue(cost, "USD"));
metrics.put("AmortizedCost", new MetricValue(cost, "USD"));
metrics.put("NetUnblendedCost", new MetricValue(cost, "USD"));
metrics.put("NetAmortizedCost", new MetricValue(cost, "USD"));
metrics.put("UsageQuantity", new MetricValue(quantity, quantityUnit));
metrics.put("NormalizedUsageAmount", new MetricValue(quantity, quantityUnit));
return metrics;
}
private static boolean isUsdDenominated(UsageLine line) {
String rt = line.recordType();
if (rt == null) {
return false;
}
return UsageLine.RECORD_TYPE_CREDIT.equals(rt)
|| UsageLine.RECORD_TYPE_REFUND.equals(rt)
|| UsageLine.RECORD_TYPE_TAX.equals(rt)
|| UsageLine.RECORD_TYPE_SP_UPFRONT_FEE.equals(rt)
|| UsageLine.RECORD_TYPE_SP_RECURRING_FEE.equals(rt);
}
private double lookupRate(UsageLine line) {
Map<String, Double> svc = rateCache.computeIfAbsent(
line.service() + "|" + line.region(),
key -> rates.ratesFor(line.service(), line.region()));
return svc.getOrDefault(line.usageType(), 0.0);
}
record MetricValue(double amount, String unit) {}
}
@@ -0,0 +1,104 @@
package io.github.hectorvent.floci.services.ce;
import io.github.hectorvent.floci.core.common.UsageLine;
import java.time.Instant;
import java.time.YearMonth;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
/**
* Emits a synthetic {@code Credit} {@code RECORD_TYPE} line per calendar month
* covered by the request, sized at {@code -min(creditUsd, monthly Usage)} so net
* cost never goes below zero.
* <p>
* Configured by {@code FLOCI_SERVICES_CE_CREDIT_USD_MONTHLY}. When zero, no
* credit lines are emitted.
*/
final class CreditLineEmitter {
private final double monthlyCreditUsd;
CreditLineEmitter(double monthlyCreditUsd) {
this.monthlyCreditUsd = monthlyCreditUsd;
}
/**
* Returns a stream of credit lines, one per (region, month) pair where
* {@code lines} contains usage in that region and month.
* Each credit line carries a quantity equal to {@code -monthlyCreditUsd}
* capped at the monthly usage cost, with {@code USD} as the unit.
* <p>
* Each input usage line may span an arbitrary window — enumerators emit one
* line for the whole request period — so the line's cost is split across
* every calendar month its window touches, weighted by the second-overlap
* with each month, before per-month credits are computed.
*/
Stream<UsageLine> emit(Stream<UsageLine> lines, CostSynthesizer synthesizer) {
if (monthlyCreditUsd <= 0) {
return Stream.empty();
}
Map<String, Double> usageCostByKey = new HashMap<>();
Map<String, Instant[]> windowByKey = new HashMap<>();
Map<String, String> regionByKey = new HashMap<>();
Map<String, String> accountByKey = new HashMap<>();
lines.forEach(line -> {
if (!UsageLine.RECORD_TYPE_USAGE.equals(line.recordType())) {
return;
}
double totalCost = synthesizer.compute(line).get("UnblendedCost").amount();
if (totalCost == 0.0) {
return;
}
long lineSeconds = Math.max(1, line.periodEnd().getEpochSecond() - line.periodStart().getEpochSecond());
YearMonth ym = YearMonth.from(line.periodStart().atOffset(ZoneOffset.UTC));
Instant cursor = line.periodStart();
while (cursor.isBefore(line.periodEnd())) {
Instant monthStart = ym.atDay(1).atStartOfDay(ZoneOffset.UTC).toInstant();
Instant monthEnd = ym.plusMonths(1).atDay(1).atStartOfDay(ZoneOffset.UTC).toInstant();
Instant overlapStart = cursor.isAfter(monthStart) ? cursor : monthStart;
Instant overlapEnd = line.periodEnd().isBefore(monthEnd) ? line.periodEnd() : monthEnd;
long overlapSeconds = Math.max(0, overlapEnd.getEpochSecond() - overlapStart.getEpochSecond());
if (overlapSeconds > 0) {
double monthCost = totalCost * (overlapSeconds / (double) lineSeconds);
String key = line.region() + "|" + ym;
usageCostByKey.merge(key, monthCost, Double::sum);
YearMonth captured = ym;
windowByKey.computeIfAbsent(key, k -> new Instant[] {
captured.atDay(1).atStartOfDay(ZoneOffset.UTC).toInstant(),
captured.plusMonths(1).atDay(1).atStartOfDay(ZoneOffset.UTC).toInstant() });
regionByKey.put(key, line.region());
accountByKey.put(key, line.linkedAccountId());
}
cursor = monthEnd;
ym = ym.plusMonths(1);
}
});
List<UsageLine> credits = new ArrayList<>();
for (Map.Entry<String, Double> entry : usageCostByKey.entrySet()) {
String key = entry.getKey();
double appliedCredit = Math.min(monthlyCreditUsd, entry.getValue());
if (appliedCredit <= 0) {
continue;
}
Instant[] window = windowByKey.get(key);
credits.add(new UsageLine(
window[0], window[1],
"Credits", regionByKey.get(key),
"Credit-Promotional", "ApplyPromoCredit",
UsageLine.RECORD_TYPE_CREDIT,
accountByKey.get(key),
null,
Map.of(),
-appliedCredit,
"USD"));
}
return credits.stream();
}
}
@@ -0,0 +1,139 @@
package io.github.hectorvent.floci.services.ce;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.UsageLine;
import java.util.HashSet;
import java.util.Set;
/**
* Recursive evaluator for the AWS Cost Explorer {@code Expression} filter shape:
* {@code {And, Or, Not, Dimensions, Tags, CostCategories}}.
* <p>
* MatchOptions supported:
* <ul>
* <li>{@code EQUALS} — exact equality (default)</li>
* <li>{@code CASE_SENSITIVE} — paired with EQUALS, AWS treats it as the default</li>
* <li>{@code CASE_INSENSITIVE} — case-insensitive equality</li>
* </ul>
* Other AWS match options (e.g. {@code STARTS_WITH}, {@code GREATER_THAN_OR_EQUAL})
* are accepted in the request but treated as EQUALS for now; full coverage can land
* in a follow-up PR.
*/
final class FilterExpressionEvaluator {
static boolean matches(JsonNode expression, UsageLine line) {
if (expression == null || expression.isNull() || expression.isMissingNode()) {
return true;
}
JsonNode and = expression.path("And");
if (and.isArray() && !and.isEmpty()) {
for (JsonNode child : and) {
if (!matches(child, line)) {
return false;
}
}
return true;
}
JsonNode or = expression.path("Or");
if (or.isArray() && !or.isEmpty()) {
for (JsonNode child : or) {
if (matches(child, line)) {
return true;
}
}
return false;
}
JsonNode not = expression.path("Not");
if (not.isObject() && !not.isEmpty()) {
return !matches(not, line);
}
JsonNode dimensions = expression.path("Dimensions");
if (dimensions.isObject() && !dimensions.isEmpty()) {
return matchDimensions(dimensions, line);
}
JsonNode tags = expression.path("Tags");
if (tags.isObject() && !tags.isEmpty()) {
return matchTags(tags, line);
}
JsonNode costCategories = expression.path("CostCategories");
if (costCategories.isObject() && !costCategories.isEmpty()) {
// No cost categories defined — never matches.
return false;
}
return true;
}
private static boolean matchDimensions(JsonNode node, UsageLine line) {
String key = node.path("Key").asText(null);
if (key == null || key.isEmpty()) {
throw new AwsException("ValidationException",
"Dimensions filter requires a Key.", 400);
}
Set<String> values = readValues(node.path("Values"));
Set<String> matchOptions = readValues(node.path("MatchOptions"));
boolean caseInsensitive = matchOptions.contains("CASE_INSENSITIVE");
String actual = dimensionValue(key, line);
return valueMatches(actual, values, caseInsensitive);
}
private static boolean matchTags(JsonNode node, UsageLine line) {
String key = node.path("Key").asText(null);
if (key == null || key.isEmpty()) {
throw new AwsException("ValidationException",
"Tags filter requires a Key.", 400);
}
Set<String> values = readValues(node.path("Values"));
Set<String> matchOptions = readValues(node.path("MatchOptions"));
boolean caseInsensitive = matchOptions.contains("CASE_INSENSITIVE");
String actual = line.tags() == null ? null : line.tags().get(key);
return valueMatches(actual, values, caseInsensitive);
}
private static boolean valueMatches(String actual, Set<String> values, boolean caseInsensitive) {
if (values.isEmpty()) {
return actual != null;
}
if (actual == null) {
return false;
}
if (caseInsensitive) {
for (String v : values) {
if (v.equalsIgnoreCase(actual)) {
return true;
}
}
return false;
}
return values.contains(actual);
}
/** Maps a Cost Explorer dimension name to the equivalent {@link UsageLine} field. */
static String dimensionValue(String dimension, UsageLine line) {
return switch (dimension) {
case "SERVICE", "SERVICE_CODE" -> line.service();
case "REGION" -> line.region();
case "USAGE_TYPE" -> line.usageType();
case "OPERATION" -> line.operation();
case "RECORD_TYPE" -> line.recordType();
case "LINKED_ACCOUNT", "PAYER_ACCOUNT", "LINKED_ACCOUNT_NAME" -> line.linkedAccountId();
case "RESOURCE_ID" -> line.resourceId();
default -> null;
};
}
private static Set<String> readValues(JsonNode arr) {
Set<String> out = new HashSet<>();
if (arr.isArray()) {
for (JsonNode v : arr) {
if (!v.isNull() && !v.asText().isEmpty()) {
out.add(v.asText());
}
}
}
return out;
}
private FilterExpressionEvaluator() {}
}
@@ -0,0 +1,143 @@
package io.github.hectorvent.floci.services.ce;
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.AwsException;
import io.github.hectorvent.floci.core.common.UsageLine;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Aggregates per-bucket usage lines into the AWS Cost Explorer
* {@code ResultsByTime[].Groups} / {@code ResultsByTime[].Total} shape.
*/
final class GroupAggregator {
private final ObjectMapper objectMapper;
GroupAggregator(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
/**
* Builds a single {@code ResultByTime} entry covering {@code [bucketStart, bucketEnd)}
* from the provided lines (already filtered + costed).
*/
ObjectNode buildResultByTime(java.time.Instant bucketStart, java.time.Instant bucketEnd,
List<UsageLine> lines, List<GroupBy> groupBys, Set<String> metrics,
CostSynthesizer synthesizer) {
ObjectNode result = objectMapper.createObjectNode();
ObjectNode timePeriod = result.putObject("TimePeriod");
timePeriod.put("Start", bucketStart.toString());
timePeriod.put("End", bucketEnd.toString());
// Group key -> metric name -> running total
Map<List<String>, Map<String, Double>> groupAmounts = new LinkedHashMap<>();
Map<List<String>, Map<String, String>> groupUnits = new HashMap<>();
Map<String, Double> totalAmounts = new HashMap<>();
Map<String, String> totalUnits = new HashMap<>();
for (UsageLine line : lines) {
Map<String, CostSynthesizer.MetricValue> computed = synthesizer.compute(line);
for (String metric : metrics) {
CostSynthesizer.MetricValue mv = computed.get(metric);
if (mv == null) {
continue;
}
totalAmounts.merge(metric, mv.amount(), Double::sum);
totalUnits.putIfAbsent(metric, mv.unit() == null ? "" : mv.unit());
if (!groupBys.isEmpty()) {
List<String> key = groupKey(groupBys, line);
groupAmounts.computeIfAbsent(key, k -> new HashMap<>())
.merge(metric, mv.amount(), Double::sum);
groupUnits.computeIfAbsent(key, k -> new HashMap<>())
.putIfAbsent(metric, mv.unit() == null ? "" : mv.unit());
}
}
}
ObjectNode totalNode = result.putObject("Total");
for (Map.Entry<String, Double> entry : totalAmounts.entrySet()) {
ObjectNode m = totalNode.putObject(entry.getKey());
m.put("Amount", formatAmount(entry.getValue()));
m.put("Unit", totalUnits.getOrDefault(entry.getKey(), ""));
}
ArrayNode groups = result.putArray("Groups");
for (Map.Entry<List<String>, Map<String, Double>> entry : groupAmounts.entrySet()) {
ObjectNode group = groups.addObject();
ArrayNode keys = group.putArray("Keys");
for (String k : entry.getKey()) {
keys.add(k);
}
ObjectNode m = group.putObject("Metrics");
for (Map.Entry<String, Double> me : entry.getValue().entrySet()) {
ObjectNode mv = m.putObject(me.getKey());
mv.put("Amount", formatAmount(me.getValue()));
mv.put("Unit", groupUnits.get(entry.getKey()).getOrDefault(me.getKey(), ""));
}
}
result.put("Estimated", false);
return result;
}
private static List<String> groupKey(List<GroupBy> groupBys, UsageLine line) {
List<String> out = new ArrayList<>(groupBys.size());
for (GroupBy gb : groupBys) {
out.add(switch (gb.type()) {
case "DIMENSION" -> {
String v = FilterExpressionEvaluator.dimensionValue(gb.key(), line);
yield v == null ? "" : v;
}
case "TAG" -> line.tags() == null ? "" : line.tags().getOrDefault(gb.key(), "");
case "COST_CATEGORY" -> "";
default -> throw new AwsException("ValidationException",
"Unsupported GroupBy.Type: " + gb.type(), 400);
});
}
return out;
}
static List<GroupBy> parseGroupBy(JsonNode node) {
List<GroupBy> out = new ArrayList<>();
if (!node.isArray()) {
return out;
}
for (JsonNode entry : node) {
String type = entry.path("Type").asText("DIMENSION");
String key = entry.path("Key").asText(null);
if (key == null || key.isEmpty()) {
throw new AwsException("ValidationException",
"GroupBy entries must include a Key.", 400);
}
out.add(new GroupBy(type, key));
}
return out;
}
static Set<String> parseMetrics(JsonNode node) {
Set<String> out = new java.util.LinkedHashSet<>();
if (node.isArray()) {
for (JsonNode v : node) {
if (!v.isNull() && !v.asText().isEmpty()) {
out.add(v.asText());
}
}
}
return out;
}
static String formatAmount(double amount) {
// AWS returns amounts as decimal strings.
return String.format(java.util.Locale.ROOT, "%.10f", amount);
}
record GroupBy(String type, String key) {}
}
@@ -0,0 +1,134 @@
package io.github.hectorvent.floci.services.ce;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.services.pricing.PricingService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Looks up unit prices from the bundled {@link PricingService} snapshot.
* Used by {@link CostSynthesizer} to attach a USD rate to each
* {@link io.github.hectorvent.floci.core.common.UsageLine}.
*
* <p>Maps a {@code (serviceCode, regionCode, usageType)} key to {@code USD per unit}.
* Cache is sized per {@code (serviceCode, regionCode)} pair on first hit and reused
* for the lifetime of the request — the snapshot itself is read-only.
*/
@ApplicationScoped
public class PricingRateLookup {
private static final Logger LOG = Logger.getLogger(PricingRateLookup.class);
private final PricingService pricing;
private final ObjectMapper objectMapper;
@Inject
public PricingRateLookup(PricingService pricing, ObjectMapper objectMapper) {
this.pricing = pricing;
this.objectMapper = objectMapper;
}
/**
* Returns USD-per-unit for {@code usageType} under {@code (serviceCode, regionCode)}.
* Returns {@code 0.0} when no matching offer exists in the snapshot.
*/
public double rate(String serviceCode, String regionCode, String usageType) {
return ratesFor(serviceCode, regionCode).getOrDefault(usageType, 0.0);
}
/** Returns the full {@code usageType -> USD/unit} map for a (service, region) pair. */
public Map<String, Double> ratesFor(String serviceCode, String regionCode) {
Map<String, Double> result = new HashMap<>();
try {
ObjectNode response = pricing.getProducts(
serviceCode,
List.of(new PricingService.FilterSpec("TERM_MATCH", "regionCode", regionCode)),
null,
null,
1000);
JsonNode priceList = response.path("PriceList");
if (!priceList.isArray()) {
return result;
}
for (JsonNode entry : priceList) {
JsonNode product;
try {
product = objectMapper.readTree(entry.asText());
} catch (Exception e) {
continue;
}
String usageType = product.path("product").path("attributes").path("usagetype").asText(null);
if (usageType == null || usageType.isEmpty()) {
// Fallback for user-supplied snapshots that don't include
// a usagetype attribute. The bundled fixtures populate it
// directly, so this path applies only to externally provided
// snapshots via FLOCI_SERVICES_PRICING_SNAPSHOT_PATH.
usageType = synthesizeUsageType(product, serviceCode);
}
if (usageType == null) {
continue;
}
double rate = extractOnDemandRate(product.path("terms"));
if (rate > 0) {
result.merge(usageType, rate, Double::max);
}
}
} catch (Exception e) {
LOG.warnv(e, "Pricing rate lookup failed for {0}/{1}", serviceCode, regionCode);
}
return result;
}
/**
* Returns a synthesized usage-type key for a product offer that doesn't carry
* the {@code usagetype} attribute. Compatibility-only fallback for incomplete
* external snapshots; bundled fixtures populate {@code usagetype} directly,
* and future enumerators should emit AWS-native usage types that match the
* snapshot's real {@code usagetype} attribute rather than relying on this
* synthesis path.
*/
private static String synthesizeUsageType(JsonNode product, String serviceCode) {
JsonNode attrs = product.path("product").path("attributes");
return switch (serviceCode) {
case "AmazonEC2" -> "BoxUsage:" + attrs.path("instanceType").asText("");
case "AmazonS3" -> "TimedStorage-" + attrs.path("volumeType").asText("");
case "AWSLambda" -> attrs.path("group").asText("AWS-Lambda-Requests");
default -> null;
};
}
private static double extractOnDemandRate(JsonNode terms) {
JsonNode onDemand = terms.path("OnDemand");
if (!onDemand.isObject()) {
return 0.0;
}
java.util.Iterator<java.util.Map.Entry<String, JsonNode>> termIter = onDemand.fields();
while (termIter.hasNext()) {
JsonNode dimensions = termIter.next().getValue().path("priceDimensions");
if (!dimensions.isObject()) {
continue;
}
java.util.Iterator<java.util.Map.Entry<String, JsonNode>> dimIter = dimensions.fields();
while (dimIter.hasNext()) {
JsonNode dim = dimIter.next().getValue();
String usd = dim.path("pricePerUnit").path("USD").asText("0");
try {
double v = Double.parseDouble(usd);
if (v > 0) {
return v;
}
} catch (NumberFormatException ignored) {
// skip malformed entries
}
}
}
return 0.0;
}
}
@@ -0,0 +1,141 @@
package io.github.hectorvent.floci.services.ce;
import io.github.hectorvent.floci.core.common.AwsException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.YearMonth;
import java.time.ZoneOffset;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;
/**
* Splits a Cost Explorer {@code TimePeriod} into AWS-shaped granularity buckets.
* <p>
* AWS truncates {@code Start}/{@code End} to whole-day boundaries for DAILY
* and HOURLY, and to the first day of the month for MONTHLY. The window is
* half-open: {@code Start} inclusive, {@code End} exclusive.
*/
final class TimeBucketing {
enum Granularity { HOURLY, DAILY, MONTHLY }
static Granularity parseGranularity(String value) {
if (value == null || value.isEmpty()) {
throw new AwsException("ValidationException",
"1 validation error detected: Value at 'Granularity' failed to satisfy constraint: Member must not be null.", 400);
}
return switch (value) {
case "HOURLY" -> Granularity.HOURLY;
case "DAILY" -> Granularity.DAILY;
case "MONTHLY" -> Granularity.MONTHLY;
default -> throw new AwsException("ValidationException",
"1 validation error detected: Value '" + value + "' at 'Granularity' failed to satisfy constraint: Member must satisfy enum value set: [DAILY, MONTHLY, HOURLY]", 400);
};
}
static Instant parseDate(String value, String field) {
if (value == null || value.isEmpty()) {
throw new AwsException("ValidationException",
"1 validation error detected: Value at '" + field + "' failed to satisfy constraint: Member must not be null.", 400);
}
// AWS accepts "YYYY-MM-DD" (most common) and ISO-8601 timestamps.
try {
return LocalDate.parse(value).atStartOfDay(ZoneOffset.UTC).toInstant();
} catch (DateTimeParseException ignored) {
// fall through
}
try {
return OffsetDateTime.parse(value).toInstant();
} catch (DateTimeParseException ignored) {
// fall through
}
try {
return LocalDateTime.parse(value).toInstant(ZoneOffset.UTC);
} catch (DateTimeParseException e) {
throw new AwsException("ValidationException",
field + " must be a YYYY-MM-DD date or ISO-8601 timestamp.", 400);
}
}
/** A half-open [start, end) bucket aligned to the requested granularity. */
record Bucket(Instant start, Instant end) {}
static List<Bucket> split(Instant start, Instant end, Granularity granularity) {
if (!end.isAfter(start)) {
throw new AwsException("DataUnavailableException",
"End date must be after Start date.", 400);
}
// Truncate Start down and End up to the granularity boundary so every
// emitted bucket aligns to the period AWS would return.
Instant alignedStart = floor(start, granularity);
Instant alignedEnd = ceil(end, granularity);
return switch (granularity) {
case HOURLY -> splitHourly(alignedStart, alignedEnd);
case DAILY -> splitDaily(alignedStart, alignedEnd);
case MONTHLY -> splitMonthly(alignedStart, alignedEnd);
};
}
private static Instant floor(Instant instant, Granularity granularity) {
return switch (granularity) {
case HOURLY -> instant.truncatedTo(java.time.temporal.ChronoUnit.HOURS);
case DAILY -> instant.truncatedTo(java.time.temporal.ChronoUnit.DAYS);
case MONTHLY -> YearMonth.from(instant.atOffset(ZoneOffset.UTC))
.atDay(1).atStartOfDay(ZoneOffset.UTC).toInstant();
};
}
private static Instant ceil(Instant instant, Granularity granularity) {
Instant floored = floor(instant, granularity);
if (floored.equals(instant)) {
return instant;
}
return switch (granularity) {
case HOURLY -> floored.plusSeconds(3600);
case DAILY -> floored.plus(java.time.Duration.ofDays(1));
case MONTHLY -> YearMonth.from(floored.atOffset(ZoneOffset.UTC))
.plusMonths(1).atDay(1).atStartOfDay(ZoneOffset.UTC).toInstant();
};
}
private static List<Bucket> splitHourly(Instant start, Instant end) {
List<Bucket> out = new ArrayList<>();
Instant cursor = start;
while (cursor.isBefore(end)) {
Instant next = cursor.plusSeconds(3600);
out.add(new Bucket(cursor, next.isAfter(end) ? end : next));
cursor = next;
}
return out;
}
private static List<Bucket> splitDaily(Instant start, Instant end) {
List<Bucket> out = new ArrayList<>();
Instant cursor = start;
while (cursor.isBefore(end)) {
Instant next = cursor.plus(java.time.Duration.ofDays(1));
out.add(new Bucket(cursor, next.isAfter(end) ? end : next));
cursor = next;
}
return out;
}
private static List<Bucket> splitMonthly(Instant start, Instant end) {
List<Bucket> out = new ArrayList<>();
YearMonth ym = YearMonth.from(start.atOffset(ZoneOffset.UTC));
Instant cursor = start;
while (cursor.isBefore(end)) {
ym = ym.plusMonths(1);
Instant next = ym.atDay(1).atStartOfDay(ZoneOffset.UTC).toInstant();
out.add(new Bucket(cursor, next.isAfter(end) ? end : next));
cursor = next;
}
return out;
}
private TimeBucketing() {}
}
@@ -0,0 +1,100 @@
package io.github.hectorvent.floci.services.ce.enumerator;
import io.github.hectorvent.floci.core.common.ResourceUsageEnumerator;
import io.github.hectorvent.floci.core.common.UsageLine;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.github.hectorvent.floci.services.ec2.model.Reservation;
import io.github.hectorvent.floci.services.ec2.model.Tag;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
/**
* Enumerates running EC2 instances as Cost Explorer usage lines.
* Emits one {@code Hrs} line per instance per region, sized to the requested period.
*/
@ApplicationScoped
public class Ec2UsageEnumerator implements ResourceUsageEnumerator {
static final String SERVICE_CODE = "AmazonEC2";
private final Ec2Service ec2;
@Inject
public Ec2UsageEnumerator(Ec2Service ec2) {
this.ec2 = ec2;
}
@Override
public Stream<UsageLine> enumerate(Instant periodStart, Instant periodEnd, String region) {
List<Reservation> reservations = ec2.describeInstances(region, List.of(), Map.of());
Stream.Builder<UsageLine> out = Stream.builder();
// Use seconds with fractional-hour conversion so HOURLY queries with
// non-aligned windows (e.g. 90 minutes) and sub-hour windows still
// surface the correct partial-hour quantity.
long periodSeconds = Duration.between(periodStart, periodEnd).toSeconds();
if (periodSeconds <= 0) {
return Stream.empty();
}
double hours = periodSeconds / 3600.0;
// Always emit a zero-quantity catalog line so the service surfaces in
// GetDimensionValues SERVICE even when no instances are running.
out.add(catalogLine(periodStart, periodEnd, region));
for (Reservation reservation : reservations) {
String accountId = reservation.getOwnerId() != null ? reservation.getOwnerId() : "000000000000";
for (Instance instance : reservation.getInstances()) {
// AWS only bills BoxUsage hours for instances in the running state.
// pending / stopping / stopped / shutting-down / terminated incur no
// instance-hour cost (storage and other dimensions are billed separately
// and are out of scope for this enumerator).
if (instance.getState() == null
|| !"running".equalsIgnoreCase(instance.getState().getName())) {
continue;
}
String instanceType = instance.getInstanceType();
if (instanceType == null || instanceType.isEmpty()) {
continue;
}
String usageType = "BoxUsage:" + instanceType;
Map<String, String> tags = collectTags(instance);
out.add(new UsageLine(
periodStart, periodEnd,
SERVICE_CODE, region,
usageType, "RunInstances",
UsageLine.RECORD_TYPE_USAGE,
accountId,
instance.getInstanceId(),
tags,
hours,
"Hrs"));
}
}
return out.build();
}
private static UsageLine catalogLine(Instant start, Instant end, String region) {
return new UsageLine(start, end, SERVICE_CODE, region,
"BoxUsage", "RunInstances",
UsageLine.RECORD_TYPE_USAGE, "000000000000", null, Map.of(),
0.0, "Hrs");
}
private static Map<String, String> collectTags(Instance instance) {
Map<String, String> tags = new HashMap<>();
if (instance.getTags() != null) {
for (Tag tag : instance.getTags()) {
if (tag.getKey() != null) {
tags.put(tag.getKey(), tag.getValue() == null ? "" : tag.getValue());
}
}
}
return tags;
}
}
@@ -0,0 +1,67 @@
package io.github.hectorvent.floci.services.ce.enumerator;
import io.github.hectorvent.floci.core.common.ResourceUsageEnumerator;
import io.github.hectorvent.floci.core.common.UsageLine;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
/**
* Enumerates Lambda functions as Cost Explorer usage lines.
* Floci does not measure real invocation count or duration in this PR; each
* function emits a zero-quantity line so the function still surfaces in
* {@code GetDimensionValues SERVICE} responses without billed cost. The shape
* is in place for a follow-up PR that tracks invocations.
*/
@ApplicationScoped
public class LambdaUsageEnumerator implements ResourceUsageEnumerator {
static final String SERVICE_CODE = "AWSLambda";
private final LambdaService lambdaService;
@Inject
public LambdaUsageEnumerator(LambdaService lambdaService) {
this.lambdaService = lambdaService;
}
@Override
public Stream<UsageLine> enumerate(Instant periodStart, Instant periodEnd, String region) {
if (Duration.between(periodStart, periodEnd).toSeconds() <= 0) {
return Stream.empty();
}
List<LambdaFunction> functions = lambdaService.listFunctions(region);
Stream.Builder<UsageLine> out = Stream.builder();
// Always emit a zero-quantity catalog line so the service surfaces in
// GetDimensionValues SERVICE even when no functions exist.
out.add(new UsageLine(periodStart, periodEnd,
SERVICE_CODE, region,
"AWS-Lambda-Requests", "Invoke",
UsageLine.RECORD_TYPE_USAGE,
"000000000000", null, new HashMap<>(),
0.0, "Requests"));
for (LambdaFunction fn : functions) {
Map<String, String> tags = fn.getTags() == null ? new HashMap<>() : new HashMap<>(fn.getTags());
String accountId = fn.getAccountId() != null ? fn.getAccountId() : "000000000000";
out.add(new UsageLine(
periodStart, periodEnd,
SERVICE_CODE, region,
"AWS-Lambda-Requests", "Invoke",
UsageLine.RECORD_TYPE_USAGE,
accountId,
fn.getFunctionArn(),
tags,
0.0,
"Requests"));
}
return out.build();
}
}
@@ -0,0 +1,99 @@
package io.github.hectorvent.floci.services.ce.enumerator;
import io.github.hectorvent.floci.core.common.ResourceUsageEnumerator;
import io.github.hectorvent.floci.core.common.UsageLine;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.Bucket;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
/**
* Enumerates S3 buckets as Cost Explorer storage-usage lines.
* Aggregates object sizes per bucket and emits one {@code GB-Mo} line scaled
* to the fraction of a 30-day month covered by the requested period.
*/
@ApplicationScoped
public class S3UsageEnumerator implements ResourceUsageEnumerator {
static final String SERVICE_CODE = "AmazonS3";
/**
* AWS-native usage type for S3 Standard-class storage. Must match the
* {@code usagetype} attribute on the corresponding product offer in the
* Pricing snapshot.
*/
static final String STANDARD_STORAGE_USAGE_TYPE = "TimedStorage-Standard";
private static final double BYTES_PER_GB = 1_073_741_824.0;
private static final double SECONDS_PER_MONTH = 30.0 * 86_400.0;
private final S3Service s3;
@Inject
public S3UsageEnumerator(S3Service s3) {
this.s3 = s3;
}
@Override
public Stream<UsageLine> enumerate(Instant periodStart, Instant periodEnd, String region) {
long periodSeconds = Duration.between(periodStart, periodEnd).toSeconds();
if (periodSeconds <= 0) {
return Stream.empty();
}
double monthFraction = periodSeconds / SECONDS_PER_MONTH;
List<Bucket> buckets = s3.listBuckets();
Stream.Builder<UsageLine> out = Stream.builder();
// Always emit a zero-quantity catalog line so the service surfaces in
// GetDimensionValues SERVICE even when no buckets are present.
out.add(new UsageLine(periodStart, periodEnd, SERVICE_CODE, region,
STANDARD_STORAGE_USAGE_TYPE, "StandardStorage",
UsageLine.RECORD_TYPE_USAGE, "000000000000", null, new HashMap<>(),
0.0, "GB-Mo"));
for (Bucket bucket : buckets) {
String bucketRegion = bucket.getRegion();
if (bucketRegion == null) {
bucketRegion = "us-east-1";
}
if (!bucketRegion.equals(region)) {
continue;
}
double totalGb = totalBucketGb(bucket.getName());
if (totalGb <= 0) {
continue;
}
double gbMonths = totalGb * monthFraction;
Map<String, String> tags = bucket.getTags() == null ? new HashMap<>() : new HashMap<>(bucket.getTags());
out.add(new UsageLine(
periodStart, periodEnd,
SERVICE_CODE, region,
STANDARD_STORAGE_USAGE_TYPE, "StandardStorage",
UsageLine.RECORD_TYPE_USAGE,
"000000000000",
"arn:aws:s3:::" + bucket.getName(),
tags,
gbMonths,
"GB-Mo"));
}
return out.build();
}
private double totalBucketGb(String bucketName) {
try {
List<S3Object> objects = s3.listObjects(bucketName, null, null, Integer.MAX_VALUE);
long bytes = 0;
for (S3Object obj : objects) {
bytes += Math.max(0, obj.getSize());
}
return bytes / BYTES_PER_GB;
} catch (RuntimeException ignored) {
return 0.0;
}
}
}
@@ -0,0 +1,80 @@
package io.github.hectorvent.floci.services.ce.enumerator;
import io.github.hectorvent.floci.core.common.ResourceUsageEnumerator;
import io.github.hectorvent.floci.core.common.UsageLine;
import jakarta.enterprise.context.ApplicationScoped;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
/**
* Emits zero-quantity placeholder lines for Floci services that don't have
* unit-price data in the bundled snapshot yet. Keeps these services discoverable
* via {@code GetDimensionValues SERVICE} without contributing billed cost.
*
* <p>Each service ships its own AWS-shaped {@code ServiceCode} per the AWS Price
* List naming convention.
*/
@ApplicationScoped
public class UnpricedServicesEnumerator implements ResourceUsageEnumerator {
/**
* AWS Price List service codes for the Floci services Floci's pricing snapshot
* does not yet cover. Update when a new {@code *UsageEnumerator} bean lands
* with rate data.
*/
private static final List<String> SERVICE_CODES = List.of(
"AmazonDynamoDB",
"AmazonSQS",
"AmazonSNS",
"AmazonSES",
"AmazonKinesis",
"AmazonKinesisFirehose",
"AWSSecretsManager",
"AmazonCloudWatch",
"AWSCloudFormation",
"AmazonAPIGateway",
"AWSStepFunctions",
"AmazonECR",
"AmazonECS",
"AmazonEKS",
"AmazonRDS",
"AmazonElastiCache",
"AmazonOpenSearchService",
"AmazonAthena",
"AWSGlue",
"AWSEvents",
"AmazonCognito",
"AWSCodeBuild",
"AWSCodeDeploy",
"AmazonRoute53",
"AWSCertificateManager",
"AWSKeyManagementService",
"AWSBackup",
"AWSTransfer",
"AmazonMSK",
"AWSSystemsManager",
"AWSAppConfig",
"AmazonTextract",
"AmazonBedrock");
@Override
public Stream<UsageLine> enumerate(Instant periodStart, Instant periodEnd, String region) {
if (Duration.between(periodStart, periodEnd).toSeconds() <= 0) {
return Stream.empty();
}
return SERVICE_CODES.stream().map(code -> new UsageLine(
periodStart, periodEnd,
code, region,
"Unknown", "Unknown",
UsageLine.RECORD_TYPE_USAGE,
"000000000000",
null,
Map.of(),
0.0,
"Unknown"));
}
}