feat(parity): LocalStack drop-in compatibility (#696)

- Translate LocalStack env vars (LOCALSTACK_HOST, PERSISTENCE, LAMBDA_DOCKER_NETWORK, etc.)
  to Floci equivalents automatically at startup; opt out with LOCALSTACK_PARITY=false
- Serve /_localstack/init and /_localstack/health alongside /_floci/* equivalents
- Report executed scripts with path, state, and return_code in /_floci/init response
- Add /_aws/sqs/messages GET (non-destructive peek) and DELETE (purge) inspection endpoint
- Add /_aws/execute-api/{apiId}/{stageName} LocalStack-compat path for REST API invocation
- Add four-phase init hook lifecycle (boot/start/ready/stop) with dual-path discovery
  (/etc/floci/init/ and /etc/localstack/init/ compat paths)
- Install Python 3, AWS CLI, boto3 in standard image; wrap aws binary to pre-configure
  --endpoint-url=http://localhost:4566 so init scripts need no extra flags
- Wire entrypoint.sh + gosu privilege drop into all Dockerfile variants
- Add migration guide and update README, docker-compose, docker-images, SQS, and
  initialization-hooks docs
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-05-04 01:15:59 -05:00
1 parent b84d205b89
commit 023880b7d9
35 files changed
+1676 -272

No files matched your search

@@ -0,0 +1,87 @@
package io.github.hectorvent.floci.lifecycle;
import io.github.hectorvent.floci.core.common.ServiceRegistry;
import io.github.hectorvent.floci.lifecycle.inithook.InitializationHook;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.LinkedHashMap;
import java.util.Map;
@Path("{prefix:(_floci|_localstack)}")
@Produces(MediaType.APPLICATION_JSON)
public class EmulatorInfoController {
private final ServiceRegistry serviceRegistry;
private final InitLifecycleState initLifecycleState;
private final String version;
@Inject
public EmulatorInfoController(ServiceRegistry serviceRegistry, InitLifecycleState initLifecycleState) {
this.serviceRegistry = serviceRegistry;
this.initLifecycleState = initLifecycleState;
this.version = resolveVersion();
}
@GET
@Path("/health")
public Response health() {
return Response.ok(Map.of(
"services", serviceRegistry.getServices(),
"edition", "community",
"original_edition", "floci-always-free",
"version", version)).build();
}
@GET
@Path("/init")
public Response init() {
Map<String, Object> completed = new LinkedHashMap<>();
completed.put("boot", initLifecycleState.isBootCompleted());
completed.put("start", initLifecycleState.isStartCompleted());
completed.put("ready", initLifecycleState.isReadyCompleted());
completed.put("shutdown", initLifecycleState.isShutdownStarted());
Map<String, Object> scripts = new LinkedHashMap<>();
for (InitializationHook hook : InitializationHook.values()) {
scripts.put(hook.getResponseKey(), initLifecycleState.getScripts(hook).stream()
.map(r -> Map.of("script", r.script(), "state", r.state(), "return_code", r.returnCode()))
.toList());
}
Map<String, Object> body = new LinkedHashMap<>();
body.put("completed", completed);
body.put("scripts", scripts);
return Response.ok(body).build();
}
@GET
@Path("/info")
public Response info() {
return Response.ok(Map.of("version", version, "edition", "community", "original_edition", "floci-always-free")).build();
}
@GET
@Path("/diagnose")
public Response diagnose() {
return Response.ok(Map.of()).build();
}
@GET
@Path("/config")
public Response config() {
return Response.ok(Map.of()).build();
}
static String resolveVersion() {
String env = System.getenv("FLOCI_VERSION");
if (env != null && !env.isBlank()) {
return env;
}
return "dev";
}
}
@@ -46,6 +46,7 @@ public class EmulatorLifecycle {
private final DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller;
private final PipesService pipesService;
private final Ec2MetadataServer ec2MetadataServer;
private final InitLifecycleState initLifecycleState;
@Inject
public EmulatorLifecycle(StorageFactory storageFactory, ServiceRegistry serviceRegistry,
@@ -59,7 +60,8 @@ public class EmulatorLifecycle {
KinesisEventSourcePoller kinesisPoller,
DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller,
PipesService pipesService,
Ec2MetadataServer ec2MetadataServer) {
Ec2MetadataServer ec2MetadataServer,
InitLifecycleState initLifecycleState) {
this.storageFactory = storageFactory;
this.serviceRegistry = serviceRegistry;
this.config = config;
@@ -73,6 +75,7 @@ public class EmulatorLifecycle {
this.dynamodbStreamsPoller = dynamodbStreamsPoller;
this.pipesService = pipesService;
this.ec2MetadataServer = ec2MetadataServer;
this.initLifecycleState = initLifecycleState;
}
void onStart(@Observes StartupEvent ignored) {
@@ -80,6 +83,17 @@ public class EmulatorLifecycle {
LOG.infov("Storage mode: {0}", config.storage().mode());
LOG.infov("Persistent path: {0}", config.storage().persistentPath());
// BOOT hooks run before service initialization — scripts cannot use AWS APIs yet.
try {
initializationHooksRunner.run(InitializationHook.BOOT);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Boot hook execution interrupted", e);
} catch (IOException e) {
throw new IllegalStateException("Boot hook execution failed", e);
}
initLifecycleState.markBootCompleted();
serviceRegistry.logEnabledServices();
storageFactory.loadAll();
@@ -95,29 +109,46 @@ public class EmulatorLifecycle {
});
}
if (!initializationHooksRunner.hasHooks(InitializationHook.START)) {
boolean hasStart = initializationHooksRunner.hasHooks(InitializationHook.START);
boolean hasReady = initializationHooksRunner.hasHooks(InitializationHook.READY);
if (!hasStart && !hasReady) {
initLifecycleState.markStartCompleted();
initLifecycleState.markReadyCompleted();
LOG.info("=== AWS Local Emulator Ready ===");
}
}
void onHttpStart(@ObservesAsync HttpServerStart event) {
if ((event.options().getPort() == HTTP_PORT) &&
initializationHooksRunner.hasHooks(InitializationHook.START)){
try {
if (event.options().getPort() != HTTP_PORT) {
return;
}
boolean hasStart = initializationHooksRunner.hasHooks(InitializationHook.START);
boolean hasReady = initializationHooksRunner.hasHooks(InitializationHook.READY);
if (!hasStart && !hasReady) {
return;
}
try {
if (hasStart) {
initializationHooksRunner.run(InitializationHook.START);
LOG.info("=== AWS Local Emulator Ready ===");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOG.error("Startup hook execution interrupted — shutting down", e);
} catch (Exception e) {
LOG.error("Startup hook execution failed — shutting down", e);
Quarkus.asyncExit();
}
initLifecycleState.markStartCompleted();
if (hasReady) {
initializationHooksRunner.run(InitializationHook.READY);
}
initLifecycleState.markReadyCompleted();
LOG.info("=== AWS Local Emulator Ready ===");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOG.error("Startup hook execution interrupted — shutting down", e);
} catch (Exception e) {
LOG.error("Startup hook execution failed — shutting down", e);
Quarkus.asyncExit();
}
}
void onPreShutdown(@Observes ShutdownDelayInitiatedEvent ignored) {
LOG.info("=== AWS Local Emulator Shutting Down ===");
initLifecycleState.markShutdownStarted();
// Log-and-continue for every failure mode. Resource cleanup in onStop() must still run,
// and cleanup routines (proxy/container/storage shutdown) must not see an interrupted
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.lifecycle;
import io.github.hectorvent.floci.core.common.ServiceRegistry;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
@@ -9,18 +10,14 @@ import jakarta.ws.rs.core.Response;
import java.util.Map;
/**
* Internal health endpoint at /_floci/health.
* Returns the Floci version and the status of each enabled service.
* Compatible with the LocalStack /_localstack/health pattern.
*/
@Path("{path:(_floci|_localstack)/health}")
@Path("/health")
@Produces(MediaType.APPLICATION_JSON)
public class HealthController {
private final ServiceRegistry serviceRegistry;
private final String version;
@Inject
public HealthController(ServiceRegistry serviceRegistry) {
this.serviceRegistry = serviceRegistry;
this.version = resolveVersion();
@@ -28,10 +25,14 @@ public class HealthController {
@GET
public Response health() {
return Response.ok(Map.of("services", serviceRegistry.getServices(), "edition", "floci-always-free", "version", version)).build();
return Response.ok(Map.of(
"services", serviceRegistry.getServices(),
"edition", "community",
"original_edition", "floci-always-free",
"version", version)).build();
}
private static String resolveVersion() {
static String resolveVersion() {
String env = System.getenv("FLOCI_VERSION");
if (env != null && !env.isBlank()) {
return env;
@@ -0,0 +1,40 @@
package io.github.hectorvent.floci.lifecycle;
import io.github.hectorvent.floci.lifecycle.inithook.InitializationHook;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
@ApplicationScoped
public class InitLifecycleState {
public record ScriptRecord(String script, String state, int returnCode) {}
private volatile boolean bootCompleted = false;
private volatile boolean startCompleted = false;
private volatile boolean readyCompleted = false;
private volatile boolean shutdownStarted = false;
private final Map<InitializationHook, List<ScriptRecord>> scriptsByPhase = new EnumMap<>(InitializationHook.class);
public void markBootCompleted() { bootCompleted = true; }
public void markStartCompleted() { startCompleted = true; }
public void markReadyCompleted() { readyCompleted = true; }
public void markShutdownStarted() { shutdownStarted = true; }
public boolean isBootCompleted() { return bootCompleted; }
public boolean isStartCompleted() { return startCompleted; }
public boolean isReadyCompleted() { return readyCompleted; }
public boolean isShutdownStarted() { return shutdownStarted; }
public synchronized void addScript(InitializationHook hook, String scriptPath, String state, int returnCode) {
scriptsByPhase.computeIfAbsent(hook, k -> new ArrayList<>()).add(new ScriptRecord(scriptPath, state, returnCode));
}
public synchronized List<ScriptRecord> getScripts(InitializationHook hook) {
return List.copyOf(scriptsByPhase.getOrDefault(hook, List.of()));
}
}
@@ -20,12 +20,16 @@ public class HookScriptExecutor {
this.initHooksConfig = emulatorConfig.initHooks();
}
public void run(final File scriptFile) throws IOException, InterruptedException {
run(scriptFile.getParentFile(), scriptFile.getName());
}
public void run(final File hookDirectory, final String scriptFileName) throws IOException, InterruptedException {
final String shellExecutable = initHooksConfig.shellExecutable();
LOG.debugv("Executing hook script {0} via {1}", scriptFileName, shellExecutable);
final String command = scriptFileName.endsWith(".py") ? "python3" : initHooksConfig.shellExecutable();
LOG.debugv("Executing hook script {0} via {1}", scriptFileName, command);
// Inherit parent I/O so script output is streamed directly and does not block on unconsumed buffers.
final Process process = new ProcessBuilder(shellExecutable, scriptFileName).directory(hookDirectory).inheritIO().start();
final Process process = new ProcessBuilder(command, scriptFileName).directory(hookDirectory).inheritIO().start();
run(process, scriptFileName);
}
@@ -1,26 +1,51 @@
package io.github.hectorvent.floci.lifecycle.inithook;
import java.io.File;
import java.util.List;
public enum InitializationHook {
STOP("shutdown", "/etc/floci/init/stop.d"),
START("startup", "/etc/floci/init/start.d");
BOOT("boot", "boot",
List.of("/etc/floci/init/boot.d"),
List.of("/etc/localstack/init/boot.d")),
START("startup", "start",
List.of("/etc/floci/init/start.d"),
List.of("/etc/localstack/init/start.d")),
READY("ready", "ready",
List.of("/etc/floci/init/ready.d"),
List.of("/etc/localstack/init/ready.d")),
STOP("shutdown", "shutdown",
List.of("/etc/floci/init/stop.d", "/etc/floci/init/shutdown.d"),
List.of("/etc/localstack/init/shutdown.d"));
private final String name;
private final File path;
private final String responseKey;
private final List<File> primaryPaths;
private final List<File> compatPaths;
InitializationHook(final String name, final String path) {
InitializationHook(String name, String responseKey, List<String> primaryPaths, List<String> compatPaths) {
this.name = name;
this.path = new File(path);
this.responseKey = responseKey;
this.primaryPaths = primaryPaths.stream().map(File::new).toList();
this.compatPaths = compatPaths.stream().map(File::new).toList();
}
public String getName() {
return name;
}
public File getPath() {
return path;
/** Key used in the {@code /_floci/init} and {@code /_localstack/init} response body. */
public String getResponseKey() {
return responseKey;
}
/** Floci-native directories for this phase. First occurrence of a filename wins. */
public List<File> getPrimaryPaths() {
return primaryPaths;
}
/** LocalStack-compat directories for this phase. Only used when a filename is not already in a primary path. */
public List<File> getCompatPaths() {
return compatPaths;
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.lifecycle.inithook;
import io.github.hectorvent.floci.lifecycle.InitLifecycleState;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -8,65 +9,135 @@ import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@ApplicationScoped
public class InitializationHooksRunner {
private static final Logger LOG = Logger.getLogger(InitializationHooksRunner.class);
private static final String SHELL_SCRIPT_EXTENSION = ".sh";
private static final FilenameFilter FILE_EXTENSION_FILTER = (ignored, name) -> name.endsWith(SHELL_SCRIPT_EXTENSION);
private static final FilenameFilter SCRIPT_FILE_FILTER =
(ignored, name) -> name.endsWith(".sh") || name.endsWith(".py");
private final HookScriptExecutor hookScriptExecutor;
private final InitLifecycleState initLifecycleState;
@Inject
public InitializationHooksRunner(final HookScriptExecutor hookScriptExecutor) {
public InitializationHooksRunner(final HookScriptExecutor hookScriptExecutor,
final InitLifecycleState initLifecycleState) {
this.hookScriptExecutor = hookScriptExecutor;
}
private static String[] findScriptFileNames(final String hookName, final File hookDirectory) {
final String hookDirectoryPath = hookDirectory.getAbsolutePath();
if (!hookDirectory.exists()) {
LOG.debugv("{0} hook directory does not exist: {1}", hookName, hookDirectoryPath);
return new String[0];
} else if (!hookDirectory.isDirectory()) {
LOG.warnv("{0} hook path is not a directory: {1}", hookName, hookDirectoryPath);
return new String[0];
}
final String[] scriptFileNames = hookDirectory.list(FILE_EXTENSION_FILTER);
if ((scriptFileNames == null) || (scriptFileNames.length == 0)) {
LOG.debugv("No {0} hook scripts found in {1}", hookName, hookDirectoryPath);
return new String[0];
}
Arrays.sort(scriptFileNames);
return scriptFileNames;
this.initLifecycleState = initLifecycleState;
}
public boolean hasHooks(final InitializationHook hook) {
return findScriptFileNames(hook.getName(), hook.getPath()).length > 0;
return !findMergedScripts(hook).isEmpty();
}
public void run(final InitializationHook hook) throws IOException, InterruptedException {
final String hookName = hook.getName();
final File hookDirectory = hook.getPath();
run(hookName, hookDirectory);
final List<File> scripts = findMergedScripts(hook);
if (!scripts.isEmpty()) {
LOG.infov("Running {0} hook with {1} script(s): {2}",
hook.getName(), scripts.size(),
scripts.stream().map(File::getAbsolutePath).toList());
for (final File script : scripts) {
LOG.infov("Executing {0} hook script: {1}", hook.getName(), script.getAbsolutePath());
try {
hookScriptExecutor.run(script);
initLifecycleState.addScript(hook, script.getAbsolutePath(), "successful", 0);
} catch (IllegalStateException e) {
initLifecycleState.addScript(hook, script.getAbsolutePath(), "error", parseExitCode(e));
throw e;
}
}
}
}
private static int parseExitCode(IllegalStateException e) {
String msg = e.getMessage();
if (msg != null && msg.contains("exited with code ")) {
try {
return Integer.parseInt(msg.substring(msg.lastIndexOf(' ') + 1));
} catch (NumberFormatException ignored) {
}
}
return 1;
}
/**
* Runs scripts from an arbitrary directory — kept for test utilities and direct invocations.
*/
public void run(final String hookName, final File hookDirectory) throws IOException, InterruptedException {
final String[] scriptFileNames = findScriptFileNames(hookName, hookDirectory);
if (scriptFileNames.length > 0) {
final String hookDirectoryPath = hookDirectory.getAbsolutePath();
final String scriptList = Arrays.toString(scriptFileNames);
LOG.infov("Running {0} hook with {1} script(s) from {2}: {3}", hookName, scriptFileNames.length, hookDirectoryPath, scriptList);
// Hook scripts are executed sequentially and treated as dependent steps.
// Stop at the first script failure to avoid continuing in a partially initialized state
for (var scriptFileName : scriptFileNames) {
LOG.infov("Running {0} hook with {1} script(s) from {2}: {3}",
hookName, scriptFileNames.length, hookDirectory.getAbsolutePath(),
Arrays.toString(scriptFileNames));
for (final String scriptFileName : scriptFileNames) {
LOG.infov("Executing {0} hook script: {1}", hookName, scriptFileName);
hookScriptExecutor.run(hookDirectory, scriptFileName);
}
}
}
/**
* Merges scripts from all primary (Floci) paths and then compat (LocalStack) paths.
* First occurrence of a filename wins; merged list is sorted lexicographically.
*/
private static List<File> findMergedScripts(final InitializationHook hook) {
final Map<String, File> merged = new LinkedHashMap<>();
for (final File dir : hook.getPrimaryPaths()) {
collectScripts(hook.getName(), dir, merged);
}
for (final File dir : hook.getCompatPaths()) {
collectScripts(hook.getName(), dir, merged);
}
return merged.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.map(Map.Entry::getValue)
.toList();
}
private static void collectScripts(final String hookName, final File dir,
final Map<String, File> target) {
if (!dir.exists()) {
LOG.debugv("{0} hook directory does not exist: {1}", hookName, dir.getAbsolutePath());
return;
}
if (!dir.isDirectory()) {
LOG.warnv("{0} hook path is not a directory: {1}", hookName, dir.getAbsolutePath());
return;
}
final File[] scripts = dir.listFiles(SCRIPT_FILE_FILTER);
if (scripts == null || scripts.length == 0) {
LOG.debugv("No {0} hook scripts found in {1}", hookName, dir.getAbsolutePath());
return;
}
for (final File script : scripts) {
if (target.putIfAbsent(script.getName(), script) == null) {
LOG.debugv("Found {0} hook script: {1}", hookName, script.getAbsolutePath());
} else {
LOG.debugv("Skipping {0} (shadowed by higher-priority path)", script.getAbsolutePath());
}
}
}
private static String[] findScriptFileNames(final String hookName, final File hookDirectory) {
if (!hookDirectory.exists()) {
LOG.debugv("{0} hook directory does not exist: {1}", hookName, hookDirectory.getAbsolutePath());
return new String[0];
}
if (!hookDirectory.isDirectory()) {
LOG.warnv("{0} hook path is not a directory: {1}", hookName, hookDirectory.getAbsolutePath());
return new String[0];
}
final String[] scriptFileNames = hookDirectory.list(SCRIPT_FILE_FILTER);
if (scriptFileNames == null || scriptFileNames.length == 0) {
LOG.debugv("No {0} hook scripts found in {1}", hookName, hookDirectory.getAbsolutePath());
return new String[0];
}
Arrays.sort(scriptFileNames);
return scriptFileNames;
}
}
@@ -0,0 +1,74 @@
package io.github.hectorvent.floci.services.apigateway;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.*;
/**
* LocalStack-compatible execute endpoint for deployed REST APIs.
*
* <p>Supports the {@code /_aws/} prefix URL format used by LocalStack and compatible tooling:
* {@code /_aws/execute-api/{apiId}/{stageName}/{proxy+}}
*
* <p>This is equivalent to the standard execute-api path:
* {@code /execute-api/{apiId}/{stageName}/{proxy+}}
*/
@Path("/_aws/execute-api/{apiId}/{stageName}")
@Produces(MediaType.WILDCARD)
public class ApiGatewayAwsExecuteController {
private final ApiGatewayExecuteController executeController;
@Inject
public ApiGatewayAwsExecuteController(ApiGatewayExecuteController executeController) {
this.executeController = executeController;
}
@GET
@Path("/{proxy: .*}")
public Response handleGet(@Context HttpHeaders headers, @Context UriInfo uriInfo,
@PathParam("apiId") String apiId,
@PathParam("stageName") String stageName,
@PathParam("proxy") String proxy) {
return executeController.dispatch("GET", apiId, stageName, proxy, headers, uriInfo, null);
}
@POST
@Path("/{proxy: .*}")
public Response handlePost(@Context HttpHeaders headers, @Context UriInfo uriInfo,
@PathParam("apiId") String apiId,
@PathParam("stageName") String stageName,
@PathParam("proxy") String proxy,
byte[] body) {
return executeController.dispatch("POST", apiId, stageName, proxy, headers, uriInfo, body);
}
@PUT
@Path("/{proxy: .*}")
public Response handlePut(@Context HttpHeaders headers, @Context UriInfo uriInfo,
@PathParam("apiId") String apiId,
@PathParam("stageName") String stageName,
@PathParam("proxy") String proxy,
byte[] body) {
return executeController.dispatch("PUT", apiId, stageName, proxy, headers, uriInfo, body);
}
@DELETE
@Path("/{proxy: .*}")
public Response handleDelete(@Context HttpHeaders headers, @Context UriInfo uriInfo,
@PathParam("apiId") String apiId,
@PathParam("stageName") String stageName,
@PathParam("proxy") String proxy) {
return executeController.dispatch("DELETE", apiId, stageName, proxy, headers, uriInfo, null);
}
@PATCH
@Path("/{proxy: .*}")
public Response handlePatch(@Context HttpHeaders headers, @Context UriInfo uriInfo,
@PathParam("apiId") String apiId,
@PathParam("stageName") String stageName,
@PathParam("proxy") String proxy,
byte[] body) {
return executeController.dispatch("PATCH", apiId, stageName, proxy, headers, uriInfo, body);
}
}
@@ -195,6 +195,12 @@ class GuardedMessageQueue {
}
}
List<Message> peekAll() {
try (var _ = hold()) {
return new ArrayList<>(messages);
}
}
boolean isEmpty() {
try (var _ = hold()) {
return messages.isEmpty();
@@ -0,0 +1,109 @@
package io.github.hectorvent.floci.services.sqs;
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.services.sqs.model.Message;
import io.github.hectorvent.floci.services.sqs.model.MessageAttributeValue;
import jakarta.inject.Inject;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.List;
import java.util.Map;
/**
* LocalStack-compatible REST endpoint for inspecting SQS queue contents.
* Provides non-destructive peek of all messages (visible and in-flight) for test helpers.
*/
@Path("/_aws/sqs/messages")
@Produces(MediaType.APPLICATION_JSON)
public class SqsInspectionController {
private final SqsService sqsService;
private final ObjectMapper objectMapper;
@Inject
public SqsInspectionController(SqsService sqsService, ObjectMapper objectMapper) {
this.sqsService = sqsService;
this.objectMapper = objectMapper;
}
@GET
public Response getMessages(@QueryParam("QueueUrl") String queueUrl) {
if (queueUrl == null || queueUrl.isBlank()) {
return Response.status(400)
.entity(objectMapper.createObjectNode().put("message", "QueueUrl query parameter is required"))
.build();
}
List<Message> messages = sqsService.peekMessages(queueUrl);
ArrayNode messagesArray = objectMapper.createArrayNode();
for (Message msg : messages) {
ObjectNode node = objectMapper.createObjectNode();
node.put("MessageId", msg.getMessageId());
node.put("MD5OfBody", msg.getMd5OfBody());
node.put("Body", msg.getBody());
if (msg.getReceiptHandle() != null) {
node.put("ReceiptHandle", msg.getReceiptHandle());
} else {
node.putNull("ReceiptHandle");
}
ObjectNode attributes = node.putObject("Attributes");
if (msg.getSentTimestamp() != null) {
attributes.put("SentTimestamp", String.valueOf(msg.getSentTimestamp().toEpochMilli()));
}
attributes.put("ApproximateReceiveCount", String.valueOf(msg.getReceiveCount()));
if (msg.getMessageGroupId() != null) {
attributes.put("MessageGroupId", msg.getMessageGroupId());
}
if (msg.getMessageDeduplicationId() != null) {
attributes.put("MessageDeduplicationId", msg.getMessageDeduplicationId());
}
if (msg.getSequenceNumber() != 0) {
attributes.put("SequenceNumber", String.valueOf(msg.getSequenceNumber()));
}
ObjectNode messageAttributes = node.putObject("MessageAttributes");
if (msg.getMessageAttributes() != null) {
for (Map.Entry<String, MessageAttributeValue> entry : msg.getMessageAttributes().entrySet()) {
ObjectNode attrNode = messageAttributes.putObject(entry.getKey());
MessageAttributeValue val = entry.getValue();
attrNode.put("DataType", val.getDataType());
if (val.getStringValue() != null) {
attrNode.put("StringValue", val.getStringValue());
}
if (val.getBinaryValue() != null) {
attrNode.put("BinaryValue", val.getBinaryValue());
}
}
}
messagesArray.add(node);
}
ObjectNode result = objectMapper.createObjectNode();
result.set("messages", messagesArray);
return Response.ok(result).build();
}
@DELETE
public Response purgeQueue(@QueryParam("QueueUrl") String queueUrl) {
if (queueUrl == null || queueUrl.isBlank()) {
return Response.status(400)
.entity(objectMapper.createObjectNode().put("message", "QueueUrl query parameter is required"))
.build();
}
sqsService.purgeQueue(queueUrl);
return Response.ok().build();
}
}
@@ -578,6 +578,16 @@ public class SqsService {
}
}
public List<Message> peekMessages(String queueUrl) {
return peekMessages(queueUrl, regionResolver.getDefaultRegion());
}
public List<Message> peekMessages(String queueUrl, String region) {
String storageKey = regionKey(region, queueUrl);
ensureQueueExists(storageKey);
return getOrCreateQueue(storageKey).peekAll();
}
public void deleteMessage(String queueUrl, String receiptHandle) {
deleteMessage(queueUrl, receiptHandle, regionResolver.getDefaultRegion());
}