# Single-node tidalDB server image.
#
# Build context is this repository's root (the workspace `Cargo.toml` /
# `Cargo.lock` and every member crate live there). Build from the repo root:
#
#     docker build -f docker/standalone/Dockerfile -t tidaldb:standalone .
#
# tidal-server is a workspace member at `tidal-server/` and depends on the
# `tidal/` engine crate plus `tidal-net/` (gRPC cluster transport). The repo-root
# allowlist `.dockerignore` strips target/, node_modules/, .git, and .env* from
# the context, so `COPY . .` brings in exactly the workspace sources cargo needs
# to resolve the member graph and build `-p tidal-server`.
# Pin the builder to bookworm so its glibc matches the bookworm-slim runtime.
# The default `rust:1.91` tracks Debian trixie, whose vectorized-math
# `libmvec.so.1` is absent on bookworm and aborts the binary at startup.
FROM rust:1.91-bookworm AS builder
ARG DEBIAN_FRONTEND=noninteractive
WORKDIR /app

# g++ builds the usearch C++ HNSW core; protobuf-compiler (protoc) is needed by
# tidal-net's build script (tonic-build compiles the WAL-shipping .proto).
RUN apt-get update && apt-get install -y --no-install-recommends g++ protobuf-compiler && rm -rf /var/lib/apt/lists/*

# Copy the full workspace and build only the server binary. The unified
# workspace requires every member manifest present to resolve metadata, so we
# copy the whole (already-pruned) context rather than a fragile manifest-only
# subset.
COPY . .
RUN cargo build -p tidal-server --release --locked

FROM debian:bookworm-slim
ARG DEBIAN_FRONTEND=noninteractive
WORKDIR /srv

RUN useradd --system --home /srv tidal && \
    apt-get update && apt-get install -y --no-install-recommends ca-certificates curl && \
    rm -rf /var/lib/apt/lists/*

COPY --from=builder /app/target/release/tidal-server /usr/local/bin/tidal-server
COPY --chown=tidal:tidal tidal-server/config /etc/tidal-server

# Persistent data lives under /data, owned by the runtime user. Without this
# directory + the `--data-dir /data` flag below the server boots EPHEMERAL and
# loses every write on restart.
RUN mkdir -p /data && chown tidal:tidal /data
VOLUME ["/data"]

# Path the server reads its schema/topology from. The binary-side clap wiring
# for this lives in tidal-server (see sibling task T5); keep the name and
# default in sync with it here.
ENV TIDAL_CONFIG=/etc/tidal-server

USER tidal
EXPOSE 9400 9091

HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
    CMD curl -f -H "Authorization: Bearer ${TIDAL_API_KEY:-}" http://localhost:9400/health || exit 1

# ENTRYPOINT is just the binary so `docker run tidaldb:standalone <subcommand>`
# overrides work (e.g. `... cluster ...` or an ad-hoc inspect). CMD carries the
# default standalone invocation, including `--data-dir /data` for durability.
ENTRYPOINT ["tidal-server"]
CMD ["standalone", \
    "--listen", "0.0.0.0:9400", \
    "--data-dir", "/data", \
    "--metrics", "0.0.0.0:9091"]
