feat(cur, bcm-data-exports): add Cost and Usage Reports + BCM Data Exports (#850)

Implements PR 3 of the 3-PR billing-API scope discussed in #791. Adds
two service surfaces that share one underlying export pipeline:

- `cur:*` — legacy Cost and Usage Reports management plane, target
  prefix `AWSOrigamiServiceGatewayService.*`.
- `bcm-data-exports:*` — modern Billing and Cost Management Data
  Exports management plane, target prefix
  `AWSBillingAndCostManagementDataExports.*`.

Both run as JSON 1.1 services dispatched through the existing
`AwsJson11Controller`.

## Operations

CUR (7):

- `PutReportDefinition`, `ModifyReportDefinition`,
  `DescribeReportDefinitions`, `DeleteReportDefinition`
- `TagResource` / `UntagResource` / `ListTagsForResource` (stubs)

BCM Data Exports (7):

- `CreateExport`, `GetExport`, `ListExports`, `UpdateExport`,
  `DeleteExport`
- `ListExecutions`, `GetExecution`

AWS-shaped error codes throughout: `DuplicateReportNameException`,
`ReportLimitReachedException`, `ReportNotFoundException`,
`ResourceNotFoundException`, `ValidationException`,
`UnknownOperationException`. Storage keys are account-scoped
(`<accountId>::<region>::<reportName>` for CUR;
`<accountId>::<exportArn>` and `<accountId>::<exportArn>::<executionId>`
for BCM) so both services participate in Floci's per-account
isolation.

## Parquet emission

The same `ResourceUsageEnumerator` SPI introduced in #832 (Cost
Explorer) backs the Parquet artifact:

1. `EmissionEngine` collects `UsageLine` rows from every
   `@ApplicationScoped` enumerator bean.
2. `FocusRowProjector` projects them into FOCUS 1.2 / CUR 2.0 column
   shape, reusing #821's bundled Pricing snapshot for unit prices.
3. Rows are staged as newline-delimited JSON in
   `s3://floci-cur-staging/...` via Floci's S3 service — escape-safe
   for tags, descriptions, and resource identifiers.
4. The `floci-duck` sidecar runs
   `COPY (SELECT * FROM read_json_auto('s3://...')) TO 's3://...'
   (FORMAT PARQUET)` so Parquet writes happen inside DuckDB, not in
   the Java process. This avoids pulling Apache Parquet / Hadoop /
   Avro into Floci's classpath and keeps the native binary footprint
   unchanged.
5. Staging objects are removed in a best-effort `finally` block; each
   run carries a fresh `runId` (UUID) in both staging and
   destination keys so concurrent emissions cannot clobber each other.

The emission engine is shared between CUR and BCM, but the management
planes are otherwise independent — they each own their own validation,
storage, and JSON dispatch.

## Run modes

`FLOCI_SERVICES_CUR_EMIT_MODE` and
`FLOCI_SERVICES_BCM_DATA_EXPORTS_EMIT_MODE`:

- `synchronous` (default): emit on every report/export mutation
- `daily`: emit once per 24h via a CUR-owned single-thread
  `ScheduledExecutorService` — separate from the EventBridge
  Scheduler dispatcher, so internal billing exports do not surface as
  user-visible Scheduler resources.
- `off`: management plane only

Emission failures never roll back the management mutation. Failures
surface as `ReportStatus.LastStatus = ERROR` on CUR and
`Execution.ExecutionStatus.StatusCode = DELIVERY_FAILURE` on BCM.

## Tests

42 new tests across 5 classes:

- `CurIntegrationTest` (11) — full CRUD on report definitions,
  duplicate / not-found / validation paths
- `BcmDataExportsIntegrationTest` (16) — full CRUD on exports +
  executions, all validation paths
- `FocusRowProjectorTest` (9) — pure-unit projection: usage rows,
  USD-denominated record types (Credit / Refund / Tax), missing
  resource id, tags JSON, billing-period anchoring, region+account
  flow-through, rate cache reuse
- `ParquetEmitterIntegrationTest` (3) — DuckDB readback,
  staging cleanup, concurrent run isolation
- `CurEmissionIntegrationTest` (3) — end-to-end:
  PutReportDefinition -> emit -> Parquet readable through DuckDB;
  ReportStatus updates; CreateExport produces an execution record

Full Floci suite stays green (4194/4194, excluding the pre-existing
local-env flakes documented during PR #821 / #832 and the two
duck-required tests added here that need the `floci-duck` sidecar
and a fixed Floci HTTP port to verify cross-container S3 access).

## Documentation

- `docs/services/cur.md` — operations, validation rules, emission
  pipeline, configuration, examples.
- `docs/services/bcm-data-exports.md` — operations, validation,
  execution lifecycle, configuration, examples.
- README service table updated with rows for both, plus a note that
  CUR / BCM Data Exports share one Parquet engine.

Refs: https://github.com/orgs/floci-io/discussions/791
Refs: #823
Builds on: #821, #832
This commit is contained in:
Shubham Srivastava authored and GitHub committed 2026-05-15 22:55:11 -05:00
1 parent b5b863c386
commit 6d36f66e5f
33 files changed
+4474 -5

No files matched your search

