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

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

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

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

## Operations

CUR (7):

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

BCM Data Exports (7):

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

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

## Parquet emission

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

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

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

## Run modes

`FLOCI_SERVICES_CUR_EMIT_MODE` and
`FLOCI_SERVICES_BCM_DATA_EXPORTS_EMIT_MODE`:

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

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

## Tests

42 new tests across 5 classes:

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

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

## Documentation

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

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

No files matched your search

@@ -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();
@@ -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;
@Inject
public 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 target
@@ -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())
));
}
@@ -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;
}
}
@@ -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);
}
}
}
}
@@ -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; }
}
@@ -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; }
}
}
@@ -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; }
}
@@ -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; }
}
@@ -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; }
}
@@ -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();
}
}
@@ -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;
}
}
@@ -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);
}
}
}
}
@@ -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;
}
}
@@ -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) {
}
@@ -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) {
}
}
@@ -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);
}
}
}
}
@@ -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; }
}
@@ -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;