# check=skip=FromPlatformFlagConstDisallowed
# (The constant --platform below is the point of this image, not an oversight
# -- see the FROM comment. Parser directives must lead the file, so this one
# sits above the header rather than next to what it excuses.)

# Full Virtual Accelerator image: PyAT physics + the LUME serving stack +
# osprey (the VA service ships as osprey.services.virtual_accelerator, part of
# the osprey package itself). entrypoint.py reads the simulator view under the
# data mount, builds one composite over it and hands that to ModelRunner, which
# serves every address of the view's addresses.json on Channel Access and the
# model RPC on PVAccess.
#
# Build context MUST be a staging directory containing exactly:
#   pyproject.toml, uv.lock, README.md, src/, packages/,
#   docker/virtual-accelerator/Containerfile
# (see scripts/va/build_and_boot_check.sh, which stages it) --
# NOT the repo root, which also contains .venv/.git/worktrees and would
# make every build re-tar gigabytes of unrelated content.
#
# linux/amd64, pinned -- deliberately single-arch; arm64 is not built, and
# there is no source-build path for it. pcaspy publishes no linux/aarch64
# wheel at any interpreter, so an arm64 image would have to compile EPICS base
# -> epics-modules/pcas -> pcaspy from source on every cold build. amd64 is
# also what CI runs and the only architecture on which a client importing this
# stack's CA server extension alongside the aioca client has been measured
# to work (scripts/va/live_ca/ is that measurement).
# The accepted cost: on an Apple Silicon host the image runs emulated.
# The third-party dependency set, exported from uv.lock in a stage of its own,
# so the image installs exactly the versions CI and the dev venv run against.
# pip does not read uv.lock: resolving the manifests' ranges with pip instead
# takes the newest release each range admits on the day of the build, so the
# physics and serving stack this image serves from would drift away from the
# locked one the unit lanes test, with no signal (PyAT had to be hand-pinned
# here for exactly that reason). `uv export --frozen` reads the lock as
# committed and never re-resolves, so a lock out of step with a manifest fails
# the build here rather than quietly picking something else.
#
# What the export selects: --all-packages takes every workspace member's
# requirements as well as the framework's, --extra virtual-accelerator the
# serving stack, --no-dev leaves the dev group out, and --no-emit-workspace
# drops the workspace's own distributions, which install from source below
# (pip would otherwise go to PyPI for them). Hashes are kept, so the install
# below runs in pip's hash-checking mode and a re-uploaded artifact cannot
# slip in under a locked version.
# --quiet only because uv also echoes the export to stdout, which would put
# some five thousand lines into every build log.
#
# uv is pinned for the same reason as in scripts/va/live_ca/Containerfile,
# whose image this reuses: what an export emits from a given lock is uv's
# behaviour, not the lock's, so an unpinned uv could change what the image
# installs without any change to the repo. 0.9.30 reads the lock's current
# revision; a lock written by a uv too new for it fails --frozen loudly here.
#
# The export needs the lock and every project's manifest -- the members'
# pyproject.toml files under packages/ define the workspace -- but no source.
# packages/ is copied whole because COPY cannot keep the directory layout of
# a glob; that costs only a rerun of this cheap stage on a member source edit.
# Only the resulting requirements file reaches the image, and the layer that
# installs it is cached on that file's content: a change to src/ or to a
# member's code leaves it byte-identical, so the expensive download-and-install
# layer restores from cache and only the from-source builds rerun. Without this
# split the one pip layer sat after `COPY src/` and every source change
# re-downloaded and re-installed the whole closure.
FROM --platform=linux/amd64 ghcr.io/astral-sh/uv:0.9.30-python3.11-bookworm-slim AS dependency-set
WORKDIR /spec
COPY pyproject.toml uv.lock /spec/
COPY packages/ /spec/packages/
RUN uv export --quiet --frozen --no-dev --all-packages \
        --extra virtual-accelerator --no-emit-workspace -o /spec/requirements.txt \
    && test -s /spec/requirements.txt

FROM --platform=linux/amd64 python:3.11-slim