@@ -0,0 +1,83 @@
package io.github.hectorvent.floci.services.bcmdataexports;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.bcmdataexports.model.Export;
import io.github.hectorvent.floci.services.bcmdataexports.model.ExportExecution;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
/**
* Pure unit test that simulates two distinct accounts owning BCM exports and
* asserts {@link BcmDataExportsService#listAllExportsByAccount} surfaces both
* — necessary for the daily emission scheduler to emit for accounts other
* than the default.
*/
class BcmDataExportsAccountIsolationTest {
@Test
void listAllExportsByAccount_returnsEntriesFromEveryAccount() {
InMemoryStorage<String, Export> rawExports = new InMemoryStorage<>();
InMemoryStorage<String, ExportExecution> rawExecutions = new InMemoryStorage<>();
AccountAwareStorageBackend<Export> exportStore =
new AccountAwareStorageBackend<>(rawExports, null, "000000000000");
AccountAwareStorageBackend<ExportExecution> executionStore =
new AccountAwareStorageBackend<>(rawExecutions, null, "000000000000");
exportStore.putForAccount("111111111111",
"arn:aws:bcm-data-exports:us-east-1:111111111111:export/alpha",
exportNamed("alpha", "111111111111"));
exportStore.putForAccount("222222222222",
"arn:aws:bcm-data-exports:us-east-1:222222222222:export/bravo",
exportNamed("bravo", "222222222222"));
BcmDataExportsService service = new BcmDataExportsService(exportStore, executionStore,
new RegionResolver("us-east-1", "000000000000"));
Map<String, List<Export>> grouped = service.listAllExportsByAccount();
assertThat(grouped, hasKey("111111111111"));
assertThat(grouped, hasKey("222222222222"));
assertThat(grouped.get("111111111111").stream().map(Export::getName).toList(),
containsInAnyOrder("alpha"));
assertThat(grouped.get("222222222222").stream().map(Export::getName).toList(),
containsInAnyOrder("bravo"));
}
@Test
void recordExecution_landsInRequestedAccountPartition() {
InMemoryStorage<String, Export> rawExports = new InMemoryStorage<>();
InMemoryStorage<String, ExportExecution> rawExecutions = new InMemoryStorage<>();
AccountAwareStorageBackend<Export> exportStore =
new AccountAwareStorageBackend<>(rawExports, null, "000000000000");
AccountAwareStorageBackend<ExportExecution> executionStore =
new AccountAwareStorageBackend<>(rawExecutions, null, "000000000000");
BcmDataExportsService service = new BcmDataExportsService(exportStore, executionStore,
new RegionResolver("us-east-1", "000000000000"));
ExportExecution exec = service.recordExecution("777777777777",
"arn:aws:bcm-data-exports:us-east-1:777777777777:export/x", "SCHEDULE");
// Looking up via the same account should find it.
ExportExecution roundtrip = executionStore.getForAccount("777777777777",
"arn:aws:bcm-data-exports:us-east-1:777777777777:export/x::"
+ exec.getExecutionId()).orElseThrow();
assertThat(roundtrip.getCreatedBy(), equalTo("SCHEDULE"));
}
private static Export exportNamed(String name, String ownerAccountId) {
Export e = new Export();
e.setName(name);
e.setExportArn("arn:aws:bcm-data-exports:us-east-1:" + ownerAccountId + ":export/" + name);
e.setOwnerAccountId(ownerAccountId);
return e;
}
}
@@ -0,0 +1,362 @@
package io.github.hectorvent.floci.services.bcmdataexports;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
/**
* Integration tests for the BCM Data Exports management plane.
*
* Protocol: JSON 1.1 — Content-Type: application/x-amz-json-1.1,
* X-Amz-Target: AWSBillingAndCostManagementDataExports.&lt;Action&gt;
*/
@QuarkusTest
@TestProfile(BcmDataExportsIntegrationTest.IsolatedProfile.class)
class BcmDataExportsIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/bcm-data-exports/aws4_request";
public static final class IsolatedProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.storage.mode", "memory");
}
}
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private static String validExportBody(String name) {
return "{\"Export\":{" +
"\"Name\":\"" + name + "\"," +
"\"Description\":\"daily focus export\"," +
"\"DataQuery\":{\"QueryStatement\":\"SELECT * FROM COST_AND_USAGE_REPORT\"}," +
"\"DestinationConfigurations\":{\"S3Destination\":{" +
"\"S3Bucket\":\"my-bucket\",\"S3Prefix\":\"out/\",\"S3Region\":\"us-east-1\"," +
"\"S3OutputConfigurations\":{\"Format\":\"PARQUET\",\"Compression\":\"PARQUET\",\"OutputType\":\"CUSTOM\",\"Overwrite\":\"OVERWRITE_REPORT\"}}}," +
"\"RefreshCadence\":{\"Frequency\":\"SYNCHRONOUS\"}}}";
}
private static String createExportAndReturnArn(String name) {
return given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.CreateExport")
.header("Authorization", AUTH).body(validExportBody(name))
.when().post("/")
.then()
.statusCode(200)
.body("ExportArn", notNullValue())
.extract().path("ExportArn");
}
@Test
void createExport_succeeds() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.CreateExport")
.header("Authorization", AUTH).body(validExportBody("create-success"))
.when().post("/")
.then()
.statusCode(200)
.body("ExportArn", containsString("export/create-success"));
}
@Test
void createExport_duplicate_returnsValidation() {
createExportAndReturnArn("dup-export");
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.CreateExport")
.header("Authorization", AUTH).body(validExportBody("dup-export"))
.when().post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void createExport_invalidName_returnsValidation() {
String body = validExportBody("bad name with spaces");
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.CreateExport")
.header("Authorization", AUTH).body(body)
.when().post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void createExport_missingDataQuery_returnsValidation() {
String body = "{\"Export\":{" +
"\"Name\":\"no-query\"," +
"\"DestinationConfigurations\":{\"S3Destination\":{" +
"\"S3Bucket\":\"b\",\"S3Region\":\"us-east-1\"}}," +
"\"RefreshCadence\":{\"Frequency\":\"SYNCHRONOUS\"}}}";
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.CreateExport")
.header("Authorization", AUTH).body(body)
.when().post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void createExport_invalidFrequency_returnsValidation() {
String body = "{\"Export\":{" +
"\"Name\":\"bad-cadence\"," +
"\"DataQuery\":{\"QueryStatement\":\"SELECT 1\"}," +
"\"DestinationConfigurations\":{\"S3Destination\":{" +
"\"S3Bucket\":\"b\",\"S3Region\":\"us-east-1\"}}," +
"\"RefreshCadence\":{\"Frequency\":\"DAILY\"}}}";
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.CreateExport")
.header("Authorization", AUTH).body(body)
.when().post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void getExport_returnsCreated() {
String arn = createExportAndReturnArn("get-target");
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.GetExport")
.header("Authorization", AUTH).body("{\"ExportArn\":\"" + arn + "\"}")
.when().post("/")
.then()
.statusCode(200)
.body("Export.Name", equalTo("get-target"))
.body("Export.RefreshCadence.Frequency", equalTo("SYNCHRONOUS"));
}
@Test
void getExport_notFound_returns400() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.GetExport")
.header("Authorization", AUTH).body("{\"ExportArn\":\"arn:aws:bcm-data-exports:us-east-1:000000000000:export/missing\"}")
.when().post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"));
}
@Test
void listExports_includesCreated() {
createExportAndReturnArn("listed-export");
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.ListExports")
.header("Authorization", AUTH).body("{}")
.when().post("/")
.then()
.statusCode(200)
.body("Exports.ExportName", hasItem("listed-export"));
}
@Test
void updateExport_replacesDescription() {
String arn = createExportAndReturnArn("upd-target");
String body = "{\"ExportArn\":\"" + arn + "\"," +
"\"Export\":{" +
"\"Name\":\"upd-target\"," +
"\"Description\":\"updated description\"," +
"\"DataQuery\":{\"QueryStatement\":\"SELECT 2\"}," +
"\"DestinationConfigurations\":{\"S3Destination\":{\"S3Bucket\":\"new-bucket\",\"S3Region\":\"us-east-1\"}}," +
"\"RefreshCadence\":{\"Frequency\":\"SYNCHRONOUS\"}}}";
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.UpdateExport")
.header("Authorization", AUTH).body(body)
.when().post("/")
.then()
.statusCode(200)
.body("ExportArn", equalTo(arn));
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.GetExport")
.header("Authorization", AUTH).body("{\"ExportArn\":\"" + arn + "\"}")
.when().post("/")
.then()
.statusCode(200)
.body("Export.Description", equalTo("updated description"))
.body("Export.DestinationConfigurations.S3Destination.S3Bucket", equalTo("new-bucket"));
}
@Test
void updateExport_notFound_returns400() {
String body = "{\"ExportArn\":\"arn:aws:bcm-data-exports:us-east-1:000000000000:export/missing\"," +
"\"Export\":{\"Name\":\"missing\"," +
"\"DataQuery\":{\"QueryStatement\":\"SELECT 1\"}," +
"\"DestinationConfigurations\":{\"S3Destination\":{\"S3Bucket\":\"valid-bucket\",\"S3Region\":\"us-east-1\"}}," +
"\"RefreshCadence\":{\"Frequency\":\"SYNCHRONOUS\"}}}";
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.UpdateExport")
.header("Authorization", AUTH).body(body)
.when().post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"));
}
@Test
void deleteExport_removes() {
String arn = createExportAndReturnArn("del-target");
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.DeleteExport")
.header("Authorization", AUTH).body("{\"ExportArn\":\"" + arn + "\"}")
.when().post("/")
.then().statusCode(200);
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.GetExport")
.header("Authorization", AUTH).body("{\"ExportArn\":\"" + arn + "\"}")
.when().post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"));
}
@Test
void deleteExport_unknownArn_returns200() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.DeleteExport")
.header("Authorization", AUTH).body("{\"ExportArn\":\"arn:aws:bcm-data-exports:us-east-1:000000000000:export/never-was\"}")
.when().post("/")
.then().statusCode(200);
}
@Test
void listExecutions_emptyForFreshExport() {
String arn = createExportAndReturnArn("exec-list");
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.ListExecutions")
.header("Authorization", AUTH).body("{\"ExportArn\":\"" + arn + "\"}")
.when().post("/")
.then()
.statusCode(200)
.body("Executions", hasSize(0));
}
@Test
void listExecutions_unknownExport_returns400() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.ListExecutions")
.header("Authorization", AUTH).body("{\"ExportArn\":\"arn:aws:bcm-data-exports:us-east-1:000000000000:export/missing\"}")
.when().post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"));
}
@Test
void getExecution_unknownIds_returns400() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.GetExecution")
.header("Authorization", AUTH).body("{\"ExportArn\":\"arn:aws:bcm-data-exports:us-east-1:000000000000:export/missing\",\"ExecutionId\":\"x\"}")
.when().post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"));
}
@Test
void createExport_invalidBucketName_returnsValidation() {
String body = "{\"Export\":{" +
"\"Name\":\"bad-bucket\"," +
"\"DataQuery\":{\"QueryStatement\":\"SELECT 1\"}," +
"\"DestinationConfigurations\":{\"S3Destination\":{" +
"\"S3Bucket\":\"InvalidUpper\",\"S3Region\":\"us-east-1\"}}," +
"\"RefreshCadence\":{\"Frequency\":\"SYNCHRONOUS\"}}}";
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.CreateExport")
.header("Authorization", AUTH).body(body)
.when().post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void createExport_quoteInS3Prefix_returnsValidation() {
String body = "{\"Export\":{" +
"\"Name\":\"quote-prefix\"," +
"\"DataQuery\":{\"QueryStatement\":\"SELECT 1\"}," +
"\"DestinationConfigurations\":{\"S3Destination\":{" +
"\"S3Bucket\":\"valid-bucket\"," +
"\"S3Prefix\":\"out'); DROP DATABASE; --\"," +
"\"S3Region\":\"us-east-1\"}}," +
"\"RefreshCadence\":{\"Frequency\":\"SYNCHRONOUS\"}}}";
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.CreateExport")
.header("Authorization", AUTH).body(body)
.when().post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void createExport_textOrCsvFormat_returnsValidation() {
String body = "{\"Export\":{" +
"\"Name\":\"csv-attempt\"," +
"\"DataQuery\":{\"QueryStatement\":\"SELECT 1\"}," +
"\"DestinationConfigurations\":{\"S3Destination\":{" +
"\"S3Bucket\":\"valid-bucket\",\"S3Region\":\"us-east-1\"," +
"\"S3OutputConfigurations\":{\"Format\":\"TEXT_OR_CSV\",\"Compression\":\"GZIP\",\"OutputType\":\"CUSTOM\"}}}," +
"\"RefreshCadence\":{\"Frequency\":\"SYNCHRONOUS\"}}}";
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.CreateExport")
.header("Authorization", AUTH).body(body)
.when().post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void unknownAction_returnsUnknownOperation() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.GetBogusAction")
.header("Authorization", AUTH).body("{}")
.when().post("/")
.then()
.statusCode(400)
.body("__type", equalTo("UnknownOperationException"));
}
}
@@ -0,0 +1,84 @@
package io.github.hectorvent.floci.services.cur;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.cur.model.ReportDefinition;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* Pure unit test for {@link CurService#listAllReportsByAccount} — no Quarkus
* boot. Simulates two distinct accounts writing reports through an
* {@link AccountAwareStorageBackend} backed by {@link InMemoryStorage}, then
* asserts the daily-scheduler iteration sees BOTH partitions, not just the
* default account.
*/
class CurAccountIsolationTest {
@Test
void listAllReportsByAccount_returnsEntriesFromEveryAccount() {
InMemoryStorage<String, ReportDefinition> raw = new InMemoryStorage<>();
AccountAwareStorageBackend<ReportDefinition> aware =
new AccountAwareStorageBackend<>(raw, null, "000000000000");
// Two accounts, two reports each. Account 111 owns "alpha"+"bravo",
// account 222 owns "charlie".
aware.putForAccount("111111111111", "us-east-1::alpha", reportNamed("alpha", "111111111111"));
aware.putForAccount("111111111111", "us-east-1::bravo", reportNamed("bravo", "111111111111"));
aware.putForAccount("222222222222", "us-east-1::charlie", reportNamed("charlie", "222222222222"));
CurService service = new CurService(aware,
new RegionResolver("us-east-1", "000000000000"));
Map<String, List<ReportDefinition>> grouped = service.listAllReportsByAccount();
assertNotNull(grouped);
assertThat(grouped, hasKey("111111111111"));
assertThat(grouped, hasKey("222222222222"));
assertThat(grouped.get("111111111111").stream().map(ReportDefinition::getReportName).toList(),
containsInAnyOrder("alpha", "bravo"));
assertThat(grouped.get("222222222222").stream().map(ReportDefinition::getReportName).toList(),
contains("charlie"));
}
@Test
void listAllReportsByAccount_attributesFallbackAccountWhenOwnerMissing() {
InMemoryStorage<String, ReportDefinition> raw = new InMemoryStorage<>();
AccountAwareStorageBackend<ReportDefinition> aware =
new AccountAwareStorageBackend<>(raw, null, "999988887777");
// Pre-existing entry without ownerAccountId set (e.g. data persisted by
// an older version of Floci) must still surface, attributed to the
// configured default account so the daily loop won't skip it.
ReportDefinition orphan = reportNamed("orphan", null);
aware.putForAccount("999988887777", "us-east-1::orphan", orphan);
CurService service = new CurService(aware,
new RegionResolver("us-east-1", "999988887777"));
Map<String, List<ReportDefinition>> grouped = service.listAllReportsByAccount();
assertThat(grouped, hasKey("999988887777"));
assertThat(grouped.get("999988887777").get(0).getReportName(), equalTo("orphan"));
}
private static ReportDefinition reportNamed(String name, String ownerAccountId) {
ReportDefinition r = new ReportDefinition();
r.setReportName(name);
r.setTimeUnit("DAILY");
r.setFormat("Parquet");
r.setCompression("Parquet");
r.setS3Bucket("valid-bucket");
r.setS3Region("us-east-1");
r.setOwnerAccountId(ownerAccountId);
return r;
}
}
@@ -0,0 +1,146 @@
package io.github.hectorvent.floci.services.cur;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import java.util.HashMap;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
/**
* Verifies that the daily emission loop honors per-report owner accounts:
* NDJSON staging (Java-side {@code S3Service.putObject}) and DuckDB-side
* Parquet reads/writes both happen under the report owner's account, not the
* default account that the scheduler thread starts in.
*
* <p>This is the daily-mode counterpart to
* {@link CurNonDefaultAccountEmissionIntegrationTest}, which covers the
* synchronous path. Without {@code CurEmissionScheduler#runUnderAccount}, the
* staging write would land in the default account's S3 partition while
* DuckDB would try to read it from account 111111111111 — triggering
* {@code NoSuchBucket}.
*/
@QuarkusTest
@TestProfile(CurDailyEmissionAccountIsolationIntegrationTest.DailyProfile.class)
@EnabledIfEnvironmentVariable(named = "FLOCI_DUCK_CROSS_CONTAINER_TEST", matches = "1|true|yes")
class CurDailyEmissionAccountIsolationIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String ACCOUNT_ID = "111111111111";
private static final String CUR_AUTH =
"AWS4-HMAC-SHA256 Credential=" + ACCOUNT_ID + "/20260101/us-east-1/cur/aws4_request";
private static final String S3_AUTH =
"AWS4-HMAC-SHA256 Credential=" + ACCOUNT_ID + "/20260101/us-east-1/s3/aws4_request";
public static final class DailyProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
Map<String, String> o = new HashMap<>();
o.put("quarkus.http.test-port", "4566");
o.put("floci.base-url", "http://localhost:4566");
// Sync mode is off so the put-report call below does NOT emit
// immediately. The test then drives the scheduler's runDaily
// codepath directly via the engine to simulate the daily tick.
o.put("floci.services.cur.emit-mode", "off");
o.put("floci.services.bcm-data-exports.emit-mode", "off");
return o;
}
}
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Inject
EmissionEngine engine;
@Inject
CurService curService;
@Test
void dailyEmissionLoopHonorsOwnerAccount() {
String destBucket = "ce-daily-acct-" + System.currentTimeMillis();
// Bucket created under account 111111111111 only.
given()
.header("Authorization", S3_AUTH)
.header("Host", "localhost")
.when()
.put("/" + destBucket)
.then()
.statusCode(anyOf(equalTo(200), equalTo(204)));
// Persist a report definition under the same account.
String body = "{\"ReportDefinition\":{" +
"\"ReportName\":\"daily-acct-emit\"," +
"\"TimeUnit\":\"MONTHLY\"," +
"\"Format\":\"Parquet\",\"Compression\":\"Parquet\"," +
"\"AdditionalSchemaElements\":[]," +
"\"S3Bucket\":\"" + destBucket + "\"," +
"\"S3Prefix\":\"focus\"," +
"\"S3Region\":\"us-east-1\"" +
"}}";
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.PutReportDefinition")
.header("Authorization", CUR_AUTH).body(body)
.when().post("/")
.then().statusCode(200);
// Simulate the scheduler's runDaily codepath: iterate every account's
// report definitions and emit under the owner-account context. The
// helper below mirrors what CurEmissionScheduler.runUnderAccount does,
// since the @Test thread is also outside any incoming HTTP scope here
// (the prior REST-Assured calls have terminated their request scopes).
Map<String, java.util.List<io.github.hectorvent.floci.services.cur.model.ReportDefinition>> grouped =
curService.listAllReportsByAccount();
assertThat(grouped, org.hamcrest.Matchers.hasKey(ACCOUNT_ID));
io.quarkus.arc.ManagedContext rc = io.quarkus.arc.Arc.container().requestContext();
boolean wasActive = rc.isActive();
if (!wasActive) {
rc.activate();
}
try {
io.github.hectorvent.floci.core.common.RequestContext ctx =
io.quarkus.arc.Arc.container()
.instance(io.github.hectorvent.floci.core.common.RequestContext.class).get();
ctx.setAccountId(ACCOUNT_ID);
for (io.github.hectorvent.floci.services.cur.model.ReportDefinition def
: grouped.get(ACCOUNT_ID)) {
engine.emitForCurrentMonth(def.getReportName(), def.getS3Bucket(),
def.getS3Prefix(), def.getS3Region(), ACCOUNT_ID);
}
} finally {
if (!wasActive) {
rc.terminate();
}
}
// Confirm the Parquet artifact landed in account 111111111111's bucket.
String listResponse = given()
.header("Authorization", S3_AUTH)
.queryParam("prefix", "focus/daily-acct-emit/")
.queryParam("list-type", "2")
.when()
.get("/" + destBucket)
.then()
.statusCode(200)
.extract().asString();
assertThat(listResponse, containsString("focus/daily-acct-emit/"));
assertThat(listResponse, containsString(".parquet"));
}
}
@@ -0,0 +1,172 @@
package io.github.hectorvent.floci.services.cur;
import io.github.hectorvent.floci.services.floci.FlociDuckClient;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* End-to-end test that exercises the full sync emission path:
* {@code PutReportDefinition} -&gt; {@link CurEmissionScheduler} -&gt;
* {@link EmissionEngine} -&gt; {@link ParquetEmitter} -&gt; DuckDB sidecar -&gt;
* Parquet object readable from Floci S3.
*/
/*
* Requires the {@code floci-duck} sidecar plus a host-network where the
* sidecar can reach Floci's S3 service. Opt in via
* {@code FLOCI_DUCK_CROSS_CONTAINER_TEST=1}; see
* {@link ParquetEmitterIntegrationTest} for prerequisites.
*/
@QuarkusTest
@TestProfile(CurEmissionIntegrationTest.SyncProfile.class)
@EnabledIfEnvironmentVariable(named = "FLOCI_DUCK_CROSS_CONTAINER_TEST", matches = "1|true|yes")
class CurEmissionIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/cur/aws4_request";
private static final String S3_AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/s3/aws4_request";
/**
* Wires the full sync path: emit-mode=synchronous, fixed Floci HTTP port so
* the DuckDB sidecar can reach Floci S3 over the network.
*/
public static final class SyncProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
Map<String, String> o = new HashMap<>();
o.put("quarkus.http.test-port", "4566");
o.put("floci.base-url", "http://localhost:4566");
o.put("floci.services.cur.emit-mode", "synchronous");
o.put("floci.services.bcm-data-exports.emit-mode", "synchronous");
return o;
}
}
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Inject
FlociDuckClient duckClient;
@Inject
S3Service s3Service;
@Test
void putReportDefinition_triggersSyncEmissionAndWritesParquet() {
String destBucket = "ce-emit-bucket-" + System.currentTimeMillis();
// Pre-create the destination so the emitter doesn't trip on a missing bucket.
s3Service.createBucket(destBucket, "us-east-1");
String body = "{\"ReportDefinition\":{" +
"\"ReportName\":\"sync-emit\"," +
"\"TimeUnit\":\"MONTHLY\"," +
"\"Format\":\"Parquet\"," +
"\"Compression\":\"Parquet\"," +
"\"AdditionalSchemaElements\":[\"RESOURCES\"]," +
"\"S3Bucket\":\"" + destBucket + "\"," +
"\"S3Prefix\":\"billing/\"," +
"\"S3Region\":\"us-east-1\"" +
"}}";
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.PutReportDefinition")
.header("Authorization", AUTH).body(body)
.when().post("/")
.then().statusCode(200);
// Find the freshly written Parquet object by listing the destination prefix.
var listing = s3Service.listObjects(destBucket, "billing/sync-emit/", null, Integer.MAX_VALUE);
assertThat(listing.size(), greaterThanOrEqualTo(1));
String parquetKey = listing.get(0).getKey();
assertThat(parquetKey, startsWith("billing/sync-emit/"));
assertThat(parquetKey.endsWith(".parquet"), org.hamcrest.Matchers.equalTo(true));
// Confirm DuckDB can read the artifact back.
String s3Uri = "s3://" + destBucket + "/" + parquetKey;
List<Map<String, Object>> rows = duckClient.query(
"SELECT \"ServiceName\" FROM read_parquet('" + s3Uri + "') LIMIT 5",
null);
assertNotNull(rows);
}
@Test
void describeReportDefinitions_reportsLastStatusAfterSync() {
String destBucket = "ce-emit-status-" + System.currentTimeMillis();
s3Service.createBucket(destBucket, "us-east-1");
String body = "{\"ReportDefinition\":{" +
"\"ReportName\":\"sync-status\"," +
"\"TimeUnit\":\"MONTHLY\",\"Format\":\"Parquet\",\"Compression\":\"Parquet\"," +
"\"AdditionalSchemaElements\":[]," +
"\"S3Bucket\":\"" + destBucket + "\",\"S3Region\":\"us-east-1\"}}";
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.PutReportDefinition")
.header("Authorization", AUTH).body(body)
.when().post("/")
.then()
.statusCode(200)
.body("ReportStatus.LastStatus", notNullValue());
}
@Test
void createExport_recordsExecution() {
String destBucket = "ce-emit-exec-" + System.currentTimeMillis();
s3Service.createBucket(destBucket, "us-east-1");
String createBody = "{\"Export\":{" +
"\"Name\":\"sync-export\"," +
"\"DataQuery\":{\"QueryStatement\":\"SELECT * FROM COST_AND_USAGE_REPORT\"}," +
"\"DestinationConfigurations\":{\"S3Destination\":{" +
"\"S3Bucket\":\"" + destBucket + "\",\"S3Prefix\":\"out/\",\"S3Region\":\"us-east-1\"," +
"\"S3OutputConfigurations\":{\"Format\":\"PARQUET\",\"Compression\":\"PARQUET\",\"OutputType\":\"CUSTOM\",\"Overwrite\":\"OVERWRITE_REPORT\"}}}," +
"\"RefreshCadence\":{\"Frequency\":\"SYNCHRONOUS\"}}}";
String arn = given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.CreateExport")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/bcm-data-exports/aws4_request")
.body(createBody)
.when().post("/")
.then().statusCode(200)
.extract().path("ExportArn");
// The sync emission hook must have produced exactly one execution record.
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSBillingAndCostManagementDataExports.ListExecutions")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/bcm-data-exports/aws4_request")
.body("{\"ExportArn\":\"" + arn + "\"}")
.when().post("/")
.then().statusCode(200)
.body("Executions.size()", greaterThanOrEqualTo(1))
.body("Executions[0].ExecutionStatus.StatusCode",
org.hamcrest.Matchers.either(org.hamcrest.Matchers.equalTo("DELIVERY_SUCCESS"))
.or(org.hamcrest.Matchers.equalTo("DELIVERY_FAILURE")));
}
}
@@ -0,0 +1,293 @@
package io.github.hectorvent.floci.services.cur;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.quarkus.test.junit.QuarkusTestProfile;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
/**
* Integration tests for the CUR management plane. Each test runs against a
* dedicated profile so report-store state is isolated from sibling tests.
*
* Protocol: JSON 1.1 — Content-Type: application/x-amz-json-1.1,
* X-Amz-Target: AWSOrigamiServiceGatewayService.&lt;Action&gt;
*/
@QuarkusTest
@TestProfile(CurIntegrationTest.IsolatedProfile.class)
class CurIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/cur/aws4_request";
public static final class IsolatedProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.storage.mode", "memory");
}
}
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private static String validReportBody(String name) {
return "{\"ReportDefinition\":{" +
"\"ReportName\":\"" + name + "\"," +
"\"TimeUnit\":\"DAILY\"," +
"\"Format\":\"Parquet\"," +
"\"Compression\":\"Parquet\"," +
"\"AdditionalSchemaElements\":[\"RESOURCES\"]," +
"\"S3Bucket\":\"my-bucket\"," +
"\"S3Prefix\":\"reports/\"," +
"\"S3Region\":\"us-east-1\"," +
"\"AdditionalArtifacts\":[\"ATHENA\"]," +
"\"RefreshClosedReports\":true," +
"\"ReportVersioning\":\"OVERWRITE_REPORT\"" +
"}}";
}
@Test
void putReportDefinition_create_succeeds() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.PutReportDefinition")
.header("Authorization", AUTH)
.body(validReportBody("create-success"))
.when()
.post("/")
.then()
.statusCode(200)
.body("ReportName", equalTo("create-success"))
.body("Format", equalTo("Parquet"));
}
@Test
void putReportDefinition_duplicate_returnsDuplicateException() {
String body = validReportBody("dup-report");
given().contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.PutReportDefinition")
.header("Authorization", AUTH).body(body)
.when().post("/").then().statusCode(200);
given().contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.PutReportDefinition")
.header("Authorization", AUTH).body(body)
.when().post("/").then()
.statusCode(400)
.body("__type", equalTo("DuplicateReportNameException"));
}
@Test
void putReportDefinition_invalidName_returnsValidation() {
String body = "{\"ReportDefinition\":{" +
"\"ReportName\":\"has spaces\"," +
"\"TimeUnit\":\"DAILY\",\"Format\":\"Parquet\",\"Compression\":\"Parquet\"," +
"\"AdditionalSchemaElements\":[]," +
"\"S3Bucket\":\"b\",\"S3Region\":\"us-east-1\"}}";
given().contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.PutReportDefinition")
.header("Authorization", AUTH).body(body)
.when().post("/").then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void putReportDefinition_invalidTimeUnit_returnsValidation() {
String body = "{\"ReportDefinition\":{" +
"\"ReportName\":\"bad-tu\"," +
"\"TimeUnit\":\"YEARLY\",\"Format\":\"Parquet\",\"Compression\":\"Parquet\"," +
"\"AdditionalSchemaElements\":[]," +
"\"S3Bucket\":\"b\",\"S3Region\":\"us-east-1\"}}";
given().contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.PutReportDefinition")
.header("Authorization", AUTH).body(body)
.when().post("/").then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void describeReportDefinitions_returnsCreated() {
given().contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.PutReportDefinition")
.header("Authorization", AUTH).body(validReportBody("describe-test"))
.when().post("/").then().statusCode(200);
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.DescribeReportDefinitions")
.header("Authorization", AUTH).body("{}")
.when().post("/")
.then()
.statusCode(200)
.body("ReportDefinitions.ReportName", hasItem("describe-test"));
}
@Test
void modifyReportDefinition_updates() {
given().contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.PutReportDefinition")
.header("Authorization", AUTH).body(validReportBody("modify-target"))
.when().post("/").then().statusCode(200);
String modify = "{\"ReportName\":\"modify-target\"," +
"\"ReportDefinition\":{" +
"\"ReportName\":\"modify-target\"," +
"\"TimeUnit\":\"MONTHLY\",\"Format\":\"Parquet\",\"Compression\":\"Parquet\"," +
"\"AdditionalSchemaElements\":[\"RESOURCES\"]," +
"\"S3Bucket\":\"new-bucket\",\"S3Region\":\"us-east-1\"" +
"}}";
given().contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.ModifyReportDefinition")
.header("Authorization", AUTH).body(modify)
.when().post("/")
.then()
.statusCode(200)
.body("TimeUnit", equalTo("MONTHLY"))
.body("S3Bucket", equalTo("new-bucket"));
}
@Test
void modifyReportDefinition_notFound_returns400() {
String modify = "{\"ReportName\":\"missing-report\"," +
"\"ReportDefinition\":{" +
"\"ReportName\":\"missing-report\"," +
"\"TimeUnit\":\"DAILY\",\"Format\":\"Parquet\",\"Compression\":\"Parquet\"," +
"\"AdditionalSchemaElements\":[]," +
"\"S3Bucket\":\"valid-bucket\",\"S3Region\":\"us-east-1\"}}";
given().contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.ModifyReportDefinition")
.header("Authorization", AUTH).body(modify)
.when().post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ReportNotFoundException"));
}
@Test
void modifyReportDefinition_nameMismatch_returnsValidation() {
given().contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.PutReportDefinition")
.header("Authorization", AUTH).body(validReportBody("orig-name"))
.when().post("/").then().statusCode(200);
String modify = "{\"ReportName\":\"orig-name\"," +
"\"ReportDefinition\":{" +
"\"ReportName\":\"different-name\"," +
"\"TimeUnit\":\"DAILY\",\"Format\":\"Parquet\",\"Compression\":\"Parquet\"," +
"\"AdditionalSchemaElements\":[]," +
"\"S3Bucket\":\"b\",\"S3Region\":\"us-east-1\"}}";
given().contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.ModifyReportDefinition")
.header("Authorization", AUTH).body(modify)
.when().post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void deleteReportDefinition_removes() {
given().contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.PutReportDefinition")
.header("Authorization", AUTH).body(validReportBody("to-delete"))
.when().post("/").then().statusCode(200);
given().contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.DeleteReportDefinition")
.header("Authorization", AUTH).body("{\"ReportName\":\"to-delete\"}")
.when().post("/")
.then().statusCode(200);
given().contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.DescribeReportDefinitions")
.header("Authorization", AUTH).body("{}")
.when().post("/")
.then().statusCode(200)
.body("ReportDefinitions.ReportName", not(hasItem("to-delete")));
}
@Test
void deleteReportDefinition_unknownName_returns200() {
// AWS treats DeleteReportDefinition as idempotent — deleting a missing
// report should not raise.
given().contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.DeleteReportDefinition")
.header("Authorization", AUTH).body("{\"ReportName\":\"never-existed\"}")
.when().post("/")
.then().statusCode(200);
}
@Test
void putReportDefinition_invalidBucketName_returnsValidation() {
// S3 bucket names must be 3-63 chars, lowercase alphanumerics, '-' or '.'.
// Reject before the value can reach DuckDB SQL interpolation.
String body = "{\"ReportDefinition\":{" +
"\"ReportName\":\"bad-bucket\"," +
"\"TimeUnit\":\"DAILY\",\"Format\":\"Parquet\",\"Compression\":\"Parquet\"," +
"\"AdditionalSchemaElements\":[]," +
"\"S3Bucket\":\"AB\",\"S3Region\":\"us-east-1\"}}";
given().contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.PutReportDefinition")
.header("Authorization", AUTH).body(body)
.when().post("/").then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void putReportDefinition_quoteInS3Prefix_returnsValidation() {
// A single quote in S3Prefix would terminate the SQL string literal that
// ParquetEmitter feeds to DuckDB; reject at the management plane.
String body = "{\"ReportDefinition\":{" +
"\"ReportName\":\"quote-prefix\"," +
"\"TimeUnit\":\"DAILY\",\"Format\":\"Parquet\",\"Compression\":\"Parquet\"," +
"\"AdditionalSchemaElements\":[]," +
"\"S3Bucket\":\"valid-bucket\"," +
"\"S3Prefix\":\"foo'); DROP TABLE x; --\"," +
"\"S3Region\":\"us-east-1\"}}";
given().contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.PutReportDefinition")
.header("Authorization", AUTH).body(body)
.when().post("/").then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void putReportDefinition_textCsvFormat_returnsValidation() {
// Floci only emits Parquet today; accepting textORcsv would let a
// report persist that the emitter can't actually fulfill.
String body = "{\"ReportDefinition\":{" +
"\"ReportName\":\"csv-attempt\"," +
"\"TimeUnit\":\"DAILY\",\"Format\":\"textORcsv\",\"Compression\":\"GZIP\"," +
"\"AdditionalSchemaElements\":[]," +
"\"S3Bucket\":\"valid-bucket\",\"S3Region\":\"us-east-1\"}}";
given().contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.PutReportDefinition")
.header("Authorization", AUTH).body(body)
.when().post("/").then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void unknownAction_returnsUnknownOperation() {
given().contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.GetBogusAction")
.header("Authorization", AUTH).body("{}")
.when().post("/")
.then().statusCode(400)
.body("__type", equalTo("UnknownOperationException"));
}
}
@@ -0,0 +1,116 @@
package io.github.hectorvent.floci.services.cur;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import java.util.HashMap;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
/**
* Verifies that a CUR report created under a non-default 12-digit AWS account
* still reaches its own account-aware S3 partition during synchronous Parquet
* emission. Without owner-account threading through {@code FlociDuckClient},
* the Parquet read/write would fall back to the default account and fail with
* {@code NoSuchBucket} or write into a same-named default-account bucket.
*
* <p>Requires the {@code floci-duck} sidecar plus a host-network where the
* sidecar can reach Floci's S3 service. Opt in via
* {@code FLOCI_DUCK_CROSS_CONTAINER_TEST=1}; see
* {@link ParquetEmitterIntegrationTest} for prerequisites.
*/
@QuarkusTest
@TestProfile(CurNonDefaultAccountEmissionIntegrationTest.SyncProfile.class)
@EnabledIfEnvironmentVariable(named = "FLOCI_DUCK_CROSS_CONTAINER_TEST", matches = "1|true|yes")
class CurNonDefaultAccountEmissionIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String ACCOUNT_ID = "111111111111";
private static final String CUR_AUTH =
"AWS4-HMAC-SHA256 Credential=" + ACCOUNT_ID + "/20260101/us-east-1/cur/aws4_request";
private static final String S3_AUTH =
"AWS4-HMAC-SHA256 Credential=" + ACCOUNT_ID + "/20260101/us-east-1/s3/aws4_request";
public static final class SyncProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
Map<String, String> o = new HashMap<>();
o.put("quarkus.http.test-port", "4566");
o.put("floci.base-url", "http://localhost:4566");
o.put("floci.services.cur.emit-mode", "synchronous");
o.put("floci.services.bcm-data-exports.emit-mode", "synchronous");
return o;
}
}
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void putReportDefinitionUnderNonDefaultAccount_writesParquetIntoThatAccountsBucket() {
String destBucket = "ce-acct-bucket-" + System.currentTimeMillis();
// Create the destination bucket under the SAME 12-digit access key the
// CUR call will use; AccountResolver routes both calls into account
// 111111111111's S3 partition.
given()
.header("Authorization", S3_AUTH)
.header("Host", "localhost")
.when()
.put("/" + destBucket)
.then()
.statusCode(anyOf(equalTo(200), equalTo(204)));
String body = "{\"ReportDefinition\":{" +
"\"ReportName\":\"acct-emit\"," +
"\"TimeUnit\":\"MONTHLY\"," +
"\"Format\":\"Parquet\"," +
"\"Compression\":\"Parquet\"," +
"\"AdditionalSchemaElements\":[]," +
"\"S3Bucket\":\"" + destBucket + "\"," +
"\"S3Prefix\":\"focus\"," +
"\"S3Region\":\"us-east-1\"" +
"}}";
// Synchronous emission must land in account 111111111111's bucket.
// ReportStatus.LastStatus = SUCCESS means DuckDB resolved the bucket
// under the owner account; ERROR would indicate a default-account
// fallback hitting NoSuchBucket.
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSOrigamiServiceGatewayService.PutReportDefinition")
.header("Authorization", CUR_AUTH).body(body)
.when().post("/")
.then()
.statusCode(200)
.body("ReportStatus.LastStatus", equalTo("SUCCESS"));
// List the same account's bucket and confirm the Parquet artifact is
// there. The list call is itself account-scoped, so a default-account
// write would not surface here.
String listResponse = given()
.header("Authorization", S3_AUTH)
.queryParam("prefix", "focus/acct-emit/")
.queryParam("list-type", "2")
.when()
.get("/" + destBucket)
.then()
.statusCode(200)
.extract().asString();
assertThat(listResponse, containsString("focus/acct-emit/"));
assertThat(listResponse, containsString(".parquet"));
}
}
@@ -0,0 +1,234 @@
package io.github.hectorvent.floci.services.cur;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.UsageLine;
import io.github.hectorvent.floci.services.ce.PricingRateLookup;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.aMapWithSize;
import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* Pure unit tests for {@link FocusRowProjector} — no Quarkus boot, no HTTP,
* no DuckDB, no S3.
*/
class FocusRowProjectorTest {
private static final Instant JAN_15 = Instant.parse("2026-01-15T00:00:00Z");
private static final Instant JAN_16 = Instant.parse("2026-01-16T00:00:00Z");
private FocusRowProjector projector;
@BeforeEach
void setUp() {
// Stub rate lookup that knows about exactly one usage type.
PricingRateLookup stubLookup = new PricingRateLookup(null, null) {
@Override
public Map<String, Double> ratesFor(String serviceCode, String regionCode) {
if ("AmazonEC2".equals(serviceCode) && "us-east-1".equals(regionCode)) {
return Map.of("BoxUsage:t3.micro", 0.0104);
}
return Map.of();
}
};
projector = new FocusRowProjector(stubLookup);
}
@Test
void usageRow_costEqualsQuantityTimesRate() {
UsageLine line = new UsageLine(JAN_15, JAN_16,
"AmazonEC2", "us-east-1", "BoxUsage:t3.micro", "RunInstances",
UsageLine.RECORD_TYPE_USAGE,
"111122223333", "i-test", Map.of("Owner", "team-a"),
24.0, "Hrs");
FocusRow row = projector.project(List.of(line)).get(0);
assertThat(row.serviceName(), equalTo("AmazonEC2"));
assertThat(row.serviceCategory(), equalTo("Compute"));
assertThat(row.region(), equalTo("us-east-1"));
assertThat(row.resourceId(), equalTo("i-test"));
assertThat(row.resourceType(), equalTo("Instance"));
assertThat(row.chargeCategory(), equalTo("Usage"));
assertThat(row.chargeFrequency(), equalTo("Usage-Based"));
assertThat(row.chargeSubcategory(), equalTo("BoxUsage:t3.micro"));
assertThat(row.usageQuantity(), closeTo(24.0, 1e-9));
assertThat(row.usageUnit(), equalTo("Hrs"));
assertThat(row.billedCost(), closeTo(24.0 * 0.0104, 1e-9));
assertThat(row.effectiveCost(), closeTo(24.0 * 0.0104, 1e-9));
assertThat(row.listCost(), closeTo(24.0 * 0.0104, 1e-9));
assertThat(row.contractedCost(), closeTo(24.0 * 0.0104, 1e-9));
assertThat(row.billingCurrency(), equalTo("USD"));
assertThat(row.billingAccountId(), equalTo("111122223333"));
assertThat(row.subAccountId(), equalTo("111122223333"));
}
@Test
void creditRow_billedCostEqualsQuantity_negativeAllowed() {
// Credits arrive with quantity already in USD; projector must NOT multiply
// by a per-unit rate (there's none for service "Credits").
UsageLine credit = new UsageLine(JAN_15, JAN_16,
"Credits", "us-east-1", "Credit-Promotional", "ApplyPromoCredit",
UsageLine.RECORD_TYPE_CREDIT,
"000000000000", null, Map.of(),
-100.0, "USD");
FocusRow row = projector.projectOne(credit, new HashMap<>());
assertThat(row.chargeCategory(), equalTo("Credit"));
assertThat(row.billedCost(), equalTo(-100.0));
assertThat(row.effectiveCost(), equalTo(-100.0));
assertThat(row.usageQuantity(), equalTo(-100.0));
assertThat(row.usageUnit(), equalTo("USD"));
}
@Test
void taxAndRefund_areUsdDenominated() {
UsageLine tax = new UsageLine(JAN_15, JAN_16,
"Tax", "us-east-1", "Tax", "Tax",
UsageLine.RECORD_TYPE_TAX,
"000000000000", null, Map.of(),
7.50, "USD");
FocusRow taxRow = projector.projectOne(tax, new HashMap<>());
assertThat(taxRow.chargeCategory(), equalTo("Tax"));
assertThat(taxRow.billedCost(), equalTo(7.50));
UsageLine refund = new UsageLine(JAN_15, JAN_16,
"Refund", "us-east-1", "Refund", "Refund",
UsageLine.RECORD_TYPE_REFUND,
"000000000000", null, Map.of(),
-12.0, "USD");
FocusRow refundRow = projector.projectOne(refund, new HashMap<>());
assertThat(refundRow.chargeCategory(), equalTo("Refund"));
assertThat(refundRow.billedCost(), equalTo(-12.0));
}
@Test
void missingResourceId_setsNullResourceFields() {
UsageLine line = new UsageLine(JAN_15, JAN_16,
"AmazonRDS", "us-east-1", "InstanceUsage:db.t3.micro", "CreateDBInstance",
UsageLine.RECORD_TYPE_USAGE,
"111122223333", null, Map.of(),
24.0, "Hrs");
FocusRow row = projector.projectOne(line, new HashMap<>());
assertThat(row.resourceId(), nullValue());
assertThat(row.resourceName(), nullValue());
assertThat(row.resourceType(), equalTo("DBInstance"));
// No rate registered for AmazonRDS, so cost should be zero (not throw).
assertThat(row.billedCost(), equalTo(0.0));
}
@Test
void tagsAreSerializedAsJsonObject() throws Exception {
Map<String, String> tags = new java.util.LinkedHashMap<>();
tags.put("Owner", "team-a");
tags.put("CostCenter", "1234");
UsageLine line = new UsageLine(JAN_15, JAN_16,
"AmazonEC2", "us-east-1", "BoxUsage:t3.micro", "RunInstances",
UsageLine.RECORD_TYPE_USAGE,
"111122223333", "i-tagged", tags,
24.0, "Hrs");
FocusRow row = projector.projectOne(line, new HashMap<>());
assertThat(row.tags(), aMapWithSize(2));
assertThat(row.tags(), hasEntry("Owner", "team-a"));
assertThat(row.tags(), hasEntry("CostCenter", "1234"));
// Round-trip through Jackson to verify the FocusRow shape Jackson emits is
// a plain JSON object (which is what DuckDB's read_json_auto expects).
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(row);
assertThat(json.contains("\"Tags\":{\"Owner\":\"team-a\",\"CostCenter\":\"1234\"}"),
equalTo(true));
}
@Test
void billingPeriodAlignsToCalendarMonth() {
UsageLine line = new UsageLine(
Instant.parse("2026-03-17T13:30:00Z"),
Instant.parse("2026-03-18T13:30:00Z"),
"AmazonEC2", "us-east-1", "BoxUsage:t3.micro", "RunInstances",
UsageLine.RECORD_TYPE_USAGE,
"111122223333", "i-billing", Map.of(),
24.0, "Hrs");
FocusRow row = projector.projectOne(line, new HashMap<>());
// Billing period must always be first-of-month → first-of-next-month.
assertThat(row.billingPeriodStart(), equalTo("2026-03-01T00:00:00Z"));
assertThat(row.billingPeriodEnd(), equalTo("2026-04-01T00:00:00Z"));
// Charge period preserves the line's exact window.
assertThat(row.chargePeriodStart(), equalTo("2026-03-17T13:30:00Z"));
assertThat(row.chargePeriodEnd(), equalTo("2026-03-18T13:30:00Z"));
}
@Test
void regionAndAccountFlowThrough() {
UsageLine line = new UsageLine(JAN_15, JAN_16,
"AmazonS3", "eu-west-1", "TimedStorage-Standard", "StandardStorage",
UsageLine.RECORD_TYPE_USAGE,
"999988887777", "arn:aws:s3:::my-bucket", Map.of(),
10.0, "GB-Mo");
FocusRow row = projector.projectOne(line, new HashMap<>());
assertThat(row.region(), equalTo("eu-west-1"));
assertThat(row.billingAccountId(), equalTo("999988887777"));
assertThat(row.subAccountId(), equalTo("999988887777"));
assertThat(row.serviceCategory(), equalTo("Storage"));
assertThat(row.resourceType(), equalTo("Bucket"));
assertThat(row.resourceId(), equalTo("arn:aws:s3:::my-bucket"));
}
@Test
void emptyTagsMapIsEmittedNotNull() {
UsageLine line = new UsageLine(JAN_15, JAN_16,
"AWSLambda", "us-east-1", "AWS-Lambda-Requests", "Invoke",
UsageLine.RECORD_TYPE_USAGE,
"000000000000", null, null,
0.0, "Requests");
FocusRow row = projector.projectOne(line, new HashMap<>());
// Null tags input becomes empty map (Jackson omits null but we want {} for DuckDB).
assertThat(row.tags(), notNullValue());
assertThat(row.tags().isEmpty(), equalTo(true));
}
@Test
void rateCacheIsReusedAcrossLines() {
// Two lines with same (service, region) — only one ratesFor() call.
int[] callCount = {0};
PricingRateLookup countingLookup = new PricingRateLookup(null, null) {
@Override
public Map<String, Double> ratesFor(String serviceCode, String regionCode) {
callCount[0]++;
return Map.of("BoxUsage:t3.micro", 0.0104);
}
};
FocusRowProjector p = new FocusRowProjector(countingLookup);
UsageLine line1 = new UsageLine(JAN_15, JAN_16,
"AmazonEC2", "us-east-1", "BoxUsage:t3.micro", "RunInstances",
UsageLine.RECORD_TYPE_USAGE, "000", "i1", Map.of(), 1.0, "Hrs");
UsageLine line2 = new UsageLine(JAN_15, JAN_16,
"AmazonEC2", "us-east-1", "BoxUsage:t3.micro", "RunInstances",
UsageLine.RECORD_TYPE_USAGE, "000", "i2", Map.of(), 2.0, "Hrs");
p.project(List.of(line1, line2));
assertThat(callCount[0], equalTo(1));
}
}
@@ -0,0 +1,181 @@
package io.github.hectorvent.floci.services.cur;
import io.github.hectorvent.floci.core.common.UsageLine;
import io.github.hectorvent.floci.services.floci.FlociDuckClient;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import java.util.HashMap;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* End-to-end Parquet emission test: drives {@link ParquetEmitter} with a small
* {@link UsageLine} batch, then reads the Parquet artifact back through
* {@link FlociDuckClient#query} and verifies the rows.
*
* <p>This test boots Floci's full stack including the {@code floci-duck}
* sidecar container, so it requires a running Docker daemon and pulls
* {@code floci/floci-duck:latest} on first run. Same prerequisite as
* {@code AthenaIntegrationTest}.
*/
/*
* Requires the {@code floci-duck} sidecar container plus a network where
* the sidecar can reach Floci's S3 service via {@code host.docker.internal}.
* That works on macOS / Windows Docker Desktop out of the box, but Linux
* CI runners don't resolve that hostname unless the container is started
* with {@code --add-host=host.docker.internal:host-gateway}, which Floci's
* {@code FlociDuckManager} doesn't do today. Opt in via
* {@code FLOCI_DUCK_CROSS_CONTAINER_TEST=1} (e.g. local macOS, or a CI
* runner that adds the host alias).
*/
@QuarkusTest
@TestProfile(ParquetEmitterIntegrationTest.FixedPortProfile.class)
@EnabledIfEnvironmentVariable(named = "FLOCI_DUCK_CROSS_CONTAINER_TEST", matches = "1|true|yes")
class ParquetEmitterIntegrationTest {
/**
* Force Floci's HTTP server onto a known port so the floci-duck sidecar can
* reach it via {@code host.docker.internal:<port>}. The default test port
* of {@code 0} (random) is fine for tests that only hit the JVM-local API,
* but DuckDB writes Parquet by talking back to Floci's S3 service over the
* network and so needs a stable port.
*/
public static final class FixedPortProfile implements QuarkusTestProfile {
@Override
public java.util.Map<String, String> getConfigOverrides() {
java.util.Map<String, String> overrides = new HashMap<>();
overrides.put("quarkus.http.test-port", "4566");
overrides.put("floci.base-url", "http://localhost:4566");
return overrides;
}
}
private static final Instant JAN_15 = Instant.parse("2026-01-15T00:00:00Z");
private static final Instant JAN_16 = Instant.parse("2026-01-16T00:00:00Z");
@Inject
ParquetEmitter emitter;
@Inject
FlociDuckClient duckClient;
@Inject
S3Service s3Service;
@Test
void emit_writesParquetThatRoundTripsThroughDuckDB() {
String destBucket = "ce-parquet-roundtrip-" + System.currentTimeMillis();
s3Service.createBucket(destBucket, "us-east-1");
List<UsageLine> lines = List.of(
new UsageLine(JAN_15, JAN_16,
"AmazonEC2", "us-east-1", "BoxUsage:t3.micro", "RunInstances",
UsageLine.RECORD_TYPE_USAGE,
"111122223333", "i-roundtrip-1", Map.of("Owner", "team-a"),
24.0, "Hrs"),
new UsageLine(JAN_15, JAN_16,
"AmazonEC2", "us-east-1", "BoxUsage:t3.micro", "RunInstances",
UsageLine.RECORD_TYPE_USAGE,
"111122223333", "i-roundtrip-2", Map.of("Owner", "team-b"),
12.0, "Hrs"));
ParquetEmitter.Result result = emitter.emit("roundtrip-report", destBucket, "billing/", lines);
assertNotNull(result);
assertNotNull(result.runId());
assertThat(result.bucket(), equalTo(destBucket));
assertThat(result.s3Uri(), startsWith("s3://" + destBucket + "/billing/roundtrip-report/"));
assertThat(result.s3Uri().endsWith(".parquet"), equalTo(true));
assertThat(result.rowCount(), equalTo(2));
// Confirm the Parquet object actually landed in S3.
var parquetObject = s3Service.getObject(destBucket, result.key());
assertNotNull(parquetObject);
assertThat(parquetObject.getSize(), greaterThanOrEqualTo(1L));
// Read it back through DuckDB and assert the row count + a couple of columns.
List<Map<String, Object>> rows = duckClient.query(
"SELECT \"BillingAccountId\", \"ServiceName\", \"BilledCost\", \"ResourceId\" "
+ "FROM read_parquet('" + result.s3Uri() + "') ORDER BY \"ResourceId\"",
null);
assertThat(rows.size(), equalTo(2));
Map<String, Object> first = rows.get(0);
assertThat((String) first.get("BillingAccountId"), equalTo("111122223333"));
assertThat((String) first.get("ServiceName"), equalTo("AmazonEC2"));
assertThat((String) first.get("ResourceId"), equalTo("i-roundtrip-1"));
// Bundled snapshot prices BoxUsage:t3.micro at 0.0104 USD/hour.
assertThat(((Number) first.get("BilledCost")).doubleValue(),
closeTo(24.0 * 0.0104, 1e-6));
Map<String, Object> second = rows.get(1);
assertThat((String) second.get("ResourceId"), equalTo("i-roundtrip-2"));
assertThat(((Number) second.get("BilledCost")).doubleValue(),
closeTo(12.0 * 0.0104, 1e-6));
}
@Test
void emit_stagingObjectIsCleanedUp() {
String destBucket = "ce-parquet-cleanup-" + System.currentTimeMillis();
s3Service.createBucket(destBucket, "us-east-1");
List<UsageLine> lines = List.of(new UsageLine(JAN_15, JAN_16,
"AmazonS3", "us-east-1", "TimedStorage-Standard", "StandardStorage",
UsageLine.RECORD_TYPE_USAGE,
"111122223333", "arn:aws:s3:::cleanup", Map.of(),
10.0, "GB-Mo"));
ParquetEmitter.Result result = emitter.emit("cleanup-report", destBucket, null, lines);
// Staging bucket exists, but no staging objects should remain for this run.
var staging = s3Service.listObjects("floci-cur-staging",
"cur-staging/cleanup-report/" + result.runId(), null, Integer.MAX_VALUE);
assertTrue(staging.isEmpty(),
"Expected no leftover staging objects, found: " + staging);
}
@Test
void emit_concurrentRunsDoNotClobberEachOther() throws InterruptedException {
String destBucket = "ce-parquet-concurrent-" + System.currentTimeMillis();
s3Service.createBucket(destBucket, "us-east-1");
List<UsageLine> linesA = List.of(new UsageLine(JAN_15, JAN_16,
"AmazonEC2", "us-east-1", "BoxUsage:t3.micro", "RunInstances",
UsageLine.RECORD_TYPE_USAGE,
"111122223333", "i-A", Map.of(), 24.0, "Hrs"));
List<UsageLine> linesB = List.of(new UsageLine(JAN_15, JAN_16,
"AmazonEC2", "us-east-1", "BoxUsage:t3.micro", "RunInstances",
UsageLine.RECORD_TYPE_USAGE,
"111122223333", "i-B", Map.of(), 48.0, "Hrs"));
// Same report name on purpose — runId must keep the two outputs separate.
ParquetEmitter.Result resultA = emitter.emit("shared-report", destBucket, null, linesA);
ParquetEmitter.Result resultB = emitter.emit("shared-report", destBucket, null, linesB);
assertThat(resultA.runId(), notNullValue());
assertThat(resultB.runId(), notNullValue());
assertThat(resultA.runId().equals(resultB.runId()), equalTo(false));
assertThat(resultA.s3Uri().equals(resultB.s3Uri()), equalTo(false));
// Both Parquet objects must exist independently.
assertNotNull(s3Service.getObject(destBucket, resultA.key()));
assertNotNull(s3Service.getObject(destBucket, resultB.key()));
}
}