feat(athena): real SQL execution via floci-duck DuckDB sidecar (#584)

* feat(athena): real SQL execution via floci-duck DuckDB sidecar

  - Lazy-start floci/floci-duck:latest on first StartQueryExecution call;
    reuse the running container for all subsequent queries
  - Inject Glue tables as CREATE OR REPLACE VIEW statements via setup_sql
    before the user SQL so DDL runs outside the COPY(...) wrapper
  - SerDe-aware format inference: inferReadFunction now checks
    SerdeInfo.SerializationLibrary in addition to InputFormat, so standard
    AWS JSON tables (TextInputFormat + JsonSerDe) map to read_json_auto
  - ImageCacheService: skip Docker Hub pull when image is already present
    locally, preventing local builds from being overwritten
  - Add AthenaIntegrationTest (5 unit integration tests)
  - Add AthenaTest and DataLakeTest SDK compatibility tests
  - Update docs: athena.md (full rewrite), glue.md, README, CHANGELOG

* fix: docker image check fix
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-04-25 08:28:20 -05:00
1 parent 5ad4c06d74
commit 1ddbec0efb
22 files changed
+1231 -81

No files matched your search

@@ -440,6 +440,15 @@ public interface EmulatorConfig {
interface AthenaServiceConfig {
@WithDefault("true")
boolean enabled();
@WithDefault("false")
boolean mock();
/** When set, Floci uses this URL and skips floci-duck container management. */
Optional<String> duckUrl();
@WithDefault("floci/floci-duck:latest")
String defaultImage();
}
interface GlueServiceConfig {
@@ -4,6 +4,8 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.athena.model.QueryExecution;
import io.github.hectorvent.floci.services.athena.model.QueryExecutionContext;
import io.github.hectorvent.floci.services.athena.model.ResultConfiguration;
import io.github.hectorvent.floci.services.athena.model.ResultSet;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -28,11 +30,18 @@ public class AthenaJsonHandler {
case "StartQueryExecution" -> {
String query = request.get("QueryString").asText();
String workGroup = request.has("WorkGroup") ? request.get("WorkGroup").asText() : "primary";
String database = "default";
if (request.has("QueryExecutionContext") && request.get("QueryExecutionContext").has("Database")) {
database = request.get("QueryExecutionContext").get("Database").asText();
QueryExecutionContext context = null;
if (request.has("QueryExecutionContext")) {
context = mapper.treeToValue(request.get("QueryExecutionContext"), QueryExecutionContext.class);
}
String id = athenaService.startQueryExecution(query, workGroup, database);
ResultConfiguration resultConfiguration = null;
if (request.has("ResultConfiguration")) {
resultConfiguration = mapper.treeToValue(request.get("ResultConfiguration"), ResultConfiguration.class);
}
String id = athenaService.startQueryExecution(query, workGroup, context, resultConfiguration);
yield Response.ok(Map.of("QueryExecutionId", id)).build();
}
case "GetQueryExecution" -> {
@@ -46,8 +55,9 @@ public class AthenaJsonHandler {
yield Response.ok(Map.of("ResultSet", results)).build();
}
case "ListQueryExecutions" -> {
yield Response.ok(Map.of("QueryExecutionIds",
athenaService.listQueryExecutions().stream().map(QueryExecution::getQueryExecutionId).toList())).build();
yield Response.ok(Map.of("QueryExecutionIds",
athenaService.listQueryExecutions().stream()
.map(QueryExecution::getQueryExecutionId).toList())).build();
}
default -> throw new AwsException("InvalidAction", "Action " + action + " is not supported", 400);
};
@@ -1,14 +1,30 @@
package io.github.hectorvent.floci.services.athena;
import com.fasterxml.jackson.core.type.TypeReference;
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.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.athena.model.*;
import io.github.hectorvent.floci.services.athena.FlociDuckManager;
import io.github.hectorvent.floci.services.glue.GlueService;
import io.github.hectorvent.floci.services.glue.model.Table;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import io.vertx.core.Vertx;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.*;
@@ -16,31 +32,85 @@ import java.util.*;
public class AthenaService {
private static final Logger LOG = Logger.getLogger(AthenaService.class);
private static final String DEFAULT_OUTPUT_BUCKET = "floci-athena-results";
private final StorageBackend<String, QueryExecution> queryStore;
private final FlociDuckManager duckManager;
private final GlueService glueService;
private final S3Service s3Service;
private final EmulatorConfig config;
private final Vertx vertx;
private final ObjectMapper mapper;
private final HttpClient httpClient;
@Inject
public AthenaService(StorageFactory storageFactory) {
this.queryStore = storageFactory.create("athena", "queries.json", new TypeReference<Map<String, QueryExecution>>() {});
public AthenaService(StorageFactory storageFactory,
FlociDuckManager duckManager,
GlueService glueService,
S3Service s3Service,
EmulatorConfig config,
Vertx vertx,
ObjectMapper mapper) {
this.queryStore = storageFactory.create("athena", "queries.json",
new TypeReference<Map<String, QueryExecution>>() {});
this.duckManager = duckManager;
this.glueService = glueService;
this.s3Service = s3Service;
this.config = config;
this.vertx = vertx;
this.mapper = mapper;
this.httpClient = HttpClient.newHttpClient();
}
public String startQueryExecution(String query, String workGroup, String database) {
public String startQueryExecution(String query,
String workGroup,
QueryExecutionContext context,
ResultConfiguration resultConfiguration) {
String id = UUID.randomUUID().toString();
QueryExecution execution = new QueryExecution(id, query, workGroup);
queryStore.put(id, execution);
String database = context != null && context.getDatabase() != null ? context.getDatabase() : "default";
// Ensure output location has a trailing slash so floci-duck writes into the prefix
String outputLocation = resolveOutputLocation(resultConfiguration, id);
ResultConfiguration resolvedResult = new ResultConfiguration(outputLocation);
QueryExecution execution = new QueryExecution(id, query, workGroup, resolvedResult, context);
execution.getStatus().setState(QueryExecutionState.RUNNING);
execution.getStatus().setState(QueryExecutionState.SUCCEEDED);
execution.getStatus().setCompletionDateTime(Instant.now());
queryStore.put(id, execution);
LOG.infov("Query {0} accepted (mock mode — no execution engine)", id);
if (config.services().athena().mock()) {
execution.getStatus().setState(QueryExecutionState.SUCCEEDED);
execution.getStatus().setCompletionDateTime(Instant.now());
queryStore.put(id, execution);
LOG.infov("Query {0} accepted (mock mode)", id);
return id;
}
// Submit async — caller gets the ID immediately while execution runs in background
String finalDatabase = database;
vertx.executeBlocking(() -> {
String duckUrl = duckManager.ensureReady();
String setupDdl = buildGlueDdl(finalDatabase);
callDuck(duckUrl, query, setupDdl, outputLocation, id);
return null;
}).onSuccess(v -> {
execution.getStatus().setState(QueryExecutionState.SUCCEEDED);
execution.getStatus().setCompletionDateTime(Instant.now());
queryStore.put(id, execution);
LOG.infov("Query {0} succeeded", id);
}).onFailure(e -> {
execution.getStatus().setState(QueryExecutionState.FAILED);
execution.getStatus().setStateChangeReason(e.getMessage());
queryStore.put(id, execution);
LOG.warnv("Query {0} failed: {1}", id, e.getMessage());
});
return id;
}
public QueryExecution getQueryExecution(String id) {
return queryStore.get(id)
.orElseThrow(() -> new AwsException("InvalidRequestException", "Query execution not found: " + id, 400));
.orElseThrow(() -> new AwsException("InvalidRequestException",
"Query execution not found: " + id, 400));
}
public List<QueryExecution> listQueryExecutions() {
@@ -49,9 +119,228 @@ public class AthenaService {
public ResultSet getQueryResults(String id) {
QueryExecution execution = getQueryExecution(id);
if (execution.getStatus().getState() != QueryExecutionState.SUCCEEDED) {
throw new AwsException("InvalidRequestException", "Query has not succeeded yet", 400);
}
if (config.services().athena().mock()
|| execution.getResultConfiguration() == null
|| execution.getResultConfiguration().getOutputLocation() == null) {
return new ResultSet(List.of(), new ResultSet.ResultSetMetadata(List.of()));
}
return readResultsFromS3(execution.getResultConfiguration().getOutputLocation(), id);
}
// ── private helpers ───────────────────────────────────────────────────────
private String buildGlueDdl(String database) {
StringBuilder sb = new StringBuilder();
try {
List<Table> tables = glueService.getTables(database);
for (Table table : tables) {
String location = table.getStorageDescriptor() != null
? table.getStorageDescriptor().getLocation()
: null;
if (location == null || location.isBlank()) {
continue;
}
String readFn = inferReadFunction(table);
String normalizedLocation = location.endsWith("/")
? location.substring(0, location.length() - 1) : location;
sb.append("CREATE OR REPLACE VIEW \"")
.append(table.getName())
.append("\" AS SELECT * FROM ")
.append(readFn)
.append("('").append(normalizedLocation).append("/**');\n");
}
} catch (Exception e) {
LOG.debugv("Could not inject Glue DDL for database {0}: {1}", database, e.getMessage());
}
return sb.toString();
}
private String inferReadFunction(Table table) {
if (table.getStorageDescriptor() == null) {
return "read_csv_auto";
}
String format = table.getStorageDescriptor().getInputFormat();
String serde = table.getStorageDescriptor().getSerdeInfo() != null
? table.getStorageDescriptor().getSerdeInfo().getSerializationLibrary()
: null;
if (containsIgnoreCase(format, "parquet") || containsIgnoreCase(serde, "parquet")) {
return "read_parquet";
}
if (containsIgnoreCase(format, "json") || containsIgnoreCase(serde, "json")
|| containsIgnoreCase(format, "hive")) {
return "read_json_auto";
}
return "read_csv_auto";
}
private static boolean containsIgnoreCase(String str, String sub) {
return str != null && str.toLowerCase().contains(sub);
}
private String resolveOutputLocation(ResultConfiguration rc, String queryId) {
String base = (rc != null && rc.getOutputLocation() != null && !rc.getOutputLocation().isBlank())
? rc.getOutputLocation()
: "s3://" + DEFAULT_OUTPUT_BUCKET + "/results/";
return base.endsWith("/") ? base + queryId + "/" : base + "/" + queryId + "/";
}
private void callDuck(String duckUrl, String sql, String setupDdl, String outputS3Path, String queryId) {
try {
// Ensure the output bucket exists
String bucket = extractBucket(outputS3Path);
if (bucket != null) {
try {
s3Service.createBucket(bucket, config.defaultRegion());
} catch (Exception ignored) {}
}
Map<String, Object> body = new LinkedHashMap<>();
body.put("sql", sql);
if (setupDdl != null && !setupDdl.isBlank()) {
body.put("setup_sql", setupDdl);
}
body.put("s3_endpoint", config.baseUrl());
body.put("s3_region", config.defaultRegion());
body.put("s3_access_key", "test");
body.put("s3_secret_key", "test");
body.put("s3_url_style", "path");
body.put("output_s3_path", outputS3Path + "results.csv");
String json = mapper.writeValueAsString(body);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(duckUrl + "/execute"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
throw new RuntimeException("floci-duck returned HTTP " + response.statusCode()
+ ": " + response.body());
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Failed to call floci-duck for query " + queryId + ": " + e.getMessage(), e);
}
}
private ResultSet readResultsFromS3(String outputLocation, String queryId) {
try {
String bucket = extractBucket(outputLocation);
String prefix = extractKey(outputLocation);
if (bucket == null) {
return emptyResultSet();
}
List<S3Object> objects = s3Service.listObjects(bucket, prefix, null, 10);
Optional<S3Object> csv = objects.stream()
.filter(o -> o.getKey().endsWith(".csv"))
.findFirst()
.map(o -> s3Service.getObject(bucket, o.getKey()));
if (csv.isEmpty()) {
return emptyResultSet();
}
return parseCsv(csv.get().getData());
} catch (Exception e) {
LOG.warnv("Could not read query results for {0}: {1}", queryId, e.getMessage());
return emptyResultSet();
}
}
private ResultSet parseCsv(byte[] data) {
List<ResultSet.Row> rows = new ArrayList<>();
List<ResultSet.ColumnInfo> columns = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(new ByteArrayInputStream(data), StandardCharsets.UTF_8))) {
String headerLine = reader.readLine();
if (headerLine == null) {
return emptyResultSet();
}
String[] headers = splitCsv(headerLine);
for (String h : headers) {
columns.add(new ResultSet.ColumnInfo(h, "varchar"));
}
// Header row is included in GetQueryResults per AWS spec
rows.add(toRow(headers));
String line;
while ((line = reader.readLine()) != null) {
rows.add(toRow(splitCsv(line)));
}
} catch (Exception e) {
LOG.debugv("CSV parse error: {0}", e.getMessage());
}
return new ResultSet(rows, new ResultSet.ResultSetMetadata(columns));
}
private ResultSet.Row toRow(String[] values) {
List<ResultSet.Datum> data = new ArrayList<>();
for (String v : values) {
data.add(new ResultSet.Datum(v));
}
return new ResultSet.Row(data);
}
/** Minimal CSV split — handles quoted fields. */
private String[] splitCsv(String line) {
List<String> fields = new ArrayList<>();
StringBuilder sb = new StringBuilder();
boolean inQuotes = false;
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (c == '"') {
if (inQuotes && i + 1 < line.length() && line.charAt(i + 1) == '"') {
sb.append('"');
i++;
} else {
inQuotes = !inQuotes;
}
} else if (c == ',' && !inQuotes) {
fields.add(sb.toString());
sb.setLength(0);
} else {
sb.append(c);
}
}
fields.add(sb.toString());
return fields.toArray(new String[0]);
}
private String extractBucket(String s3Path) {
if (s3Path == null || !s3Path.startsWith("s3://")) {
return null;
}
String without = s3Path.substring(5);
int slash = without.indexOf('/');
return slash < 0 ? without : without.substring(0, slash);
}
private String extractKey(String s3Path) {
if (s3Path == null || !s3Path.startsWith("s3://")) {
return "";
}
String without = s3Path.substring(5);
int slash = without.indexOf('/');
return slash < 0 ? "" : without.substring(slash + 1);
}
private ResultSet emptyResultSet() {
return new ResultSet(List.of(), new ResultSet.ResultSetMetadata(List.of()));
}
}
@@ -0,0 +1,136 @@
package io.github.hectorvent.floci.services.athena;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.quarkus.runtime.ShutdownEvent;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.net.HttpURLConnection;
import java.net.URI;
import java.util.Optional;
/**
* Lazily starts and manages the floci-duck sidecar container.
*
* On the first call to {@link #ensureReady()}, Floci pulls the image and starts
* a named container "floci-duck". Subsequent calls return the cached URL immediately.
*
* If {@code floci.services.athena.duck-url} is configured, container management is
* skipped entirely and that URL is used as-is — useful in Docker Compose setups where
* the user runs floci-duck as a separate service.
*/
@ApplicationScoped
public class FlociDuckManager {
private static final Logger LOG = Logger.getLogger(FlociDuckManager.class);
private static final String CONTAINER_NAME = "floci-duck";
private static final int DUCK_PORT = 3000;
private static final int HEALTH_POLL_MAX_MS = 30_000;
private static final int HEALTH_POLL_INTERVAL_MS = 500;
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
private final ContainerDetector containerDetector;
private final EmulatorConfig config;
private volatile String resolvedUrl;
private volatile String containerId;
@Inject
public FlociDuckManager(ContainerBuilder containerBuilder,
ContainerLifecycleManager lifecycleManager,
ContainerDetector containerDetector,
EmulatorConfig config) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.containerDetector = containerDetector;
this.config = config;
}
/**
* Returns the floci-duck base URL, starting the container on first call if needed.
* Thread-safe — concurrent callers wait while the first thread does the pull+start.
*/
public synchronized String ensureReady() {
if (resolvedUrl != null) {
return resolvedUrl;
}
Optional<String> configured = config.services().athena().duckUrl();
if (configured.isPresent() && !configured.get().isBlank()) {
resolvedUrl = configured.get();
LOG.infov("Using pre-configured floci-duck URL: {0}", resolvedUrl);
return resolvedUrl;
}
startContainer();
return resolvedUrl;
}
private void startContainer() {
String image = config.services().athena().defaultImage();
LOG.infov("Starting floci-duck container using image {0}", image);
lifecycleManager.removeIfExists(CONTAINER_NAME);
ContainerSpec spec = containerBuilder.newContainer(image)
.withName(CONTAINER_NAME)
.withEnv("FLOCI_DUCK_S3_ACCESS_KEY", "test")
.withEnv("FLOCI_DUCK_S3_SECRET_KEY", "test")
.withEnv("FLOCI_DUCK_S3_REGION", config.defaultRegion())
.withPortBinding(DUCK_PORT, DUCK_PORT)
.withDockerNetwork(config.services().dockerNetwork())
.withLogRotation()
.build();
containerId = lifecycleManager.createAndStart(spec).containerId();
String url = containerDetector.isRunningInContainer()
? "http://" + CONTAINER_NAME + ":" + DUCK_PORT
: "http://localhost:" + DUCK_PORT;
LOG.infov("floci-duck container started, waiting for health check at {0}", url);
waitForHealth(url);
resolvedUrl = url;
LOG.infov("floci-duck is ready at {0}", resolvedUrl);
}
private void waitForHealth(String baseUrl) {
String healthUrl = baseUrl + "/health";
long deadline = System.currentTimeMillis() + HEALTH_POLL_MAX_MS;
while (System.currentTimeMillis() < deadline) {
try {
HttpURLConnection conn = (HttpURLConnection) URI.create(healthUrl).toURL().openConnection();
conn.setConnectTimeout(2000);
conn.setReadTimeout(2000);
if (conn.getResponseCode() == 200) {
return;
}
} catch (Exception ignored) {
}
try {
Thread.sleep(HEALTH_POLL_INTERVAL_MS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted while waiting for floci-duck", e);
}
}
throw new RuntimeException("floci-duck did not become healthy within " + HEALTH_POLL_MAX_MS + " ms");
}
void onStop(@Observes ShutdownEvent event) {
if (containerId == null) {
return;
}
LOG.info("Stopping floci-duck container");
lifecycleManager.stopAndRemove(containerId, null);
}
}
@@ -14,12 +14,22 @@ public class QueryExecution {
@JsonProperty("WorkGroup")
private String workGroup;
@JsonProperty("ResultConfiguration")
private ResultConfiguration resultConfiguration;
@JsonProperty("QueryExecutionContext")
private QueryExecutionContext queryExecutionContext;
public QueryExecution() {}
public QueryExecution(String id, String query, String workGroup) {
public QueryExecution(String id, String query, String workGroup,
ResultConfiguration resultConfiguration,
QueryExecutionContext queryExecutionContext) {
this.queryExecutionId = id;
this.query = query;
this.workGroup = workGroup;
this.status = new QueryExecutionStatus(QueryExecutionState.QUEUED);
this.resultConfiguration = resultConfiguration;
this.queryExecutionContext = queryExecutionContext;
}
public String getQueryExecutionId() { return queryExecutionId; }
@@ -30,4 +40,8 @@ public class QueryExecution {
public void setStatus(QueryExecutionStatus status) { this.status = status; }
public String getWorkGroup() { return workGroup; }
public void setWorkGroup(String workGroup) { this.workGroup = workGroup; }
public ResultConfiguration getResultConfiguration() { return resultConfiguration; }
public void setResultConfiguration(ResultConfiguration resultConfiguration) { this.resultConfiguration = resultConfiguration; }
public QueryExecutionContext getQueryExecutionContext() { return queryExecutionContext; }
public void setQueryExecutionContext(QueryExecutionContext queryExecutionContext) { this.queryExecutionContext = queryExecutionContext; }
}
@@ -0,0 +1,21 @@
package io.github.hectorvent.floci.services.athena.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public class QueryExecutionContext {
@JsonProperty("Database")
private String database;
@JsonProperty("Catalog")
private String catalog;
public QueryExecutionContext() {}
public String getDatabase() { return database; }
public void setDatabase(String database) { this.database = database; }
public String getCatalog() { return catalog; }
public void setCatalog(String catalog) { this.catalog = catalog; }
}
@@ -0,0 +1,20 @@
package io.github.hectorvent.floci.services.athena.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public class ResultConfiguration {
@JsonProperty("OutputLocation")
private String outputLocation;
public ResultConfiguration() {}
public ResultConfiguration(String outputLocation) {
this.outputLocation = outputLocation;
}
public String getOutputLocation() { return outputLocation; }
public void setOutputLocation(String outputLocation) { this.outputLocation = outputLocation; }
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.firehose;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
import io.github.hectorvent.floci.services.firehose.model.Record;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -29,7 +30,13 @@ public class FirehoseJsonHandler {
return switch (action) {
case "CreateDeliveryStream" -> {
String name = request.get("DeliveryStreamName").asText();
String arn = firehoseService.createDeliveryStream(name);
S3Destination s3 = null;
if (request.has("S3DestinationConfiguration")) {
s3 = mapper.treeToValue(request.get("S3DestinationConfiguration"), S3Destination.class);
} else if (request.has("ExtendedS3DestinationConfiguration")) {
s3 = mapper.treeToValue(request.get("ExtendedS3DestinationConfiguration"), S3Destination.class);
}
String arn = firehoseService.createDeliveryStream(name, s3);
yield Response.ok(Map.of("DeliveryStreamARN", arn)).build();
}
case "DescribeDeliveryStream" -> {
@@ -38,7 +45,9 @@ public class FirehoseJsonHandler {
yield Response.ok(Map.of("DeliveryStreamDescription", desc)).build();
}
case "ListDeliveryStreams" -> {
yield Response.ok(Map.of("DeliveryStreamNames", firehoseService.listDeliveryStreams(), "HasMoreDeliveryStreams", false)).build();
yield Response.ok(Map.of(
"DeliveryStreamNames", firehoseService.listDeliveryStreams(),
"HasMoreDeliveryStreams", false)).build();
}
case "DeleteDeliveryStream" -> {
String name = request.get("DeliveryStreamName").asText();
@@ -53,13 +62,15 @@ public class FirehoseJsonHandler {
}
case "PutRecordBatch" -> {
String name = request.get("DeliveryStreamName").asText();
List<Map<String, String>> responseEntries = new ArrayList<>();
List<Record> records = new ArrayList<>();
for (JsonNode recordNode : request.get("Records")) {
Record record = mapper.treeToValue(recordNode, Record.class);
firehoseService.putRecord(name, record);
responseEntries.add(Map.of("RecordId", UUID.randomUUID().toString()));
records.add(mapper.treeToValue(recordNode, Record.class));
}
yield Response.ok(Map.of("FailedPutCount", 0, "RequestResponses", responseEntries)).build();
firehoseService.putRecordBatch(name, records);
List<Map<String, String>> responses = records.stream()
.map(r -> Map.of("RecordId", UUID.randomUUID().toString()))
.toList();
yield Response.ok(Map.of("FailedPutCount", 0, "RequestResponses", responses)).build();
}
default -> throw new AwsException("InvalidAction", "Action " + action + " is not supported", 400);
};
@@ -2,9 +2,11 @@ package io.github.hectorvent.floci.services.firehose;
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.firehose.model.DeliveryStreamDescription;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
import io.github.hectorvent.floci.services.firehose.model.Record;
import io.github.hectorvent.floci.services.s3.S3Service;
import jakarta.enterprise.context.ApplicationScoped;
@@ -12,6 +14,8 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@@ -19,55 +23,79 @@ import java.util.concurrent.ConcurrentHashMap;
public class FirehoseService {
private static final Logger LOG = Logger.getLogger(FirehoseService.class);
private static final String DEFAULT_BUCKET = "floci-firehose-results";
private static final int DEFAULT_FLUSH_COUNT = 5;
private final StorageBackend<String, DeliveryStreamDescription> streamStore;
private final Map<String, List<byte[]>> buffers = new ConcurrentHashMap<>();
private final S3Service s3Service;
private final RegionResolver regionResolver;
@Inject
public FirehoseService(StorageFactory storageFactory, S3Service s3Service) {
this.streamStore = storageFactory.create("firehose", "streams.json", new TypeReference<Map<String, DeliveryStreamDescription>>() {});
public FirehoseService(StorageFactory storageFactory, S3Service s3Service, RegionResolver regionResolver) {
this.streamStore = storageFactory.create("firehose", "streams.json",
new TypeReference<Map<String, DeliveryStreamDescription>>() {});
this.s3Service = s3Service;
this.regionResolver = regionResolver;
}
public String createDeliveryStream(String name) {
String arn = "arn:aws:firehose:us-east-1:000000000000:deliverystream/" + name;
DeliveryStreamDescription description = new DeliveryStreamDescription(name, arn);
public String createDeliveryStream(String name, S3Destination s3Config) {
String arn = "arn:aws:firehose:" + regionResolver.getDefaultRegion()
+ ":" + regionResolver.getAccountId() + ":deliverystream/" + name;
DeliveryStreamDescription description = new DeliveryStreamDescription(name, arn, s3Config);
streamStore.put(name, description);
buffers.put(name, Collections.synchronizedList(new ArrayList<>()));
LOG.infov("Created Firehose Delivery Stream: {0}", name);
LOG.infov("Created Firehose delivery stream: {0}", name);
return arn;
}
public DeliveryStreamDescription describeDeliveryStream(String name) {
return streamStore.get(name)
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Stream not found: " + name, 400));
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Delivery stream not found: " + name, 400));
}
public void deleteDeliveryStream(String name) {
describeDeliveryStream(name); // Checks if it exists and throws if not
describeDeliveryStream(name);
streamStore.delete(name);
buffers.remove(name);
LOG.infov("Deleted Firehose Delivery Stream: {0}", name);
LOG.infov("Deleted Firehose delivery stream: {0}", name);
}
public List<String> listDeliveryStreams() {
return streamStore.scan(k -> true).stream().map(DeliveryStreamDescription::getDeliveryStreamName).toList();
return streamStore.scan(k -> true).stream()
.map(DeliveryStreamDescription::getDeliveryStreamName).toList();
}
public void putRecord(String streamName, Record record) {
describeDeliveryStream(streamName); // Check exists
buffers.get(streamName).add(record.getData());
DeliveryStreamDescription stream = describeDeliveryStream(streamName);
buffers.computeIfAbsent(streamName, k -> Collections.synchronizedList(new ArrayList<>()))
.add(record.getData());
// Flush every 5 records for observable local feedback
if (buffers.get(streamName).size() >= 5) {
flush(streamName);
if (buffers.get(streamName).size() >= DEFAULT_FLUSH_COUNT) {
flush(streamName, stream);
}
}
public void putRecordBatch(String streamName, List<Record> records) {
DeliveryStreamDescription stream = describeDeliveryStream(streamName);
List<byte[]> buffer = buffers.computeIfAbsent(
streamName, k -> Collections.synchronizedList(new ArrayList<>()));
for (Record r : records) {
buffer.add(r.getData());
}
if (buffer.size() >= DEFAULT_FLUSH_COUNT) {
flush(streamName, stream);
}
}
public void flush(String streamName) {
streamStore.get(streamName).ifPresent(stream -> flush(streamName, stream));
}
private void flush(String streamName, DeliveryStreamDescription stream) {
List<byte[]> buffer = buffers.get(streamName);
if (buffer.isEmpty()) {
if (buffer == null || buffer.isEmpty()) {
return;
}
@@ -78,23 +106,55 @@ public class FirehoseService {
}
try {
String bucket = resolveBucket(stream);
String prefix = resolvePrefix(stream);
String key = prefix + UUID.randomUUID() + ".json";
ensureBucket(bucket);
StringBuilder sb = new StringBuilder();
for (byte[] data : toFlush) {
sb.append(new String(data, StandardCharsets.UTF_8)).append("\n");
sb.append(new String(data, StandardCharsets.UTF_8));
if (!sb.isEmpty() && sb.charAt(sb.length() - 1) != '\n') {
sb.append('\n');
}
}
String bucket = "floci-firehose-results";
String key = streamName + "/" + UUID.randomUUID() + ".json";
try {
s3Service.createBucket(bucket, "us-east-1");
} catch (Exception ignored) {}
byte[] jsonBytes = sb.toString().getBytes(StandardCharsets.UTF_8);
s3Service.putObject(bucket, key, jsonBytes, "application/x-ndjson", Map.of());
LOG.infov("Flushed {0} records from stream {1} to s3://{2}/{3}", toFlush.size(), streamName, bucket, key);
byte[] body = sb.toString().getBytes(StandardCharsets.UTF_8);
s3Service.putObject(bucket, key, body, "application/x-ndjson", Map.of());
LOG.infov("Flushed {0} records from stream {1} to s3://{2}/{3}",
toFlush.size(), streamName, bucket, key);
} catch (Exception e) {
LOG.errorv("Failed to flush Firehose stream {0}: {1}", streamName, e.getMessage());
}
}
private String resolveBucket(DeliveryStreamDescription stream) {
S3Destination s3 = stream.s3Destination();
if (s3 != null && s3.bucketName() != null) {
return s3.bucketName();
}
return DEFAULT_BUCKET;
}
private String resolvePrefix(DeliveryStreamDescription stream) {
S3Destination s3 = stream.s3Destination();
String prefix = (s3 != null && s3.getPrefix() != null) ? s3.getPrefix() : stream.getDeliveryStreamName() + "/";
// Substitute time-based placeholders matching real Firehose
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
prefix = prefix
.replace("{year}", String.format("%04d", now.getYear()))
.replace("{month}", String.format("%02d", now.getMonthValue()))
.replace("{day}", String.format("%02d", now.getDayOfMonth()))
.replace("{hour}", String.format("%02d", now.getHour()));
return prefix.endsWith("/") ? prefix : prefix + "/";
}
private void ensureBucket(String bucket) {
try {
s3Service.createBucket(bucket, regionResolver.getDefaultRegion());
} catch (Exception ignored) {}
}
}
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.List;
@RegisterForReflection
public class DeliveryStreamDescription {
@@ -16,13 +17,16 @@ public class DeliveryStreamDescription {
@JsonProperty("CreateTimestamp")
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
private Instant createTimestamp;
@JsonProperty("Destinations")
private List<Destination> destinations;
public DeliveryStreamDescription() {}
public DeliveryStreamDescription(String name, String arn) {
public DeliveryStreamDescription(String name, String arn, S3Destination s3) {
this.deliveryStreamName = name;
this.deliveryStreamARN = arn;
this.deliveryStreamStatus = DeliveryStreamStatus.ACTIVE;
this.createTimestamp = Instant.now();
this.destinations = List.of(new Destination(s3));
}
public String getDeliveryStreamName() { return deliveryStreamName; }
@@ -33,4 +37,62 @@ public class DeliveryStreamDescription {
public void setDeliveryStreamStatus(DeliveryStreamStatus deliveryStreamStatus) { this.deliveryStreamStatus = deliveryStreamStatus; }
public Instant getCreateTimestamp() { return createTimestamp; }
public void setCreateTimestamp(Instant createTimestamp) { this.createTimestamp = createTimestamp; }
public List<Destination> getDestinations() { return destinations; }
public void setDestinations(List<Destination> destinations) { this.destinations = destinations; }
/** Convenience: returns the first S3 destination, or null if none. */
public S3Destination s3Destination() {
if (destinations == null || destinations.isEmpty()) return null;
return destinations.get(0).getS3DestinationDescription();
}
@RegisterForReflection
public static class Destination {
@JsonProperty("S3DestinationDescription")
private S3Destination s3DestinationDescription;
public Destination() {}
public Destination(S3Destination s3) { this.s3DestinationDescription = s3; }
public S3Destination getS3DestinationDescription() { return s3DestinationDescription; }
public void setS3DestinationDescription(S3Destination s3) { this.s3DestinationDescription = s3; }
}
@RegisterForReflection
public static class S3Destination {
@JsonProperty("BucketARN")
private String bucketArn;
@JsonProperty("Prefix")
private String prefix;
@JsonProperty("BufferingHints")
private BufferingHints bufferingHints;
public S3Destination() {}
public String getBucketArn() { return bucketArn; }
public void setBucketArn(String bucketArn) { this.bucketArn = bucketArn; }
public String getPrefix() { return prefix; }
public void setPrefix(String prefix) { this.prefix = prefix; }
public BufferingHints getBufferingHints() { return bufferingHints; }
public void setBufferingHints(BufferingHints bufferingHints) { this.bufferingHints = bufferingHints; }
/** Extracts bucket name from ARN: arn:aws:s3:::my-bucket → my-bucket */
public String bucketName() {
if (bucketArn == null) return null;
int last = bucketArn.lastIndexOf(':');
return last >= 0 ? bucketArn.substring(last + 1) : bucketArn;
}
}
@RegisterForReflection
public static class BufferingHints {
@JsonProperty("SizeInMBs")
private int sizeInMBs = 5;
@JsonProperty("IntervalInSeconds")
private int intervalInSeconds = 300;
public BufferingHints() {}
public int getSizeInMBs() { return sizeInMBs; }
public void setSizeInMBs(int sizeInMBs) { this.sizeInMBs = sizeInMBs; }
public int getIntervalInSeconds() { return intervalInSeconds; }
public void setIntervalInSeconds(int intervalInSeconds) { this.intervalInSeconds = intervalInSeconds; }
}
}
@@ -42,6 +42,11 @@ public class ImageCacheService {
if (pulledImages.contains(imageUri)) {
return;
}
if (isLocalImagePresent(imageUri)) {
pulledImages.add(imageUri);
LOG.infov("Image already present locally, skipping pull: {0}", imageUri);
return;
}
LOG.infov("Pulling image: {0}", imageUri);
try {
dockerClient.pullImageCmd(imageUri)
@@ -57,6 +62,18 @@ public class ImageCacheService {
}
}
private boolean isLocalImagePresent(String imageUri) {
try {
dockerClient.inspectImageCmd(imageUri).exec();
return true;
} catch (com.github.dockerjava.api.exception.NotFoundException e) {
return false;
} catch (Exception e) {
LOG.debugv("Could not check local image presence for {0}: {1}", imageUri, e.getMessage());
return false;
}
}
private AuthConfig resolveAuth(String imageUri) {
String host = extractRegistryHost(imageUri);
for (EmulatorConfig.DockerConfig.RegistryCredential cred : registryCredentials) {