# Refuse to build anywhere but amd64. The pin above should make this
# unreachable, but a `--platform` override on the command line, or someone
# lifting this recipe into another file, would otherwise produce an image that
# BUILDS CLEANLY AND CANNOT SERVE: there is no pcaspy wheel for linux/aarch64
# at any interpreter, and osprey's `virtual-accelerator` extra marks
# lume-pva-apg, whose `ca` extra brings pcaspy,
# `sys_platform == 'linux' and platform_machine == 'x86_64'` -- so on aarch64
# the Channel Access server is simply not installed, silently, because an
# unmatched environment marker is not an error. The first sign would be an
# ImportError when serving/runner.py imports the serving package
# (lume_pva_apg), whose Channel Access server is pcaspy, long after the build
# reported success. Fail here instead, where the message can say why.
RUN arch="$(dpkg --print-architecture)"; [ "$arch" = "amd64" ] \
    || { echo "ERROR: the virtual accelerator image is linux/amd64 only (this build is $arch). No pcaspy wheel exists for linux/aarch64 at any interpreter, so an aarch64 image would carry no Channel Access server." >&2; exit 1; }

# Third-party dependencies, from the dependency-set stage above (see there for
# why this layer comes before any source and why it is the lock's export).
# --require-hashes makes pip refuse any artifact whose hash the lock does not
# list; the export carries a hash for every entry, so it costs nothing.
#
# --only-binary pcaspy is a guard, not an optimisation. pcaspy's sdist needs a
# full EPICS base + epics-modules/pcas build -- minutes, not seconds -- and on
# amd64 a wheel always exists, so if pip ever reaches for that sdist here
# something is wrong and the build should say so rather than stall. Everything
# else installs from prebuilt manylinux_x86_64 wheels too, so the image carries
# no C toolchain at all.
COPY --from=dependency-set /spec/requirements.txt /opt/osprey-deps/requirements.txt
RUN pip install --no-cache-dir --require-hashes --only-binary pcaspy \
        -r /opt/osprey-deps/requirements.txt

# osprey itself -- manifest/lattice/serving/entrypoint live under
# src/osprey/services/virtual_accelerator/ and install as part of the
# package, so no separate COPY of a docker/virtual-accelerator source tree
# is needed. Built from the source copied in below -- never from PyPI -- so
# the image always matches whatever checkout produced it (this feature may
# not be released yet).
WORKDIR /opt/osprey
COPY pyproject.toml README.md /opt/osprey/
COPY src/ /opt/osprey/src/
# Every workspace member under packages/ rides along and installs from source
# below, for the same reason osprey itself does: pip cannot see a uv workspace,
# so without this the framework's requirement on each member would resolve from
# PyPI -- a released snapshot beside checkout framework code (or nothing at all,
# for a member that has never been published), exactly the version skew one
# image built from one checkout exists to rule out.
COPY packages/ /opt/osprey/packages/

# osprey's version comes from the git tag (hatch-vcs), and the staged build
# context has no .git -- deliberately, since staging one would mean copying the
# repository history into every build. Without a version the build backend
# refuses to produce metadata at all, so the host passes the version it
# resolved and setuptools-scm is told to use it verbatim. The un-suffixed
# SETUPTOOLS_SCM_PRETEND_VERSION is the one that works here: the
# ``_FOR_<DIST_NAME>`` form needs the backend to hand setuptools-scm a dist
# name, which hatch-vcs does not, so that form is silently ignored and the
# build fails as if nothing had been set. So the un-scoped variable is set per
# pip call below rather than once for the layer: osprey and pyaml-cs-osprey
# (which versions with the framework) build with OSPREY_VERSION, and
# osprey-connectors, which has its own calendar stream on its own
# osprey-connectors-v* tags, with OSPREY_CONNECTORS_VERSION -- the number
# scripts/va/connectors_version.py derives on the host with the package's own
# describe glob. A build that passes only OSPREY_VERSION (any caller from before
# the split) stamps connectors with the framework's number instead, as the image
# always did; the framework's connectors floor accepts either. The build hook
# stamps whatever lands here into src/osprey/_version.py, which is what
# ``osprey.__version__`` reports at runtime -- so a build that does not pass
# OSPREY_VERSION yields an image that honestly reports an unknown version
# rather than a plausible wrong one.
ARG OSPREY_VERSION=0.0.0.dev0+unknown
ARG OSPREY_CONNECTORS_VERSION=

