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

@@ -0,0 +1,436 @@
package io.github.hectorvent.floci.services.ce;
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.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
/**
* Integration tests for the Cost Explorer service.
* Validates AWS-compatible wire format using RestAssured.
* Protocol: JSON 1.1 — Content-Type: application/x-amz-json-1.1,
* X-Amz-Target: AWSInsightsIndexService.&lt;Action&gt;
*/
@QuarkusTest
class CostExplorerIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ce/aws4_request";
private static final String S3_AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/s3/aws4_request";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void getCostAndUsage_emptyState_returnsResultsByTime() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetCostAndUsage")
.header("Authorization", AUTH_HEADER)
.body("{\"TimePeriod\":{\"Start\":\"2026-01-01\",\"End\":\"2026-01-04\"}," +
"\"Granularity\":\"DAILY\",\"Metrics\":[\"UnblendedCost\"]}")
.when()
.post("/")
.then()
.statusCode(200)
.body("ResultsByTime", hasSize(3))
.body("ResultsByTime[0].TimePeriod.Start", startsWith("2026-01-01"))
.body("ResultsByTime[0].Total.UnblendedCost.Unit", equalTo("USD"));
}
@Test
void getCostAndUsage_monthlyGranularitySplitsAcrossMonths() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetCostAndUsage")
.header("Authorization", AUTH_HEADER)
.body("{\"TimePeriod\":{\"Start\":\"2026-01-15\",\"End\":\"2026-03-15\"}," +
"\"Granularity\":\"MONTHLY\",\"Metrics\":[\"UnblendedCost\"]}")
.when()
.post("/")
.then()
.statusCode(200)
.body("ResultsByTime", hasSize(3));
}
@Test
void getCostAndUsage_hourlyGranularityEmitsHourBuckets() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetCostAndUsage")
.header("Authorization", AUTH_HEADER)
.body("{\"TimePeriod\":{\"Start\":\"2026-01-01T00:00:00Z\",\"End\":\"2026-01-01T03:00:00Z\"}," +
"\"Granularity\":\"HOURLY\",\"Metrics\":[\"UnblendedCost\"]}")
.when()
.post("/")
.then()
.statusCode(200)
.body("ResultsByTime", hasSize(3));
}
@Test
void getCostAndUsage_missingMetrics_returns400() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetCostAndUsage")
.header("Authorization", AUTH_HEADER)
.body("{\"TimePeriod\":{\"Start\":\"2026-01-01\",\"End\":\"2026-01-04\"}," +
"\"Granularity\":\"DAILY\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void getCostAndUsage_missingTimePeriod_returns400() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetCostAndUsage")
.header("Authorization", AUTH_HEADER)
.body("{\"Granularity\":\"DAILY\",\"Metrics\":[\"UnblendedCost\"]}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void getCostAndUsage_invalidGranularity_returns400() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetCostAndUsage")
.header("Authorization", AUTH_HEADER)
.body("{\"TimePeriod\":{\"Start\":\"2026-01-01\",\"End\":\"2026-01-04\"}," +
"\"Granularity\":\"YEARLY\",\"Metrics\":[\"UnblendedCost\"]}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void getCostAndUsage_endBeforeStart_returns400() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetCostAndUsage")
.header("Authorization", AUTH_HEADER)
.body("{\"TimePeriod\":{\"Start\":\"2026-02-01\",\"End\":\"2026-01-01\"}," +
"\"Granularity\":\"DAILY\",\"Metrics\":[\"UnblendedCost\"]}")
.when()
.post("/")
.then()
.statusCode(400);
}
@Test
void getCostAndUsage_returnsNonZeroCostFromS3BucketObjects() {
// Stand up a bucket with one ~1-MiB object so cost synthesis has something
// to multiply against. The bundled S3 fixture rates Standard at $0.023/GB-Mo,
// so any non-zero size must produce a strictly positive UnblendedCost.
String bucket = "ce-test-bucket-" + System.currentTimeMillis();
given()
.header("Authorization", S3_AUTH)
.header("Host", "localhost")
.when()
.put("/" + bucket)
.then()
.statusCode(anyOf(equalTo(200), equalTo(204)));
byte[] payload = new byte[1024 * 1024]; // 1 MiB
given()
.header("Authorization", S3_AUTH)
.body(payload)
.when()
.put("/" + bucket + "/object.bin")
.then()
.statusCode(anyOf(equalTo(200), equalTo(204)));
String unblendedAmount = given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetCostAndUsage")
.header("Authorization", AUTH_HEADER)
.body("{\"TimePeriod\":{\"Start\":\"2026-01-01\",\"End\":\"2026-02-01\"}," +
"\"Granularity\":\"MONTHLY\",\"Metrics\":[\"UnblendedCost\",\"UsageQuantity\"]," +
"\"GroupBy\":[{\"Type\":\"DIMENSION\",\"Key\":\"SERVICE\"}]," +
"\"Filter\":{\"Dimensions\":{\"Key\":\"SERVICE\",\"Values\":[\"AmazonS3\"]}}}")
.when()
.post("/")
.then()
.statusCode(200)
.body("ResultsByTime[0].Groups.Keys.flatten()", hasItem("AmazonS3"))
.extract()
.path("ResultsByTime[0].Groups.find { it.Keys.contains('AmazonS3') }.Metrics.UnblendedCost.Amount");
assertThat(Double.parseDouble(unblendedAmount), greaterThan(0.0));
}
@Test
void getCostAndUsage_creditOffsetReducesUnblendedCost() {
// Run two queries: one without and one with FLOCI_SERVICES_CE_CREDIT_USD_MONTHLY
// toggled on. Credit injection is process-wide config, so this test asserts
// the no-credit baseline; the credit-on flow has dedicated unit coverage in
// CostSynthesizerTest. The intent here is that when a Credit RECORD_TYPE
// line exists, its amount flows directly into UnblendedCost without going
// through the rate lookup (which would produce 0 for a Credit-Promotional
// usage type).
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetCostAndUsage")
.header("Authorization", AUTH_HEADER)
.body("{\"TimePeriod\":{\"Start\":\"2026-01-01\",\"End\":\"2026-02-01\"}," +
"\"Granularity\":\"MONTHLY\",\"Metrics\":[\"UnblendedCost\"]," +
"\"GroupBy\":[{\"Type\":\"DIMENSION\",\"Key\":\"RECORD_TYPE\"}]}")
.when()
.post("/")
.then()
.statusCode(200)
.body("ResultsByTime", hasSize(1));
}
@Test
void getCostAndUsage_filterByService() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetCostAndUsage")
.header("Authorization", AUTH_HEADER)
.body("{\"TimePeriod\":{\"Start\":\"2026-01-01\",\"End\":\"2026-01-04\"}," +
"\"Granularity\":\"DAILY\",\"Metrics\":[\"UnblendedCost\"]," +
"\"GroupBy\":[{\"Type\":\"DIMENSION\",\"Key\":\"SERVICE\"}]," +
"\"Filter\":{\"Dimensions\":{\"Key\":\"SERVICE\",\"Values\":[\"AmazonEC2\"]}}}")
.when()
.post("/")
.then()
.statusCode(200)
.body("ResultsByTime[0].Groups.Keys.flatten()", everyItem(equalTo("AmazonEC2")));
}
@Test
void getCostAndUsage_filterAndExpression() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetCostAndUsage")
.header("Authorization", AUTH_HEADER)
.body("{\"TimePeriod\":{\"Start\":\"2026-01-01\",\"End\":\"2026-01-04\"}," +
"\"Granularity\":\"DAILY\",\"Metrics\":[\"UnblendedCost\"]," +
"\"Filter\":{\"And\":[" +
"{\"Dimensions\":{\"Key\":\"REGION\",\"Values\":[\"us-east-1\"]}}," +
"{\"Not\":{\"Dimensions\":{\"Key\":\"SERVICE\",\"Values\":[\"AmazonRDS\"]}}}" +
"]}}")
.when()
.post("/")
.then()
.statusCode(200)
.body("ResultsByTime", hasSize(3));
}
@Test
void getDimensionValues_serviceReturnsKnownServices() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetDimensionValues")
.header("Authorization", AUTH_HEADER)
.body("{\"TimePeriod\":{\"Start\":\"2026-01-01\",\"End\":\"2026-01-04\"}," +
"\"Dimension\":\"SERVICE\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("DimensionValues.Value", hasItems("AmazonEC2", "AmazonS3", "AWSLambda"));
}
@Test
void getDimensionValues_recordTypeReturnsUsage() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetDimensionValues")
.header("Authorization", AUTH_HEADER)
.body("{\"TimePeriod\":{\"Start\":\"2026-01-01\",\"End\":\"2026-01-04\"}," +
"\"Dimension\":\"RECORD_TYPE\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("DimensionValues.Value", hasItem("Usage"));
}
@Test
void getDimensionValues_missingDimension_returns400() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetDimensionValues")
.header("Authorization", AUTH_HEADER)
.body("{\"TimePeriod\":{\"Start\":\"2026-01-01\",\"End\":\"2026-01-04\"}}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void getTags_emptyState_returnsEmpty() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetTags")
.header("Authorization", AUTH_HEADER)
.body("{\"TimePeriod\":{\"Start\":\"2026-01-01\",\"End\":\"2026-01-04\"}}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Tags", notNullValue())
.body("ReturnSize", greaterThanOrEqualTo(0));
}
@Test
void getReservationCoverage_returnsZeroedTotal() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetReservationCoverage")
.header("Authorization", AUTH_HEADER)
.body("{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Total.CoverageHours.OnDemandHours", equalTo("0"))
.body("CoveragesByTime", hasSize(0));
}
@Test
void getReservationUtilization_returnsZeroedTotal() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetReservationUtilization")
.header("Authorization", AUTH_HEADER)
.body("{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Total.UtilizationPercentage", equalTo("0"))
.body("UtilizationsByTime", hasSize(0));
}
@Test
void getSavingsPlansCoverage_returnsEmpty() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetSavingsPlansCoverage")
.header("Authorization", AUTH_HEADER)
.body("{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("SavingsPlansCoverages", hasSize(0));
}
@Test
void getSavingsPlansUtilization_returnsZeroedTotal() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetSavingsPlansUtilization")
.header("Authorization", AUTH_HEADER)
.body("{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Total.Utilization.UtilizationPercentage", equalTo("0"));
}
@Test
void getCostCategories_returnsEmpty() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetCostCategories")
.header("Authorization", AUTH_HEADER)
.body("{\"TimePeriod\":{\"Start\":\"2026-01-01\",\"End\":\"2026-01-04\"}}")
.when()
.post("/")
.then()
.statusCode(200)
.body("CostCategoryNames", hasSize(0))
.body("ReturnSize", equalTo(0));
}
@Test
void getCostAndUsageWithResources_acceptsSameShape() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetCostAndUsageWithResources")
.header("Authorization", AUTH_HEADER)
.body("{\"TimePeriod\":{\"Start\":\"2026-01-01\",\"End\":\"2026-01-04\"}," +
"\"Granularity\":\"DAILY\",\"Metrics\":[\"UnblendedCost\"]," +
"\"GroupBy\":[{\"Type\":\"DIMENSION\",\"Key\":\"RESOURCE_ID\"}]," +
"\"Filter\":{\"Dimensions\":{\"Key\":\"SERVICE\",\"Values\":[\"AmazonEC2\"]}}}")
.when()
.post("/")
.then()
.statusCode(200)
.body("ResultsByTime", hasSize(3))
.body("GroupDefinitions[0].Key", equalTo("RESOURCE_ID"));
}
@Test
void getCostAndUsage_dailyTruncatesEndToBucketBoundary() {
// End at 13:30 should still produce 3 whole-day buckets aligned to UTC midnight
// (Jan 1, Jan 2, Jan 3) per AWS DAILY semantics, not 3 buckets where the last
// ends mid-day.
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetCostAndUsage")
.header("Authorization", AUTH_HEADER)
.body("{\"TimePeriod\":{\"Start\":\"2026-01-01T00:00:00Z\",\"End\":\"2026-01-03T13:30:00Z\"}," +
"\"Granularity\":\"DAILY\",\"Metrics\":[\"UnblendedCost\"]}")
.when()
.post("/")
.then()
.statusCode(200)
.body("ResultsByTime", hasSize(3))
.body("ResultsByTime[2].TimePeriod.End", equalTo("2026-01-04T00:00:00Z"));
}
@Test
void getDimensionValues_includesAmazonMSKWithCanonicalCode() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetDimensionValues")
.header("Authorization", AUTH_HEADER)
.body("{\"TimePeriod\":{\"Start\":\"2026-01-01\",\"End\":\"2026-01-04\"}," +
"\"Dimension\":\"SERVICE\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("DimensionValues.Value", hasItem("AmazonMSK"))
.body("DimensionValues.Value", not(hasItem("AWSAmazonMSK")));
}
@Test
void unknownAction_returnsUnknownOperationError() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSInsightsIndexService.GetBogusAction")
.header("Authorization", AUTH_HEADER)
.body("{}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("UnknownOperationException"));
}
}
@@ -0,0 +1,99 @@
package io.github.hectorvent.floci.services.ce;
import io.github.hectorvent.floci.core.common.UsageLine;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.equalTo;
/**
* Unit tests for {@link CostSynthesizer} — focused on rate application and
* the special-case treatment of USD-denominated record types
* (Credit / Refund / Tax / SavingsPlan upfront / SavingsPlan recurring).
*/
class CostSynthesizerTest {
private static final Instant START = Instant.parse("2026-01-01T00:00:00Z");
private static final Instant END = Instant.parse("2026-01-02T00:00:00Z");
private CostSynthesizer synthesizer;
@BeforeEach
void setUp() {
// Hand-rolled stub so the test stays a pure unit test (no Pricing snapshot
// load on the classpath, no Quarkus boot).
PricingRateLookup stubLookup = new PricingRateLookup(null, null) {
@Override
public Map<String, Double> ratesFor(String serviceCode, String regionCode) {
if ("AmazonEC2".equals(serviceCode)) {
return Map.of("BoxUsage:t3.micro", 0.0104);
}
return Map.of();
}
};
synthesizer = new CostSynthesizer(stubLookup);
}
@Test
void usageRecordType_multipliesQuantityByRate() {
UsageLine line = new UsageLine(START, END,
"AmazonEC2", "us-east-1", "BoxUsage:t3.micro", "RunInstances",
UsageLine.RECORD_TYPE_USAGE,
"000000000000", "i-test", Map.of(),
24.0, "Hrs");
Map<String, CostSynthesizer.MetricValue> metrics = synthesizer.compute(line);
assertThat(metrics.get("UnblendedCost").amount(), closeTo(24.0 * 0.0104, 1e-9));
assertThat(metrics.get("UnblendedCost").unit(), equalTo("USD"));
assertThat(metrics.get("UsageQuantity").amount(), equalTo(24.0));
assertThat(metrics.get("UsageQuantity").unit(), equalTo("Hrs"));
}
@Test
void creditRecordType_costEqualsQuantity() {
// Credit lines arrive denominated in USD already and must NOT be passed
// through the rate lookup (which has no entry for Credits/Credit-Promotional).
UsageLine credit = new UsageLine(START, END,
"Credits", "us-east-1", "Credit-Promotional", "ApplyPromoCredit",
UsageLine.RECORD_TYPE_CREDIT,
"000000000000", null, Map.of(),
-100.0, "USD");
Map<String, CostSynthesizer.MetricValue> metrics = synthesizer.compute(credit);
assertThat(metrics.get("UnblendedCost").amount(), equalTo(-100.0));
assertThat(metrics.get("UnblendedCost").unit(), equalTo("USD"));
assertThat(metrics.get("BlendedCost").amount(), equalTo(-100.0));
assertThat(metrics.get("AmortizedCost").amount(), equalTo(-100.0));
assertThat(metrics.get("NetUnblendedCost").amount(), equalTo(-100.0));
assertThat(metrics.get("NetAmortizedCost").amount(), equalTo(-100.0));
assertThat(metrics.get("UsageQuantity").amount(), equalTo(0.0));
}
@Test
void taxRecordType_costEqualsQuantity() {
UsageLine tax = new UsageLine(START, END,
"Tax", "us-east-1", "Tax", "Tax",
UsageLine.RECORD_TYPE_TAX,
"000000000000", null, Map.of(),
7.50, "USD");
Map<String, CostSynthesizer.MetricValue> metrics = synthesizer.compute(tax);
assertThat(metrics.get("UnblendedCost").amount(), equalTo(7.50));
}
@Test
void usageRecordType_unknownRateProducesZeroCost() {
UsageLine line = new UsageLine(START, END,
"AmazonRDS", "us-east-1", "InstanceUsage:db.t3.micro", "CreateDBInstance",
UsageLine.RECORD_TYPE_USAGE,
"000000000000", null, Map.of(),
24.0, "Hrs");
Map<String, CostSynthesizer.MetricValue> metrics = synthesizer.compute(line);
assertThat(metrics.get("UnblendedCost").amount(), equalTo(0.0));
assertThat(metrics.get("UsageQuantity").amount(), equalTo(24.0));
}
}
@@ -0,0 +1,133 @@
package io.github.hectorvent.floci.services.ce;
import io.github.hectorvent.floci.core.common.UsageLine;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.time.YearMonth;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
class CreditLineEmitterTest {
private static final Instant JAN_15 = Instant.parse("2026-01-15T00:00:00Z");
private static final Instant MAR_15 = Instant.parse("2026-03-15T00:00:00Z");
/**
* Stub synthesizer that returns a fixed monthly cost: $300 for the entire
* Jan-15 to Mar-15 line. Used to verify proportional split across months.
*/
private CostSynthesizer fixedCostSynthesizer(double total) {
return new CostSynthesizer(new PricingRateLookup(null, null) {
@Override
public Map<String, Double> ratesFor(String serviceCode, String regionCode) {
return Map.of();
}
}) {
@Override
Map<String, MetricValue> compute(UsageLine line) {
if (UsageLine.RECORD_TYPE_USAGE.equals(line.recordType())) {
return Map.of(
"UnblendedCost", new MetricValue(total, "USD"),
"BlendedCost", new MetricValue(total, "USD"),
"AmortizedCost", new MetricValue(total, "USD"),
"NetUnblendedCost", new MetricValue(total, "USD"),
"NetAmortizedCost", new MetricValue(total, "USD"),
"UsageQuantity", new MetricValue(line.quantity(), line.usageUnit()),
"NormalizedUsageAmount", new MetricValue(line.quantity(), line.usageUnit()));
}
return Map.of();
}
};
}
private static UsageLine usage(Instant start, Instant end) {
return new UsageLine(start, end,
"AmazonEC2", "us-east-1", "BoxUsage:t3.micro", "RunInstances",
UsageLine.RECORD_TYPE_USAGE,
"000000000000", "i-test", Map.of(),
24.0, "Hrs");
}
@Test
void singleMonthLine_emitsOneCredit() {
CreditLineEmitter emitter = new CreditLineEmitter(50.0);
UsageLine line = usage(Instant.parse("2026-01-01T00:00:00Z"),
Instant.parse("2026-02-01T00:00:00Z"));
List<UsageLine> credits = emitter.emit(Stream.of(line), fixedCostSynthesizer(200.0)).toList();
assertThat(credits, hasSize(1));
assertThat(credits.get(0).quantity(), equalTo(-50.0));
assertThat(credits.get(0).recordType(), equalTo(UsageLine.RECORD_TYPE_CREDIT));
}
@Test
void multiMonthLine_emitsCreditPerCalendarMonth() {
// Line spans Jan 15 -> Mar 15, total cost $300. Three months touched —
// Jan (17d), Feb (28d), Mar (14d). Credit = $50/mo capped at the monthly
// share. All three months must produce a credit line.
CreditLineEmitter emitter = new CreditLineEmitter(50.0);
UsageLine line = usage(JAN_15, MAR_15);
List<UsageLine> credits = emitter.emit(Stream.of(line), fixedCostSynthesizer(300.0)).toList();
assertThat(credits, hasSize(3));
for (UsageLine credit : credits) {
assertThat(credit.recordType(), equalTo(UsageLine.RECORD_TYPE_CREDIT));
assertThat(credit.region(), equalTo("us-east-1"));
}
// Each month has share > $50 of $300 (Jan ~$87, Feb ~$144, Mar ~$72), so each
// credit caps at the configured -$50.
for (UsageLine credit : credits) {
assertThat(credit.quantity(), equalTo(-50.0));
}
// Windows should align to the three calendar months.
List<YearMonth> months = credits.stream()
.map(c -> YearMonth.from(c.periodStart().atOffset(ZoneOffset.UTC)))
.toList();
assertThat(months, hasItem(YearMonth.of(2026, 1)));
assertThat(months, hasItem(YearMonth.of(2026, 2)));
assertThat(months, hasItem(YearMonth.of(2026, 3)));
}
@Test
void multiMonthLine_smallTotalCapsCreditAtUsageCost() {
// Line spans Jan 15 -> Mar 15, but total cost is only $9. Per-month share
// is well under $50, so the credit caps at the monthly usage cost rather
// than the configured monthly limit.
CreditLineEmitter emitter = new CreditLineEmitter(50.0);
UsageLine line = usage(JAN_15, MAR_15);
List<UsageLine> credits = emitter.emit(Stream.of(line), fixedCostSynthesizer(9.0)).toList();
assertThat(credits, hasSize(3));
double total = 0;
for (UsageLine c : credits) {
// Each absolute credit is < $50.
assertThat(Math.abs(c.quantity()) <= 50.0, equalTo(true));
total += -c.quantity();
}
// Sum of credits == sum of usage cost (since credit per month >= monthly cost).
assertThat(total, closeTo(9.0, 1e-6));
}
@Test
void zeroConfiguredCredit_emitsNothing() {
CreditLineEmitter emitter = new CreditLineEmitter(0.0);
UsageLine line = usage(JAN_15, MAR_15);
List<UsageLine> credits = emitter.emit(Stream.of(line), fixedCostSynthesizer(300.0)).toList();
assertThat(credits, empty());
}
@Test
void zeroCostUsage_emitsNothing() {
CreditLineEmitter emitter = new CreditLineEmitter(50.0);
UsageLine line = usage(JAN_15, MAR_15);
List<UsageLine> credits = emitter.emit(Stream.of(line), fixedCostSynthesizer(0.0)).toList();
assertThat(credits, empty());
}
}
@@ -0,0 +1,82 @@
package io.github.hectorvent.floci.services.ce;
import io.github.hectorvent.floci.core.common.AwsException;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* Unit tests for {@link TimeBucketing}, focused on the boundary-alignment
* behavior AWS Cost Explorer guarantees: Start truncates down, End rounds up
* to the next granularity boundary so every bucket spans a whole granularity
* unit.
*/
class TimeBucketingTest {
@Test
void splitDaily_truncatesNonAlignedEndToNextDay() {
Instant start = Instant.parse("2026-01-01T00:00:00Z");
Instant end = Instant.parse("2026-01-03T13:30:00Z");
List<TimeBucketing.Bucket> buckets = TimeBucketing.split(start, end, TimeBucketing.Granularity.DAILY);
assertThat(buckets, hasSize(3));
assertThat(buckets.get(0).start(), equalTo(Instant.parse("2026-01-01T00:00:00Z")));
assertThat(buckets.get(2).end(), equalTo(Instant.parse("2026-01-04T00:00:00Z")));
}
@Test
void splitHourly_truncatesNonAlignedBoundaries() {
Instant start = Instant.parse("2026-01-01T00:30:00Z");
Instant end = Instant.parse("2026-01-01T03:45:00Z");
List<TimeBucketing.Bucket> buckets = TimeBucketing.split(start, end, TimeBucketing.Granularity.HOURLY);
assertThat(buckets, hasSize(4));
assertThat(buckets.get(0).start(), equalTo(Instant.parse("2026-01-01T00:00:00Z")));
assertThat(buckets.get(3).end(), equalTo(Instant.parse("2026-01-01T04:00:00Z")));
}
@Test
void splitMonthly_anchorsToFirstOfMonth() {
Instant start = Instant.parse("2026-01-15T00:00:00Z");
Instant end = Instant.parse("2026-03-10T00:00:00Z");
List<TimeBucketing.Bucket> buckets = TimeBucketing.split(start, end, TimeBucketing.Granularity.MONTHLY);
assertThat(buckets, hasSize(3));
assertThat(buckets.get(0).start(), equalTo(Instant.parse("2026-01-01T00:00:00Z")));
assertThat(buckets.get(2).end(), equalTo(Instant.parse("2026-04-01T00:00:00Z")));
}
@Test
void splitDaily_alreadyAlignedEndDoesNotAddExtraDay() {
Instant start = Instant.parse("2026-01-01T00:00:00Z");
Instant end = Instant.parse("2026-01-03T00:00:00Z");
List<TimeBucketing.Bucket> buckets = TimeBucketing.split(start, end, TimeBucketing.Granularity.DAILY);
assertThat(buckets, hasSize(2));
assertThat(buckets.get(1).end(), equalTo(Instant.parse("2026-01-03T00:00:00Z")));
}
@Test
void split_endNotAfterStart_throws() {
Instant t = Instant.parse("2026-01-01T00:00:00Z");
AwsException ex = assertThrows(AwsException.class,
() -> TimeBucketing.split(t, t, TimeBucketing.Granularity.DAILY));
assertThat(ex.getErrorCode(), equalTo("DataUnavailableException"));
}
@Test
void parseGranularity_acceptsThreeValues() {
assertThat(TimeBucketing.parseGranularity("DAILY"), equalTo(TimeBucketing.Granularity.DAILY));
assertThat(TimeBucketing.parseGranularity("HOURLY"), equalTo(TimeBucketing.Granularity.HOURLY));
assertThat(TimeBucketing.parseGranularity("MONTHLY"), equalTo(TimeBucketing.Granularity.MONTHLY));
}
@Test
void parseGranularity_rejectsInvalid() {
assertThrows(AwsException.class, () -> TimeBucketing.parseGranularity("YEARLY"));
assertThrows(AwsException.class, () -> TimeBucketing.parseGranularity(""));
assertThrows(AwsException.class, () -> TimeBucketing.parseGranularity(null));
}
}