Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

Hector Ventura023880b7d90e
diff --git a/.dockerignore b/.dockerignore
index 253b19dbd5..eede665231 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -1,5 +1,6 @@
*
!docker/entrypoint.sh
+!docker/localstack-parity.sh
!pom.xml
!src/**
!target/*.so
diff --git a/README.md b/README.md
index 79541685b9..e08736ae6f 100644
--- a/README.md
+++ b/README.md
@@ -76,6 +76,35 @@
**Broad AWS coverage. Free forever.**
+## Migrating from LocalStack
+
+Floci is a drop-in replacement for LocalStack Community. The port (`4566`), credentials, and all AWS SDK and CLI calls work unchanged — swap the image and you're done.
+
+```yaml
+# Before
+image: localstack/localstack
+
+# After — no init scripts, or scripts that don't call aws / boto3
+image: floci/floci:latest
+
+# After — init scripts that use aws CLI or boto3
+image: floci/floci:latest-compat # includes Python 3, AWS CLI, boto3 pre-configured
+```
+
+**LocalStack environment variables are translated automatically** — no renaming required:
+
+| LocalStack | Floci equivalent |
+|---|---|
+| `LOCALSTACK_HOST` | `FLOCI_HOSTNAME` |
+| `PERSISTENCE=1` | `FLOCI_STORAGE_MODE=persistent` |
+| `LAMBDA_DOCKER_NETWORK` | `FLOCI_SERVICES_LAMBDA_DOCKER_NETWORK` |
+| `LAMBDA_REMOVE_CONTAINERS=1` | `FLOCI_SERVICES_LAMBDA_EPHEMERAL=true` |
+| `DEBUG=1` | `QUARKUS_LOG_LEVEL=DEBUG` |
+
+Init scripts mounted under `/etc/localstack/init/` run unchanged. The `/_localstack/init` and `/_localstack/health` endpoints are still served. Set `LOCALSTACK_PARITY=false` to opt out of the automatic translation.
+
+→ [Full migration guide](https://floci.io/floci/getting-started/migrate-from-localstack/)
+
## Architecture Overview
```mermaid
diff --git a/docker-compose.yml b/docker-compose.yml
index bdfe7e4d24..d20f64816e 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -10,8 +10,6 @@ services:
- "9200-9299:9200-9299"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- - ./scripts:/etc/floci/init/start.d
- - ./scripts:/etc/floci/init/stop.d
- ./data:/app/data
environment:
FLOCI_SERVICES_DOCKER_NETWORK: floci_default
diff --git a/docker/Dockerfile b/docker/Dockerfile
index d4c9d89895..924b91ec96 100644
--- a/docker/Dockerfile
+++ b/docker/Dockerfile
@@ -17,11 +17,45 @@ ARG VERSION=latest
ENV FLOCI_VERSION=${VERSION}
ENV FLOCI_STORAGE_PERSISTENT_PATH=/app/data
+ENV AWS_DEFAULT_REGION=us-east-1
+ENV AWS_ACCESS_KEY_ID=test
+ENV AWS_SECRET_ACCESS_KEY=test
+ENV AWS_CONFIG_FILE=/etc/floci/aws/config
+
+ENV GOSU_VERSION=1.17
+ENV GOSU_AMD64_SHA256=bbc4136d03ab138b1ad66fa4fc051bafc6cc7ffae632b069a53657279a450de3
+ENV GOSU_ARM64_SHA256=c3805a85d17f4454c23d7059bcb97e1ec1af272b90126e79ed002342de08389b
+RUN set -eux; \
+ apk add --no-cache shadow ca-certificates python3 py3-pip; \
+ pip3 install --no-cache-dir --break-system-packages awscli boto3; \
+ mv /usr/bin/aws /usr/bin/aws.real; \
+ printf '#!/bin/sh\nexec /usr/bin/aws.real --endpoint-url=http://localhost:4566 "$@"\n' > /usr/bin/aws; \
+ chmod +x /usr/bin/aws; \
+ useradd -r -u 1001 -g root -d /app -s /sbin/nologin floci; \
+ arch="$(apk --print-arch)"; \
+ case "$arch" in \
+ x86_64) gosuArch='amd64'; gosuSha256="$GOSU_AMD64_SHA256" ;; \
+ aarch64) gosuArch='arm64'; gosuSha256="$GOSU_ARM64_SHA256" ;; \
+ *) echo >&2 "unsupported arch: $arch"; exit 1 ;; \
+ esac; \
+ wget -q -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/${GOSU_VERSION}/gosu-${gosuArch}"; \
+ echo "${gosuSha256} /usr/local/bin/gosu" | sha256sum -c -; \
+ chmod +x /usr/local/bin/gosu
+
WORKDIR /app
+RUN mkdir -p /app/data /etc/floci/aws \
+ && printf '[default]\nendpoint_url = http://localhost:4566\n' > /etc/floci/aws/config \
+ && chown 1001:root /app \
+ && chmod "g+rwX" /app \
+ && chown 1001:root /app/data
+
COPY --from=build /build/target/quarkus-app/ quarkus-app/
+RUN chown -R 1001:root /app/quarkus-app
+
+COPY --chmod=755 docker/entrypoint.sh /usr/local/bin/docker-entrypoint.sh
+COPY --chmod=755 docker/localstack-parity.sh /usr/local/bin/localstack-parity.sh
-RUN mkdir -p /app/data
VOLUME /app/data
EXPOSE 4566 6379-6399
@@ -29,4 +63,5 @@ EXPOSE 4566 6379-6399
HEALTHCHECK --interval=5s --timeout=3s --retries=5 \
CMD wget -q --spider http://localhost:4566/_floci/health || exit 1
-ENTRYPOINT ["java", "--enable-native-access=ALL-UNNAMED", "-jar", "quarkus-app/quarkus-run.jar"]
+ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
+CMD ["java", "--enable-native-access=ALL-UNNAMED", "-jar", "/app/quarkus-app/quarkus-run.jar"]
diff --git a/docker/Dockerfile.compat b/docker/Dockerfile.compat
index 4e6e8dc882..5211382ee3 100644
--- a/docker/Dockerfile.compat
+++ b/docker/Dockerfile.compat
@@ -1,6 +1,11 @@
ARG VERSION=latest
FROM floci/floci:${VERSION}
+ENV AWS_DEFAULT_REGION=us-east-1
+ENV AWS_ACCESS_KEY_ID=test
+ENV AWS_SECRET_ACCESS_KEY=test
+ENV AWS_CONFIG_FILE=/etc/floci/aws/config
+
USER root
RUN microdnf install -y --nodocs python3 python3-pip \
&& pip3 install --no-cache-dir awscli boto3 \
diff --git a/docker/Dockerfile.jvm-package b/docker/Dockerfile.jvm-package
index 638b75ab60..6d39e13584 100644
--- a/docker/Dockerfile.jvm-package
+++ b/docker/Dockerfile.jvm-package
@@ -37,6 +37,7 @@ RUN mkdir -p /app/data \
VOLUME /app/data
COPY --chmod=755 docker/entrypoint.sh /usr/local/bin/docker-entrypoint.sh
+COPY --chmod=755 docker/localstack-parity.sh /usr/local/bin/localstack-parity.sh
COPY --chown=1001:root target/quarkus-app quarkus-app/
EXPOSE 4566 6379-6399
diff --git a/docker/Dockerfile.native b/docker/Dockerfile.native
index e3f394af55..d5d8248a51 100644
--- a/docker/Dockerfile.native
+++ b/docker/Dockerfile.native
@@ -65,6 +65,7 @@ ENV FLOCI_STORAGE_PERSISTENT_PATH=/app/data
COPY --from=build /app/target/*-runner /app/application
COPY --chmod=755 docker/entrypoint.sh /usr/local/bin/docker-entrypoint.sh
+COPY --chmod=755 docker/localstack-parity.sh /usr/local/bin/localstack-parity.sh
RUN chmod +x /app/application
diff --git a/docker/Dockerfile.native-package b/docker/Dockerfile.native-package
index 2ef4794e75..7c95a677d2 100644
--- a/docker/Dockerfile.native-package
+++ b/docker/Dockerfile.native-package
@@ -38,6 +38,7 @@ COPY --chown=1001:root native/${TARGETARCH}/ /app/
RUN mv /app/*-runner /app/application && chmod +x /app/application
COPY --chmod=755 docker/entrypoint.sh /usr/local/bin/docker-entrypoint.sh
+COPY --chmod=755 docker/localstack-parity.sh /usr/local/bin/localstack-parity.sh
EXPOSE 4566
diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh
index 14f63051ca..a7314eff2b 100755
--- a/docker/entrypoint.sh
+++ b/docker/entrypoint.sh
@@ -37,4 +37,8 @@ if [ "$(id -u)" = '0' ]; then
exec gosu floci "$0" "$@"
fi
+if [ "${LOCALSTACK_PARITY:-true}" != "false" ]; then
+ . /usr/local/bin/localstack-parity.sh
+fi
+
exec "$@"
diff --git a/docker/localstack-parity.sh b/docker/localstack-parity.sh
new file mode 100644
index 0000000000..f8915c0de9
--- /dev/null
+++ b/docker/localstack-parity.sh
@@ -0,0 +1,66 @@
+#!/bin/sh
+# Maps LocalStack Community environment variables to their Floci equivalents.
+# Sourced by entrypoint.sh when LOCALSTACK_PARITY=true.
+# Floci vars always win: every mapping uses ${FLOCI_VAR:-<derived>} so an
+# explicitly-set Floci var is never overwritten.
+
+# Storage mode — PERSISTENCE=1 / PERSIST_STATE=1 → persistent storage
+if [ -n "${PERSISTENCE:-}" ] || [ -n "${PERSIST_STATE:-}" ]; then
+ _ls_persist="${PERSISTENCE:-${PERSIST_STATE:-}}"
+ if [ "${_ls_persist}" = "1" ] || [ "${_ls_persist}" = "true" ]; then
+ export FLOCI_STORAGE_MODE="${FLOCI_STORAGE_MODE:-persistent}"
+ fi
+fi
+
+# Bind port — EDGE_PORT → FLOCI_PORT
+[ -n "${EDGE_PORT:-}" ] && export FLOCI_PORT="${FLOCI_PORT:-${EDGE_PORT}}"
+
+# Hostname returned in response URLs — LOCALSTACK_HOST / LOCALSTACK_HOSTNAME → FLOCI_HOSTNAME
+_ls_host="${LOCALSTACK_HOST:-${LOCALSTACK_HOSTNAME:-}}"
+[ -n "${_ls_host}" ] && export FLOCI_HOSTNAME="${FLOCI_HOSTNAME:-${_ls_host}}"
+
+# Bind address — GATEWAY_LISTEN → QUARKUS_HTTP_HOST
+[ -n "${GATEWAY_LISTEN:-}" ] && export QUARKUS_HTTP_HOST="${QUARKUS_HTTP_HOST:-${GATEWAY_LISTEN}}"
+
+# Log level — LS_LOG / DEBUG=1 → QUARKUS_LOG_LEVEL
+if [ -n "${LS_LOG:-}" ]; then
+ export QUARKUS_LOG_LEVEL="${QUARKUS_LOG_LEVEL:-${LS_LOG}}"
+elif [ "${DEBUG:-}" = "1" ]; then
+ export QUARKUS_LOG_LEVEL="${QUARKUS_LOG_LEVEL:-DEBUG}"
+fi
+
+# Lambda — LAMBDA_EXECUTOR is intentionally ignored; Floci always runs Lambda in Docker containers.
+
+# Lambda Docker network
+[ -n "${LAMBDA_DOCKER_NETWORK:-}" ] && \
+ export FLOCI_SERVICES_LAMBDA_DOCKER_NETWORK="${FLOCI_SERVICES_LAMBDA_DOCKER_NETWORK:-${LAMBDA_DOCKER_NETWORK}}"
+
+# Lambda ephemeral containers
+if [ "${LAMBDA_REMOVE_CONTAINERS:-}" = "1" ] || [ "${LAMBDA_REMOVE_CONTAINERS:-}" = "true" ]; then
+ export FLOCI_SERVICES_LAMBDA_EPHEMERAL="${FLOCI_SERVICES_LAMBDA_EPHEMERAL:-true}"
+fi
+
+# LAMBDA_REMOTE_DOCKER — not fully supported.
+# Floci's hot-reload is per-function opt-in (S3Bucket=hot-reload), not a global bind-mount mode.
+if [ -n "${LAMBDA_REMOTE_DOCKER:-}" ]; then
+ echo "[floci-parity] WARNING: LAMBDA_REMOTE_DOCKER is not fully supported by Floci." >&2
+ echo "[floci-parity] Use S3Bucket=hot-reload per function instead. See https://floci.io/docs/services/lambda" >&2
+fi
+
+# Docker host
+[ -n "${DOCKER_HOST:-}" ] && export FLOCI_DOCKER_DOCKER_HOST="${FLOCI_DOCKER_DOCKER_HOST:-${DOCKER_HOST}}"
+
+# Docker network — shared across all container-based services (Lambda, RDS, ElastiCache, MSK, OpenSearch, EKS).
+# Per-service overrides (e.g. FLOCI_SERVICES_LAMBDA_DOCKER_NETWORK) take precedence when set.
+[ -n "${DOCKER_NETWORK:-}" ] && export FLOCI_SERVICES_DOCKER_NETWORK="${FLOCI_SERVICES_DOCKER_NETWORK:-${DOCKER_NETWORK}}"
+
+# DNS suffixes — register LocalStack and Floci hostname suffixes so that container-to-container
+# hostname routing (Function URLs, presigned S3, SQS QueueUrl, etc.) works without manual config.
+_parity_suffixes="localhost.localstack.cloud,localhost.floci.io"
+if [ -n "${FLOCI_DNS_EXTRA_SUFFIXES:-}" ]; then
+ export FLOCI_DNS_EXTRA_SUFFIXES="${FLOCI_DNS_EXTRA_SUFFIXES},${_parity_suffixes}"
+else
+ export FLOCI_DNS_EXTRA_SUFFIXES="${_parity_suffixes}"
+fi
+
+# SERVICES — intentionally ignored; Floci starts all 41 services in ~24ms.
diff --git a/docker/test-localstack-parity.sh b/docker/test-localstack-parity.sh
new file mode 100755
index 0000000000..c9628778e7
--- /dev/null
+++ b/docker/test-localstack-parity.sh
@@ -0,0 +1,141 @@
+#!/bin/sh
+# Unit tests for localstack-parity.sh.
+# Run directly: sh docker/test-localstack-parity.sh
+# Exit 0 on success, non-zero on first failure.
+
+set -eu
+
+SCRIPT="$(dirname "$0")/localstack-parity.sh"
+PASS=0
+FAIL=0
+
+# Run the parity script in a subshell with a given environment and print the
+# value of a single variable. Arguments: VAR_NAME [ENV_KEY=VALUE ...]
+_run() {
+ var="$1"; shift
+ env -i "$@" sh -c ". '${SCRIPT}'; printf '%s' \"\${${var}:-}\""
+}
+
+# Assert that _run produces an expected value.
+assert_eq() {
+ desc="$1"; expected="$2"; actual="$3"
+ if [ "${actual}" = "${expected}" ]; then
+ printf '[PASS] %s\n' "${desc}"
+ PASS=$((PASS + 1))
+ else
+ printf '[FAIL] %s\n expected: %s\n actual: %s\n' "${desc}" "${expected}" "${actual}"
+ FAIL=$((FAIL + 1))
+ fi
+}
+
+# --- PERSISTENCE ---
+assert_eq "PERSISTENCE=1 sets FLOCI_STORAGE_MODE=persistent" \
+ "persistent" \
+ "$(_run FLOCI_STORAGE_MODE PERSISTENCE=1)"
+
+assert_eq "PERSISTENCE=true sets FLOCI_STORAGE_MODE=persistent" \
+ "persistent" \
+ "$(_run FLOCI_STORAGE_MODE PERSISTENCE=true)"
+
+assert_eq "PERSIST_STATE=1 sets FLOCI_STORAGE_MODE=persistent" \
+ "persistent" \
+ "$(_run FLOCI_STORAGE_MODE PERSIST_STATE=1)"
+
+assert_eq "FLOCI_STORAGE_MODE wins over PERSISTENCE" \
+ "hybrid" \
+ "$(_run FLOCI_STORAGE_MODE PERSISTENCE=1 FLOCI_STORAGE_MODE=hybrid)"
+
+# --- EDGE_PORT ---
+assert_eq "EDGE_PORT sets FLOCI_PORT" \
+ "4567" \
+ "$(_run FLOCI_PORT EDGE_PORT=4567)"
+
+assert_eq "FLOCI_PORT wins over EDGE_PORT" \
+ "4568" \
+ "$(_run FLOCI_PORT EDGE_PORT=4567 FLOCI_PORT=4568)"
+
+# --- LOCALSTACK_HOST / LOCALSTACK_HOSTNAME ---
+assert_eq "LOCALSTACK_HOST sets FLOCI_HOSTNAME" \
+ "myhost" \
+ "$(_run FLOCI_HOSTNAME LOCALSTACK_HOST=myhost)"
+
+assert_eq "LOCALSTACK_HOSTNAME sets FLOCI_HOSTNAME when LOCALSTACK_HOST unset" \
+ "myhost2" \
+ "$(_run FLOCI_HOSTNAME LOCALSTACK_HOSTNAME=myhost2)"
+
+assert_eq "LOCALSTACK_HOST takes priority over LOCALSTACK_HOSTNAME" \
+ "primary" \
+ "$(_run FLOCI_HOSTNAME LOCALSTACK_HOST=primary LOCALSTACK_HOSTNAME=secondary)"
+
+assert_eq "FLOCI_HOSTNAME wins over LOCALSTACK_HOST" \
+ "explicit" \
+ "$(_run FLOCI_HOSTNAME LOCALSTACK_HOST=myhost FLOCI_HOSTNAME=explicit)"
+
+# --- GATEWAY_LISTEN ---
+assert_eq "GATEWAY_LISTEN sets QUARKUS_HTTP_HOST" \
+ "0.0.0.0" \
+ "$(_run QUARKUS_HTTP_HOST GATEWAY_LISTEN=0.0.0.0)"
+
+# --- LOG LEVEL ---
+assert_eq "LS_LOG sets QUARKUS_LOG_LEVEL" \
+ "WARN" \
+ "$(_run QUARKUS_LOG_LEVEL LS_LOG=WARN)"
+
+assert_eq "DEBUG=1 sets QUARKUS_LOG_LEVEL=DEBUG" \
+ "DEBUG" \
+ "$(_run QUARKUS_LOG_LEVEL DEBUG=1)"
+
+assert_eq "LS_LOG takes priority over DEBUG=1" \
+ "TRACE" \
+ "$(_run QUARKUS_LOG_LEVEL LS_LOG=TRACE DEBUG=1)"
+
+assert_eq "QUARKUS_LOG_LEVEL wins over LS_LOG" \
+ "INFO" \
+ "$(_run QUARKUS_LOG_LEVEL LS_LOG=DEBUG QUARKUS_LOG_LEVEL=INFO)"
+
+# --- LAMBDA ---
+assert_eq "LAMBDA_DOCKER_NETWORK sets FLOCI_SERVICES_LAMBDA_DOCKER_NETWORK" \
+ "mynet" \
+ "$(_run FLOCI_SERVICES_LAMBDA_DOCKER_NETWORK LAMBDA_DOCKER_NETWORK=mynet)"
+
+assert_eq "FLOCI_SERVICES_LAMBDA_DOCKER_NETWORK wins over LAMBDA_DOCKER_NETWORK" \
+ "floci-net" \
+ "$(_run FLOCI_SERVICES_LAMBDA_DOCKER_NETWORK LAMBDA_DOCKER_NETWORK=mynet FLOCI_SERVICES_LAMBDA_DOCKER_NETWORK=floci-net)"
+
+assert_eq "LAMBDA_REMOVE_CONTAINERS=1 sets FLOCI_SERVICES_LAMBDA_EPHEMERAL=true" \
+ "true" \
+ "$(_run FLOCI_SERVICES_LAMBDA_EPHEMERAL LAMBDA_REMOVE_CONTAINERS=1)"
+
+assert_eq "LAMBDA_REMOVE_CONTAINERS=true sets FLOCI_SERVICES_LAMBDA_EPHEMERAL=true" \
+ "true" \
+ "$(_run FLOCI_SERVICES_LAMBDA_EPHEMERAL LAMBDA_REMOVE_CONTAINERS=true)"
+
+assert_eq "FLOCI_SERVICES_LAMBDA_EPHEMERAL wins over LAMBDA_REMOVE_CONTAINERS" \
+ "false" \
+ "$(_run FLOCI_SERVICES_LAMBDA_EPHEMERAL LAMBDA_REMOVE_CONTAINERS=1 FLOCI_SERVICES_LAMBDA_EPHEMERAL=false)"
+
+# --- DOCKER HOST / NETWORK ---
+assert_eq "DOCKER_HOST sets FLOCI_DOCKER_DOCKER_HOST" \
+ "unix:///var/run/docker.sock" \
+ "$(_run FLOCI_DOCKER_DOCKER_HOST DOCKER_HOST=unix:///var/run/docker.sock)"
+
+assert_eq "DOCKER_NETWORK sets FLOCI_SERVICES_DOCKER_NETWORK" \
+ "shared" \
+ "$(_run FLOCI_SERVICES_DOCKER_NETWORK DOCKER_NETWORK=shared)"
+
+assert_eq "FLOCI_SERVICES_DOCKER_NETWORK wins over DOCKER_NETWORK" \
+ "override" \
+ "$(_run FLOCI_SERVICES_DOCKER_NETWORK DOCKER_NETWORK=shared FLOCI_SERVICES_DOCKER_NETWORK=override)"
+
+# --- DNS SUFFIXES ---
+assert_eq "DNS suffixes set when FLOCI_DNS_EXTRA_SUFFIXES unset" \
+ "localhost.localstack.cloud,localhost.floci.io" \
+ "$(_run FLOCI_DNS_EXTRA_SUFFIXES)"
+
+assert_eq "DNS suffixes appended to existing FLOCI_DNS_EXTRA_SUFFIXES" \
+ "custom.internal,localhost.localstack.cloud,localhost.floci.io" \
+ "$(_run FLOCI_DNS_EXTRA_SUFFIXES FLOCI_DNS_EXTRA_SUFFIXES=custom.internal)"
+
+# --- Summary ---
+printf '\nResults: %d passed, %d failed\n' "${PASS}" "${FAIL}"
+[ "${FAIL}" -eq 0 ]
diff --git a/docs/configuration/docker-compose.md b/docs/configuration/docker-compose.md
index 4d7f457b00..a97b6809cd 100644
--- a/docs/configuration/docker-compose.md
+++ b/docs/configuration/docker-compose.md
@@ -13,7 +13,7 @@ services:
volumes:
- ./data:/app/data
- ./init/start.d:/etc/floci/init/start.d:ro
- - ./init/stop.d:/etc/floci/init/stop.d:ro
+ - ./init/ready.d:/etc/floci/init/ready.d:ro
```
## Full Setup (with ElastiCache and RDS)
@@ -98,20 +98,31 @@ This affects any response field that embeds the endpoint hostname:
## Initialization Hooks
-Hook scripts can be mounted into the container to run custom setup and teardown logic:
+Hook scripts can be mounted into the container to run custom setup and teardown logic at each lifecycle phase:
-```yaml
+```yaml title="docker-compose.yml"
services:
floci:
- image: floci/floci:latest
+ image: floci/floci:latest-compat
ports:
- "4566:4566"
volumes:
- - ./init/start.d:/etc/floci/init/start.d:ro
- - ./init/stop.d:/etc/floci/init/stop.d:ro
+ - ./init/boot.d:/etc/floci/init/boot.d:ro # before storage loads, no AWS APIs
+ - ./init/start.d:/etc/floci/init/start.d:ro # after HTTP server is ready
+ - ./init/ready.d:/etc/floci/init/ready.d:ro # after all start hooks complete
+ - ./init/stop.d:/etc/floci/init/stop.d:ro # during shutdown, while HTTP is still up
+```
+
+Phases you don't need can be omitted. Use the `latest-compat` image when your scripts call `aws` or `boto3` — it includes the AWS CLI and boto3 with the local endpoint pre-configured, so no `--endpoint-url` flag is needed.
+
+If you have existing LocalStack init scripts, mount them under the LocalStack-compat paths and they run unchanged:
+
+```yaml title="docker-compose.yml"
+volumes:
+ - ./localstack-init/ready.d:/etc/localstack/init/ready.d:ro
```
-See [Initialization Hooks](./initialization-hooks.md) for execution behavior and configuration details.
+See [Initialization Hooks](./initialization-hooks.md) for execution behavior, script types, and configuration details.
## Persistence
diff --git a/docs/configuration/docker-images.md b/docs/configuration/docker-images.md
index ca7a69afac..2d39c09e1c 100644
--- a/docs/configuration/docker-images.md
+++ b/docs/configuration/docker-images.md
@@ -62,10 +62,29 @@ All images are published as multi-arch manifests supporting `linux/amd64` and `l
The compat image installs the following on top of the standard image:
-- Python 3 + pip (via `microdnf` on `ubi9-minimal`)
+- Python 3 + pip
- [AWS CLI](https://pypi.org/project/awscli/) (via pip)
- [boto3](https://pypi.org/project/boto3/) (via pip)
+The AWS CLI is pre-configured to talk to the local Floci endpoint — no `--endpoint-url` flag is needed in hook scripts:
+
+```sh
+#!/bin/sh
+aws sqs create-queue --queue-name my-queue # works without --endpoint-url
+aws s3 mb s3://my-bucket
+```
+
+The following environment variables are set in both the standard and compat images:
+
+| Variable | Value |
+|---|---|
+| `AWS_DEFAULT_REGION` | `us-east-1` |
+| `AWS_ACCESS_KEY_ID` | `test` |
+| `AWS_SECRET_ACCESS_KEY` | `test` |
+| `AWS_CONFIG_FILE` | `/etc/floci/aws/config` (sets `endpoint_url = http://localhost:4566`) |
+
+Override any of them at runtime via `docker run -e` or the Compose `environment` block.
+
## Local Development
The project ships a `docker-compose.yml` at the repository root configured for local development. By default it uses `docker/Dockerfile` (a fast JVM build suited for iteration). Switch the `dockerfile` entry to test the native image locally:
diff --git a/docs/configuration/initialization-hooks.md b/docs/configuration/initialization-hooks.md
index e572a0e01c..fdebad37fe 100644
--- a/docs/configuration/initialization-hooks.md
+++ b/docs/configuration/initialization-hooks.md
@@ -1,147 +1,178 @@
# Initialization Hooks
-Floci allows you to execute custom shell scripts when it starts and stops. These scripts can help set up your
-environment (creating buckets, populating data, configuring resources, etc.) or tidy up during shutdown.
+Floci supports init hook scripts that run at defined points in the startup and shutdown lifecycle.
+Use them to seed resources, configure state, or clean up after a run — before or after the AWS APIs are available.
-Hook scripts ending with `.sh` are discovered in the following directories:
+!!! tip "Use the compat image for scripts that call `aws` or `boto3`"
+ Scripts that invoke the AWS CLI or Python boto3 require the compat image, which bundles Python 3, the AWS CLI, and boto3 — all pre-configured for `http://localhost:4566`.
+ Use `floci/floci:latest-compat` (or a pinned `x.y.z-compat`) instead of the standard image.
-- **Startup hooks** (`/etc/floci/init/start.d`) run after the HTTP server is ready and accepting connections on port 4566. This means hooks can safely make HTTP calls back to Floci (e.g. using the AWS CLI).
-- **Shutdown hooks** (`/etc/floci/init/stop.d`) run during the pre-shutdown phase, while the HTTP server is still accepting connections, so hooks can make HTTP calls back to Floci (e.g. using the AWS CLI). The server only stops once all shutdown hooks have completed.
+## Lifecycle Phases
-If a hook directory does not exist or contains no `.sh` scripts, Floci skips it and continues normally.
-If the hook path exists but is not a directory, it is ignored.
+Floci runs hooks in four ordered phases:
-## Execution
+| Phase | When it runs | AWS APIs available? | Directory |
+|---|---|---|---|
+| **boot** | Before storage is loaded, before services start | No | `boot.d` |
+| **start** | After the HTTP server is ready on port 4566 | Yes ✅ | `start.d` |
+| **ready** | After all `start` hooks complete | Yes ✅ | `ready.d` |
+| **stop** | During pre-shutdown, while HTTP server is still up | Yes ✅ | `stop.d` |
-### Execution Environment
+The `/_floci/init` and `/_localstack/init` endpoints reflect each phase's completion status in real time, so external tooling can wait for `ready` before proceeding.
-Hooks run:
+## Hook Directories
-- Inside the Floci runtime environment (same context as Floci services)
-- Using the configured shell (default: `/bin/sh`)
-- With access to configured services and their endpoints
-- With the same environment variables as Floci
+Floci merges scripts from two directory trees. The Floci-native tree has priority — if the same filename exists in both, the Floci copy runs and the LocalStack copy is skipped:
-Hooks can call Floci service endpoints directly from inside the container (e.g. `http://localhost:4566`).
+| Phase | Floci path | LocalStack-compat path |
+|---|---|---|
+| boot | `/etc/floci/init/boot.d` | `/etc/localstack/init/boot.d` |
+| start | `/etc/floci/init/start.d` | `/etc/localstack/init/start.d` |
+| ready | `/etc/floci/init/ready.d` | `/etc/localstack/init/ready.d` |
+| stop | `/etc/floci/init/stop.d` or `/etc/floci/init/shutdown.d` | `/etc/localstack/init/shutdown.d` |
-The published Docker images are available on Docker Hub:
+The LocalStack-compat paths let existing LocalStack bootstrap scripts work without modification.
+Mount them under `/etc/localstack/init/` and they run as-is.
-- `floci/floci:latest` — native image (minimal, no apk)
-- `floci/floci:latest-jvm` — JVM image (Alpine-based, has apk)
-- `floci/floci:latest-aws` — JVM image with AWS CLI pre-installed
+## Script Types
-If your hooks require the AWS CLI, use one of these options:
+Floci discovers scripts with the following extensions:
-**Option 1: Use the pre-built AWS CLI image**
+- `.sh` — executed with the configured shell (default `/bin/sh`)
+- `.py` — executed with `python3`
-```dockerfile
-FROM floci/floci:latest-aws
-# AWS CLI is already installed
-```
+Files with any other extension are ignored.
-**Option 2: Extend the JVM image (Alpine-based)**
+## Execution Order and Behavior
-```dockerfile
-FROM floci/floci:latest-jvm
-RUN apk add --no-cache aws-cli
-```
+Within each phase, scripts run in **lexicographical order** and **sequentially** (one at a time).
+Prefix filenames with numbers to control order: `01-`, `02-`, `03-`, etc.
-**Option 3: Extend the JVM image with additional tools**
+Floci uses a fail-fast strategy:
-```dockerfile
-FROM floci/floci:latest-jvm
-RUN apk add --no-cache aws-cli jq curl
-```
+- If a script exits with a non-zero status, remaining scripts in that phase are skipped.
+- If a script exceeds the configured timeout, it is terminated and treated as a failure.
+- A `boot` or `start`/`ready` hook failure causes Floci to shut down.
+- A `stop` hook failure is logged but does not prevent shutdown or resource cleanup.
-If a hook depends on additional CLI tools, make sure those tools are available in the runtime image.
+## AWS CLI in Hook Scripts
-### Execution Behavior
+The compat image (`floci/floci:latest-compat`) includes the AWS CLI and boto3 with the local endpoint pre-configured.
+Scripts can call `aws` directly — no `--endpoint-url` flag needed:
-Scripts are executed:
+```sh
+#!/bin/sh
+set -eu
+aws sqs create-queue --queue-name my-queue
+aws s3 mb s3://my-bucket
+aws ssm put-parameter --name /app/config --type String --value production
+```
-- In **lexicographical (alphabetical) order**
-- **Sequentially** (one at a time)
+The following environment variables are pre-set in the compat image:
-When execution order matters, prefix filenames with numbers such as `01-`, `02-`, and `03-`.
+| Variable | Value |
+|---|---|
+| `AWS_DEFAULT_REGION` | `us-east-1` |
+| `AWS_ACCESS_KEY_ID` | `test` |
+| `AWS_SECRET_ACCESS_KEY` | `test` |
+| `AWS_CONFIG_FILE` | `/etc/floci/aws/config` (sets `endpoint_url = http://localhost:4566`) |
-Execution uses a fail-fast strategy:
+Override any of them via `docker run -e` or the compose `environment` block.
-- If a script exits with a non-zero status, remaining hooks are not executed.
-- If a script exceeds the configured timeout, it is terminated and remaining hooks are not executed.
-- A startup hook failure triggers application shutdown.
-- A shutdown hook failure is logged but does not prevent the shutdown from completing.
+Python scripts can use boto3 the same way — the config file is read automatically:
-## Examples
+```python
+#!/usr/bin/env python3
+import boto3
-The following examples assume the runtime image includes the AWS CLI and that Floci is reachable at
-`http://localhost:4566`.
+sqs = boto3.client("sqs")
+sqs.create_queue(QueueName="my-queue")
-### Startup Hook
+s3 = boto3.client("s3")
+s3.create_bucket(Bucket="my-bucket")
+```
-For example, a startup hook could look like this:
+## Mounting Hook Directories
+
+```yaml title="docker-compose.yml"
+services:
+ floci:
+ image: floci/floci:latest-compat
+ ports:
+ - "4566:4566"
+ volumes:
+ - ./init/boot.d:/etc/floci/init/boot.d:ro
+ - ./init/start.d:/etc/floci/init/start.d:ro
+ - ./init/ready.d:/etc/floci/init/ready.d:ro
+ - ./init/stop.d:/etc/floci/init/stop.d:ro
+```
-```sh
-#!/bin/sh
-set -eu
+Phases you don't need can be omitted — Floci skips missing or empty directories.
+
+### Migrating from LocalStack
-aws --endpoint-url http://localhost:4566 \
- ssm put-parameter \
- --name /demo/app/bootstrapped \
- --type String \
- --value true \
- --overwrite
+If you have existing LocalStack init scripts, mount them under the LocalStack-compat paths and they work unchanged:
+
+```yaml title="docker-compose.yml"
+volumes:
+ - ./localstack-init/ready.d:/etc/localstack/init/ready.d:ro
```
-This example assumes the script is stored at `/etc/floci/init/start.d/01-seed-parameter.sh`.
-It seeds a known SSM parameter during startup so tests or local services can rely on it.
+To override individual scripts with Floci-specific versions while keeping the rest:
-### Shutdown Hook
+```yaml title="docker-compose.yml"
+volumes:
+ - ./localstack-init/ready.d:/etc/localstack/init/ready.d:ro # existing scripts
+ - ./floci-init/ready.d:/etc/floci/init/ready.d:ro # overrides (take priority)
+```
-For example, a shutdown hook could look like this:
+## Examples
-```sh
+### Seed resources on startup
+
+```sh title="/etc/floci/init/ready.d/01-seed.sh"
#!/bin/sh
set -eu
-
-aws --endpoint-url http://localhost:4566 \
- ssm delete-parameter \
- --name /demo/app/bootstrapped
+aws sqs create-queue --queue-name orders
+aws s3 mb s3://assets
+aws ssm put-parameter --name /app/bootstrapped --type String --value true
```
-This example assumes the script is stored at `/etc/floci/init/stop.d/01-cleanup-parameter.sh`.
-It removes the parameter during shutdown to leave the environment clean.
+### Seed with Python + boto3
-!!! note "Shutdown timing"
- Shutdown hooks run before the HTTP server stops, so Floci's total shutdown time
- grows by the cumulative runtime of all stop hooks. Make sure external orchestrator
- grace periods accommodate this (e.g. Kubernetes `terminationGracePeriodSeconds`,
- Docker Compose `stop_grace_period`).
+```python title="/etc/floci/init/ready.d/01-seed.py"
+#!/usr/bin/env python3
+import boto3
-## Configuration
+boto3.client("sqs").create_queue(QueueName="orders")
+boto3.client("s3").create_bucket(Bucket="assets")
+```
-You can customize hook behavior via configuration:
+### Clean up on shutdown
-| Key | Default | Description |
-|--------------------------------------------------|-------------|------------------------------------------------------------------------------------------------------------------|
-| `floci.init-hooks.shell-executable` | `/bin/sh` | Shell executable used to run scripts |
-| `floci.init-hooks.timeout-seconds` | `30` | Maximum execution time per script before it is terminated and considered failed |
-| `floci.init-hooks.shutdown-grace-period-seconds` | `2` | Time to wait after calling `destroy()` before forcefully stopping the process (allows cleanup hooks to complete) |
+```sh title="/etc/floci/init/stop.d/01-cleanup.sh"
+#!/bin/sh
+set -eu
+aws ssm delete-parameter --name /app/bootstrapped
+```
-### Example
+!!! note "Shutdown timing"
+ Stop hooks run before the HTTP server shuts down, so Floci's total shutdown time grows by
+ the cumulative runtime of all stop hooks. Adjust your orchestrator grace period accordingly
+ (e.g. Kubernetes `terminationGracePeriodSeconds`, Docker Compose `stop_grace_period`).
-The following configuration can be useful when startup hooks perform more in-depth setup work, such as seeding test
-data or provisioning resources before an integration test suite starts.
+## Configuration
-```yaml
+| Key | Default | Description |
+|---|---|---|
+| `floci.init-hooks.shell-executable` | `/bin/sh` | Shell used to run `.sh` scripts |
+| `floci.init-hooks.timeout-seconds` | `30` | Maximum runtime per script before it is killed and treated as a failure |
+| `floci.init-hooks.shutdown-grace-period-seconds` | `2` | Extra wait after terminating a timed-out process |
+
+```yaml title="application.yml"
floci:
init-hooks:
shell-executable: /bin/sh
timeout-seconds: 60
shutdown-grace-period-seconds: 10
```
-
-In this example:
-
-- `shell-executable` uses `/bin/sh` for portable POSIX-compatible scripts.
-- `timeout-seconds: 60` gives startup hooks more time to complete initialization tasks.
-- `shutdown-grace-period-seconds: 10` gives shutdown hooks more time to finish cleanup before Floci stops.
\ No newline at end of file
diff --git a/docs/getting-started/migrate-from-localstack.md b/docs/getting-started/migrate-from-localstack.md
new file mode 100644
index 0000000000..7e5b08b064
--- /dev/null
+++ b/docs/getting-started/migrate-from-localstack.md
@@ -0,0 +1,221 @@
+# Migrate from LocalStack
+
+Floci is a drop-in replacement for LocalStack Community. The wire protocol, port, credentials, and SDK configuration are identical, so most migrations require only an image swap. This page documents every change and provides a compatibility mode for projects that need a gentler transition.
+
+## Compatibility mode
+
+LocalStack environment variable translation is **on by default**. Floci automatically maps LocalStack variables to their Floci equivalents at startup, so you can keep your existing environment variables unchanged:
+
+```yaml title="docker-compose.yml"
+services:
+ floci:
+ image: floci/floci:latest
+ ports:
+ - "4566:4566"
+ environment:
+ # These LocalStack vars are automatically translated — no extra config needed:
+ PERSISTENCE: "1" # → FLOCI_STORAGE_MODE=persistent
+ LOCALSTACK_HOST: floci # → FLOCI_HOSTNAME=floci
+ LAMBDA_DOCKER_NETWORK: mynet # → FLOCI_SERVICES_LAMBDA_DOCKER_NETWORK=mynet
+ LAMBDA_REMOVE_CONTAINERS: "1" # → FLOCI_SERVICES_LAMBDA_EPHEMERAL=true
+ DEBUG: "1" # → QUARKUS_LOG_LEVEL=DEBUG
+```
+
+Explicitly set Floci variables always win — the translation only fills in values that haven't been set. To disable the translation entirely, set `LOCALSTACK_PARITY=false`.
+
+## Step-by-step migration
+
+### 1 — Change the image
+
+Pick the variant that matches your needs:
+
+```yaml title="docker-compose.yml"
+# Before
+image: localstack/localstack
+
+# After — no init scripts, or init scripts that don't call aws / boto3
+image: floci/floci:latest
+
+# After — init scripts that use aws CLI or boto3 (AWS CLI + Python 3 + boto3 pre-installed)
+image: floci/floci:latest-compat
+```
+
+To pin a specific release, replace `latest` / `latest-compat` with a version tag:
+
+```yaml
+image: floci/floci:1.5.11
+image: floci/floci:1.5.11-compat
+```
+
+The port (`4566`), credentials (`test` / `test`), and AWS SDK configuration are unchanged.
+
+### 2 — Map environment variables
+
+| LocalStack variable | Floci equivalent | Notes |
+|---|---|---|
+| `LOCALSTACK_HOST` | `FLOCI_HOSTNAME` | Hostname embedded in response URLs |
+| `LOCALSTACK_HOSTNAME` | `FLOCI_HOSTNAME` | Alias — same effect |
+| `PERSISTENCE=1` | `FLOCI_STORAGE_MODE=persistent` | Enable disk persistence |
+| `EDGE_PORT` | `FLOCI_PORT` | Bind port override |
+| `GATEWAY_LISTEN` | `QUARKUS_HTTP_HOST` | Bind address override |
+| `LS_LOG` / `DEBUG=1` | `QUARKUS_LOG_LEVEL` | Log verbosity |
+| `LAMBDA_DOCKER_NETWORK` | `FLOCI_SERVICES_LAMBDA_DOCKER_NETWORK` | Network for Lambda containers |
+| `DOCKER_NETWORK` | `FLOCI_SERVICES_DOCKER_NETWORK` | Network for all spawned containers |
+| `LAMBDA_REMOVE_CONTAINERS=1` | `FLOCI_SERVICES_LAMBDA_EPHEMERAL=true` | Remove Lambda containers after invocation |
+| `SERVICES` | _(not needed)_ | Floci starts all 41 services instantly; no selection required |
+| `LAMBDA_EXECUTOR` | _(not needed)_ | Floci always runs Lambda in Docker containers |
+
+### 3 — Init scripts (no change required)
+
+LocalStack init scripts mounted under `/etc/localstack/init/` run unchanged in Floci:
+
+```yaml title="docker-compose.yml"
+volumes:
+ - ./init/ready.d:/etc/localstack/init/ready.d:ro # works as-is
+```
+
+Floci reads both `/etc/localstack/init/` (compat) and `/etc/floci/init/` (native). When the same filename exists in both, the Floci copy takes priority.
+
+To use native Floci paths going forward:
+
+```yaml title="docker-compose.yml"
+volumes:
+ - ./init/ready.d:/etc/floci/init/ready.d:ro
+```
+
+See [Initialization Hooks](../configuration/initialization-hooks.md) for the full four-phase lifecycle (`boot`, `start`, `ready`, `stop`) and script type details (`.sh`, `.py`).
+
+### 4 — Init script tooling (compat image)
+
+If your init scripts call `aws` or `boto3`, switch from `localstack/localstack` to `floci/floci:latest-compat`:
+
+```yaml title="docker-compose.yml"
+# Before
+image: localstack/localstack
+
+# After (includes Python 3, AWS CLI, boto3 — pre-configured for localhost:4566)
+image: floci/floci:latest-compat
+```
+
+The compat image pre-configures the AWS CLI to talk to `http://localhost:4566` — no `--endpoint-url` flag is needed in scripts:
+
+```sh
+#!/bin/sh
+aws sqs create-queue --queue-name orders # no --endpoint-url needed
+aws s3 mb s3://assets
+```
+
+### 5 — Health and status endpoints
+
+Floci serves the LocalStack-compatible status endpoint at both paths:
+
+```
+GET /_localstack/init # LocalStack compat path — still works
+GET /_floci/init # native path
+```
+
+If you wait on `/_localstack/init` or `/_localstack/health` in CI or scripts, no change is needed.
+
+### 6 — Inspection endpoints
+
+| Endpoint | Notes |
+|---|---|
+| `GET /_aws/ses` | Captured emails — identical |
+| `GET /_aws/ses?id=<id>` | Single message — identical |
+| `DELETE /_aws/ses` | Clear mailbox — identical |
+| `GET /_aws/sqs/messages?QueueUrl=<url>` | Non-destructive queue peek — identical |
+| `DELETE /_aws/sqs/messages?QueueUrl=<url>` | Purge queue — identical |
+
+### 7 — Testcontainers
+
+=== "Java"
+
+ Replace the `@LocalStackContainer` module with the Floci module:
+
+ ```xml title="pom.xml"
+ <!-- Before -->
+ <dependency>
+ <groupId>org.testcontainers</groupId>
+ <artifactId>localstack</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <!-- After -->
+ <dependency>
+ <groupId>io.github.hectorvent</groupId>
+ <artifactId>floci-testcontainers</artifactId>
+ <version>LATEST</version>
+ <scope>test</scope>
+ </dependency>
+ ```
+
+ See the [Java Testcontainers guide](../testcontainers/java.md) for full setup.
+
+=== "Python"
+
+ See the [Python Testcontainers guide](../testcontainers/python.md).
+
+=== "Node.js"
+
+ See the [Node.js Testcontainers guide](../testcontainers/nodejs.md).
+
+=== "Go"
+
+ See the [Go Testcontainers guide](../testcontainers/go.md).
+
+## Complete before / after example
+
+```yaml title="docker-compose.yml (before — LocalStack)"
+services:
+ localstack:
+ image: localstack/localstack
+ ports:
+ - "4566:4566"
+ environment:
+ LOCALSTACK_HOST: localstack
+ PERSISTENCE: "1"
+ LAMBDA_DOCKER_NETWORK: myapp_default
+ volumes:
+ - /var/run/docker.sock:/var/run/docker.sock
+ - ./data:/var/lib/localstack
+ - ./init/ready.d:/etc/localstack/init/ready.d:ro
+```
+
+```yaml title="docker-compose.yml (after — Floci, minimal change)"
+services:
+ floci:
+ image: floci/floci:latest-compat # (1)
+ ports:
+ - "4566:4566"
+ environment:
+ LOCALSTACK_HOST: floci # translated automatically — no rename needed
+ PERSISTENCE: "1"
+ LAMBDA_DOCKER_NETWORK: myapp_default
+ volumes:
+ - /var/run/docker.sock:/var/run/docker.sock
+ - ./data:/app/data # (2)
+ - ./init/ready.d:/etc/localstack/init/ready.d:ro # compat path — unchanged
+```
+
+1. Switch to `latest-compat` if your init scripts use `aws` or `boto3`.
+2. LocalStack stores data in `/var/lib/localstack`; Floci uses `/app/data`.
+
+## What stays the same
+
+- Port `4566`
+- All AWS SDK and CLI calls — no code changes
+- Dummy credentials (`test` / `test`)
+- Init scripts under `/etc/localstack/init/` (compat paths)
+- `/_localstack/init` and `/_localstack/health` endpoints
+- `/_aws/ses` and `/_aws/sqs/messages` inspection endpoints
+- Docker socket mount for Lambda, RDS, and ElastiCache
+
+## Known differences
+
+| Area | LocalStack | Floci |
+|---|---|---|
+| Lambda executor | Configurable (`LAMBDA_EXECUTOR`) | Always Docker containers |
+| `LAMBDA_REMOTE_DOCKER` | Supported | Not supported — use per-function `S3Bucket=hot-reload` instead |
+| Service selection | `SERVICES=sqs,s3,...` | All 41 services start automatically; no selection |
+| Data directory | `/var/lib/localstack` | `/app/data` |
+| Log variable | `LS_LOG` / `DEBUG` | `QUARKUS_LOG_LEVEL` |
diff --git a/docs/services/sqs.md b/docs/services/sqs.md
index 1d1dbf3d10..37e6c2543d 100644
--- a/docs/services/sqs.md
+++ b/docs/services/sqs.md
@@ -28,6 +28,53 @@
| `StartMessageMoveTask` | Start a DLQ redrive task |
| `ListMessageMoveTasks` | List DLQ redrive tasks |
+## Local Inspection Endpoint
+
+For test assertions and debugging, Floci exposes a LocalStack-compatible endpoint that lets you peek at queue contents without consuming messages:
+
+| Method | Path | Description |
+|---|---|---|
+| `GET` | `/_aws/sqs/messages?QueueUrl=<url>` | List all messages in the queue (non-destructive) |
+| `DELETE` | `/_aws/sqs/messages?QueueUrl=<url>` | Purge all messages from the queue |
+
+`GET` returns every message currently in the queue — including in-flight messages — without changing visibility timeouts or advancing receive counts. It does not remove messages.
+
+`DELETE` is equivalent to `PurgeQueue` and removes all messages.
+
+### Response shape
+
+```json
+{
+ "messages": [
+ {
+ "MessageId": "abc123",
+ "MD5OfBody": "...",
+ "Body": "{\"event\":\"order.placed\"}",
+ "ReceiptHandle": null,
+ "Attributes": {
+ "SentTimestamp": "1714000000000",
+ "ApproximateReceiveCount": "0"
+ },
+ "MessageAttributes": {}
+ }
+ ]
+}
+```
+
+`ReceiptHandle` is `null` for messages that have not yet been received. FIFO messages include `MessageGroupId`, `MessageDeduplicationId`, and `SequenceNumber` in `Attributes` when set.
+
+### Example
+
+```bash
+QUEUE_URL="http://localhost:4566/000000000000/orders"
+
+# Peek at messages without consuming them
+curl "http://localhost:4566/_aws/sqs/messages?QueueUrl=$QUEUE_URL"
+
+# Purge the queue
+curl -X DELETE "http://localhost:4566/_aws/sqs/messages?QueueUrl=$QUEUE_URL"
+```
+
## Configuration
```yaml
diff --git a/floci_banner.svg b/floci_banner.svg
index 072f6e01df..a23cbc929f 100644
--- a/floci_banner.svg
+++ b/floci_banner.svg
@@ -108,7 +108,7 @@
<!-- Stat 3: Services -->
<text x="770" y="548"
font-family="'Courier New', Courier, monospace"
- font-size="42" font-weight="700" fill="#ffe082" text-anchor="middle">~40
+ font-size="42" font-weight="700" fill="#ffe082" text-anchor="middle">~41
</text>
<text x="770" y="574"
font-family="'Helvetica Neue', Helvetica, Arial, sans-serif"
diff --git a/mkdocs.yml b/mkdocs.yml
index c21c5efee0..2d38d48432 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -59,6 +59,7 @@ nav:
- Quick Start: getting-started/quick-start.md
- Installation: getting-started/installation.md
- AWS CLI & SDK Setup: getting-started/aws-setup.md
+ - Migrate from LocalStack: getting-started/migrate-from-localstack.md
- Configuration:
- Docker Images: configuration/docker-images.md
- Docker Compose: configuration/docker-compose.md
diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorInfoController.java b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorInfoController.java
new file mode 100644
index 0000000000..5eab37dd5d
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorInfoController.java
@@ -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";
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java
index 8d0deb5694..04b775a241 100644
--- a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java
+++ b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java
@@ -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
diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/HealthController.java b/src/main/java/io/github/hectorvent/floci/lifecycle/HealthController.java
index 0d322755e6..88c666b7b6 100644
--- a/src/main/java/io/github/hectorvent/floci/lifecycle/HealthController.java
+++ b/src/main/java/io/github/hectorvent/floci/lifecycle/HealthController.java
@@ -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;
diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/InitLifecycleState.java b/src/main/java/io/github/hectorvent/floci/lifecycle/InitLifecycleState.java
new file mode 100644
index 0000000000..511521fb5a
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/lifecycle/InitLifecycleState.java
@@ -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()));
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/HookScriptExecutor.java b/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/HookScriptExecutor.java
index f760f67a90..ee7fb12d19 100644
--- a/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/HookScriptExecutor.java
+++ b/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/HookScriptExecutor.java
@@ -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);
}
diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHook.java b/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHook.java
index 63e22c7c6c..938d1efb24 100644
--- a/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHook.java
+++ b/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHook.java
@@ -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;
+ }
}
diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHooksRunner.java b/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHooksRunner.java
index d6af7f709a..886bc495d5 100644
--- a/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHooksRunner.java
+++ b/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHooksRunner.java
@@ -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;
+ }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAwsExecuteController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAwsExecuteController.java
new file mode 100644
index 0000000000..6c13e974c4
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAwsExecuteController.java
@@ -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);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/GuardedMessageQueue.java b/src/main/java/io/github/hectorvent/floci/services/sqs/GuardedMessageQueue.java
index 214924a4a4..daa3fd555b 100644
--- a/src/main/java/io/github/hectorvent/floci/services/sqs/GuardedMessageQueue.java
+++ b/src/main/java/io/github/hectorvent/floci/services/sqs/GuardedMessageQueue.java
@@ -195,6 +195,12 @@ class GuardedMessageQueue {
}
}
+ List<Message> peekAll() {
+ try (var _ = hold()) {
+ return new ArrayList<>(messages);
+ }
+ }
+
boolean isEmpty() {
try (var _ = hold()) {
return messages.isEmpty();
diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsInspectionController.java b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsInspectionController.java
new file mode 100644
index 0000000000..082acbe2b2
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsInspectionController.java
@@ -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();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java
index a3cde1e22c..f73dfdb219 100644
--- a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java
@@ -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());
}
diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorInfoControllerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorInfoControllerIntegrationTest.java
new file mode 100644
index 0000000000..442e46df47
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorInfoControllerIntegrationTest.java
@@ -0,0 +1,122 @@
+package io.github.hectorvent.floci.lifecycle;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.junit.jupiter.api.Test;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+@QuarkusTest
+class EmulatorInfoControllerIntegrationTest {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private static final String EXPECTED_SERVICES_JSON = """
+ {
+ "ssm": "running",
+ "sqs": "running",
+ "s3": "running",
+ "dynamodb": "running",
+ "sns": "running",
+ "lambda": "running",
+ "apigateway": "running",
+ "iam": "running",
+ "kafka": "running",
+ "elasticache": "running",
+ "rds": "running",
+ "events": "running",
+ "scheduler": "running",
+ "logs": "running",
+ "monitoring": "running",
+ "secretsmanager": "running",
+ "apigatewayv2": "running",
+ "kinesis": "running",
+ "kms": "running",
+ "cognito-idp": "running",
+ "states": "running",
+ "cloudformation": "running",
+ "acm": "running",
+ "athena": "running",
+ "glue": "running",
+ "firehose": "running",
+ "email": "running",
+ "es": "running",
+ "ec2": "running",
+ "ecs": "running",
+ "appconfig": "running",
+ "appconfigdata": "running",
+ "ecr": "running",
+ "tagging": "running",
+ "bedrock-runtime": "running",
+ "eks": "running",
+ "pipes": "running",
+ "elasticloadbalancing": "running",
+ "codebuild": "running",
+ "codedeploy": "running",
+ "autoscaling": "running"
+ }
+ """;
+
+ @ParameterizedTest
+ @ValueSource(strings = {"/_floci/health", "/_localstack/health"})
+ void health_returnsSameResponseOnBothPaths(String path) throws Exception {
+ String body = given()
+ .when().get(path)
+ .then()
+ .statusCode(200)
+ .contentType("application/json")
+ .extract().body().asString();
+
+ var tree = MAPPER.readTree(body);
+ assertEquals("community", tree.get("edition").asText());
+ assertEquals("floci-always-free", tree.get("original_edition").asText());
+ assertEquals("dev", tree.get("version").asText());
+ assertEquals(MAPPER.readTree(EXPECTED_SERVICES_JSON), tree.get("services"));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"/_floci/init", "/_localstack/init"})
+ void init_returnsLifecycleStateOnBothPaths(String path) {
+ given()
+ .when().get(path)
+ .then()
+ .statusCode(200)
+ .contentType("application/json")
+ .body("completed.boot", equalTo(true))
+ .body("completed.start", equalTo(true))
+ .body("completed.ready", equalTo(true))
+ .body("completed.shutdown", equalTo(false))
+ .body("scripts.boot", hasSize(0))
+ .body("scripts.start", hasSize(0))
+ .body("scripts.ready", hasSize(0))
+ .body("scripts.shutdown", hasSize(0));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"/_floci/info", "/_localstack/info"})
+ void info_returnsVersionAndEditionOnBothPaths(String path) {
+ given()
+ .when().get(path)
+ .then()
+ .statusCode(200)
+ .contentType("application/json")
+ .body("edition", equalTo("community"))
+ .body("version", notNullValue());
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"/_floci/diagnose", "/_localstack/diagnose"})
+ void diagnose_returns200OnBothPaths(String path) {
+ given().when().get(path).then().statusCode(200).contentType("application/json");
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"/_floci/config", "/_localstack/config"})
+ void config_returns200OnBothPaths(String path) {
+ given().when().get(path).then().statusCode(200).contentType("application/json");
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java
index 0ac7d3d8b7..1bcd5a4835 100644
--- a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java
+++ b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.lifecycle;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.ServiceRegistry;
import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.lifecycle.InitLifecycleState;
import io.github.hectorvent.floci.lifecycle.inithook.InitializationHook;
import io.github.hectorvent.floci.lifecycle.inithook.InitializationHooksRunner;
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerManager;
@@ -51,6 +52,7 @@ class EmulatorLifecycleTest {
@Mock private DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller;
@Mock private PipesService pipesService;
@Mock private Ec2MetadataServer ec2MetadataServer;
+ @Mock private InitLifecycleState initLifecycleState;
private EmulatorLifecycle emulatorLifecycle;
@@ -65,7 +67,7 @@ class EmulatorLifecycleTest {
elastiCacheContainerManager, elastiCacheProxyManager,
rdsContainerManager, rdsProxyManager, initializationHooksRunner,
sqsPoller, kinesisPoller, dynamodbStreamsPoller, pipesService,
- ec2MetadataServer);
+ ec2MetadataServer, initLifecycleState);
}
private void stubStorageConfig() {
@@ -75,15 +77,32 @@ class EmulatorLifecycleTest {
}
@Test
- @DisplayName("Should log Ready immediately when no startup hooks exist")
+ @DisplayName("Should run BOOT hooks before loading storage, then mark boot complete")
+ void shouldRunBootHooksBeforeStorageLoad() throws IOException, InterruptedException {
+ stubStorageConfig();
+ when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false);
+ when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);
+
+ emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
+
+ var inOrder = Mockito.inOrder(initializationHooksRunner, storageFactory, initLifecycleState);
+ inOrder.verify(initializationHooksRunner).run(InitializationHook.BOOT);
+ inOrder.verify(initLifecycleState).markBootCompleted();
+ inOrder.verify(storageFactory).loadAll();
+ }
+
+ @Test
+ @DisplayName("Should log Ready immediately when no startup or ready hooks exist")
void shouldLogReadyImmediatelyWhenNoHooksExist() throws IOException, InterruptedException {
stubStorageConfig();
when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false);
+ when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
verify(storageFactory).loadAll();
- verify(initializationHooksRunner).hasHooks(InitializationHook.START);
+ verify(initLifecycleState).markStartCompleted();
+ verify(initLifecycleState).markReadyCompleted();
verify(initializationHooksRunner, never()).run(InitializationHook.START);
}
@@ -92,13 +111,14 @@ class EmulatorLifecycleTest {
void shouldDeferHookExecutionWhenHooksExist() throws IOException, InterruptedException {
stubStorageConfig();
when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(true);
+ when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
verify(storageFactory).loadAll();
- verify(initializationHooksRunner).hasHooks(InitializationHook.START);
- // run() is NOT called synchronously — it will be called by the virtual thread
+ // run() is NOT called synchronously from onStart — it will be called by onHttpStart
verify(initializationHooksRunner, never()).run(InitializationHook.START);
+ verify(initLifecycleState, never()).markStartCompleted();
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/HealthControllerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/HealthControllerIntegrationTest.java
deleted file mode 100644
index f23406e357..0000000000
--- a/src/test/java/io/github/hectorvent/floci/lifecycle/HealthControllerIntegrationTest.java
+++ /dev/null
@@ -1,90 +0,0 @@
-package io.github.hectorvent.floci.lifecycle;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import io.quarkus.test.junit.QuarkusTest;
-import org.junit.jupiter.api.Test;
-
-import static io.restassured.RestAssured.given;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-@QuarkusTest
-class HealthControllerIntegrationTest {
-
- private static final ObjectMapper MAPPER = new ObjectMapper();
-
- private static final String EXPECTED_HEALTH_JSON = """
- {
- "services": {
- "ssm": "running",
- "sqs": "running",
- "s3": "running",
- "dynamodb": "running",
- "sns": "running",
- "lambda": "running",
- "apigateway": "running",
- "iam": "running",
- "kafka": "running",
- "elasticache": "running",
- "rds": "running",
- "events": "running",
- "scheduler": "running",
- "logs": "running",
- "monitoring": "running",
- "secretsmanager": "running",
- "apigatewayv2": "running",
- "kinesis": "running",
- "kms": "running",
- "cognito-idp": "running",
- "states": "running",
- "cloudformation": "running",
- "acm": "running",
- "athena": "running",
- "glue": "running",
- "firehose": "running",
- "email": "running",
- "es": "running",
- "ec2": "running",
- "ecs": "running",
- "appconfig": "running",
- "appconfigdata": "running",
- "ecr": "running",
- "tagging": "running",
- "bedrock-runtime": "running",
- "eks": "running",
- "pipes": "running",
- "elasticloadbalancing": "running",
- "codebuild": "running",
- "codedeploy": "running",
- "autoscaling": "running"
- },
- "edition": "floci-always-free",
- "version": "dev"
- }
- """;
-
- @Test
- void healthEndpoint_returnsExpectedJson() throws Exception {
- String body = given()
- .when()
- .get("/_floci/health")
- .then()
- .statusCode(200)
- .contentType("application/json")
- .extract().body().asString();
-
- assertEquals(MAPPER.readTree(EXPECTED_HEALTH_JSON), MAPPER.readTree(body));
- }
-
- @Test
- void healthEndpoint_localstackCompatPath() throws Exception {
- String body = given()
- .when()
- .get("/_localstack/health")
- .then()
- .statusCode(200)
- .contentType("application/json")
- .extract().body().asString();
-
- assertEquals(MAPPER.readTree(EXPECTED_HEALTH_JSON), MAPPER.readTree(body));
- }
-}
diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHooksRunnerTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHooksRunnerTest.java
index 9239ab3699..cc2c424b24 100644
--- a/src/test/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHooksRunnerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHooksRunnerTest.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.lifecycle.inithook;
+import io.github.hectorvent.floci.lifecycle.InitLifecycleState;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@@ -15,6 +16,7 @@ import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.util.List;
@ExtendWith(MockitoExtension.class)
class InitializationHooksRunnerTest {
@@ -22,6 +24,9 @@ class InitializationHooksRunnerTest {
@Mock
private HookScriptExecutor hookScriptExecutorMock;
+ @Mock
+ private InitLifecycleState initLifecycleStateMock;
+
@InjectMocks
private InitializationHooksRunner initializationHooksRunner;
@@ -156,34 +161,71 @@ class InitializationHooksRunnerTest {
}
@Test
- @DisplayName("hasHooks should return true when scripts exist in hook directory")
+ @DisplayName("hasHooks should return true when scripts exist in a primary directory")
void hasHooksShouldReturnTrueWhenScriptsExist(@TempDir Path tempDir) throws IOException {
Files.createFile(tempDir.resolve("01-setup.sh"));
InitializationHook hook = Mockito.mock(InitializationHook.class);
Mockito.when(hook.getName()).thenReturn("startup");
- Mockito.when(hook.getPath()).thenReturn(tempDir.toFile());
+ Mockito.when(hook.getPrimaryPaths()).thenReturn(List.of(tempDir.toFile()));
+ Mockito.when(hook.getCompatPaths()).thenReturn(List.of());
+
+ Assertions.assertTrue(initializationHooksRunner.hasHooks(hook));
+ }
+
+ @Test
+ @DisplayName("hasHooks should return true when scripts exist only in a compat directory")
+ void hasHooksShouldReturnTrueWhenScriptsExistInCompatDir(@TempDir Path tempDir) throws IOException {
+ Files.createFile(tempDir.resolve("01-setup.sh"));
+ InitializationHook hook = Mockito.mock(InitializationHook.class);
+ Mockito.when(hook.getName()).thenReturn("startup");
+ Mockito.when(hook.getPrimaryPaths()).thenReturn(List.of());
+ Mockito.when(hook.getCompatPaths()).thenReturn(List.of(tempDir.toFile()));
Assertions.assertTrue(initializationHooksRunner.hasHooks(hook));
}
@Test
- @DisplayName("hasHooks should return false when hook directory is empty")
+ @DisplayName("hasHooks should return false when all hook directories are empty")
void hasHooksShouldReturnFalseWhenDirectoryIsEmpty(@TempDir Path tempDir) {
InitializationHook hook = Mockito.mock(InitializationHook.class);
Mockito.when(hook.getName()).thenReturn("startup");
- Mockito.when(hook.getPath()).thenReturn(tempDir.toFile());
+ Mockito.when(hook.getPrimaryPaths()).thenReturn(List.of(tempDir.toFile()));
+ Mockito.when(hook.getCompatPaths()).thenReturn(List.of());
Assertions.assertFalse(initializationHooksRunner.hasHooks(hook));
}
@Test
- @DisplayName("hasHooks should return false when hook directory does not exist")
+ @DisplayName("hasHooks should return false when hook directories do not exist")
void hasHooksShouldReturnFalseWhenDirectoryDoesNotExist() {
InitializationHook hook = Mockito.mock(InitializationHook.class);
Mockito.when(hook.getName()).thenReturn("startup");
- Mockito.when(hook.getPath()).thenReturn(new File("/nonexistent/path"));
+ Mockito.when(hook.getPrimaryPaths()).thenReturn(List.of(new File("/nonexistent/path")));
+ Mockito.when(hook.getCompatPaths()).thenReturn(List.of());
Assertions.assertFalse(initializationHooksRunner.hasHooks(hook));
}
+ @Test
+ @DisplayName("Primary path script should shadow same-named compat path script")
+ void primaryPathShouldShadowCompatPathForSameFilename(@TempDir Path primaryDir, @TempDir Path compatDir)
+ throws IOException, InterruptedException {
+ Files.createFile(primaryDir.resolve("01-seed.sh"));
+ Files.createFile(compatDir.resolve("01-seed.sh"));
+ Files.createFile(compatDir.resolve("02-extra.sh"));
+
+ InitializationHook hook = Mockito.mock(InitializationHook.class);
+ Mockito.when(hook.getName()).thenReturn("ready");
+ Mockito.when(hook.getPrimaryPaths()).thenReturn(List.of(primaryDir.toFile()));
+ Mockito.when(hook.getCompatPaths()).thenReturn(List.of(compatDir.toFile()));
+
+ initializationHooksRunner.run(hook);
+
+ // 01-seed.sh from primaryDir wins; 02-extra.sh from compatDir is included
+ var inOrder = Mockito.inOrder(hookScriptExecutorMock);
+ inOrder.verify(hookScriptExecutorMock).run(primaryDir.resolve("01-seed.sh").toFile());
+ inOrder.verify(hookScriptExecutorMock).run(compatDir.resolve("02-extra.sh").toFile());
+ inOrder.verifyNoMoreInteractions();
+ }
+
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAwsExecuteIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAwsExecuteIntegrationTest.java
new file mode 100644
index 0000000000..1eec2541c8
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAwsExecuteIntegrationTest.java
@@ -0,0 +1,126 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.http.ContentType;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.*;
+
+/**
+ * Verifies that the LocalStack-compatible {@code /_aws/execute-api} URL prefix
+ * correctly routes to the same execution logic as the standard execute-api path.
+ *
+ * <p>LocalStack URL: {@code /_aws/execute-api/{apiId}/{stageName}/{proxy+}}
+ * <p>Standard URL: {@code /execute-api/{apiId}/{stageName}/{proxy+}}
+ */
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class ApiGatewayAwsExecuteIntegrationTest {
+
+ private static String apiId;
+ private static String rootId;
+ private static String resourceId;
+ private static String deploymentId;
+
+ @Test @Order(1)
+ void createRestApi() {
+ apiId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"name\":\"aws-execute-test-api\"}")
+ .when().post("/restapis")
+ .then()
+ .statusCode(201)
+ .body("id", notNullValue())
+ .extract().path("id");
+ }
+
+ @Test @Order(2)
+ void setupMockIntegration() {
+ rootId = given()
+ .when().get("/restapis/" + apiId + "/resources")
+ .then()
+ .statusCode(200)
+ .extract().path("item[0].id");
+
+ resourceId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"hello\"}")
+ .when().post("/restapis/" + apiId + "/resources/" + rootId)
+ .then()
+ .statusCode(201)
+ .extract().path("id");
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"authorizationType\":\"NONE\"}")
+ .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET")
+ .then()
+ .statusCode(201);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"responseParameters\":{}}")
+ .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/responses/200")
+ .then()
+ .statusCode(201);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"type\":\"MOCK\",\"requestTemplates\":{\"application/json\":\"{\\\"statusCode\\\": 200}\"}}")
+ .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration")
+ .then()
+ .statusCode(201);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"{\\\"message\\\":\\\"ok\\\"}\"}}")
+ .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration/responses/200")
+ .then()
+ .statusCode(201);
+ }
+
+ @Test @Order(3)
+ void createDeploymentAndStage() {
+ deploymentId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"description\":\"v1\"}")
+ .when().post("/restapis/" + apiId + "/deployments")
+ .then()
+ .statusCode(201)
+ .extract().path("id");
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"stageName\":\"prod\",\"deploymentId\":\"" + deploymentId + "\"}")
+ .when().post("/restapis/" + apiId + "/stages")
+ .then()
+ .statusCode(201);
+ }
+
+ @Test @Order(4)
+ void executeViaAwsPrefix() {
+ given()
+ .when().get("/_aws/execute-api/" + apiId + "/prod/hello")
+ .then()
+ .statusCode(200)
+ .body("message", equalTo("ok"));
+ }
+
+ @Test @Order(5)
+ void executeViaStandardPath_stillWorks() {
+ given()
+ .when().get("/execute-api/" + apiId + "/prod/hello")
+ .then()
+ .statusCode(200)
+ .body("message", equalTo("ok"));
+ }
+
+ @Test @Order(6)
+ void cleanup() {
+ given().when().delete("/restapis/" + apiId).then().statusCode(202);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsInspectionControllerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsInspectionControllerIntegrationTest.java
new file mode 100644
index 0000000000..48c734e06b
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsInspectionControllerIntegrationTest.java
@@ -0,0 +1,114 @@
+package io.github.hectorvent.floci.services.sqs;
+
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.*;
+
+@QuarkusTest
+class SqsInspectionControllerIntegrationTest {
+
+ private static final String QUEUE_NAME = "inspection-test-queue";
+ private static final String CONTENT_TYPE = "application/x-www-form-urlencoded";
+
+ private String queueUrl;
+
+ @BeforeEach
+ void setUp() {
+ queueUrl = given()
+ .contentType(CONTENT_TYPE)
+ .formParam("Action", "CreateQueue")
+ .formParam("QueueName", QUEUE_NAME)
+ .when().post("/")
+ .then().statusCode(200)
+ .extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");
+
+ given()
+ .contentType(CONTENT_TYPE)
+ .formParam("Action", "PurgeQueue")
+ .formParam("QueueUrl", queueUrl)
+ .when().post("/").then().statusCode(200);
+ }
+
+ @Test
+ @DisplayName("GET /_aws/sqs/messages returns empty list for empty queue")
+ void shouldReturnEmptyListForEmptyQueue() {
+ given()
+ .queryParam("QueueUrl", queueUrl)
+ .when().get("/_aws/sqs/messages")
+ .then()
+ .statusCode(200)
+ .body("messages", hasSize(0));
+ }
+
+ @Test
+ @DisplayName("GET /_aws/sqs/messages returns all messages without consuming them")
+ void shouldReturnMessagesWithoutConsuming() {
+ given().contentType(CONTENT_TYPE)
+ .formParam("Action", "SendMessage")
+ .formParam("QueueUrl", queueUrl)
+ .formParam("MessageBody", "hello world")
+ .when().post("/").then().statusCode(200);
+
+ given().contentType(CONTENT_TYPE)
+ .formParam("Action", "SendMessage")
+ .formParam("QueueUrl", queueUrl)
+ .formParam("MessageBody", "second message")
+ .when().post("/").then().statusCode(200);
+
+ given()
+ .queryParam("QueueUrl", queueUrl)
+ .when().get("/_aws/sqs/messages")
+ .then()
+ .statusCode(200)
+ .body("messages", hasSize(2))
+ .body("messages[0].Body", notNullValue())
+ .body("messages[0].MessageId", notNullValue())
+ .body("messages[0].MD5OfBody", notNullValue())
+ .body("messages[0].Attributes.SentTimestamp", notNullValue())
+ .body("messages[0].Attributes.ApproximateReceiveCount", equalTo("0"));
+
+ // messages must still be there after peek
+ given()
+ .queryParam("QueueUrl", queueUrl)
+ .when().get("/_aws/sqs/messages")
+ .then()
+ .statusCode(200)
+ .body("messages", hasSize(2));
+ }
+
+ @Test
+ @DisplayName("DELETE /_aws/sqs/messages purges the queue")
+ void shouldPurgeQueueOnDelete() {
+ given().contentType(CONTENT_TYPE)
+ .formParam("Action", "SendMessage")
+ .formParam("QueueUrl", queueUrl)
+ .formParam("MessageBody", "to be purged")
+ .when().post("/").then().statusCode(200);
+
+ given()
+ .queryParam("QueueUrl", queueUrl)
+ .when().delete("/_aws/sqs/messages")
+ .then()
+ .statusCode(200);
+
+ given()
+ .queryParam("QueueUrl", queueUrl)
+ .when().get("/_aws/sqs/messages")
+ .then()
+ .statusCode(200)
+ .body("messages", hasSize(0));
+ }
+
+ @Test
+ @DisplayName("GET /_aws/sqs/messages returns 400 when QueueUrl is missing")
+ void shouldReturn400WhenQueueUrlMissing() {
+ given()
+ .when().get("/_aws/sqs/messages")
+ .then()
+ .statusCode(400);
+ }
+}