# Every source build here is --no-deps: the third-party closure is already in
# place from the lock, and letting pip resolve on top of it would let pip pick
# a newer release than the lock's for any requirement a member or the
# framework declares -- the drift the export above exists to rule out. What
# the closure holds is decided by the export alone; `pip check` afterwards
# fails the build if a project here requires something the export left out or
# pinned outside its range, so the two cannot disagree silently.
#
# The framework still installs as `.[virtual-accelerator]`, matching the
# service Dockerfile and the export's --extra, so the line says which serving
# set the image carries; under --no-deps the extra itself installs nothing.
# That extra is where the whole serving stack comes from: `lume-pva-apg[ca,pva]`,
# exact-pinned, carrying pcaspy for Channel Access and p4p for PVAccess -- the
# two transports the runner serves.
#
# The members install one by one ahead of the framework, looping over packages/
# rather than naming them so a new member is picked up the day it lands. `||
# exit 1` keeps a failed member build from being masked by the next
# iteration's success.
#
# The build backends (hatchling, hatch-vcs) are not in the lock: pip's build
# isolation fetches them from PyPI for each source build. They shape how a
# project is packaged, not what the image runs against.
#
# The install ends by asserting that the `pyaml` import package has exactly one
# owning distribution (osprey.deployment.pyaml_owner): every pyAML distribution
# writes the same `pyaml/` files, and pip does not notice two of them together.
RUN for member in ./packages/*/; do \
           version="${OSPREY_VERSION}"; \
           case "$member" in \
               */osprey-connectors/) version="${OSPREY_CONNECTORS_VERSION:-${OSPREY_VERSION}}" ;; \
           esac; \
           SETUPTOOLS_SCM_PRETEND_VERSION="$version" \
           pip install --no-cache-dir --no-deps "$member" || exit 1; \
       done \
    && SETUPTOOLS_SCM_PRETEND_VERSION="${OSPREY_VERSION}" \
       pip install --no-cache-dir --no-deps ".[virtual-accelerator]" \
    && pip check \
    && python -m osprey.deployment.pyaml_owner

# Channel Access server port. TCP only is required -- CA name-server mode
# (EPICS_CA_NAME_SERVERS=<host>:5064, EPICS_CA_AUTO_ADDR_LIST=NO on the
# client side) is the one host<->container configuration proven to work
# across container runtimes (see
# scripts/va/probe_pcaspy/README.md); UDP broadcast
# discovery is not published because it is not relied upon.
#
# The published port and the port the server binds must be the SAME number:
# a CA search reply carries the server's own port, so a remap like
# -p 5164:5064 hands every client a port it cannot reach, with no useful
# error. The PVAccess server's port (5075) is deliberately not exposed --
# PVA is served inside the container only.
EXPOSE 5064/tcp
ENV EPICS_CA_SERVER_PORT=5064

# The image runs the shipped entrypoint module by name. `exec` replaces the
# shell so SIGTERM reaches python directly and entrypoint.py's shutdown
# handlers still run on `docker stop`.
#
# EPICS_CAS_SERVER_PORT is derived here rather than baked as an ENV, because
# it has to track EPICS_CA_SERVER_PORT: the CA *server* library reads the CAS
# variable and does not fall back to the client-side one, so an image whose
# CAS port were frozen at build time would keep binding 5064 while a
# `-e EPICS_CA_SERVER_PORT=...` run told its clients some other port.
CMD ["/bin/sh", "-c", "export EPICS_CAS_SERVER_PORT=\"${EPICS_CAS_SERVER_PORT:-${EPICS_CA_SERVER_PORT:-5064}}\"; exec python -u -m osprey.services.virtual_accelerator.entrypoint"]
