Files
floci/docs/services/cur.md
T
Shubham Srivastava 6d36f66e5f 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
2026-05-15 22:55:11 -05:00

141 lines
5.0 KiB
Markdown

# Cost and Usage Reports (`cur:*`)
**Protocol:** JSON 1.1
**Header:** `X-Amz-Target: AWSOrigamiServiceGatewayService.<Action>`
**Endpoint prefix:** `cur`
Floci emulates the legacy AWS Cost and Usage Report (CUR) API. Report
definitions are persisted in Floci's storage backend; emission produces
real Parquet artifacts in Floci's S3 service via the `floci-duck` sidecar.
## Supported Operations
| Operation | Notes |
|-----------|-------|
| `PutReportDefinition` | Creates a new report; rejects duplicates with `DuplicateReportNameException`; enforces a 5-report-per-account limit |
| `ModifyReportDefinition` | Replaces an existing report's mutable fields |
| `DescribeReportDefinitions` | Returns every report owned by the calling account |
| `DeleteReportDefinition` | Idempotent; removing a missing report returns 200 |
| `TagResource` / `UntagResource` / `ListTagsForResource` | Stub responses (empty bodies) so SDK clients that probe for them succeed |
## Validation rules
- `ReportName`: alphanumerics + `-_`, max 256 chars
- `TimeUnit`: `HOURLY` / `DAILY` / `MONTHLY`
- `Format`: `Parquet` (CSV emission not yet implemented; `textORcsv` returns `ValidationException`)
- `Compression`: `Parquet` (`ZIP` / `GZIP` not yet implemented)
- `ReportVersioning`: `CREATE_NEW_REPORT` / `OVERWRITE_REPORT`
- `AdditionalArtifacts`: subset of `REDSHIFT` / `QUICKSIGHT` / `ATHENA`
- `AdditionalSchemaElements`: subset of `RESOURCES` / `SPLIT_COST_ALLOCATION_DATA` / `MANUAL_DISCOUNT_COMPATIBILITY`
- Required: `ReportName`, `TimeUnit`, `Format`, `Compression`, `S3Bucket`, `S3Region`
## Storage keys
Report definitions are persisted as
`<accountId>::<region>::<reportName>` so the same name is allowed in
different regions or different accounts.
## Emission
Emission produces a Parquet artifact at
`s3://<S3Bucket>/<S3Prefix>/<reportName>/<runId>.parquet`. Each run gets a
fresh UUID, so concurrent emissions never clobber each other.
The pipeline:
1. The shared `EmissionEngine` collects `UsageLine` rows from every
service that implements the `ResourceUsageEnumerator` SPI introduced
in [Cost Explorer](ce.md).
2. `FocusRowProjector` converts those rows to FOCUS 1.2 / CUR 2.0 column
shape using the bundled [Pricing snapshot](pricing.md).
3. The rows are staged as newline-delimited JSON in
`s3://floci-cur-staging/cur-staging/<reportName>/<runId>.ndjson`.
4. The `floci-duck` sidecar runs
`COPY (SELECT * FROM read_json_auto(...)) TO 's3://...' (FORMAT PARQUET)`
to produce the final Parquet object back in Floci S3.
5. The staging object is deleted in a best-effort `finally` block.
### `FLOCI_SERVICES_CUR_EMIT_MODE`
| Value | Behavior |
|-------|----------|
| `synchronous` (default) | Emit on every `PutReportDefinition` / `ModifyReportDefinition` |
| `daily` | Emit every 24h via a CUR-owned scheduled executor (separate from EventBridge Scheduler) |
| `off` | Management plane only — no emission |
`synchronous` mode swallows emission errors so the management mutation
always succeeds; the failure is reflected in
`ReportStatus.LastStatus = ERROR` on the persisted definition.
## Configuration
| Variable | Default | Description |
|---|---|---|
| `FLOCI_SERVICES_CUR_ENABLED` | `true` | Enable or disable the service |
| `FLOCI_SERVICES_CUR_EMIT_MODE` | `synchronous` | Run mode (see above) |
| `FLOCI_SERVICES_CUR_STAGING_BUCKET` | `floci-cur-staging` | S3 bucket used to stage NDJSON before DuckDB writes Parquet |
The `floci-duck` sidecar is started lazily on the first emission, the
same way Athena starts it.
## Examples
```bash
export AWS_ENDPOINT_URL=http://localhost:4566
export AWS_DEFAULT_REGION=us-east-1
export AWS_ACCESS_KEY_ID=test
export AWS_SECRET_ACCESS_KEY=test
aws cur put-report-definition --report-definition '{
"ReportName": "monthly-report",
"TimeUnit": "MONTHLY",
"Format": "Parquet",
"Compression": "Parquet",
"AdditionalSchemaElements": ["RESOURCES"],
"S3Bucket": "my-billing",
"S3Prefix": "reports",
"S3Region": "us-east-1",
"AdditionalArtifacts": ["ATHENA"],
"ReportVersioning": "OVERWRITE_REPORT"
}'
aws cur describe-report-definitions
aws s3 ls s3://my-billing/reports/monthly-report/
```
```python
import boto3, json
cur = boto3.client(
"cur",
endpoint_url="http://localhost:4566",
region_name="us-east-1",
)
cur.put_report_definition(ReportDefinition={
"ReportName": "monthly-report",
"TimeUnit": "MONTHLY",
"Format": "Parquet",
"Compression": "Parquet",
"AdditionalSchemaElements": ["RESOURCES"],
"S3Bucket": "my-billing",
"S3Prefix": "reports",
"S3Region": "us-east-1",
})
# Read the resulting Parquet via DuckDB or pyarrow.
import pyarrow.dataset as ds
table = ds.dataset("s3://my-billing/reports/monthly-report/", format="parquet").to_table()
print(table.column_names)
```
## Out of Scope
- Resource-tag-keyed report selection beyond what the bundled
enumerators emit
- `RefreshClosedReports` semantics (accepted but not retroactively
re-emitted)
- Server-side validation of S3 bucket policies on the destination
bucket (Floci's S3 service still applies its own bucket-policy
checks during the write)