Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cur, bcm-data-exports): add Cost and Usage Reports + BCM Data Exports (#850)
Shubham Srivastava6d36f66e5feb
diff --git a/README.md b/README.mdindex 6c29e1802e..7703b52455 100644--- a/README.md+++ b/README.md@@ -301,6 +301,8 @@ All default images are configurable via environment variables — useful for pin| **Textract** | In-process (stub) | API-compatible stubs for all operations; dummy block data with realistic shape and metadata; async job simulation with immediate SUCCEEDED status || **Pricing (Price List Service)** | In-process + bundled static snapshot | `DescribeServices`, `GetAttributeValues`, `GetProducts`, `ListPriceLists`, `GetPriceListFileUrl`; pagination; filesystem override via `FLOCI_SERVICES_PRICING_SNAPSHOT_PATH` || **Cost Explorer** | In-process; cost synthesized from Floci resource state × Pricing snapshot | `GetCostAndUsage` (full `Filter`/`GroupBy`/`Metrics`/`RECORD_TYPE`), `GetCostAndUsageWithResources`, `GetDimensionValues`, `GetTags`, RI/SP coverage+utilization stubs; CDI-discovered `ResourceUsageEnumerator` SPI for new services to emit cost lines without touching CE |+| **Cost and Usage Reports (CUR)** | In-process management plane + `floci-duck` sidecar for Parquet emission | `PutReportDefinition`, `ModifyReportDefinition`, `DescribeReportDefinitions`, `DeleteReportDefinition`; FOCUS 1.2 / CUR 2.0 columns; account-scoped storage; `synchronous` / `daily` / `off` emit modes |+| **BCM Data Exports** | In-process management plane sharing the CUR Parquet engine | `CreateExport`, `GetExport`, `ListExports`, `UpdateExport`, `DeleteExport`, `ListExecutions`, `GetExecution`; AWS-compatible execution lifecycle (`INITIATION_IN_PROCESS` → `DELIVERY_SUCCESS` / `DELIVERY_FAILURE`) |---diff --git a/docs/services/bcm-data-exports.md b/docs/services/bcm-data-exports.mdnew file mode 100644index 0000000000..81bc4f5bbb--- /dev/null+++ b/docs/services/bcm-data-exports.md@@ -0,0 +1,154 @@+# BCM Data Exports (`bcm-data-exports:*`)++**Protocol:** JSON 1.1+**Header:** `X-Amz-Target: AWSBillingAndCostManagementDataExports.<Action>`+**Endpoint prefix:** `bcm-data-exports`++Floci emulates the BCM Data Exports management plane that ships with+CUR 2.0 / FOCUS 1.2. Exports share the same Parquet emission engine as+the legacy [`cur:*`](cur.md) service — the two are alternative+management surfaces over one underlying export pipeline.++## Supported Operations++| Operation | Notes |+|-----------|-------|+| `CreateExport` | Creates an export; rejects duplicate `Name` with `ValidationException` |+| `GetExport` | Returns one export by ARN; missing ARN returns `ResourceNotFoundException` |+| `ListExports` | Returns every export owned by the calling account |+| `UpdateExport` | Replaces mutable fields on an existing export |+| `DeleteExport` | Idempotent; deletes orphan executions too |+| `ListExecutions` | Returns all execution records for an export |+| `GetExecution` | Returns one execution record |++## Validation rules++- `Export.Name`: alphanumerics + `-_`, max 128 chars+- `Export.DataQuery.QueryStatement`: required (free-form SQL — Floci does+ not parse it; the export shape is determined by the bundled FOCUS+ schema)+- `Export.DestinationConfigurations.S3Destination`: required;+ `S3Bucket` + `S3Region` mandatory+- `S3OutputConfigurations.Format`: `PARQUET` (CSV emission not yet implemented; `TEXT_OR_CSV` returns `ValidationException`)+- `S3OutputConfigurations.Compression`: `PARQUET` (`GZIP` not yet implemented)+- `S3OutputConfigurations.Overwrite`: `CREATE_NEW_REPORT` / `OVERWRITE_REPORT`+- `S3OutputConfigurations.OutputType`: `CUSTOM`+- `RefreshCadence.Frequency`: `SYNCHRONOUS` (the only AWS-supported+ value at the time of writing)++## Storage keys++Account-scoped throughout:++- Export: `<accountId>::<exportArn>`+- Execution: `<accountId>::<exportArn>::<executionId>`++Deleting an export removes all of its executions in the same call to+avoid orphan records.++## Execution lifecycle++A successful `CreateExport` in `synchronous` mode produces exactly one+execution record:++```+INITIATION_IN_PROCESS (recorded at create-time)+ |+ v+DELIVERY_SUCCESS or DELIVERY_FAILURE+```++Status transitions on `UpdateExport` too. Both `success` and `failure`+end states are visible via `GetExecution.Execution.ExecutionStatus`.++## Emission++The Parquet pipeline is the same as for [`cur:*`](cur.md): rows from+the `ResourceUsageEnumerator` SPI go through `FocusRowProjector`, are+staged as NDJSON in `floci-cur-staging`, and written as Parquet by the+`floci-duck` sidecar via `COPY ... TO ... (FORMAT PARQUET)`. Each+execution produces an artifact at+`s3://<S3Bucket>/<S3Prefix>/<Name>/<runId>.parquet`.++### `FLOCI_SERVICES_BCM_DATA_EXPORTS_EMIT_MODE`++| Value | Behavior |+|-------|----------|+| `synchronous` (default) | Emit on every `CreateExport` / `UpdateExport` |+| `daily` | Emit every 24h via the shared CUR scheduled executor |+| `off` | Management plane only — no emission |++## Configuration++| Variable | Default | Description |+|---|---|---|+| `FLOCI_SERVICES_BCM_DATA_EXPORTS_ENABLED` | `true` | Enable or disable the service |+| `FLOCI_SERVICES_BCM_DATA_EXPORTS_EMIT_MODE` | `synchronous` | Run mode (see above) |++## Examples++```bash+export AWS_ENDPOINT_URL=http://localhost:4566+export AWS_DEFAULT_REGION=us-east-1+export AWS_ACCESS_KEY_ID=test+export AWS_SECRET_ACCESS_KEY=test++aws bcm-data-exports create-export --export '{+ "Name": "focus-monthly",+ "DataQuery": {"QueryStatement": "SELECT * FROM COST_AND_USAGE_REPORT"},+ "DestinationConfigurations": {+ "S3Destination": {+ "S3Bucket": "my-billing",+ "S3Prefix": "focus",+ "S3Region": "us-east-1",+ "S3OutputConfigurations": {+ "Format": "PARQUET",+ "Compression": "PARQUET",+ "OutputType": "CUSTOM",+ "Overwrite": "OVERWRITE_REPORT"+ }+ }+ },+ "RefreshCadence": {"Frequency": "SYNCHRONOUS"}+}'++aws bcm-data-exports list-exports++aws bcm-data-exports list-executions \+ --export-arn arn:aws:bcm-data-exports:us-east-1:000000000000:export/focus-monthly+```++```python+import boto3++client = boto3.client(+ "bcm-data-exports",+ endpoint_url="http://localhost:4566",+ region_name="us-east-1",+)+resp = client.create_export(Export={+ "Name": "focus-monthly",+ "DataQuery": {"QueryStatement": "SELECT * FROM COST_AND_USAGE_REPORT"},+ "DestinationConfigurations": {"S3Destination": {+ "S3Bucket": "my-billing",+ "S3Prefix": "focus",+ "S3Region": "us-east-1",+ "S3OutputConfigurations": {+ "Format": "PARQUET", "Compression": "PARQUET",+ "OutputType": "CUSTOM", "Overwrite": "OVERWRITE_REPORT",+ },+ }},+ "RefreshCadence": {"Frequency": "SYNCHRONOUS"},+})+print(resp["ExportArn"])+```++## Out of Scope++- Custom SQL evaluation in `DataQuery.QueryStatement` — Floci ignores+ the SQL and emits the FOCUS shape directly. The query string is+ persisted faithfully so SDK round-trips work, but it has no effect on+ the Parquet output.+- Cost categories, billing views, and pricing-model overrides+- Real `RefreshCadence` scheduling beyond `SYNCHRONOUS` and the+ `daily` Floci-internal modediff --git a/docs/services/cur.md b/docs/services/cur.mdnew file mode 100644index 0000000000..338a839e6b--- /dev/null+++ b/docs/services/cur.md@@ -0,0 +1,140 @@+# Cost and Usage Reports (`cur:*`)++**Protocol:** JSON 1.1+**Header:** `X-Amz-Target: AWSOrigamiServiceGatewayService.<Action>`+**Endpoint prefix:** `cur`++Floci emulates the legacy AWS Cost and Usage Report (CUR) API. Report+definitions are persisted in Floci's storage backend; emission produces+real Parquet artifacts in Floci's S3 service via the `floci-duck` sidecar.++## Supported Operations++| Operation | Notes |+|-----------|-------|+| `PutReportDefinition` | Creates a new report; rejects duplicates with `DuplicateReportNameException`; enforces a 5-report-per-account limit |+| `ModifyReportDefinition` | Replaces an existing report's mutable fields |+| `DescribeReportDefinitions` | Returns every report owned by the calling account |+| `DeleteReportDefinition` | Idempotent; removing a missing report returns 200 |+| `TagResource` / `UntagResource` / `ListTagsForResource` | Stub responses (empty bodies) so SDK clients that probe for them succeed |++## Validation rules++- `ReportName`: alphanumerics + `-_`, max 256 chars+- `TimeUnit`: `HOURLY` / `DAILY` / `MONTHLY`+- `Format`: `Parquet` (CSV emission not yet implemented; `textORcsv` returns `ValidationException`)+- `Compression`: `Parquet` (`ZIP` / `GZIP` not yet implemented)+- `ReportVersioning`: `CREATE_NEW_REPORT` / `OVERWRITE_REPORT`+- `AdditionalArtifacts`: subset of `REDSHIFT` / `QUICKSIGHT` / `ATHENA`+- `AdditionalSchemaElements`: subset of `RESOURCES` / `SPLIT_COST_ALLOCATION_DATA` / `MANUAL_DISCOUNT_COMPATIBILITY`+- Required: `ReportName`, `TimeUnit`, `Format`, `Compression`, `S3Bucket`, `S3Region`++## Storage keys++Report definitions are persisted as+`<accountId>::<region>::<reportName>` so the same name is allowed in+different regions or different accounts.++## Emission++Emission produces a Parquet artifact at+`s3://<S3Bucket>/<S3Prefix>/<reportName>/<runId>.parquet`. Each run gets a+fresh UUID, so concurrent emissions never clobber each other.++The pipeline:++1. The shared `EmissionEngine` collects `UsageLine` rows from every+ service that implements the `ResourceUsageEnumerator` SPI introduced+ in [Cost Explorer](ce.md).+2. `FocusRowProjector` converts those rows to FOCUS 1.2 / CUR 2.0 column+ shape using the bundled [Pricing snapshot](pricing.md).+3. The rows are staged as newline-delimited JSON in+ `s3://floci-cur-staging/cur-staging/<reportName>/<runId>.ndjson`.+4. The `floci-duck` sidecar runs+ `COPY (SELECT * FROM read_json_auto(...)) TO 's3://...' (FORMAT PARQUET)`+ to produce the final Parquet object back in Floci S3.+5. The staging object is deleted in a best-effort `finally` block.++### `FLOCI_SERVICES_CUR_EMIT_MODE`++| Value | Behavior |+|-------|----------|+| `synchronous` (default) | Emit on every `PutReportDefinition` / `ModifyReportDefinition` |+| `daily` | Emit every 24h via a CUR-owned scheduled executor (separate from EventBridge Scheduler) |+| `off` | Management plane only — no emission |++`synchronous` mode swallows emission errors so the management mutation+always succeeds; the failure is reflected in+`ReportStatus.LastStatus = ERROR` on the persisted definition.++## Configuration++| Variable | Default | Description |+|---|---|---|+| `FLOCI_SERVICES_CUR_ENABLED` | `true` | Enable or disable the service |+| `FLOCI_SERVICES_CUR_EMIT_MODE` | `synchronous` | Run mode (see above) |+| `FLOCI_SERVICES_CUR_STAGING_BUCKET` | `floci-cur-staging` | S3 bucket used to stage NDJSON before DuckDB writes Parquet |++The `floci-duck` sidecar is started lazily on the first emission, the+same way Athena starts it.++## Examples++```bash+export AWS_ENDPOINT_URL=http://localhost:4566+export AWS_DEFAULT_REGION=us-east-1+export AWS_ACCESS_KEY_ID=test+export AWS_SECRET_ACCESS_KEY=test++aws cur put-report-definition --report-definition '{+ "ReportName": "monthly-report",+ "TimeUnit": "MONTHLY",+ "Format": "Parquet",+ "Compression": "Parquet",+ "AdditionalSchemaElements": ["RESOURCES"],+ "S3Bucket": "my-billing",+ "S3Prefix": "reports",+ "S3Region": "us-east-1",+ "AdditionalArtifacts": ["ATHENA"],+ "ReportVersioning": "OVERWRITE_REPORT"+}'++aws cur describe-report-definitions++aws s3 ls s3://my-billing/reports/monthly-report/+```++```python+import boto3, json++cur = boto3.client(+ "cur",+ endpoint_url="http://localhost:4566",+ region_name="us-east-1",+)+cur.put_report_definition(ReportDefinition={+ "ReportName": "monthly-report",+ "TimeUnit": "MONTHLY",+ "Format": "Parquet",+ "Compression": "Parquet",+ "AdditionalSchemaElements": ["RESOURCES"],+ "S3Bucket": "my-billing",+ "S3Prefix": "reports",+ "S3Region": "us-east-1",+})++# Read the resulting Parquet via DuckDB or pyarrow.+import pyarrow.dataset as ds+table = ds.dataset("s3://my-billing/reports/monthly-report/", format="parquet").to_table()+print(table.column_names)+```++## Out of Scope++- Resource-tag-keyed report selection beyond what the bundled+ enumerators emit+- `RefreshClosedReports` semantics (accepted but not retroactively+ re-emitted)+- Server-side validation of S3 bucket policies on the destination+ bucket (Floci's S3 service still applies its own bucket-policy+ checks during the write)diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex 81a2cda437..50c65a7ea8 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -304,6 +304,8 @@ public interface EmulatorConfig {DuckConfig duck();TranscribeServiceConfig transcribe();CostExplorerServiceConfig ce();+ CurServiceConfig cur();+ BcmDataExportsServiceConfig bcmDataExports();}interface TransferServiceConfig {@@ -678,6 +680,41 @@ public interface EmulatorConfig {double creditUsdMonthly();}+ interface CurServiceConfig {+ @WithDefault("true")+ boolean enabled();++ /**+ * Controls when CUR Parquet artifacts are emitted:+ * <ul>+ * <li>{@code synchronous} — emit on report definition mutations (default; suits tests)</li>+ * <li>{@code daily} — emit once per 24h via the CUR-owned scheduled executor</li>+ * <li>{@code off} — management plane only, no Parquet emission</li>+ * </ul>+ */+ @WithDefault("synchronous")+ String emitMode();++ /**+ * S3 bucket used to stage NDJSON row payloads before DuckDB writes the+ * final Parquet artifact. Created on first use if it doesn't exist.+ */+ @WithDefault("floci-cur-staging")+ String stagingBucket();+ }++ interface BcmDataExportsServiceConfig {+ @WithDefault("true")+ boolean enabled();++ /**+ * Same semantics as {@code floci.services.cur.emit-mode} but applied to+ * BCM Data Exports {@code Export} records.+ */+ @WithDefault("synchronous")+ String emitMode();+ }+interface EcrServiceConfig {@WithDefault("true")boolean enabled();diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.javaindex 9d607ecf91..cf873d6cae 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java@@ -12,7 +12,9 @@ import io.github.hectorvent.floci.services.ecs.EcsJsonHandler;import io.github.hectorvent.floci.services.firehose.FirehoseJsonHandler;import io.github.hectorvent.floci.services.glue.GlueJsonHandler;import io.github.hectorvent.floci.services.resourcegroupstagging.ResourceGroupsTaggingJsonHandler;+import io.github.hectorvent.floci.services.bcmdataexports.BcmDataExportsJsonHandler;import io.github.hectorvent.floci.services.ce.CostExplorerJsonHandler;+import io.github.hectorvent.floci.services.cur.CurJsonHandler;import io.github.hectorvent.floci.services.pricing.PricingJsonHandler;import io.github.hectorvent.floci.services.textract.TextractJsonHandler;import io.github.hectorvent.floci.services.transcribe.TranscribeJsonHandler;@@ -72,6 +74,8 @@ public class AwsJson11Controller {private final PricingJsonHandler pricingJsonHandler;private final TranscribeJsonHandler transcribeJsonHandler;private final CostExplorerJsonHandler costExplorerJsonHandler;+ private final CurJsonHandler curJsonHandler;+ private final BcmDataExportsJsonHandler bcmDataExportsJsonHandler;@Injectpublic AwsJson11Controller(ObjectMapper objectMapper, ResolvedServiceCatalog catalog,@@ -94,7 +98,9 @@ public class AwsJson11Controller {TextractJsonHandler textractJsonHandler,PricingJsonHandler pricingJsonHandler,TranscribeJsonHandler transcribeJsonHandler,- CostExplorerJsonHandler costExplorerJsonHandler) {+ CostExplorerJsonHandler costExplorerJsonHandler,+ CurJsonHandler curJsonHandler,+ BcmDataExportsJsonHandler bcmDataExportsJsonHandler) {this.objectMapper = objectMapper;this.catalog = catalog;this.regionResolver = regionResolver;@@ -121,6 +127,8 @@ public class AwsJson11Controller {this.pricingJsonHandler = pricingJsonHandler;this.transcribeJsonHandler = transcribeJsonHandler;this.costExplorerJsonHandler = costExplorerJsonHandler;+ this.curJsonHandler = curJsonHandler;+ this.bcmDataExportsJsonHandler = bcmDataExportsJsonHandler;}@POST@@ -172,6 +180,8 @@ public class AwsJson11Controller {case "pricing" -> pricingJsonHandler.handle(action, request, region);case "transcribe" -> transcribeJsonHandler.handle(action, request, region);case "ce" -> costExplorerJsonHandler.handle(action, request, region);+ case "cur" -> curJsonHandler.handle(action, request, region);+ case "bcm-data-exports" -> bcmDataExportsJsonHandler.handle(action, request, region);default -> null;};// catalog.matchTarget is protocol-agnostic: a JSON 1.0 targetdiff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.javaindex a3e5497497..5be92a02d7 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java@@ -255,7 +255,15 @@ public class ResolvedServiceCatalog {descriptor("ce", "ce", config.services().ce().enabled(), true,null, null, 5000L, null, ServiceProtocol.JSON,protocols(ServiceProtocol.JSON),- Set.of("AWSInsightsIndexService."), Set.of("ce"), Set.of(), Set.of())+ Set.of("AWSInsightsIndexService."), Set.of("ce"), Set.of(), Set.of()),+ descriptor("cur", "cur", config.services().cur().enabled(), true,+ "cur", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,+ protocols(ServiceProtocol.JSON),+ Set.of("AWSOrigamiServiceGatewayService."), Set.of("cur"), Set.of(), Set.of()),+ descriptor("bcm-data-exports", "bcmdataexports", config.services().bcmDataExports().enabled(), true,+ "bcmdataexports", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,+ protocols(ServiceProtocol.JSON),+ Set.of("AWSBillingAndCostManagementDataExports."), Set.of("bcm-data-exports"), Set.of(), Set.of())));}diff --git a/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsJsonHandler.javanew file mode 100644index 0000000000..43c1ec240c--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsJsonHandler.java@@ -0,0 +1,314 @@+package io.github.hectorvent.floci.services.bcmdataexports;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ArrayNode;+import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.core.common.AwsErrorResponse;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.services.bcmdataexports.model.DataQuery;+import io.github.hectorvent.floci.services.bcmdataexports.model.DestinationConfiguration;+import io.github.hectorvent.floci.services.bcmdataexports.model.Export;+import io.github.hectorvent.floci.services.bcmdataexports.model.ExportExecution;+import io.github.hectorvent.floci.services.bcmdataexports.model.RefreshCadence;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import jakarta.ws.rs.core.Response;+import org.jboss.logging.Logger;++import java.time.Instant;+import java.util.HashMap;+import java.util.Iterator;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;++/**+ * JSON 1.1 handler for AWS BCM Data Exports operations.+ * Dispatches {@code X-Amz-Target: AWSBillingAndCostManagementDataExports.*}+ * actions to {@link BcmDataExportsService}.+ */+@ApplicationScoped+public class BcmDataExportsJsonHandler {++ private static final Logger LOG = Logger.getLogger(BcmDataExportsJsonHandler.class);++ private final BcmDataExportsService service;+ private final ObjectMapper objectMapper;+ private final io.github.hectorvent.floci.services.cur.CurEmissionScheduler scheduler;++ @Inject+ public BcmDataExportsJsonHandler(BcmDataExportsService service,+ ObjectMapper objectMapper,+ io.github.hectorvent.floci.services.cur.CurEmissionScheduler scheduler) {+ this.service = service;+ this.objectMapper = objectMapper;+ this.scheduler = scheduler;+ }++ public Response handle(String action, JsonNode request, String region) {+ LOG.debugv("BcmDataExports action: {0}", action);+ return switch (action) {+ case "CreateExport" -> handleCreate(request, region);+ case "GetExport" -> handleGet(request);+ case "ListExports" -> handleList();+ case "UpdateExport" -> handleUpdate(request);+ case "DeleteExport" -> handleDelete(request);+ case "ListExecutions" -> handleListExecutions(request);+ case "GetExecution" -> handleGetExecution(request);+ default -> Response.status(400)+ .entity(new AwsErrorResponse("UnknownOperationException",+ "Unknown operation: AWSBillingAndCostManagementDataExports." + action))+ .build();+ };+ }++ private Response handleCreate(JsonNode request, String region) {+ Export incoming = parseExport(request.path("Export"));+ Map<String, String> tags = parseResourceTags(request.path("ResourceTags"));+ Export created = service.createExport(incoming, tags, region);+ try {+ scheduler.emitForExportSync(created, region, "USER");+ } catch (RuntimeException e) {+ LOG.warnv(e, "Synchronous emission failed for {0}; export still created.", created.getName());+ }+ ObjectNode response = objectMapper.createObjectNode();+ response.put("ExportArn", created.getExportArn());+ return Response.ok(response).build();+ }++ private Response handleGet(JsonNode request) {+ String arn = stringOrNull(request, "ExportArn");+ Export export = service.getExport(arn);+ ObjectNode response = objectMapper.createObjectNode();+ response.set("Export", serializeExport(export));+ return Response.ok(response).build();+ }++ private Response handleList() {+ List<Export> exports = service.listExports();+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode arr = response.putArray("Exports");+ for (Export export : exports) {+ arr.add(serializeExportReference(export));+ }+ return Response.ok(response).build();+ }++ private Response handleUpdate(JsonNode request) {+ String arn = stringOrNull(request, "ExportArn");+ Export incoming = parseExport(request.path("Export"));+ Export updated = service.updateExport(arn, incoming);+ try {+ scheduler.emitForExportSync(updated, null, "USER");+ } catch (RuntimeException e) {+ LOG.warnv(e, "Synchronous emission failed for {0}; export still updated.", updated.getExportArn());+ }+ ObjectNode response = objectMapper.createObjectNode();+ response.put("ExportArn", updated.getExportArn());+ return Response.ok(response).build();+ }++ private Response handleDelete(JsonNode request) {+ String arn = stringOrNull(request, "ExportArn");+ service.deleteExport(arn);+ ObjectNode response = objectMapper.createObjectNode();+ response.put("ExportArn", arn == null ? "" : arn);+ return Response.ok(response).build();+ }++ private Response handleListExecutions(JsonNode request) {+ String arn = stringOrNull(request, "ExportArn");+ List<ExportExecution> executions = service.listExecutions(arn);+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode arr = response.putArray("Executions");+ for (ExportExecution exec : executions) {+ arr.add(serializeExecution(exec));+ }+ return Response.ok(response).build();+ }++ private Response handleGetExecution(JsonNode request) {+ String arn = stringOrNull(request, "ExportArn");+ String executionId = stringOrNull(request, "ExecutionId");+ ExportExecution exec = service.getExecution(arn, executionId);+ ObjectNode response = objectMapper.createObjectNode();+ response.put("ExportArn", arn);+ response.set("Execution", serializeExecution(exec));+ return Response.ok(response).build();+ }++ private Export parseExport(JsonNode node) {+ if (node == null || !node.isObject() || node.isEmpty()) {+ throw new AwsException("ValidationException", "Export is required.", 400);+ }+ Export e = new Export();+ e.setName(stringOrNull(node, "Name"));+ e.setDescription(stringOrNull(node, "Description"));+ e.setDataQuery(parseDataQuery(node.path("DataQuery")));+ e.setDestinationConfigurations(parseDestination(node.path("DestinationConfigurations")));+ e.setRefreshCadence(parseRefreshCadence(node.path("RefreshCadence")));+ return e;+ }++ private DataQuery parseDataQuery(JsonNode node) {+ if (!node.isObject() || node.isEmpty()) {+ return null;+ }+ DataQuery dq = new DataQuery();+ dq.setQueryStatement(stringOrNull(node, "QueryStatement"));+ JsonNode tableConfigs = node.path("TableConfigurations");+ if (tableConfigs.isObject()) {+ Map<String, Map<String, String>> result = new LinkedHashMap<>();+ Iterator<Map.Entry<String, JsonNode>> tables = tableConfigs.fields();+ while (tables.hasNext()) {+ Map.Entry<String, JsonNode> table = tables.next();+ Map<String, String> props = new LinkedHashMap<>();+ Iterator<Map.Entry<String, JsonNode>> propIter = table.getValue().fields();+ while (propIter.hasNext()) {+ Map.Entry<String, JsonNode> prop = propIter.next();+ props.put(prop.getKey(), prop.getValue().asText());+ }+ result.put(table.getKey(), props);+ }+ dq.setTableConfigurations(result);+ }+ return dq;+ }++ private DestinationConfiguration parseDestination(JsonNode node) {+ if (!node.isObject() || node.isEmpty()) {+ return null;+ }+ DestinationConfiguration dest = new DestinationConfiguration();+ JsonNode s3Node = node.path("S3Destination");+ if (s3Node.isObject() && !s3Node.isEmpty()) {+ DestinationConfiguration.S3Destination s3 = new DestinationConfiguration.S3Destination();+ s3.setS3Bucket(stringOrNull(s3Node, "S3Bucket"));+ s3.setS3Prefix(stringOrNull(s3Node, "S3Prefix"));+ s3.setS3Region(stringOrNull(s3Node, "S3Region"));+ JsonNode outNode = s3Node.path("S3OutputConfigurations");+ if (outNode.isObject() && !outNode.isEmpty()) {+ DestinationConfiguration.S3OutputConfigurations out = new DestinationConfiguration.S3OutputConfigurations();+ out.setCompression(stringOrNull(outNode, "Compression"));+ out.setFormat(stringOrNull(outNode, "Format"));+ out.setOutputType(stringOrNull(outNode, "OutputType"));+ out.setOverwrite(stringOrNull(outNode, "Overwrite"));+ s3.setS3OutputConfigurations(out);+ }+ dest.setS3Destination(s3);+ }+ return dest;+ }++ private RefreshCadence parseRefreshCadence(JsonNode node) {+ if (!node.isObject() || node.isEmpty()) {+ return null;+ }+ RefreshCadence cadence = new RefreshCadence();+ cadence.setFrequency(stringOrNull(node, "Frequency"));+ return cadence;+ }++ private Map<String, String> parseResourceTags(JsonNode node) {+ Map<String, String> out = new HashMap<>();+ if (node.isArray()) {+ for (JsonNode entry : node) {+ String key = stringOrNull(entry, "Key");+ String value = stringOrNull(entry, "Value");+ if (key != null) {+ out.put(key, value == null ? "" : value);+ }+ }+ }+ return out;+ }++ private ObjectNode serializeExport(Export e) {+ ObjectNode out = objectMapper.createObjectNode();+ out.put("ExportArn", e.getExportArn());+ out.put("Name", e.getName());+ if (e.getDescription() != null) {+ out.put("Description", e.getDescription());+ }+ if (e.getDataQuery() != null) {+ ObjectNode dq = out.putObject("DataQuery");+ dq.put("QueryStatement", e.getDataQuery().getQueryStatement());+ if (e.getDataQuery().getTableConfigurations() != null+ && !e.getDataQuery().getTableConfigurations().isEmpty()) {+ ObjectNode tableConfigs = dq.putObject("TableConfigurations");+ for (Map.Entry<String, Map<String, String>> table : e.getDataQuery().getTableConfigurations().entrySet()) {+ ObjectNode props = tableConfigs.putObject(table.getKey());+ for (Map.Entry<String, String> prop : table.getValue().entrySet()) {+ props.put(prop.getKey(), prop.getValue());+ }+ }+ }+ }+ if (e.getDestinationConfigurations() != null+ && e.getDestinationConfigurations().getS3Destination() != null) {+ ObjectNode dest = out.putObject("DestinationConfigurations");+ ObjectNode s3 = dest.putObject("S3Destination");+ DestinationConfiguration.S3Destination src = e.getDestinationConfigurations().getS3Destination();+ s3.put("S3Bucket", src.getS3Bucket());+ s3.put("S3Prefix", src.getS3Prefix() == null ? "" : src.getS3Prefix());+ s3.put("S3Region", src.getS3Region());+ DestinationConfiguration.S3OutputConfigurations outCfg = src.getS3OutputConfigurations();+ if (outCfg != null) {+ ObjectNode outNode = s3.putObject("S3OutputConfigurations");+ if (outCfg.getCompression() != null) outNode.put("Compression", outCfg.getCompression());+ if (outCfg.getFormat() != null) outNode.put("Format", outCfg.getFormat());+ if (outCfg.getOutputType() != null) outNode.put("OutputType", outCfg.getOutputType());+ if (outCfg.getOverwrite() != null) outNode.put("Overwrite", outCfg.getOverwrite());+ }+ }+ if (e.getRefreshCadence() != null) {+ ObjectNode cadence = out.putObject("RefreshCadence");+ cadence.put("Frequency", e.getRefreshCadence().getFrequency());+ }+ if (e.getExportStatus() != null) {+ ObjectNode status = out.putObject("ExportStatus");+ status.put("StatusCode", e.getExportStatus());+ if (e.getCreatedAt() > 0) {+ status.put("CreatedAt", Instant.ofEpochMilli(e.getCreatedAt()).toString());+ }+ if (e.getLastUpdatedAt() > 0) {+ status.put("LastUpdatedAt", Instant.ofEpochMilli(e.getLastUpdatedAt()).toString());+ }+ }+ return out;+ }++ private ObjectNode serializeExportReference(Export e) {+ ObjectNode out = objectMapper.createObjectNode();+ out.put("ExportArn", e.getExportArn());+ out.put("ExportName", e.getName());+ if (e.getExportStatus() != null) {+ ObjectNode status = out.putObject("ExportStatus");+ status.put("StatusCode", e.getExportStatus());+ }+ return out;+ }++ private ObjectNode serializeExecution(ExportExecution exec) {+ ObjectNode out = objectMapper.createObjectNode();+ out.put("ExecutionId", exec.getExecutionId());+ out.put("ExportArn", exec.getExportArn());+ if (exec.getExportStatus() != null) {+ ObjectNode status = out.putObject("ExecutionStatus");+ status.put("StatusCode", exec.getExportStatus());+ if (exec.getCreatedBy() != null) status.put("CreatedBy", exec.getCreatedBy());+ if (exec.getCreatedAt() > 0) status.put("CreatedAt",+ Instant.ofEpochMilli(exec.getCreatedAt()).toString());+ if (exec.getCompletedAt() > 0) status.put("CompletedAt",+ Instant.ofEpochMilli(exec.getCompletedAt()).toString());+ if (exec.getStatusReason() != null) status.put("StatusReason", exec.getStatusReason());+ }+ return out;+ }++ private static String stringOrNull(JsonNode node, String field) {+ JsonNode value = node == null ? null : node.get(field);+ return (value != null && !value.isNull()) ? value.asText() : null;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsService.java b/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsService.javanew file mode 100644index 0000000000..8d2fe77445--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsService.java@@ -0,0 +1,399 @@+package io.github.hectorvent.floci.services.bcmdataexports;++import com.fasterxml.jackson.core.type.TypeReference;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.StorageBackend;+import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.bcmdataexports.model.DataQuery;+import io.github.hectorvent.floci.services.bcmdataexports.model.DestinationConfiguration;+import io.github.hectorvent.floci.services.bcmdataexports.model.Export;+import io.github.hectorvent.floci.services.bcmdataexports.model.ExportExecution;+import io.github.hectorvent.floci.services.bcmdataexports.model.RefreshCadence;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.util.ArrayList;+import java.util.Collection;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.UUID;+import java.util.regex.Pattern;++/**+ * AWS BCM Data Exports management plane.+ * <p>+ * Persists {@link Export} records (keyed by {@code <accountId>::<exportArn>})+ * and {@link ExportExecution} records (keyed by+ * {@code <accountId>::<exportArn>::<executionId>}). Account-scoping mirrors+ * AWS behavior where exports are private to the owning account.+ *+ * <p>This class is management-plane only — Parquet emission lands in a+ * follow-up step on the same branch.+ *+ * @see <a href="https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_Operations_AWS_Billing_and_Cost_Management_Data_Exports.html">BCM Data Exports API</a>+ */+@ApplicationScoped+public class BcmDataExportsService {++ private static final Logger LOG = Logger.getLogger(BcmDataExportsService.class);++ private static final Pattern EXPORT_NAME_PATTERN = Pattern.compile("[A-Za-z0-9_-]+");+ private static final Set<String> ALLOWED_FREQUENCY = Set.of("SYNCHRONOUS");+ /**+ * Floci only emits Parquet at the moment. Real AWS also accepts+ * {@code TEXT_OR_CSV} / {@code GZIP} but Floci's emission engine writes+ * Parquet unconditionally; accepting other formats would let a definition+ * persist that no consumer can read. Restrict until CSV/GZIP support lands.+ */+ private static final Set<String> ALLOWED_FORMAT = Set.of("PARQUET");+ private static final Set<String> ALLOWED_COMPRESSION = Set.of("PARQUET");+ private static final Set<String> ALLOWED_OVERWRITE = Set.of("CREATE_NEW_REPORT", "OVERWRITE_REPORT");+ private static final Set<String> ALLOWED_OUTPUT_TYPE = Set.of("CUSTOM");++ private final StorageBackend<String, Export> exportStore;+ private final StorageBackend<String, ExportExecution> executionStore;+ private final RegionResolver regionResolver;++ @Inject+ public BcmDataExportsService(StorageFactory storageFactory, RegionResolver regionResolver) {+ this(storageFactory.create("bcmdataexports", "bcm-exports.json",+ new TypeReference<Map<String, Export>>() {}),+ storageFactory.create("bcmdataexports", "bcm-executions.json",+ new TypeReference<Map<String, ExportExecution>>() {}),+ regionResolver);+ }++ BcmDataExportsService(StorageBackend<String, Export> exportStore,+ StorageBackend<String, ExportExecution> executionStore,+ RegionResolver regionResolver) {+ this.exportStore = exportStore;+ this.executionStore = executionStore;+ this.regionResolver = regionResolver;+ }++ /** {@code CreateExport} — creates and persists a new {@link Export}. */+ public Export createExport(Export incoming, Map<String, String> resourceTags, String region) {+ validateExport(incoming);+ String accountId = regionResolver.getAccountId();++ if (findByName(incoming.getName()) != null) {+ throw new AwsException("ValidationException",+ "An export with the name " + incoming.getName() + " already exists.", 400);+ }++ String exportArn = buildArn(region, accountId, incoming.getName());+ long now = System.currentTimeMillis();+ incoming.setExportArn(exportArn);+ incoming.setCreatedAt(now);+ incoming.setLastUpdatedAt(now);+ incoming.setExportStatus("HEALTHY");+ incoming.setOwnerAccountId(accountId);+ if (resourceTags != null) {+ incoming.setResourceTags(new HashMap<>(resourceTags));+ }++ exportStore.put(exportKey(exportArn), incoming);+ LOG.infov("Created BCM export: {0} (arn={1})", incoming.getName(), exportArn);+ return incoming;+ }++ /** {@code GetExport} — returns the {@link Export} matching {@code exportArn}. */+ public Export getExport(String exportArn) {+ requireNonEmpty(exportArn, "ExportArn");+ return exportStore.get(exportKey(exportArn))+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",+ "Export " + exportArn + " not found.", 400));+ }++ /** {@code ListExports} — returns every export owned by the calling account. */+ public List<Export> listExports() {+ return new ArrayList<>(exportStore.scan(key -> true));+ }++ /**+ * Returns every export across every account, grouped by+ * {@code ownerAccountId}. Used by the background emission scheduler to+ * iterate exports outside a request scope.+ */+ public Map<String, List<Export>> listAllExportsByAccount() {+ Collection<Export> all;+ if (exportStore instanceof io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend<?> aware) {+ @SuppressWarnings("unchecked")+ io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend<Export> typed =+ (io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend<Export>) aware;+ all = typed.scanAllAccounts();+ } else {+ all = exportStore.scan(key -> true);+ }+ Map<String, List<Export>> result = new java.util.LinkedHashMap<>();+ for (Export export : all) {+ String account = export.getOwnerAccountId();+ if (account == null || account.isEmpty()) {+ account = regionResolver.getAccountId();+ }+ result.computeIfAbsent(account, a -> new ArrayList<>()).add(export);+ }+ return result;+ }++ /** {@code UpdateExport} — replaces an export's mutable fields. */+ public Export updateExport(String exportArn, Export incoming) {+ requireNonEmpty(exportArn, "ExportArn");+ validateExport(incoming);+ String key = exportKey(exportArn);+ Export existing = exportStore.get(key).orElseThrow(() -> new AwsException(+ "ResourceNotFoundException",+ "Export " + exportArn + " not found.", 400));++ incoming.setExportArn(exportArn);+ incoming.setCreatedAt(existing.getCreatedAt());+ incoming.setLastUpdatedAt(System.currentTimeMillis());+ incoming.setExportStatus(existing.getExportStatus() == null ? "HEALTHY" : existing.getExportStatus());+ incoming.setOwnerAccountId(existing.getOwnerAccountId() != null+ ? existing.getOwnerAccountId() : regionResolver.getAccountId());+ if (incoming.getResourceTags() == null || incoming.getResourceTags().isEmpty()) {+ incoming.setResourceTags(existing.getResourceTags());+ }+ exportStore.put(key, incoming);+ LOG.infov("Updated BCM export: {0}", exportArn);+ return incoming;+ }++ /** {@code DeleteExport} — removes an export. Idempotent. */+ public Export deleteExport(String exportArn) {+ requireNonEmpty(exportArn, "ExportArn");+ String key = exportKey(exportArn);+ Export existing = exportStore.get(key).orElse(null);+ if (existing == null) {+ return null;+ }+ exportStore.delete(key);+ // Also remove any executions tied to this export to avoid orphan records.+ String execPrefix = exportArn + "::";+ for (String execKey : new ArrayList<>(executionStore.keys())) {+ if (execKey.startsWith(execPrefix)) {+ executionStore.delete(execKey);+ }+ }+ LOG.infov("Deleted BCM export: {0}", exportArn);+ return existing;+ }++ /** {@code ListExecutions} — returns every recorded execution for the export. */+ public List<ExportExecution> listExecutions(String exportArn) {+ requireNonEmpty(exportArn, "ExportArn");+ if (exportStore.get(exportKey(exportArn)).isEmpty()) {+ throw new AwsException("ResourceNotFoundException",+ "Export " + exportArn + " not found.", 400);+ }+ String prefix = exportArn + "::";+ return new ArrayList<>(executionStore.scan(key -> key.startsWith(prefix)));+ }++ /** {@code GetExecution} — returns one execution record. */+ public ExportExecution getExecution(String exportArn, String executionId) {+ requireNonEmpty(exportArn, "ExportArn");+ requireNonEmpty(executionId, "ExecutionId");+ return executionStore.get(executionKey(exportArn, executionId))+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",+ "Execution " + executionId + " not found.", 400));+ }++ // ── Internal helpers exposed package-private for the emitter (next step) ──++ /**+ * Records a fresh execution under {@code accountId}. Used by the emission+ * scheduler. Writes through {@link io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend#putForAccount}+ * when available so background calls outside a request scope still land in+ * the correct account partition.+ */+ public ExportExecution recordExecution(String accountId, String exportArn, String createdBy) {+ ExportExecution exec = new ExportExecution();+ exec.setExecutionId(UUID.randomUUID().toString());+ exec.setExportArn(exportArn);+ exec.setExportStatus("INITIATION_IN_PROCESS");+ exec.setCreatedBy(createdBy);+ exec.setCreatedAt(System.currentTimeMillis());+ String key = executionKey(exportArn, exec.getExecutionId());+ if (executionStore instanceof io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend<?> aware) {+ @SuppressWarnings("unchecked")+ io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend<ExportExecution> typed =+ (io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend<ExportExecution>) aware;+ typed.putForAccount(accountId, key, exec);+ } else {+ executionStore.put(key, exec);+ }+ return exec;+ }++ /**+ * Extracts the account-id segment from a BCM export ARN. Returns the default+ * account when the ARN doesn't carry one — matches Floci's single-account+ * behavior for callers that don't pass a 12-digit access key.+ */+ public String accountIdFromArn(String arn) {+ if (arn == null) {+ return regionResolver.getAccountId();+ }+ // arn:aws:bcm-data-exports:<region>:<account>:export/<name>+ String[] parts = arn.split(":", 6);+ if (parts.length >= 5 && !parts[4].isEmpty()) {+ return parts[4];+ }+ return regionResolver.getAccountId();+ }++ public void completeExecution(String accountId, ExportExecution exec, boolean success, String reason) {+ exec.setExportStatus(success ? "DELIVERY_SUCCESS" : "DELIVERY_FAILURE");+ exec.setCompletedAt(System.currentTimeMillis());+ if (reason != null) {+ exec.setStatusReason(reason);+ }+ String key = executionKey(exec.getExportArn(), exec.getExecutionId());+ if (executionStore instanceof io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend<?> aware) {+ @SuppressWarnings("unchecked")+ io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend<ExportExecution> typed =+ (io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend<ExportExecution>) aware;+ typed.putForAccount(accountId, key, exec);+ } else {+ executionStore.put(key, exec);+ }+ }++ private Export findByName(String name) {+ for (Export candidate : exportStore.scan(key -> true)) {+ if (name.equals(candidate.getName())) {+ return candidate;+ }+ }+ return null;+ }++ private void validateExport(Export e) {+ if (e == null) {+ throw new AwsException("ValidationException", "Export is required.", 400);+ }+ requireNonEmpty(e.getName(), "Export.Name");+ if (!EXPORT_NAME_PATTERN.matcher(e.getName()).matches()) {+ throw new AwsException("ValidationException",+ "Export.Name may only contain alphanumeric characters, hyphens, and underscores.", 400);+ }+ if (e.getName().length() > 128) {+ throw new AwsException("ValidationException",+ "Export.Name must be at most 128 characters long.", 400);+ }+ DataQuery dq = e.getDataQuery();+ if (dq == null || dq.getQueryStatement() == null || dq.getQueryStatement().isEmpty()) {+ throw new AwsException("ValidationException",+ "Export.DataQuery.QueryStatement is required.", 400);+ }+ validateDestination(e.getDestinationConfigurations());+ validateRefreshCadence(e.getRefreshCadence());+ }++ private void validateDestination(DestinationConfiguration dest) {+ if (dest == null || dest.getS3Destination() == null) {+ throw new AwsException("ValidationException",+ "Export.DestinationConfigurations.S3Destination is required.", 400);+ }+ DestinationConfiguration.S3Destination s3 = dest.getS3Destination();+ requireNonEmpty(s3.getS3Bucket(), "S3Destination.S3Bucket");+ requireValidBucketName(s3.getS3Bucket(), "S3Destination.S3Bucket");+ requireNonEmpty(s3.getS3Region(), "S3Destination.S3Region");+ if (s3.getS3Prefix() == null) {+ s3.setS3Prefix("");+ } else if (!s3.getS3Prefix().isEmpty()) {+ requireSafeKeySegment(s3.getS3Prefix(), "S3Destination.S3Prefix");+ }+ DestinationConfiguration.S3OutputConfigurations out = s3.getS3OutputConfigurations();+ if (out != null) {+ if (out.getFormat() != null && !ALLOWED_FORMAT.contains(out.getFormat())) {+ throw new AwsException("ValidationException",+ "S3OutputConfigurations.Format must be one of " + ALLOWED_FORMAT, 400);+ }+ if (out.getCompression() != null && !ALLOWED_COMPRESSION.contains(out.getCompression())) {+ throw new AwsException("ValidationException",+ "S3OutputConfigurations.Compression must be one of " + ALLOWED_COMPRESSION, 400);+ }+ if (out.getOverwrite() != null && !ALLOWED_OVERWRITE.contains(out.getOverwrite())) {+ throw new AwsException("ValidationException",+ "S3OutputConfigurations.Overwrite must be one of " + ALLOWED_OVERWRITE, 400);+ }+ if (out.getOutputType() != null && !ALLOWED_OUTPUT_TYPE.contains(out.getOutputType())) {+ throw new AwsException("ValidationException",+ "S3OutputConfigurations.OutputType must be one of " + ALLOWED_OUTPUT_TYPE, 400);+ }+ }+ }++ private void validateRefreshCadence(RefreshCadence cadence) {+ if (cadence == null) {+ throw new AwsException("ValidationException",+ "Export.RefreshCadence is required.", 400);+ }+ if (!ALLOWED_FREQUENCY.contains(cadence.getFrequency())) {+ throw new AwsException("ValidationException",+ "RefreshCadence.Frequency must be one of " + ALLOWED_FREQUENCY, 400);+ }+ }++ private String buildArn(String region, String accountId, String exportName) {+ return regionResolver.buildArn("bcm-data-exports", region, "export/" + exportName);+ }++ private static String exportKey(String exportArn) {+ return exportArn;+ }++ private static String executionKey(String exportArn, String executionId) {+ return exportArn + "::" + executionId;+ }++ private static void requireNonEmpty(String value, String field) {+ if (value == null || value.isEmpty()) {+ throw new AwsException("ValidationException",+ "1 validation error detected: Value at '" + field + "' failed to satisfy constraint: Member must not be null.", 400);+ }+ }++ private static void requireValidBucketName(String bucket, String field) {+ if (bucket.length() < 3 || bucket.length() > 63) {+ throw new AwsException("ValidationException",+ field + " must be between 3 and 63 characters.", 400);+ }+ for (int i = 0; i < bucket.length(); i++) {+ char c = bucket.charAt(i);+ boolean valid = (c >= 'a' && c <= 'z')+ || (c >= '0' && c <= '9')+ || c == '-' || c == '.';+ if (!valid) {+ throw new AwsException("ValidationException",+ field + " contains invalid characters.", 400);+ }+ }+ if (bucket.startsWith("-") || bucket.endsWith("-")+ || bucket.startsWith(".") || bucket.endsWith(".")+ || bucket.contains("..")) {+ throw new AwsException("ValidationException",+ field + " is not a valid S3 bucket name.", 400);+ }+ }++ private static void requireSafeKeySegment(String value, String field) {+ for (int i = 0; i < value.length(); i++) {+ char c = value.charAt(i);+ boolean ok = (c >= 'A' && c <= 'Z')+ || (c >= 'a' && c <= 'z')+ || (c >= '0' && c <= '9')+ || c == '-' || c == '_' || c == '.' || c == '/';+ if (!ok) {+ throw new AwsException("ValidationException",+ field + " contains characters not permitted in an S3 key segment.", 400);+ }+ }+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/model/DataQuery.java b/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/model/DataQuery.javanew file mode 100644index 0000000000..712ec97cfc--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/model/DataQuery.java@@ -0,0 +1,25 @@+package io.github.hectorvent.floci.services.bcmdataexports.model;++import com.fasterxml.jackson.annotation.JsonInclude;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.HashMap;+import java.util.Map;++/**+ * AWS BCM Data Exports {@code DataQuery}.+ * Carries the SQL query statement plus per-table configuration.+ */+@RegisterForReflection+@JsonInclude(JsonInclude.Include.NON_NULL)+public class DataQuery {++ private String queryStatement;+ private Map<String, Map<String, String>> tableConfigurations = new HashMap<>();++ public String getQueryStatement() { return queryStatement; }+ public void setQueryStatement(String v) { this.queryStatement = v; }++ public Map<String, Map<String, String>> getTableConfigurations() { return tableConfigurations; }+ public void setTableConfigurations(Map<String, Map<String, String>> v) { this.tableConfigurations = v; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/model/DestinationConfiguration.java b/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/model/DestinationConfiguration.javanew file mode 100644index 0000000000..c718b44a78--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/model/DestinationConfiguration.java@@ -0,0 +1,59 @@+package io.github.hectorvent.floci.services.bcmdataexports.model;++import com.fasterxml.jackson.annotation.JsonInclude;+import io.quarkus.runtime.annotations.RegisterForReflection;++/**+ * S3 destination + output config for a BCM Data Exports {@code Export}.+ */+@RegisterForReflection+@JsonInclude(JsonInclude.Include.NON_NULL)+public class DestinationConfiguration {++ private S3Destination s3Destination;++ public S3Destination getS3Destination() { return s3Destination; }+ public void setS3Destination(S3Destination v) { this.s3Destination = v; }++ @RegisterForReflection+ @JsonInclude(JsonInclude.Include.NON_NULL)+ public static class S3Destination {+ private String s3Bucket;+ private String s3Prefix;+ private String s3Region;+ private S3OutputConfigurations s3OutputConfigurations;++ public String getS3Bucket() { return s3Bucket; }+ public void setS3Bucket(String v) { this.s3Bucket = v; }++ public String getS3Prefix() { return s3Prefix; }+ public void setS3Prefix(String v) { this.s3Prefix = v; }++ public String getS3Region() { return s3Region; }+ public void setS3Region(String v) { this.s3Region = v; }++ public S3OutputConfigurations getS3OutputConfigurations() { return s3OutputConfigurations; }+ public void setS3OutputConfigurations(S3OutputConfigurations v) { this.s3OutputConfigurations = v; }+ }++ @RegisterForReflection+ @JsonInclude(JsonInclude.Include.NON_NULL)+ public static class S3OutputConfigurations {+ private String compression; // GZIP | PARQUET+ private String format; // TEXT_OR_CSV | PARQUET+ private String outputType; // CUSTOM+ private String overwrite; // CREATE_NEW_REPORT | OVERWRITE_REPORT++ public String getCompression() { return compression; }+ public void setCompression(String v) { this.compression = v; }++ public String getFormat() { return format; }+ public void setFormat(String v) { this.format = v; }++ public String getOutputType() { return outputType; }+ public void setOutputType(String v) { this.outputType = v; }++ public String getOverwrite() { return overwrite; }+ public void setOverwrite(String v) { this.overwrite = v; }+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/model/Export.java b/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/model/Export.javanew file mode 100644index 0000000000..3807d420f6--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/model/Export.java@@ -0,0 +1,70 @@+package io.github.hectorvent.floci.services.bcmdataexports.model;++import com.fasterxml.jackson.annotation.JsonInclude;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.HashMap;+import java.util.Map;++/**+ * AWS BCM Data Exports {@code Export} record.+ *+ * @see <a href="https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_bcm-data-exports_Export.html">Export</a>+ */+@RegisterForReflection+@JsonInclude(JsonInclude.Include.NON_NULL)+public class Export {++ private String exportArn;+ private String name;+ private String description;+ private DataQuery dataQuery;+ private DestinationConfiguration destinationConfigurations;+ private RefreshCadence refreshCadence;+ private long createdAt;+ private long lastUpdatedAt;+ private String exportStatus; // HEALTHY | UNHEALTHY+ private Map<String, String> resourceTags = new HashMap<>();+ /**+ * Snapshot of the account that owned the request that created this export.+ * Used by the background emission scheduler to locate the export under the+ * right account partition. Not surfaced in AWS wire responses.+ */+ private String ownerAccountId;++ public Export() {+ }++ public String getExportArn() { return exportArn; }+ public void setExportArn(String v) { this.exportArn = v; }++ public String getName() { return name; }+ public void setName(String v) { this.name = v; }++ public String getDescription() { return description; }+ public void setDescription(String v) { this.description = v; }++ public DataQuery getDataQuery() { return dataQuery; }+ public void setDataQuery(DataQuery v) { this.dataQuery = v; }++ public DestinationConfiguration getDestinationConfigurations() { return destinationConfigurations; }+ public void setDestinationConfigurations(DestinationConfiguration v) { this.destinationConfigurations = v; }++ public RefreshCadence getRefreshCadence() { return refreshCadence; }+ public void setRefreshCadence(RefreshCadence v) { this.refreshCadence = v; }++ public long getCreatedAt() { return createdAt; }+ public void setCreatedAt(long v) { this.createdAt = v; }++ public long getLastUpdatedAt() { return lastUpdatedAt; }+ public void setLastUpdatedAt(long v) { this.lastUpdatedAt = v; }++ public String getExportStatus() { return exportStatus; }+ public void setExportStatus(String v) { this.exportStatus = v; }++ public Map<String, String> getResourceTags() { return resourceTags; }+ public void setResourceTags(Map<String, String> v) { this.resourceTags = v; }++ public String getOwnerAccountId() { return ownerAccountId; }+ public void setOwnerAccountId(String v) { this.ownerAccountId = v; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/model/ExportExecution.java b/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/model/ExportExecution.javanew file mode 100644index 0000000000..aec9903b06--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/model/ExportExecution.java@@ -0,0 +1,41 @@+package io.github.hectorvent.floci.services.bcmdataexports.model;++import com.fasterxml.jackson.annotation.JsonInclude;+import io.quarkus.runtime.annotations.RegisterForReflection;++/**+ * Tracking record for a single execution of an {@link Export}.+ */+@RegisterForReflection+@JsonInclude(JsonInclude.Include.NON_NULL)+public class ExportExecution {++ private String executionId;+ private String exportArn;+ private String exportStatus; // INITIATION_IN_PROCESS | QUERY_QUEUED | QUERY_IN_PROCESS | QUERY_FAILURE | DELIVERY_IN_PROCESS | DELIVERY_SUCCESS | DELIVERY_FAILURE+ private String createdBy; // USER | SCHEDULE+ private long createdAt;+ private long completedAt;+ private String statusReason; // free-text on failure++ public String getExecutionId() { return executionId; }+ public void setExecutionId(String v) { this.executionId = v; }++ public String getExportArn() { return exportArn; }+ public void setExportArn(String v) { this.exportArn = v; }++ public String getExportStatus() { return exportStatus; }+ public void setExportStatus(String v) { this.exportStatus = v; }++ public String getCreatedBy() { return createdBy; }+ public void setCreatedBy(String v) { this.createdBy = v; }++ public long getCreatedAt() { return createdAt; }+ public void setCreatedAt(long v) { this.createdAt = v; }++ public long getCompletedAt() { return completedAt; }+ public void setCompletedAt(long v) { this.completedAt = v; }++ public String getStatusReason() { return statusReason; }+ public void setStatusReason(String v) { this.statusReason = v; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/model/RefreshCadence.java b/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/model/RefreshCadence.javanew file mode 100644index 0000000000..72e7730885--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/model/RefreshCadence.java@@ -0,0 +1,18 @@+package io.github.hectorvent.floci.services.bcmdataexports.model;++import com.fasterxml.jackson.annotation.JsonInclude;+import io.quarkus.runtime.annotations.RegisterForReflection;++/**+ * Cadence at which a BCM Data Exports {@code Export} refreshes its data.+ * AWS supports {@code FREQUENCY} = {@code SYNCHRONOUS} only at the time of writing.+ */+@RegisterForReflection+@JsonInclude(JsonInclude.Include.NON_NULL)+public class RefreshCadence {++ private String frequency; // SYNCHRONOUS++ public String getFrequency() { return frequency; }+ public void setFrequency(String v) { this.frequency = v; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cur/CurEmissionScheduler.java b/src/main/java/io/github/hectorvent/floci/services/cur/CurEmissionScheduler.javanew file mode 100644index 0000000000..52a47938af--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cur/CurEmissionScheduler.java@@ -0,0 +1,259 @@+package io.github.hectorvent.floci.services.cur;++import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.services.bcmdataexports.BcmDataExportsService;+import io.github.hectorvent.floci.services.bcmdataexports.model.DestinationConfiguration;+import io.github.hectorvent.floci.services.bcmdataexports.model.Export;+import io.github.hectorvent.floci.services.bcmdataexports.model.ExportExecution;+import io.github.hectorvent.floci.core.common.RequestContext;+import io.github.hectorvent.floci.services.cur.model.ReportDefinition;+import io.quarkus.arc.Arc;+import io.quarkus.arc.ManagedContext;+import io.quarkus.runtime.ShutdownEvent;+import io.quarkus.runtime.Startup;+import jakarta.annotation.PostConstruct;+import jakarta.enterprise.context.ApplicationScoped;+import java.util.Map;+import jakarta.enterprise.event.Observes;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.util.concurrent.Executors;+import java.util.concurrent.ScheduledExecutorService;+import java.util.concurrent.TimeUnit;++/**+ * CUR / BCM Data Exports emission orchestrator.+ * <p>+ * Two run modes, controlled separately for CUR ({@code FLOCI_SERVICES_CUR_EMIT_MODE})+ * and BCM ({@code FLOCI_SERVICES_BCM_DATA_EXPORTS_EMIT_MODE}):+ * <ul>+ * <li>{@code synchronous} (default): emit on every report/export mutation+ * (called inline from the management plane).</li>+ * <li>{@code daily}: emit every 24h via a CUR-owned single-thread+ * {@link ScheduledExecutorService}.</li>+ * <li>{@code off}: never emit; management plane only.</li>+ * </ul>+ *+ * <p>This class is intentionally separate from+ * {@code services.scheduler.ScheduleDispatcher}: that dispatcher is the+ * EventBridge Scheduler target invoker visible to user-facing schedules and+ * pipes, and conflating internal billing-export jobs with it would couple+ * implementation to an unrelated user surface.+ */+@Startup+@ApplicationScoped+public class CurEmissionScheduler {++ private static final Logger LOG = Logger.getLogger(CurEmissionScheduler.class);+ private static final long DAILY_INTERVAL_SECONDS = 24L * 60L * 60L;+ private static final long DAILY_INITIAL_DELAY_SECONDS = 5L;++ private final EmulatorConfig config;+ private final CurService curService;+ private final BcmDataExportsService bcmService;+ private final EmissionEngine engine;++ private ScheduledExecutorService executor;++ @Inject+ public CurEmissionScheduler(EmulatorConfig config,+ CurService curService,+ BcmDataExportsService bcmService,+ EmissionEngine engine) {+ this.config = config;+ this.curService = curService;+ this.bcmService = bcmService;+ this.engine = engine;+ }++ @PostConstruct+ void start() {+ boolean curDaily = "daily".equals(config.services().cur().emitMode());+ boolean bcmDaily = "daily".equals(config.services().bcmDataExports().emitMode());+ if (!curDaily && !bcmDaily) {+ return;+ }+ executor = Executors.newSingleThreadScheduledExecutor(r -> {+ Thread t = new Thread(r, "cur-emission-scheduler");+ t.setDaemon(true);+ return t;+ });+ executor.scheduleAtFixedRate(this::runDaily,+ DAILY_INITIAL_DELAY_SECONDS, DAILY_INTERVAL_SECONDS, TimeUnit.SECONDS);+ LOG.infov("CUR daily emission scheduler started (cur={0}, bcm={1})", curDaily, bcmDaily);+ }++ void stop(@Observes ShutdownEvent event) {+ if (executor != null) {+ executor.shutdownNow();+ executor = null;+ }+ }++ /**+ * Synchronous emission hook for CUR. Called by {@link CurService} after+ * {@code PutReportDefinition} / {@code ModifyReportDefinition} when+ * {@code emit-mode=synchronous}; in {@code daily} mode the periodic loop+ * handles emission instead.+ */+ public void emitForReportSync(ReportDefinition definition, String region) {+ if (!"synchronous".equals(config.services().cur().emitMode())) {+ return;+ }+ emitForReport(definition, region);+ }++ /**+ * Synchronous emission hook for BCM Data Exports. Records an+ * {@link ExportExecution} bracketing the emission so callers can poll+ * {@code GetExecution} for the result.+ */+ public ExportExecution emitForExportSync(Export export, String region, String createdBy) {+ if (!"synchronous".equals(config.services().bcmDataExports().emitMode())) {+ return null;+ }+ return emitForExport(export, region, createdBy);+ }++ /**+ * Periodic loop body. Catches all exceptions so the scheduler stays alive.+ * Iterates every account that owns a report or export — necessary because+ * the loop runs outside any request scope, so the storage backend can't+ * resolve the calling account by itself.+ */+ private void runDaily() {+ try {+ if ("daily".equals(config.services().cur().emitMode())) {+ for (Map.Entry<String, java.util.List<ReportDefinition>> perAccount+ : curService.listAllReportsByAccount().entrySet()) {+ String accountId = perAccount.getKey();+ for (ReportDefinition def : perAccount.getValue()) {+ try {+ runUnderAccount(accountId,+ () -> { emitForReport(accountId, def, def.getS3Region()); return null; });+ } catch (RuntimeException e) {+ LOG.warnv(e, "Daily CUR emission failed for {0} (account={1})",+ def.getReportName(), accountId);+ }+ }+ }+ }+ if ("daily".equals(config.services().bcmDataExports().emitMode())) {+ for (Map.Entry<String, java.util.List<Export>> perAccount+ : bcmService.listAllExportsByAccount().entrySet()) {+ String accountId = perAccount.getKey();+ for (Export export : perAccount.getValue()) {+ try {+ runUnderAccount(accountId,+ () -> { emitForExport(accountId, export, exportRegionOf(export), "SCHEDULE"); return null; });+ } catch (RuntimeException e) {+ LOG.warnv(e, "Daily BCM emission failed for {0} (account={1})",+ export.getExportArn(), accountId);+ }+ }+ }+ }+ } catch (RuntimeException outer) {+ LOG.errorv(outer, "Daily emission loop failed");+ }+ }++ /**+ * Activates a synthetic CDI request scope with+ * {@link RequestContext#setAccountId} set to {@code accountId}, runs+ * {@code body}, and terminates the scope.+ *+ * <p>The Java-side staging writes that {@link ParquetEmitter} performs+ * (NDJSON staging into {@code floci-cur-staging} via {@code S3Service},+ * cleanup of that staged object) flow through+ * {@code AccountAwareStorageBackend}, which reads the calling account from+ * the active request context. The daily scheduler runs outside any+ * incoming HTTP request and would otherwise fall back to the configured+ * default account — meanwhile the DuckDB-side reads/writes already use+ * the explicit owner account passed via {@code FlociDuckClient}, so the+ * two sides would mismatch and DuckDB would 404 on the staging object.+ * Activating a request scope here keeps both sides on the same account.+ */+ private void runUnderAccount(String accountId, java.util.function.Supplier<Void> body) {+ ManagedContext requestContext = Arc.container().requestContext();+ boolean alreadyActive = requestContext.isActive();+ if (!alreadyActive) {+ requestContext.activate();+ }+ try {+ RequestContext ctx = Arc.container().instance(RequestContext.class).get();+ ctx.setAccountId(accountId);+ body.get();+ } finally {+ if (!alreadyActive) {+ requestContext.terminate();+ }+ }+ }++ private void emitForReport(ReportDefinition definition, String region) {+ // ownerAccountId is set by CurService at PutReportDefinition time, so+ // it always reflects the request account that created the report.+ emitForReport(definition.getOwnerAccountId(), definition, region);+ }++ private void emitForReport(String accountId, ReportDefinition definition, String region) {+ try {+ engine.emitForCurrentMonth(+ definition.getReportName(),+ definition.getS3Bucket(),+ definition.getS3Prefix(),+ region,+ accountId);+ if (accountId != null) {+ curService.markReportStatusForAccount(accountId,+ definition.getReportName(), region, "SUCCESS");+ } else {+ curService.markReportStatus(definition.getReportName(), region, "SUCCESS");+ }+ } catch (RuntimeException e) {+ if (accountId != null) {+ curService.markReportStatusForAccount(accountId,+ definition.getReportName(), region, "ERROR");+ } else {+ curService.markReportStatus(definition.getReportName(), region, "ERROR");+ }+ throw e;+ }+ }++ private ExportExecution emitForExport(Export export, String region, String createdBy) {+ String accountId = export.getOwnerAccountId() != null+ ? export.getOwnerAccountId()+ : bcmService.accountIdFromArn(export.getExportArn());+ return emitForExport(accountId, export, region, createdBy);+ }++ private ExportExecution emitForExport(String accountId, Export export, String region, String createdBy) {+ ExportExecution exec = bcmService.recordExecution(accountId, export.getExportArn(), createdBy);+ try {+ DestinationConfiguration.S3Destination dest =+ export.getDestinationConfigurations().getS3Destination();+ engine.emitForCurrentMonth(+ export.getName(),+ dest.getS3Bucket(),+ dest.getS3Prefix(),+ dest.getS3Region() != null ? dest.getS3Region() : region,+ accountId);+ bcmService.completeExecution(accountId, exec, true, null);+ return exec;+ } catch (RuntimeException e) {+ bcmService.completeExecution(accountId, exec, false, e.getMessage());+ throw e;+ }+ }++ private String exportRegionOf(Export export) {+ if (export.getDestinationConfigurations() == null+ || export.getDestinationConfigurations().getS3Destination() == null) {+ return null;+ }+ return export.getDestinationConfigurations().getS3Destination().getS3Region();+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cur/CurJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cur/CurJsonHandler.javanew file mode 100644index 0000000000..204058340c--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cur/CurJsonHandler.java@@ -0,0 +1,179 @@+package io.github.hectorvent.floci.services.cur;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ArrayNode;+import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.core.common.AwsErrorResponse;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.services.cur.model.ReportDefinition;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import jakarta.ws.rs.core.Response;+import org.jboss.logging.Logger;++import java.util.ArrayList;+import java.util.List;++/**+ * JSON 1.1 handler for AWS CUR operations.+ * Dispatches {@code X-Amz-Target: AWSOrigamiServiceGatewayService.*} actions to+ * {@link CurService}.+ */+@ApplicationScoped+public class CurJsonHandler {++ private static final Logger LOG = Logger.getLogger(CurJsonHandler.class);++ private final CurService service;+ private final ObjectMapper objectMapper;+ private final CurEmissionScheduler scheduler;++ @Inject+ public CurJsonHandler(CurService service, ObjectMapper objectMapper, CurEmissionScheduler scheduler) {+ this.service = service;+ this.objectMapper = objectMapper;+ this.scheduler = scheduler;+ }++ public Response handle(String action, JsonNode request, String region) {+ LOG.debugv("CUR action: {0}", action);+ return switch (action) {+ case "PutReportDefinition" -> handlePutReportDefinition(request, region);+ case "ModifyReportDefinition" -> handleModifyReportDefinition(request, region);+ case "DescribeReportDefinitions" -> handleDescribeReportDefinitions();+ case "DeleteReportDefinition" -> handleDeleteReportDefinition(request, region);+ // Tag endpoints are not yet emulated; respond with empty bodies so SDK+ // clients that probe for them don't trip on UnknownOperationException.+ case "TagResource", "UntagResource" -> Response.ok(objectMapper.createObjectNode()).build();+ case "ListTagsForResource" -> {+ ObjectNode body = objectMapper.createObjectNode();+ body.putArray("Tags");+ yield Response.ok(body).build();+ }+ default -> Response.status(400)+ .entity(new AwsErrorResponse("UnknownOperationException",+ "Unknown operation: AWSOrigamiServiceGatewayService." + action))+ .build();+ };+ }++ private Response handlePutReportDefinition(JsonNode request, String region) {+ ReportDefinition def = parseReportDefinition(request.path("ReportDefinition"));+ ReportDefinition created = service.putReportDefinition(def, region);+ // Emission failures must not roll back the management mutation — match AWS+ // semantics where the definition is created even if the first run errors.+ try {+ scheduler.emitForReportSync(created, region);+ } catch (RuntimeException e) {+ LOG.warnv(e, "Synchronous emission failed for {0}; report still created.", created.getReportName());+ }+ // Re-read after emission so the response reflects the post-emit ReportStatus.+ return Response.ok(serialize(service.getReportDefinitionOrSelf(created, region))).build();+ }++ private Response handleModifyReportDefinition(JsonNode request, String region) {+ String reportName = stringOrNull(request, "ReportName");+ ReportDefinition def = parseReportDefinition(request.path("ReportDefinition"));+ ReportDefinition updated = service.modifyReportDefinition(reportName, def, region);+ try {+ scheduler.emitForReportSync(updated, region);+ } catch (RuntimeException e) {+ LOG.warnv(e, "Synchronous emission failed for {0}; report still updated.", updated.getReportName());+ }+ return Response.ok(serialize(service.getReportDefinitionOrSelf(updated, region))).build();+ }++ private Response handleDescribeReportDefinitions() {+ List<ReportDefinition> defs = service.describeReportDefinitions();+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode arr = response.putArray("ReportDefinitions");+ for (ReportDefinition d : defs) {+ arr.add(serialize(d));+ }+ return Response.ok(response).build();+ }++ private Response handleDeleteReportDefinition(JsonNode request, String region) {+ String reportName = stringOrNull(request, "ReportName");+ ReportDefinition removed = service.deleteReportDefinition(reportName, region);+ ObjectNode response = objectMapper.createObjectNode();+ if (removed != null) {+ response.put("ResponseMessage", "Report " + reportName + " has been deleted.");+ }+ return Response.ok(response).build();+ }++ private ReportDefinition parseReportDefinition(JsonNode node) {+ if (node == null || !node.isObject() || node.isEmpty()) {+ throw new AwsException("ValidationException",+ "ReportDefinition is required.", 400);+ }+ ReportDefinition d = new ReportDefinition();+ d.setReportName(stringOrNull(node, "ReportName"));+ d.setTimeUnit(stringOrNull(node, "TimeUnit"));+ d.setFormat(stringOrNull(node, "Format"));+ d.setCompression(stringOrNull(node, "Compression"));+ d.setS3Bucket(stringOrNull(node, "S3Bucket"));+ d.setS3Prefix(stringOrNull(node, "S3Prefix"));+ d.setS3Region(stringOrNull(node, "S3Region"));+ d.setReportVersioning(stringOrNull(node, "ReportVersioning"));+ d.setBillingViewArn(stringOrNull(node, "BillingViewArn"));+ d.setRefreshClosedReports(node.path("RefreshClosedReports").asBoolean(false));+ d.setAdditionalSchemaElements(parseStringList(node.path("AdditionalSchemaElements")));+ d.setAdditionalArtifacts(parseStringList(node.path("AdditionalArtifacts")));+ return d;+ }++ private ObjectNode serialize(ReportDefinition d) {+ ObjectNode out = objectMapper.createObjectNode();+ out.put("ReportName", d.getReportName());+ out.put("TimeUnit", d.getTimeUnit());+ out.put("Format", d.getFormat());+ out.put("Compression", d.getCompression());+ out.put("S3Bucket", d.getS3Bucket());+ out.put("S3Prefix", d.getS3Prefix() == null ? "" : d.getS3Prefix());+ out.put("S3Region", d.getS3Region());+ if (d.getReportVersioning() != null) {+ out.put("ReportVersioning", d.getReportVersioning());+ }+ if (d.getBillingViewArn() != null) {+ out.put("BillingViewArn", d.getBillingViewArn());+ }+ out.put("RefreshClosedReports", d.isRefreshClosedReports());+ ArrayNode schema = out.putArray("AdditionalSchemaElements");+ if (d.getAdditionalSchemaElements() != null) {+ for (String e : d.getAdditionalSchemaElements()) {+ schema.add(e);+ }+ }+ ArrayNode artifacts = out.putArray("AdditionalArtifacts");+ if (d.getAdditionalArtifacts() != null) {+ for (String a : d.getAdditionalArtifacts()) {+ artifacts.add(a);+ }+ }+ if (d.getReportStatus() != null) {+ ObjectNode status = out.putObject("ReportStatus");+ status.put("LastStatus", d.getReportStatus());+ }+ return out;+ }++ private static List<String> parseStringList(JsonNode node) {+ List<String> out = new ArrayList<>();+ if (node.isArray()) {+ for (JsonNode v : node) {+ if (!v.isNull() && !v.asText().isEmpty()) {+ out.add(v.asText());+ }+ }+ }+ return out;+ }++ private static String stringOrNull(JsonNode node, String field) {+ JsonNode value = node == null ? null : node.get(field);+ return (value != null && !value.isNull()) ? value.asText() : null;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cur/CurService.java b/src/main/java/io/github/hectorvent/floci/services/cur/CurService.javanew file mode 100644index 0000000000..3c21e542f6--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cur/CurService.java@@ -0,0 +1,333 @@+package io.github.hectorvent.floci.services.cur;++import com.fasterxml.jackson.core.type.TypeReference;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.StorageBackend;+import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.cur.model.ReportDefinition;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.time.Instant;+import java.util.ArrayList;+import java.util.Collection;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.Set;++/**+ * AWS CUR (Cost and Usage Report) management plane.+ * <p>+ * Persists {@link ReportDefinition} records keyed by+ * {@code <accountId>::<region>::<reportName>} so the same report name is+ * scoped per account and per region (matching AWS, where CUR is regional and+ * report names are unique within an account).+ *+ * <p>This class is management-plane only — no Parquet emission. Emission lands+ * in a follow-up step on the same branch.+ *+ * @see <a href="https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_Operations_AWS_Cost_and_Usage_Report_Service.html">CUR API</a>+ */+@ApplicationScoped+public class CurService {++ private static final Logger LOG = Logger.getLogger(CurService.class);++ /** AWS hard limit per account: 5 report definitions. */+ private static final int MAX_REPORTS_PER_ACCOUNT = 5;+ /** AWS allows the report name to contain alphanumerics, hyphens, and underscores. */+ private static final java.util.regex.Pattern REPORT_NAME_PATTERN =+ java.util.regex.Pattern.compile("[A-Za-z0-9_-]+");++ private static final Set<String> ALLOWED_TIME_UNITS = Set.of("HOURLY", "DAILY", "MONTHLY");+ /**+ * Floci only emits Parquet at the moment. Real CUR also accepts+ * {@code textORcsv} but Floci's emission engine writes Parquet+ * unconditionally, so accepting {@code textORcsv} would let a definition+ * persist that no consumer can read. Reject it explicitly until CSV+ * support lands in a follow-up PR.+ */+ private static final Set<String> ALLOWED_FORMATS = Set.of("Parquet");+ private static final Set<String> ALLOWED_COMPRESSIONS = Set.of("Parquet");+ private static final Set<String> ALLOWED_VERSIONING = Set.of("CREATE_NEW_REPORT", "OVERWRITE_REPORT");+ private static final Set<String> ALLOWED_ARTIFACTS = Set.of("REDSHIFT", "QUICKSIGHT", "ATHENA");+ private static final Set<String> ALLOWED_SCHEMA_ELEMENTS = Set.of("RESOURCES", "SPLIT_COST_ALLOCATION_DATA", "MANUAL_DISCOUNT_COMPATIBILITY");++ private final StorageBackend<String, ReportDefinition> store;+ private final RegionResolver regionResolver;++ @Inject+ public CurService(StorageFactory storageFactory, RegionResolver regionResolver) {+ this(storageFactory.create("cur", "cur-report-definitions.json",+ new TypeReference<Map<String, ReportDefinition>>() {}),+ regionResolver);+ }++ CurService(StorageBackend<String, ReportDefinition> store, RegionResolver regionResolver) {+ this.store = store;+ this.regionResolver = regionResolver;+ }++ /** {@code PutReportDefinition} — creates a new report. Fails if one already exists. */+ public ReportDefinition putReportDefinition(ReportDefinition definition, String region) {+ validateReportDefinition(definition);+ String key = compositeKey(region, definition.getReportName());++ if (store.get(key).isPresent()) {+ throw new AwsException("DuplicateReportNameException",+ "A report with the name " + definition.getReportName() + " already exists.", 400);+ }+ if (countForCurrentAccount() >= MAX_REPORTS_PER_ACCOUNT) {+ throw new AwsException("ReportLimitReachedException",+ "This account has the maximum number of report definitions ("+ + MAX_REPORTS_PER_ACCOUNT + ").", 400);+ }++ Instant now = Instant.now();+ definition.setCreatedDate(now);+ definition.setLastUpdatedDate(now);+ definition.setReportStatus("PENDING");+ definition.setOwnerAccountId(regionResolver.getAccountId());+ store.put(key, definition);+ LOG.infov("Created CUR report: {0} (region={1})",+ definition.getReportName(), region);+ return definition;+ }++ /** {@code ModifyReportDefinition} — replaces an existing report's definition. */+ public ReportDefinition modifyReportDefinition(String reportName, ReportDefinition incoming, String region) {+ requireNonEmpty(reportName, "ReportName");+ if (!reportName.equals(incoming.getReportName())) {+ throw new AwsException("ValidationException",+ "ReportName in the body must match the ReportName parameter.", 400);+ }+ validateReportDefinition(incoming);++ String key = compositeKey(region, reportName);+ ReportDefinition existing = store.get(key).orElseThrow(() -> new AwsException(+ "ReportNotFoundException",+ "Report " + reportName + " not found.", 400));++ incoming.setCreatedDate(existing.getCreatedDate());+ incoming.setLastUpdatedDate(Instant.now());+ incoming.setReportStatus(existing.getReportStatus() == null ? "PENDING" : existing.getReportStatus());+ incoming.setOwnerAccountId(existing.getOwnerAccountId() != null+ ? existing.getOwnerAccountId() : regionResolver.getAccountId());+ store.put(key, incoming);+ LOG.infov("Modified CUR report: {0}", reportName);+ return incoming;+ }++ /** {@code DescribeReportDefinitions} — returns all reports for the calling account. */+ public List<ReportDefinition> describeReportDefinitions() {+ return new ArrayList<>(store.scan(key -> true));+ }++ /**+ * Returns every report definition stored across every account, keyed by+ * {@code ownerAccountId}. Used by the background emission scheduler that+ * runs outside a request scope (where the storage backend would otherwise+ * default to the single configured account and miss reports created under+ * other access keys).+ *+ * <p>Account attribution comes from the {@code ownerAccountId} field stamped+ * at {@code PutReportDefinition} time, not from the storage prefix, so this+ * also works on the in-memory test backend that has no account awareness.+ */+ public Map<String, List<ReportDefinition>> listAllReportsByAccount() {+ Collection<ReportDefinition> all;+ if (store instanceof io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend<?> aware) {+ @SuppressWarnings("unchecked")+ io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend<ReportDefinition> typed =+ (io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend<ReportDefinition>) aware;+ all = typed.scanAllAccounts();+ } else {+ all = store.scan(key -> true);+ }+ Map<String, List<ReportDefinition>> result = new java.util.LinkedHashMap<>();+ for (ReportDefinition def : all) {+ String accountId = def.getOwnerAccountId();+ if (accountId == null || accountId.isEmpty()) {+ accountId = regionResolver.getAccountId();+ }+ result.computeIfAbsent(accountId, a -> new ArrayList<>()).add(def);+ }+ return result;+ }++ /**+ * Returns the freshest stored copy of {@code definition}, or the input+ * itself when the report has been deleted between the original mutation+ * and this read. Lets handlers serialize the post-emission ReportStatus+ * without re-fetching by name.+ */+ public ReportDefinition getReportDefinitionOrSelf(ReportDefinition definition, String region) {+ return store.get(compositeKey(region, definition.getReportName()))+ .orElse(definition);+ }++ /**+ * Updates the {@code ReportStatus.LastStatus} field on a stored definition.+ * Called by {@code CurEmissionScheduler} after an emission run to expose+ * success/error to {@code DescribeReportDefinitions} consumers. Silent+ * no-op if the report has been deleted in the meantime.+ */+ public void markReportStatus(String reportName, String region, String status) {+ if (reportName == null || region == null || status == null) {+ return;+ }+ String key = compositeKey(region, reportName);+ store.get(key).ifPresent(def -> {+ def.setReportStatus(status);+ def.setLastUpdatedDate(Instant.now());+ store.put(key, def);+ });+ }++ /**+ * Variant of {@link #markReportStatus} for background workers that aren't+ * inside a request scope. Writes through the account-aware storage backend+ * directly under {@code accountId} rather than relying on the request+ * context.+ */+ public void markReportStatusForAccount(String accountId, String reportName, String region, String status) {+ if (accountId == null || reportName == null || region == null || status == null) {+ return;+ }+ if (!(store instanceof io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend<?> aware)) {+ markReportStatus(reportName, region, status);+ return;+ }+ @SuppressWarnings("unchecked")+ io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend<ReportDefinition> typed =+ (io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend<ReportDefinition>) aware;+ String key = compositeKey(region, reportName);+ typed.getForAccount(accountId, key).ifPresent(def -> {+ def.setReportStatus(status);+ def.setLastUpdatedDate(Instant.now());+ typed.putForAccount(accountId, key, def);+ });+ }++ /** {@code DeleteReportDefinition} — removes a report; idempotent (returns null when absent). */+ public ReportDefinition deleteReportDefinition(String reportName, String region) {+ requireNonEmpty(reportName, "ReportName");+ String key = compositeKey(region, reportName);+ ReportDefinition existing = store.get(key).orElse(null);+ if (existing != null) {+ store.delete(key);+ LOG.infov("Deleted CUR report: {0}", reportName);+ }+ return existing;+ }++ private long countForCurrentAccount() {+ return store.keys().size();+ }++ private void validateReportDefinition(ReportDefinition d) {+ if (d == null) {+ throw new AwsException("ValidationException", "ReportDefinition is required.", 400);+ }+ requireNonEmpty(d.getReportName(), "ReportName");+ if (!REPORT_NAME_PATTERN.matcher(d.getReportName()).matches()) {+ throw new AwsException("ValidationException",+ "ReportName may only contain alphanumeric characters, hyphens, and underscores.", 400);+ }+ if (d.getReportName().length() > 256) {+ throw new AwsException("ValidationException",+ "ReportName must be at most 256 characters long.", 400);+ }+ requireOneOf(d.getTimeUnit(), ALLOWED_TIME_UNITS, "TimeUnit");+ requireOneOf(d.getFormat(), ALLOWED_FORMATS, "Format");+ requireOneOf(d.getCompression(), ALLOWED_COMPRESSIONS, "Compression");+ requireNonEmpty(d.getS3Bucket(), "S3Bucket");+ requireValidBucketName(d.getS3Bucket(), "S3Bucket");+ if (d.getS3Prefix() != null) {+ requireSafeKeySegment(d.getS3Prefix(), "S3Prefix");+ }+ if (d.getS3Prefix() == null) {+ d.setS3Prefix("");+ }+ requireNonEmpty(d.getS3Region(), "S3Region");+ if (d.getReportVersioning() != null && !ALLOWED_VERSIONING.contains(d.getReportVersioning())) {+ throw new AwsException("ValidationException",+ "ReportVersioning must be one of " + ALLOWED_VERSIONING, 400);+ }+ if (d.getAdditionalArtifacts() != null) {+ for (String artifact : d.getAdditionalArtifacts()) {+ if (!ALLOWED_ARTIFACTS.contains(artifact)) {+ throw new AwsException("ValidationException",+ "AdditionalArtifacts must be one of " + ALLOWED_ARTIFACTS, 400);+ }+ }+ }+ if (d.getAdditionalSchemaElements() != null) {+ for (String element : d.getAdditionalSchemaElements()) {+ if (!ALLOWED_SCHEMA_ELEMENTS.contains(element)) {+ throw new AwsException("ValidationException",+ "AdditionalSchemaElements must be one of " + ALLOWED_SCHEMA_ELEMENTS, 400);+ }+ }+ }+ }++ private static String compositeKey(String region, String reportName) {+ return region + "::" + reportName;+ }++ private static void requireNonEmpty(String value, String field) {+ if (value == null || value.isEmpty()) {+ throw new AwsException("ValidationException",+ "1 validation error detected: Value at '" + field + "' failed to satisfy constraint: Member must not be null.", 400);+ }+ }++ private static void requireOneOf(String value, Set<String> allowed, String field) {+ requireNonEmpty(value, field);+ if (!allowed.contains(value)) {+ throw new AwsException("ValidationException",+ field + " must be one of " + allowed, 400);+ }+ }++ private static void requireValidBucketName(String bucket, String field) {+ if (bucket.length() < 3 || bucket.length() > 63) {+ throw new AwsException("ValidationException",+ field + " must be between 3 and 63 characters.", 400);+ }+ for (int i = 0; i < bucket.length(); i++) {+ char c = bucket.charAt(i);+ boolean valid = (c >= 'a' && c <= 'z')+ || (c >= '0' && c <= '9')+ || c == '-' || c == '.';+ if (!valid) {+ throw new AwsException("ValidationException",+ field + " contains invalid characters.", 400);+ }+ }+ if (bucket.startsWith("-") || bucket.endsWith("-")+ || bucket.startsWith(".") || bucket.endsWith(".")+ || bucket.contains("..")) {+ throw new AwsException("ValidationException",+ field + " is not a valid S3 bucket name.", 400);+ }+ }++ private static void requireSafeKeySegment(String value, String field) {+ for (int i = 0; i < value.length(); i++) {+ char c = value.charAt(i);+ boolean ok = (c >= 'A' && c <= 'Z')+ || (c >= 'a' && c <= 'z')+ || (c >= '0' && c <= '9')+ || c == '-' || c == '_' || c == '.' || c == '/';+ if (!ok) {+ throw new AwsException("ValidationException",+ field + " contains characters not permitted in an S3 key segment.", 400);+ }+ }+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cur/EmissionEngine.java b/src/main/java/io/github/hectorvent/floci/services/cur/EmissionEngine.javanew file mode 100644index 0000000000..a6969d2d25--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cur/EmissionEngine.java@@ -0,0 +1,94 @@+package io.github.hectorvent.floci.services.cur;++import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.common.ResourceUsageEnumerator;+import io.github.hectorvent.floci.core.common.UsageLine;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.enterprise.inject.Instance;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.time.Instant;+import java.time.YearMonth;+import java.time.ZoneOffset;+import java.util.ArrayList;+import java.util.List;++/**+ * Shared emission entrypoint for CUR and BCM Data Exports.+ * <p>+ * Collects {@link UsageLine}s from every {@link ResourceUsageEnumerator}+ * registered with CDI (the same SPI that backs Cost Explorer), then delegates+ * the Parquet write to {@link ParquetEmitter}. Both CUR's+ * {@code PutReportDefinition} hook and BCM's {@code CreateExport} hook call+ * through this class so the cost-line gathering logic lives in exactly one+ * place.+ *+ * <p>Window resolution: emission runs span the calendar month of {@code now},+ * matching the CUR billing period. Future PRs can extend this to honor+ * {@code TimeUnit=DAILY} or {@code HOURLY}.+ */+@ApplicationScoped+public class EmissionEngine {++ private static final Logger LOG = Logger.getLogger(EmissionEngine.class);++ private final Instance<ResourceUsageEnumerator> enumerators;+ private final ParquetEmitter parquetEmitter;+ private final RegionResolver regionResolver;++ @Inject+ public EmissionEngine(Instance<ResourceUsageEnumerator> enumerators,+ ParquetEmitter parquetEmitter,+ RegionResolver regionResolver) {+ this.enumerators = enumerators;+ this.parquetEmitter = parquetEmitter;+ this.regionResolver = regionResolver;+ }++ /**+ * Emits a Parquet artifact covering the current calendar month into the+ * configured destination. Returns the resulting {@link ParquetEmitter.Result}.+ */+ public ParquetEmitter.Result emitForCurrentMonth(String reportName, String destBucket,+ String destPrefix, String region) {+ return emitForCurrentMonth(reportName, destBucket, destPrefix, region, null);+ }++ /**+ * Variant of {@link #emitForCurrentMonth(String, String, String, String)}+ * that runs the DuckDB-side S3 read/write under the given owning account.+ * Daily emissions outside a request scope must thread {@code ownerAccountId}+ * here so the Parquet artifact lands in the correct account-aware S3+ * partition (and not the default account's).+ */+ public ParquetEmitter.Result emitForCurrentMonth(String reportName, String destBucket,+ String destPrefix, String region,+ String ownerAccountId) {+ Instant now = Instant.now();+ YearMonth ym = YearMonth.from(now.atOffset(ZoneOffset.UTC));+ Instant start = ym.atDay(1).atStartOfDay(ZoneOffset.UTC).toInstant();+ Instant end = ym.plusMonths(1).atDay(1).atStartOfDay(ZoneOffset.UTC).toInstant();++ String resolvedRegion = (region == null || region.isEmpty())+ ? regionResolver.getDefaultRegion() : region;++ List<UsageLine> lines = collectLines(start, end, resolvedRegion);+ LOG.infov("Emission: report={0} destination=s3://{1}/{2} lines={3} owner={4}",+ reportName, destBucket, destPrefix, lines.size(), ownerAccountId);+ return parquetEmitter.emit(reportName, destBucket, destPrefix, lines, ownerAccountId);+ }++ private List<UsageLine> collectLines(Instant start, Instant end, String region) {+ List<UsageLine> all = new ArrayList<>();+ for (ResourceUsageEnumerator enumerator : enumerators) {+ try {+ enumerator.enumerate(start, end, region).forEach(all::add);+ } catch (Exception e) {+ LOG.warnv(e, "Enumerator {0} failed during emission",+ enumerator.getClass().getSimpleName());+ }+ }+ return all;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cur/FocusRow.java b/src/main/java/io/github/hectorvent/floci/services/cur/FocusRow.javanew file mode 100644index 0000000000..fa84c37467--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cur/FocusRow.java@@ -0,0 +1,62 @@+package io.github.hectorvent.floci.services.cur;++import com.fasterxml.jackson.annotation.JsonInclude;+import com.fasterxml.jackson.annotation.JsonProperty;+import com.fasterxml.jackson.annotation.JsonPropertyOrder;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.Map;++/**+ * One row of a Cost and Usage Report following the FOCUS 1.2 / CUR 2.0+ * column shape. Field order is fixed via {@link JsonPropertyOrder} so the+ * NDJSON staging output that DuckDB reads is deterministic.+ *+ * @see <a href="https://focus.finops.org/">FOCUS specification</a>+ */+@RegisterForReflection+@JsonInclude(JsonInclude.Include.NON_NULL)+@JsonPropertyOrder({+ "BillingPeriodStart", "BillingPeriodEnd",+ "ChargePeriodStart", "ChargePeriodEnd",+ "BillingAccountId", "SubAccountId",+ "ServiceCategory", "ServiceName",+ "Region",+ "ResourceId", "ResourceName", "ResourceType",+ "ChargeCategory", "ChargeClass", "ChargeDescription",+ "ChargeFrequency", "ChargeSubcategory",+ "PricingQuantity", "PricingUnit",+ "UsageQuantity", "UsageUnit",+ "BilledCost", "EffectiveCost", "ListCost", "ContractedCost",+ "BillingCurrency",+ "Tags"+})+public record FocusRow(+ @JsonProperty("BillingPeriodStart") String billingPeriodStart,+ @JsonProperty("BillingPeriodEnd") String billingPeriodEnd,+ @JsonProperty("ChargePeriodStart") String chargePeriodStart,+ @JsonProperty("ChargePeriodEnd") String chargePeriodEnd,+ @JsonProperty("BillingAccountId") String billingAccountId,+ @JsonProperty("SubAccountId") String subAccountId,+ @JsonProperty("ServiceCategory") String serviceCategory,+ @JsonProperty("ServiceName") String serviceName,+ @JsonProperty("Region") String region,+ @JsonProperty("ResourceId") String resourceId,+ @JsonProperty("ResourceName") String resourceName,+ @JsonProperty("ResourceType") String resourceType,+ @JsonProperty("ChargeCategory") String chargeCategory,+ @JsonProperty("ChargeClass") String chargeClass,+ @JsonProperty("ChargeDescription") String chargeDescription,+ @JsonProperty("ChargeFrequency") String chargeFrequency,+ @JsonProperty("ChargeSubcategory") String chargeSubcategory,+ @JsonProperty("PricingQuantity") double pricingQuantity,+ @JsonProperty("PricingUnit") String pricingUnit,+ @JsonProperty("UsageQuantity") double usageQuantity,+ @JsonProperty("UsageUnit") String usageUnit,+ @JsonProperty("BilledCost") double billedCost,+ @JsonProperty("EffectiveCost") double effectiveCost,+ @JsonProperty("ListCost") double listCost,+ @JsonProperty("ContractedCost") double contractedCost,+ @JsonProperty("BillingCurrency") String billingCurrency,+ @JsonProperty("Tags") Map<String, String> tags) {+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cur/FocusRowProjector.java b/src/main/java/io/github/hectorvent/floci/services/cur/FocusRowProjector.javanew file mode 100644index 0000000000..ca74f44dd9--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cur/FocusRowProjector.java@@ -0,0 +1,175 @@+package io.github.hectorvent.floci.services.cur;++import io.github.hectorvent.floci.core.common.UsageLine;+import io.github.hectorvent.floci.services.ce.PricingRateLookup;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;++import java.time.Instant;+import java.time.YearMonth;+import java.time.ZoneOffset;+import java.util.HashMap;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.Set;++/**+ * Projects {@link UsageLine} rows into FOCUS 1.2 / CUR 2.0 column shape.+ * <p>+ * Pure transformation; no I/O. The downstream {@code ParquetEmitter} handles+ * NDJSON staging and DuckDB invocation.+ *+ * <p>Cost math mirrors {@code services.ce.CostSynthesizer}: {@code BilledCost}+ * (and the four other USD metrics) are computed as+ * {@code quantity * unitPrice} for usage lines, and as {@code quantity}+ * (already USD-denominated, may be negative) for {@code Credit} / {@code Refund}+ * / {@code Tax} / {@code SavingsPlan*Fee} record types.+ */+@ApplicationScoped+public class FocusRowProjector {++ /** Record types whose quantity is already in USD and bypasses unit-price multiplication. */+ private static final Set<String> USD_DENOMINATED = Set.of(+ UsageLine.RECORD_TYPE_CREDIT,+ UsageLine.RECORD_TYPE_REFUND,+ UsageLine.RECORD_TYPE_TAX,+ UsageLine.RECORD_TYPE_SP_UPFRONT_FEE,+ UsageLine.RECORD_TYPE_SP_RECURRING_FEE);++ private final PricingRateLookup rateLookup;++ @Inject+ public FocusRowProjector(PricingRateLookup rateLookup) {+ this.rateLookup = rateLookup;+ }++ /** Builds the FOCUS rows for {@code lines}. Empty input returns empty output. */+ public List<FocusRow> project(List<UsageLine> lines) {+ // Cache per-(service, region) rate lookups for the request scope.+ Map<String, Map<String, Double>> rateCache = new HashMap<>();+ List<FocusRow> rows = new java.util.ArrayList<>(lines.size());+ for (UsageLine line : lines) {+ rows.add(projectOne(line, rateCache));+ }+ return rows;+ }++ /** Builds a single FOCUS row. Used by both {@link #project} and tests. */+ FocusRow projectOne(UsageLine line, Map<String, Map<String, Double>> rateCache) {+ double cost = costFor(line, rateCache);+ Map<String, String> tags = line.tags() == null ? Map.of() : new LinkedHashMap<>(line.tags());++ Instant chargeStart = line.periodStart();+ Instant chargeEnd = line.periodEnd();+ BillingPeriod billing = billingPeriodFor(chargeStart);++ return new FocusRow(+ billing.start.toString(),+ billing.end.toString(),+ chargeStart.toString(),+ chargeEnd.toString(),+ line.linkedAccountId(),+ line.linkedAccountId(),+ serviceCategoryFor(line.service()),+ line.service(),+ line.region(),+ line.resourceId(),+ line.resourceId(),+ resourceTypeFor(line.service()),+ chargeCategoryFor(line.recordType()),+ "Standard",+ "Synthesized usage line",+ "Usage-Based",+ line.usageType(),+ line.quantity(), line.usageUnit(),+ line.quantity(), line.usageUnit(),+ cost, cost, cost, cost,+ "USD",+ tags);+ }++ /**+ * Returns the cost (single value reused for {@code BilledCost},+ * {@code EffectiveCost}, {@code ListCost}, {@code ContractedCost}). Floci has+ * no commitment math, so all four metrics resolve to the same number.+ */+ double costFor(UsageLine line, Map<String, Map<String, Double>> rateCache) {+ if (line.recordType() != null && USD_DENOMINATED.contains(line.recordType())) {+ return line.quantity();+ }+ Map<String, Double> rates = rateCache.computeIfAbsent(+ line.service() + "|" + line.region(),+ key -> rateLookup.ratesFor(line.service(), line.region()));+ double rate = rates.getOrDefault(line.usageType(), 0.0);+ return line.quantity() * rate;+ }++ /**+ * Returns the half-open billing-period bounds covering {@code instant}, AWS-style:+ * first day of the month at 00:00 UTC through first day of the next month at 00:00 UTC.+ */+ private static BillingPeriod billingPeriodFor(Instant instant) {+ YearMonth ym = YearMonth.from(instant.atOffset(ZoneOffset.UTC));+ Instant start = ym.atDay(1).atStartOfDay(ZoneOffset.UTC).toInstant();+ Instant end = ym.plusMonths(1).atDay(1).atStartOfDay(ZoneOffset.UTC).toInstant();+ return new BillingPeriod(start, end);+ }++ private static String serviceCategoryFor(String serviceCode) {+ if (serviceCode == null) {+ return "Other";+ }+ return switch (serviceCode) {+ case "AmazonEC2", "AWSLambda", "AmazonECS", "AmazonEKS",+ "AmazonElasticContainerService", "AWSBatch" -> "Compute";+ case "AmazonS3", "AmazonEBS" -> "Storage";+ case "AmazonRDS", "AmazonDynamoDB", "AmazonRedshift",+ "AmazonElastiCache", "AmazonOpenSearchService" -> "Databases";+ case "AmazonRoute53", "AmazonAPIGateway", "AmazonCloudFront",+ "AWSDirectConnect", "AWSTransit" -> "Networking";+ case "AWSKeyManagementService", "AWSCertificateManager",+ "AmazonCognito", "AWSSecretsManager" -> "Identity";+ case "AmazonCloudWatch", "AWSCloudFormation", "AWSSystemsManager",+ "AWSConfig" -> "Management and Governance";+ case "AmazonKinesis", "AmazonKinesisFirehose", "AmazonMSK",+ "AmazonAthena", "AWSGlue" -> "Analytics";+ default -> "Other";+ };+ }++ private static String resourceTypeFor(String serviceCode) {+ if (serviceCode == null) {+ return null;+ }+ return switch (serviceCode) {+ case "AmazonEC2" -> "Instance";+ case "AmazonS3" -> "Bucket";+ case "AWSLambda" -> "Function";+ case "AmazonRDS" -> "DBInstance";+ case "AmazonDynamoDB" -> "Table";+ default -> serviceCode;+ };+ }++ private static String chargeCategoryFor(String recordType) {+ if (recordType == null) {+ return "Usage";+ }+ return switch (recordType) {+ case UsageLine.RECORD_TYPE_USAGE,+ UsageLine.RECORD_TYPE_DISCOUNTED_USAGE,+ UsageLine.RECORD_TYPE_SP_COVERED_USAGE -> "Usage";+ case UsageLine.RECORD_TYPE_CREDIT -> "Credit";+ case UsageLine.RECORD_TYPE_TAX -> "Tax";+ case UsageLine.RECORD_TYPE_REFUND -> "Refund";+ case UsageLine.RECORD_TYPE_SP_UPFRONT_FEE,+ UsageLine.RECORD_TYPE_SP_RECURRING_FEE,+ UsageLine.RECORD_TYPE_SP_NEGATION -> "Adjustment";+ default -> "Usage";+ };+ }++ private record BillingPeriod(Instant start, Instant end) {+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cur/ParquetEmitter.java b/src/main/java/io/github/hectorvent/floci/services/cur/ParquetEmitter.javanew file mode 100644index 0000000000..e73a9e76dd--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cur/ParquetEmitter.java@@ -0,0 +1,286 @@+package io.github.hectorvent.floci.services.cur;++import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.core.common.AwsException;+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.github.hectorvent.floci.services.s3.model.Bucket;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.nio.charset.StandardCharsets;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.UUID;++/**+ * Writes a Parquet artifact for a CUR/BCM run.+ * <p>+ * Pipeline:+ * <ol>+ * <li>{@link FocusRowProjector} converts {@link UsageLine}s to {@link FocusRow}s.</li>+ * <li>Rows are serialized as newline-delimited JSON and uploaded to a CUR+ * staging bucket via {@link S3Service}; this avoids any hand-rolled SQL+ * escaping for tags, descriptions, and resource IDs.</li>+ * <li>{@link FlociDuckClient#execute} runs a {@code COPY (SELECT * FROM+ * read_json_auto('s3://staging/...')) TO 's3://dest/...' (FORMAT+ * PARQUET)}; DuckDB reads the staging object through Floci's S3 service+ * and writes the Parquet artifact straight back to Floci S3.</li>+ * <li>The staging object is removed in a best-effort {@code finally} block+ * so concurrent emissions don't accumulate noise.</li>+ * </ol>+ *+ * <p>Each emission carries a fresh {@code runId} (UUID), reflected in both+ * staging and destination keys, so two emissions cannot clobber each other+ * even when started in parallel.+ *+ * <p>The {@code /execute} endpoint always writes a CSV result to+ * {@code output_s3_path} for compatibility with the Athena code path, so we+ * pass a harmless staging key for that throwaway side effect — the real+ * artifact is the Parquet object produced by the {@code COPY} statement.+ */+@ApplicationScoped+public class ParquetEmitter {++ private static final Logger LOG = Logger.getLogger(ParquetEmitter.class);++ private final FocusRowProjector projector;+ private final FlociDuckClient duckClient;+ private final S3Service s3Service;+ private final ObjectMapper objectMapper;+ private final String stagingBucket;+ private final String defaultRegion;++ @Inject+ public ParquetEmitter(FocusRowProjector projector,+ FlociDuckClient duckClient,+ S3Service s3Service,+ ObjectMapper objectMapper,+ EmulatorConfig config) {+ this(projector, duckClient, s3Service, objectMapper,+ config.services().cur().stagingBucket(),+ config.defaultRegion());+ }++ ParquetEmitter(FocusRowProjector projector, FlociDuckClient duckClient,+ S3Service s3Service, ObjectMapper objectMapper,+ String stagingBucket, String defaultRegion) {+ this.projector = projector;+ this.duckClient = duckClient;+ this.s3Service = s3Service;+ this.objectMapper = objectMapper;+ this.stagingBucket = stagingBucket;+ this.defaultRegion = defaultRegion;+ }++ /**+ * Emits a Parquet object for {@code lines} into+ * {@code s3://<destBucket>/<destPrefix>/<reportName>/<runId>.parquet}.+ *+ * @return the resulting {@link Result} record (S3 path + row count + run id)+ * @throws AwsException when DuckDB or S3 fails; staging cleanup still runs+ */+ public Result emit(String reportName, String destBucket, String destPrefix,+ List<UsageLine> lines) {+ return emit(reportName, destBucket, destPrefix, lines, null);+ }++ /**+ * Variant of {@link #emit(String, String, String, List)} that authenticates+ * the DuckDB-side S3 client as {@code ownerAccountId} so the read of the+ * staging NDJSON object and the write of the final Parquet artifact both+ * happen under that account's S3 partition. Pass {@code null} to use the+ * default account (matches the previous behavior).+ */+ public Result emit(String reportName, String destBucket, String destPrefix,+ List<UsageLine> lines, String ownerAccountId) {+ if (reportName == null || reportName.isEmpty()) {+ throw new AwsException("ValidationException", "reportName is required.", 400);+ }+ if (destBucket == null || destBucket.isEmpty()) {+ throw new AwsException("ValidationException", "destBucket is required.", 400);+ }+ if (lines == null) {+ throw new AwsException("ValidationException", "lines is required.", 400);+ }+ // Reject anything that doesn't look like an S3 bucket / object-key+ // segment up front. The emitter interpolates these into DuckDB SQL, so+ // unconstrained input would let a quote in S3Prefix terminate the SQL+ // literal and inject additional statements via setup_sql.+ validateBucketName(destBucket);+ validatePathSegment(reportName, "reportName");+ if (destPrefix != null && !destPrefix.isEmpty()) {+ validatePathSegment(destPrefix, "destPrefix");+ }++ String runId = UUID.randomUUID().toString();+ String prefix = destPrefix == null || destPrefix.isEmpty() ? "" : trimSlashes(destPrefix) + "/";+ String stagingKey = "cur-staging/" + reportName + "/" + runId + ".ndjson";+ String destKey = prefix + reportName + "/" + runId + ".parquet";+ String destS3Path = "s3://" + destBucket + "/" + destKey;+ String stagingS3Path = "s3://" + stagingBucket + "/" + stagingKey;++ ensureStagingBucket();++ boolean stagingWritten = false;+ try {+ List<FocusRow> rows = projector.project(lines);+ byte[] payload = serializeNdjson(rows);+ s3Service.putObject(stagingBucket, stagingKey, payload,+ "application/x-ndjson", new HashMap<>());+ stagingWritten = true;++ // floci-duck's /execute wraps the main `sql` field in a CSV-emitting+ // COPY for Athena compatibility. We need raw DDL/COPY semantics, so the+ // Parquet write goes in `setup_sql` (which is executed verbatim before+ // the wrap), and the wrapped `sql` is a trivial SELECT whose CSV+ // output is treated as throwaway.+ String resultKey = "cur-staging/" + reportName + "/" + runId + ".result.csv";+ String resultS3Path = "s3://" + stagingBucket + "/" + resultKey;++ // Escape every interpolated path even though validatePathSegment+ // already rejects quotes — defense in depth.+ String setupSql = "COPY (SELECT * FROM read_json_auto('"+ + escapeSqlLiteral(stagingS3Path)+ + "', format='newline_delimited')) TO '"+ + escapeSqlLiteral(destS3Path)+ + "' (FORMAT PARQUET);";+ String sql = "SELECT 1 AS ok";++ duckClient.execute(sql, setupSql, resultS3Path, ownerAccountId);++ // Clean the side-effect CSV up too; never load-bearing.+ safeDelete(stagingBucket, resultKey);++ LOG.infov("CUR emit ok: report={0} runId={1} rows={2} parquet={3}",+ reportName, runId, rows.size(), destS3Path);+ return new Result(runId, destBucket, destKey, destS3Path, rows.size());+ } catch (AwsException e) {+ throw e;+ } catch (Exception e) {+ throw new AwsException("InternalServerException",+ "Parquet emission failed: " + e.getMessage(), 500);+ } finally {+ if (stagingWritten) {+ safeDelete(stagingBucket, stagingKey);+ }+ }+ }++ /** Surfaces emission outputs without forcing callers to parse the SQL response. */+ public record Result(String runId, String bucket, String key, String s3Uri, int rowCount) {+ }++ private void ensureStagingBucket() {+ for (Bucket b : s3Service.listBuckets()) {+ if (stagingBucket.equals(b.getName())) {+ return;+ }+ }+ try {+ s3Service.createBucket(stagingBucket, defaultRegion);+ } catch (AwsException e) {+ // BucketAlreadyOwnedByYou under race; safe to ignore.+ if (!"BucketAlreadyOwnedByYou".equals(e.getErrorCode())+ && !"BucketAlreadyExists".equals(e.getErrorCode())) {+ throw e;+ }+ }+ }++ private byte[] serializeNdjson(List<FocusRow> rows) {+ StringBuilder sb = new StringBuilder(rows.size() * 256);+ for (FocusRow row : rows) {+ try {+ sb.append(objectMapper.writeValueAsString(row));+ } catch (Exception e) {+ throw new AwsException("InternalServerException",+ "Failed to serialize FocusRow: " + e.getMessage(), 500);+ }+ sb.append('\n');+ }+ return sb.toString().getBytes(StandardCharsets.UTF_8);+ }++ private void safeDelete(String bucket, String key) {+ try {+ s3Service.deleteObject(bucket, key);+ } catch (Exception e) {+ // Best-effort cleanup; swallow to avoid masking the primary outcome.+ LOG.debugv(e, "Staging cleanup failed for s3://{0}/{1}", bucket, key);+ }+ }++ private static String trimSlashes(String prefix) {+ int start = 0;+ int end = prefix.length();+ while (start < end && prefix.charAt(start) == '/') {+ start++;+ }+ while (end > start && prefix.charAt(end - 1) == '/') {+ end--;+ }+ return prefix.substring(start, end);+ }++ /** Escapes a value for embedding inside a DuckDB single-quoted SQL literal. */+ static String escapeSqlLiteral(String raw) {+ return raw.replace("'", "''");+ }++ /**+ * Rejects bucket names that don't satisfy the AWS S3 bucket-naming rules+ * (3-63 chars, lowercase alphanumerics, hyphens, dots; no two adjacent dots;+ * no IP-address shape). This is an extra safety net on top of+ * {@link #escapeSqlLiteral}; bucket names that pass S3 validation cannot+ * contain SQL-significant characters in the first place.+ */+ private static void validateBucketName(String bucket) {+ if (bucket.length() < 3 || bucket.length() > 63) {+ throw new AwsException("ValidationException",+ "S3 bucket name must be between 3 and 63 characters.", 400);+ }+ for (int i = 0; i < bucket.length(); i++) {+ char c = bucket.charAt(i);+ boolean valid = (c >= 'a' && c <= 'z')+ || (c >= '0' && c <= '9')+ || c == '-' || c == '.';+ if (!valid) {+ throw new AwsException("ValidationException",+ "S3 bucket name contains invalid characters.", 400);+ }+ }+ if (bucket.startsWith("-") || bucket.endsWith("-")+ || bucket.startsWith(".") || bucket.endsWith(".")) {+ throw new AwsException("ValidationException",+ "S3 bucket name cannot start or end with a hyphen or period.", 400);+ }+ if (bucket.contains("..")) {+ throw new AwsException("ValidationException",+ "S3 bucket name cannot contain two adjacent periods.", 400);+ }+ }++ /**+ * Rejects path components that contain SQL-significant characters.+ * Allowed: alphanumerics, hyphens, underscores, periods, and forward slashes+ * (so callers can pass a prefix like {@code billing/2026}).+ */+ private static void validatePathSegment(String value, String field) {+ for (int i = 0; i < value.length(); i++) {+ char c = value.charAt(i);+ boolean ok = (c >= 'A' && c <= 'Z')+ || (c >= 'a' && c <= 'z')+ || (c >= '0' && c <= '9')+ || c == '-' || c == '_' || c == '.' || c == '/';+ if (!ok) {+ throw new AwsException("ValidationException",+ field + " contains characters not permitted in an S3 key segment.", 400);+ }+ }+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cur/model/ReportDefinition.java b/src/main/java/io/github/hectorvent/floci/services/cur/model/ReportDefinition.javanew file mode 100644index 0000000000..911b60c123--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cur/model/ReportDefinition.java@@ -0,0 +1,92 @@+package io.github.hectorvent.floci.services.cur.model;++import com.fasterxml.jackson.annotation.JsonInclude;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;+import java.util.ArrayList;+import java.util.List;++/**+ * AWS CUR (Cost and Usage Report) {@code ReportDefinition} record.+ *+ * @see <a href="https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_cur_ReportDefinition.html">ReportDefinition</a>+ */+@RegisterForReflection+@JsonInclude(JsonInclude.Include.NON_NULL)+public class ReportDefinition {++ private String reportName;+ private String timeUnit; // HOURLY | DAILY | MONTHLY+ private String format; // textORcsv | Parquet+ private String compression; // ZIP | GZIP | Parquet+ private List<String> additionalSchemaElements = new ArrayList<>();+ private String s3Bucket;+ private String s3Prefix;+ private String s3Region;+ private List<String> additionalArtifacts = new ArrayList<>();+ private boolean refreshClosedReports;+ private String reportVersioning; // CREATE_NEW_REPORT | OVERWRITE_REPORT+ private String billingViewArn;+ private Instant createdDate;+ private Instant lastUpdatedDate;+ private String reportStatus; // SUCCESS | ERROR | PENDING+ /**+ * Snapshot of the account that owned the request that created this report.+ * Used by the background emission scheduler to locate the report under the+ * right account partition without inheriting the scheduler thread's+ * (default) request scope. Not part of the AWS wire response.+ */+ private String ownerAccountId;++ public ReportDefinition() {+ }++ public String getReportName() { return reportName; }+ public void setReportName(String reportName) { this.reportName = reportName; }++ public String getTimeUnit() { return timeUnit; }+ public void setTimeUnit(String timeUnit) { this.timeUnit = timeUnit; }++ public String getFormat() { return format; }+ public void setFormat(String format) { this.format = format; }++ public String getCompression() { return compression; }+ public void setCompression(String compression) { this.compression = compression; }++ public List<String> getAdditionalSchemaElements() { return additionalSchemaElements; }+ public void setAdditionalSchemaElements(List<String> v) { this.additionalSchemaElements = v; }++ public String getS3Bucket() { return s3Bucket; }+ public void setS3Bucket(String s3Bucket) { this.s3Bucket = s3Bucket; }++ public String getS3Prefix() { return s3Prefix; }+ public void setS3Prefix(String s3Prefix) { this.s3Prefix = s3Prefix; }++ public String getS3Region() { return s3Region; }+ public void setS3Region(String s3Region) { this.s3Region = s3Region; }++ public List<String> getAdditionalArtifacts() { return additionalArtifacts; }+ public void setAdditionalArtifacts(List<String> v) { this.additionalArtifacts = v; }++ public boolean isRefreshClosedReports() { return refreshClosedReports; }+ public void setRefreshClosedReports(boolean v) { this.refreshClosedReports = v; }++ public String getReportVersioning() { return reportVersioning; }+ public void setReportVersioning(String v) { this.reportVersioning = v; }++ public String getBillingViewArn() { return billingViewArn; }+ public void setBillingViewArn(String v) { this.billingViewArn = v; }++ public Instant getCreatedDate() { return createdDate; }+ public void setCreatedDate(Instant v) { this.createdDate = v; }++ public Instant getLastUpdatedDate() { return lastUpdatedDate; }+ public void setLastUpdatedDate(Instant v) { this.lastUpdatedDate = v; }++ public String getReportStatus() { return reportStatus; }+ public void setReportStatus(String v) { this.reportStatus = v; }++ public String getOwnerAccountId() { return ownerAccountId; }+ public void setOwnerAccountId(String v) { this.ownerAccountId = v; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/floci/FlociDuckClient.java b/src/main/java/io/github/hectorvent/floci/services/floci/FlociDuckClient.javaindex 6b7c430de8..21fe5f63b7 100644--- a/src/main/java/io/github/hectorvent/floci/services/floci/FlociDuckClient.java+++ b/src/main/java/io/github/hectorvent/floci/services/floci/FlociDuckClient.java@@ -64,9 +64,21 @@ public class FlociDuckClient {* @param outputS3Path the S3 path where the result CSV will be written*/public void execute(String sql, String setupDdl, String outputS3Path) {+ execute(sql, setupDdl, outputS3Path, null);+ }++ /**+ * Variant of {@link #execute(String, String, String)} that authenticates+ * the DuckDB-side S3 client as a specific Floci account. Pass a 12-digit+ * AWS account ID as {@code accessKeyId} so that {@link+ * io.github.hectorvent.floci.core.common.AccountResolver} routes the+ * subsequent reads/writes to that account's S3 partition rather than the+ * default account.+ */+ public void execute(String sql, String setupDdl, String outputS3Path, String accessKeyId) {String duckUrl = duckManager.ensureReady();- Map<String, Object> body = buildBaseBody(sql, setupDdl);+ Map<String, Object> body = buildBaseBody(sql, setupDdl, accessKeyId);body.put("output_s3_path", outputS3Path);post(duckUrl + "/execute", body, "execute");@@ -81,9 +93,18 @@ public class FlociDuckClient {* @return result rows; empty list if the query matched no rows*/public List<Map<String, Object>> query(String sql, String setupDdl) {+ return query(sql, setupDdl, null);+ }++ /**+ * Variant of {@link #query(String, String)} that authenticates the+ * DuckDB-side S3 client as a specific Floci account. See+ * {@link #execute(String, String, String, String)} for details.+ */+ public List<Map<String, Object>> query(String sql, String setupDdl, String accessKeyId) {String duckUrl = duckManager.ensureReady();- Map<String, Object> body = buildBaseBody(sql, setupDdl);+ Map<String, Object> body = buildBaseBody(sql, setupDdl, accessKeyId);String responseBody = post(duckUrl + "/query", body, "query");return parseQueryRows(responseBody);@@ -92,6 +113,10 @@ public class FlociDuckClient {// ── internals ─────────────────────────────────────────────────────────────private Map<String, Object> buildBaseBody(String sql, String setupDdl) {+ return buildBaseBody(sql, setupDdl, null);+ }++ private Map<String, Object> buildBaseBody(String sql, String setupDdl, String accessKeyId) {Map<String, Object> body = new LinkedHashMap<>();body.put("sql", sql);if (setupDdl != null && !setupDdl.isBlank()) {@@ -99,7 +124,10 @@ public class FlociDuckClient {}body.put("s3_endpoint", resolveFlociEndpoint());body.put("s3_region", config.defaultRegion());- body.put("s3_access_key", "test");+ // A 12-digit access key flows through AccountResolver and selects the+ // matching account partition for any S3 read/write the SQL performs.+ // Anything else falls back to the configured default account.+ body.put("s3_access_key", accessKeyId == null || accessKeyId.isEmpty() ? "test" : accessKeyId);body.put("s3_secret_key", "test");body.put("s3_url_style", "path");return body;diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex 9bcbc44bce..140cd9602e 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -271,3 +271,10 @@ floci:ce:enabled: truecredit-usd-monthly: 0.0+ cur:+ enabled: true+ emit-mode: synchronous+ staging-bucket: floci-cur-staging+ bcm-data-exports:+ enabled: true+ emit-mode: synchronousdiff --git a/src/test/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsAccountIsolationTest.java b/src/test/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsAccountIsolationTest.javanew file mode 100644index 0000000000..b2348091d0--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsAccountIsolationTest.java@@ -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;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsIntegrationTest.javanew file mode 100644index 0000000000..5d17319e8c--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsIntegrationTest.java@@ -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.<Action>+ */+@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"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cur/CurAccountIsolationTest.java b/src/test/java/io/github/hectorvent/floci/services/cur/CurAccountIsolationTest.javanew file mode 100644index 0000000000..7124d40ebf--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cur/CurAccountIsolationTest.java@@ -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;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cur/CurDailyEmissionAccountIsolationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cur/CurDailyEmissionAccountIsolationIntegrationTest.javanew file mode 100644index 0000000000..bec094389b--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cur/CurDailyEmissionAccountIsolationIntegrationTest.java@@ -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"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cur/CurEmissionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cur/CurEmissionIntegrationTest.javanew file mode 100644index 0000000000..aa0d0ac5ad--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cur/CurEmissionIntegrationTest.java@@ -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} -> {@link CurEmissionScheduler} ->+ * {@link EmissionEngine} -> {@link ParquetEmitter} -> DuckDB sidecar ->+ * 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")));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cur/CurIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cur/CurIntegrationTest.javanew file mode 100644index 0000000000..d4c949c1cf--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cur/CurIntegrationTest.java@@ -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.<Action>+ */+@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"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cur/CurNonDefaultAccountEmissionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cur/CurNonDefaultAccountEmissionIntegrationTest.javanew file mode 100644index 0000000000..3c6319211b--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cur/CurNonDefaultAccountEmissionIntegrationTest.java@@ -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"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cur/FocusRowProjectorTest.java b/src/test/java/io/github/hectorvent/floci/services/cur/FocusRowProjectorTest.javanew file mode 100644index 0000000000..345be389d3--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cur/FocusRowProjectorTest.java@@ -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));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cur/ParquetEmitterIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cur/ParquetEmitterIntegrationTest.javanew file mode 100644index 0000000000..90e21ca7e9--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cur/ParquetEmitterIntegrationTest.java@@ -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()));+ }+}diff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex aaee623f90..a3a0b7dbd9 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -180,3 +180,9 @@ floci:enabled: truece:enabled: true+ cur:+ enabled: true+ emit-mode: off+ bcm-data-exports:+ enabled: true+ emit-mode: off