diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..e788f03d3 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,16 @@ +# Keep the build context small — none of this is needed by any Dockerfile stage. +.git +**/node_modules +server/target +server/bin +server/obj +server-tests +web/dist +e2e +api-tests +api-live-tests +allure-report +allure-results +**/*.db +**/*.db-shm +**/*.db-wal diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml new file mode 100644 index 000000000..99e99aba3 --- /dev/null +++ b/.github/workflows/rust.yml @@ -0,0 +1,41 @@ +name: Rust + +on: + push: + branches: [main] + paths: + - 'server/**' + - '.github/workflows/rust.yml' + pull_request: + branches: [main] + paths: + - 'server/**' + - '.github/workflows/rust.yml' + +defaults: + run: + working-directory: server + +jobs: + check: + name: fmt + clippy + test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Install Rust toolchain + run: rustup component add rustfmt clippy + + - name: Cache cargo + uses: actions/cache@v4 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + server/target + key: cargo-${{ runner.os }}-${{ hashFiles('server/Cargo.lock') }} + restore-keys: cargo-${{ runner.os }}- + + - run: cargo fmt --check + - run: cargo clippy --all-targets -- -D warnings + - run: cargo test --locked diff --git a/Dockerfile b/Dockerfile index b3e09f843..51e5a1fc9 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,3 +1,11 @@ +# ── Stage 0: Build the Rust API server (ADR 0033 — strangler-fig on :3001) ──── +FROM rust:1-slim AS rust-server-builder + +WORKDIR /build +COPY server/Cargo.toml server/Cargo.lock ./ +COPY server/src ./src +RUN cargo build --release --bin arrgh-server + # ── Stage 1: Build the .NET API server ─────────────────────────────────────── FROM mcr.microsoft.com/dotnet/sdk:10.0 AS server-builder @@ -25,6 +33,9 @@ COPY docker/nginx.conf /etc/nginx/sites-available/default # .NET server publish output COPY --from=server-builder /publish /app +# Rust server binary (ADR 0033) — runs alongside .NET during the migration +COPY --from=rust-server-builder /build/target/release/arrgh-server /app/arrgh-server + # Bundled plugin index (default when PluginIndexUrl not overridden) COPY plugin-index/index.json /app/plugin-index.json diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index daaabb1b8..59266ba16 100644 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -48,5 +48,12 @@ mkdir -p "$DownloadDir" # Start .NET API server in background dotnet /app/ArrghServer.dll & +# Start Rust API server in background (ADR 0033 — serves migrated /api +# prefixes on :3001; reads DatabasePath/PluginHostUrl/DownloadDir/JwtSecret +# exported above, same as .NET). Absent in older images — guard on the binary. +if [ -x /app/arrgh-server ]; then + RUST_BIND="127.0.0.1:3001" LOG_LEVEL="${LOG_LEVEL:-info}" /app/arrgh-server & +fi + # Start nginx in foreground (keeps the container alive) nginx -g "daemon off;" diff --git a/docker/nginx.conf b/docker/nginx.conf index 06c463c06..4407b1ff2 100644 --- a/docker/nginx.conf +++ b/docker/nginx.conf @@ -5,7 +5,21 @@ server { root /var/www/arrgh; index index.html; - # Proxy API calls to the .NET server + # ── Strangler-fig routing (ADR 0033) ─────────────────────────────────── + # Migrated route groups → Rust server on :3001; everything else stays on + # the .NET server on :3000. nginx matches the longest prefix, so each + # migrated `location /api/` block wins over the catch-all. Add one + # block per phase as its Hurl tests pass; delete the catch-all at S10. + + location /api/version { + proxy_pass http://127.0.0.1:3001; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_read_timeout 300s; + client_max_body_size 0; + } + + # Catch-all — .NET server (shrinks each phase, removed at cutover). location /api/ { proxy_pass http://127.0.0.1:3000; proxy_set_header Host $host; diff --git a/server/.gitignore b/server/.gitignore new file mode 100644 index 000000000..ea8c4bf7f --- /dev/null +++ b/server/.gitignore @@ -0,0 +1 @@ +/target diff --git a/server/Cargo.lock b/server/Cargo.lock new file mode 100644 index 000000000..b517fdf2c --- /dev/null +++ b/server/Cargo.lock @@ -0,0 +1,687 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "arrgh-server" +version = "0.1.7" +dependencies = [ + "anyhow", + "axum", + "http-body-util", + "serde", + "serde_json", + "tokio", + "tower", + "tower-http", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "bitflags" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d22053281f852e11534f5198498373cbb59295120a20771d90f7ed1897490a72" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mio" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6275cddf4610d1775e6d1fe9469b2e77d0f39fd98fb7450901b821e0c53649f" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "http", + "http-body", + "pin-project-lite", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/server/Cargo.toml b/server/Cargo.toml new file mode 100644 index 000000000..9cc53268d --- /dev/null +++ b/server/Cargo.toml @@ -0,0 +1,34 @@ +# *ARRgh server — Rust rewrite (ADR 0033), strangler-fig alongside the .NET +# project in this same directory. `cargo` only sees Rust files; `dotnet` only +# sees .cs. At S10 (#132) the .NET files are deleted and this stays. +# +# ponytail: single crate for now (lib + bin). The ADR's arrgh-core / +# arrgh-metadata split lands when there's actually a second crate's worth of +# code to move (S4 / S6), not before. +[package] +name = "arrgh-server" +version = "0.1.7" # single source of truth for GET /api/version +edition = "2021" +license = "MIT" +publish = false + +[lib] +path = "src/lib.rs" + +[[bin]] +name = "arrgh-server" +path = "src/main.rs" + +[dependencies] +axum = "0.8" +tokio = { version = "1", features = ["rt-multi-thread", "macros", "signal"] } +tower-http = { version = "0.6", features = ["trace"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +anyhow = "1" + +[dev-dependencies] +tower = { version = "0.5", features = ["util"] } +http-body-util = "0.1" diff --git a/server/src/api/mod.rs b/server/src/api/mod.rs new file mode 100644 index 000000000..3c315eb02 --- /dev/null +++ b/server/src/api/mod.rs @@ -0,0 +1,16 @@ +use axum::Router; +use tower_http::trace::TraceLayer; + +use crate::state::AppState; + +pub mod version; + +/// The full `/api` router. One `.nest` per route group; groups land phase by +/// phase (ADR 0033). Anything not nested here is still served by the .NET +/// process via nginx until its phase ships. +pub fn router(state: AppState) -> Router { + Router::new() + .nest("/api/version", version::routes()) + .layer(TraceLayer::new_for_http()) + .with_state(state) +} diff --git a/server/src/api/version.rs b/server/src/api/version.rs new file mode 100644 index 000000000..b7a20f161 --- /dev/null +++ b/server/src/api/version.rs @@ -0,0 +1,33 @@ +use axum::extract::State; +use axum::routing::get; +use axum::{Json, Router}; +use serde::Serialize; + +use crate::state::AppState; + +/// Compiled-in version — single source of truth (ADR 0033). Bump in +/// `server/Cargo.toml`. +pub const VERSION: &str = env!("CARGO_PKG_VERSION"); + +#[derive(Serialize)] +struct VersionResponse { + current: &'static str, + latest: Option, + release_url: Option, +} + +/// `GET /api/version` — port of the .NET `Version.GetVersion`. Same body +/// shape: `{ current, latest, release_url }`, `latest`/`release_url` null +/// unless the update checker has cached a newer release. +async fn get_version(State(state): State) -> Json { + let (latest, release_url) = state.update.get_if_newer(VERSION); + Json(VersionResponse { + current: VERSION, + latest, + release_url, + }) +} + +pub fn routes() -> Router { + Router::new().route("/", get(get_version)) +} diff --git a/server/src/config.rs b/server/src/config.rs new file mode 100644 index 000000000..410aef6ae --- /dev/null +++ b/server/src/config.rs @@ -0,0 +1,47 @@ +use std::net::SocketAddr; + +/// Runtime config. Env var names match the .NET server + `docker/entrypoint.sh` +/// so the deployment contract is unchanged (ADR 0033). +#[derive(Debug, Clone)] +pub struct Config { + /// Where the Rust server listens. Strangler-fig: .NET keeps :3000, + /// Rust takes :3001, nginx routes per-prefix. Override with `RUST_BIND`. + pub bind: SocketAddr, + /// SQLite file path (`DatabasePath`). Unused until S2 (#124). + pub database_path: String, + /// Node plugin host base URL (`PluginHostUrl`). + pub plugin_host_url: String, + /// Download target dir (`DownloadDir`). + pub download_dir: String, + /// JWT signing secret (`JwtSecret`). Required from S2 on; optional now. + pub jwt_secret: Option, +} + +impl Config { + pub fn from_env() -> anyhow::Result { + let bind = std::env::var("RUST_BIND") + .unwrap_or_else(|_| "127.0.0.1:3001".into()) + .parse()?; + + let jwt_secret = env_opt("JwtSecret").or_else(|| env_opt("JWT_SECRET")); + if jwt_secret.is_none() { + tracing::warn!("JwtSecret not set — fine for S0, required once auth (S2) lands"); + } + + Ok(Self { + bind, + database_path: env_or("DatabasePath", "arrgh.db"), + plugin_host_url: env_or("PluginHostUrl", "http://localhost:4000"), + download_dir: env_or("DownloadDir", "./downloads"), + jwt_secret, + }) + } +} + +fn env_or(key: &str, default: &str) -> String { + std::env::var(key).unwrap_or_else(|_| default.to_string()) +} + +fn env_opt(key: &str) -> Option { + std::env::var(key).ok().filter(|v| !v.is_empty()) +} diff --git a/server/src/error.rs b/server/src/error.rs new file mode 100644 index 000000000..08049e26a --- /dev/null +++ b/server/src/error.rs @@ -0,0 +1,49 @@ +use axum::http::StatusCode; +use axum::response::{IntoResponse, Response}; +use axum::Json; +use serde_json::json; + +/// One error type for every handler. Serialises to `{"error": "..."}` with the +/// matching status — same shape the .NET server returns via `Results.Problem` / +/// `Results.NotFound`. +#[derive(Debug)] +pub enum AppError { + NotFound, + Unauthorized, + Forbidden, + BadRequest(String), + Conflict(String), + /// Anything unexpected — logged at error, returned as a bare 500. + Internal(anyhow::Error), +} + +pub type AppResult = Result; + +impl IntoResponse for AppError { + fn into_response(self) -> Response { + let (status, msg) = match self { + AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()), + AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()), + AppError::Forbidden => (StatusCode::FORBIDDEN, "forbidden".to_string()), + AppError::BadRequest(m) => (StatusCode::BAD_REQUEST, m), + AppError::Conflict(m) => (StatusCode::CONFLICT, m), + AppError::Internal(e) => { + tracing::error!(error = ?e, "internal error"); + ( + StatusCode::INTERNAL_SERVER_ERROR, + "internal error".to_string(), + ) + } + }; + (status, Json(json!({ "error": msg }))).into_response() + } +} + +impl From for AppError +where + E: Into, +{ + fn from(e: E) -> Self { + AppError::Internal(e.into()) + } +} diff --git a/server/src/lib.rs b/server/src/lib.rs new file mode 100644 index 000000000..acf863c21 --- /dev/null +++ b/server/src/lib.rs @@ -0,0 +1,69 @@ +//! *ARRgh server (Rust). See ADR 0033. +//! +//! S0 skeleton: config + tracing + error type + one real endpoint +//! (`GET /api/version`). Every other `/api/*` group arrives one phase at a +//! time (#123–#131) and nginx flips its prefix here once its Hurl + +//! integration tests are green. + +pub mod api; +pub mod config; +pub mod error; +pub mod state; + +use std::net::SocketAddr; + +use tokio::net::TcpListener; +use tracing_subscriber::{fmt, EnvFilter}; + +use crate::config::Config; +use crate::state::AppState; + +/// Initialise tracing from `LOG_LEVEL` (debug|info|warn|error), matching the +/// .NET server's console behaviour. `/api/logs` (S1, #123) will add the +/// in-memory ring-buffer layer this reads from. +pub fn init_tracing() { + let level = std::env::var("LOG_LEVEL").unwrap_or_else(|_| "info".into()); + let filter = EnvFilter::try_new(format!("arrgh_server={level},tower_http={level},info")) + .unwrap_or_else(|_| EnvFilter::new("info")); + // ok() — a second init in tests is not an error worth aborting for + let _ = fmt().with_env_filter(filter).try_init(); +} + +/// Build the app and serve until SIGINT/SIGTERM. +pub async fn run() -> anyhow::Result<()> { + init_tracing(); + + let config = Config::from_env()?; + let addr: SocketAddr = config.bind; + let state = AppState::new(config); + + let listener = TcpListener::bind(addr).await?; + tracing::info!(%addr, "arrgh-server listening"); + + axum::serve(listener, api::router(state)) + .with_graceful_shutdown(shutdown_signal()) + .await?; + Ok(()) +} + +async fn shutdown_signal() { + use tokio::signal; + let ctrl_c = async { + signal::ctrl_c().await.ok(); + }; + #[cfg(unix)] + let term = async { + signal::unix::signal(signal::unix::SignalKind::terminate()) + .expect("install SIGTERM handler") + .recv() + .await; + }; + #[cfg(not(unix))] + let term = std::future::pending::<()>(); + + tokio::select! { + _ = ctrl_c => {}, + _ = term => {}, + } + tracing::info!("shutdown signal received"); +} diff --git a/server/src/main.rs b/server/src/main.rs new file mode 100644 index 000000000..01ef1c12b --- /dev/null +++ b/server/src/main.rs @@ -0,0 +1,4 @@ +#[tokio::main] +async fn main() -> anyhow::Result<()> { + arrgh_server::run().await +} diff --git a/server/src/state.rs b/server/src/state.rs new file mode 100644 index 000000000..8577bb9ff --- /dev/null +++ b/server/src/state.rs @@ -0,0 +1,56 @@ +use std::sync::{Arc, RwLock}; + +use crate::config::Config; + +/// Shared, cheaply-cloneable app state handed to every handler. +#[derive(Clone)] +pub struct AppState { + pub config: Arc, + pub update: Arc, + // S2 (#124) adds `db: sqlx::SqlitePool` here. +} + +impl AppState { + pub fn new(config: Config) -> Self { + Self { + config: Arc::new(config), + update: Arc::new(UpdateCache::default()), + } + } +} + +/// Latest GitHub release, populated by the background update checker. +/// Port of the .NET `UpdateCache` singleton. The poller task itself is +/// wired in a follow-up — for now the cache just stays empty and +/// `GET /api/version` reports no update, which is the correct default. +#[derive(Default)] +pub struct UpdateCache { + inner: RwLock>, +} + +#[derive(Clone)] +struct Release { + version: String, + html_url: String, +} + +impl UpdateCache { + pub fn set(&self, version: impl Into, html_url: impl Into) { + *self.inner.write().unwrap() = Some(Release { + version: version.into(), + html_url: html_url.into(), + }); + } + + pub fn clear(&self) { + *self.inner.write().unwrap() = None; + } + + /// `(latest, release_url)` when a newer version is cached, `(None, None)` otherwise. + pub fn get_if_newer(&self, current: &str) -> (Option, Option) { + match &*self.inner.read().unwrap() { + Some(r) if r.version != current => (Some(r.version.clone()), Some(r.html_url.clone())), + _ => (None, None), + } + } +} diff --git a/server/tests/version.rs b/server/tests/version.rs new file mode 100644 index 000000000..f4ea2a203 --- /dev/null +++ b/server/tests/version.rs @@ -0,0 +1,54 @@ +//! S0 parity check for `GET /api/version`. Mirrors `api-tests/version.hurl`. + +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use http_body_util::BodyExt; +use tower::ServiceExt; // oneshot + +use arrgh_server::config::Config; +use arrgh_server::state::AppState; + +fn test_state() -> AppState { + // Config::from_env with nothing set → all defaults, no panic. + AppState::new(Config::from_env().expect("default config")) +} + +#[tokio::test] +async fn version_returns_current_and_no_update() { + let app = arrgh_server::api::router(test_state()); + + let res = app + .oneshot(Request::get("/api/version").body(Body::empty()).unwrap()) + .await + .unwrap(); + + assert_eq!(res.status(), StatusCode::OK); + + let bytes = res.into_body().collect().await.unwrap().to_bytes(); + let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + + assert_eq!(body["current"], env!("CARGO_PKG_VERSION")); + assert!(body["latest"].is_null()); + assert!(body["release_url"].is_null()); +} + +#[tokio::test] +async fn version_reports_update_when_cache_has_newer() { + let state = test_state(); + state + .update + .set("9.9.9", "https://example.test/releases/9.9.9"); + let app = arrgh_server::api::router(state); + + let res = app + .oneshot(Request::get("/api/version").body(Body::empty()).unwrap()) + .await + .unwrap(); + + let bytes = res.into_body().collect().await.unwrap().to_bytes(); + let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + + assert_eq!(body["current"], env!("CARGO_PKG_VERSION")); + assert_eq!(body["latest"], "9.9.9"); + assert_eq!(body["release_url"], "https://example.test/releases/9.9.9"); +}