From 06861705f6908d1b58769e1bbd345f611d18abcb Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 16:03:48 +0100 Subject: [PATCH] feat(server): add the HTTP API and the client SDK `OriginService` only answered in-process. Agents, CI runners and other machines need to reach a repository over the network, and from any language. The HTTP API, under `/api/v1`, is a thin layer: each route translates a request into a service call on the repository it names, run on the blocking thread pool since calls do synchronous file system work, and renders a `ServiceError` as an `ApiError` with the matching status. This first part lists the server's repositories, fetches and puts records as packs, and lists targets and a target's log. `Repositories` holds the repositories a server hosts, by name. Every route is documented with utoipa. The server serves the OpenAPI document, `docs/openapi.json` keeps a copy for other languages, and a test fails while it's stale: `just openapi` rewrites it. `origin-client` is the Rust SDK, written by hand: each endpoint is one line of its `endpoints!` macro, over the `origin-shared` types the server uses, so the two cannot disagree on a contract, and no reqwest type is exposed. The HTTP tests drive every SDK method against a real server. --- AGENTS.md | 11 +- Cargo.lock | 850 ++++++++++++++++++++++++++++++++ Cargo.toml | 6 + apps/origin-src/Cargo.toml | 7 + apps/origin-src/src/http.rs | 266 ++++++++++ apps/origin-src/src/lib.rs | 2 + apps/origin-src/src/server.rs | 41 ++ apps/origin-src/src/service.rs | 7 +- apps/origin-src/tests/http.rs | 360 ++++++++++++++ crates/origin-client/Cargo.toml | 6 +- crates/origin-client/src/lib.rs | 181 ++++++- deny.toml | 3 + docs/openapi.json | 628 +++++++++++++++++++++++ justfile | 5 + 14 files changed, 2366 insertions(+), 7 deletions(-) create mode 100644 apps/origin-src/src/http.rs create mode 100644 apps/origin-src/src/server.rs create mode 100644 apps/origin-src/tests/http.rs create mode 100644 docs/openapi.json diff --git a/AGENTS.md b/AGENTS.md index 5070afd2..ad4a67f0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,10 +13,13 @@ review bots read and write at the same time, written in Rust. refusing network file systems), behind traits. It is the only place whose code differs by target OS. `std::os::unix`, which every supported platform has, may be used anywhere. -- `crates/origin-client`: the HTTP client, generated from the server's OpenAPI - document. Never edit generated code by hand. +- `crates/origin-client`: the SDK, a typed client for origin servers. Each + endpoint is one line of its `endpoints!` macro, over the `origin-shared` + types; no reqwest type is exposed. - `apps/origin-src`: the `origin` binary, both the command line and the - server. + server. `OriginService` (`service.rs`) is the one API over a repository: + the HTTP routes (`http.rs`) and the command line's commands that the API + offers only translate into its calls, so neither duplicates the other. - `tools/xtask`: development tasks, run with `cargo xtask`, such as timing origin against git (`just bench-git`). @@ -33,6 +36,8 @@ benchmark, and its numbers in the pull request. End-to-end tests run the `origin` binary with `ORIGIN_CONFIG_DIR` set to a temporary directory, which holds the user's `config.toml` and node key. +The HTTP tests drive every SDK method against a real server. One fails +while `docs/openapi.json` is stale: `just openapi` rewrites it. ## Commits & Pull Requests diff --git a/Cargo.lock b/Cargo.lock index 9c3e7ddd..58db82c7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -73,6 +73,70 @@ version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" +[[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 = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "bitflags" version = "2.13.2" @@ -111,6 +175,18 @@ dependencies = [ "serde_core", ] +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + [[package]] name = "cc" version = "1.8.0" @@ -243,6 +319,17 @@ dependencies = [ "crypto-common", ] +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "divan" version = "0.1.21" @@ -324,6 +411,48 @@ version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +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 = "getrandom" version = "0.4.3" @@ -347,6 +476,51 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[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 = "hybrid-array" version = "0.4.15" @@ -356,6 +530,154 @@ dependencies = [ "typenum", ] +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + [[package]] name = "indexmap" version = "2.14.2" @@ -368,6 +690,12 @@ dependencies = [ "serde_core", ] +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + [[package]] name = "is_terminal_polyfill" version = "1.70.2" @@ -390,6 +718,17 @@ dependencies = [ "libc", ] +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + [[package]] name = "libc" version = "0.2.190" @@ -402,12 +741,47 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[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.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -425,6 +799,10 @@ name = "origin-client" version = "0.1.0" dependencies = [ "origin-shared", + "reqwest", + "serde", + "serde_json", + "thiserror", ] [[package]] @@ -457,26 +835,60 @@ name = "origin-src" version = "0.1.0" dependencies = [ "anyhow", + "axum", "clap", "divan", "getrandom", + "origin-client", "origin-platform", "origin-shared", "origin-src", "serde", + "serde_json", "similar", "tempfile", "thiserror", + "tokio", "toml", + "tracing", + "utoipa", + "utoipa-axum", "zstd", ] +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + +[[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 = "pkg-config" version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -548,6 +960,38 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "rustc_version" version = "0.4.1" @@ -570,6 +1014,18 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + [[package]] name = "semver" version = "1.0.28" @@ -619,6 +1075,17 @@ dependencies = [ "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_spanned" version = "1.1.2" @@ -628,6 +1095,18 @@ dependencies = [ "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 = "sha2" version = "0.11.1" @@ -645,6 +1124,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[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 = "signature" version = "3.0.0" @@ -660,6 +1149,34 @@ dependencies = [ "bstr", ] +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" + +[[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 = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + [[package]] name = "strsim" version = "0.11.1" @@ -694,6 +1211,26 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -737,6 +1274,42 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.53.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e" +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.9", +] + [[package]] name = "toml" version = "1.1.8+spec-1.1.0" @@ -776,6 +1349,88 @@ version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" +[[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", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[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 = [ + "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", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "typenum" version = "1.20.1" @@ -788,6 +1443,24 @@ version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + [[package]] name = "utf8parse" version = "0.2.2" @@ -806,6 +1479,19 @@ dependencies = [ "utoipa-gen", ] +[[package]] +name = "utoipa-axum" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "865319162dc3d0032e1e40ed11bd49d5b78e8ef576740589fd6823e2e9977423" +dependencies = [ + "axum", + "pastey", + "tower-layer", + "tower-service", + "utoipa", +] + [[package]] name = "utoipa-gen" version = "6.0.1" @@ -818,6 +1504,87 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "windows" version = "0.62.2" @@ -943,6 +1710,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + [[package]] name = "xtask" version = "0.1.0" @@ -951,12 +1724,89 @@ dependencies = [ "origin-src", ] +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + [[package]] name = "zeroize" version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index 4c63dd4b..c50c4e2f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,12 +26,15 @@ origin-src = { version = "0.1.0", path = "apps/origin-src" } # External anyhow = "1.0.104" +axum = { version = "0.8.9", default-features = false, features = ["http1", "json", "query", "tokio", "tracing"] } blake3 = "1.8.7" clap = { version = "4.6.7", features = ["derive"] } divan = "0.1.21" ed25519-dalek = "3.0.0" getrandom = "0.4.3" reflink-copy = "0.1.30" +# No TLS yet: remotes are plain HTTP in the prototype. +reqwest = { version = "0.13.5", default-features = false, features = ["json", "query"] } # Only in origin-platform. The version and features reflink-copy uses on Linux. rustix = { version = "1.1.6", default-features = false, features = ["fs", "std"] } serde = { version = "1.0.229", features = ["derive"] } @@ -39,8 +42,11 @@ serde_json = "1.0.154" similar = "3.2.0" tempfile = "3.27.0" thiserror = "2.0.21" +tokio = { version = "1.53.3", features = ["macros", "net", "rt-multi-thread", "signal"] } toml = "1.1.8" +tracing = "0.1.44" utoipa = { version = "6.0.0", features = ["axum_extras"] } +utoipa-axum = "0.3.0" zstd = "0.14.3" [workspace.lints.rust] diff --git a/apps/origin-src/Cargo.toml b/apps/origin-src/Cargo.toml index 30ed0d94..7cc5202c 100644 --- a/apps/origin-src/Cargo.toml +++ b/apps/origin-src/Cargo.toml @@ -17,6 +17,7 @@ fixture = [] [dependencies] anyhow.workspace = true +axum.workspace = true clap.workspace = true getrandom.workspace = true origin-platform.workspace = true @@ -24,13 +25,19 @@ origin-shared.workspace = true serde.workspace = true similar.workspace = true thiserror.workspace = true +tokio.workspace = true toml.workspace = true +tracing.workspace = true +utoipa.workspace = true +utoipa-axum.workspace = true zstd.workspace = true [dev-dependencies] divan.workspace = true +origin-client.workspace = true # The benchmarks build their working trees with the fixtures. origin-src = { workspace = true, features = ["fixture"] } +serde_json.workspace = true tempfile.workspace = true [[bench]] diff --git a/apps/origin-src/src/http.rs b/apps/origin-src/src/http.rs new file mode 100644 index 00000000..d3bee4a5 --- /dev/null +++ b/apps/origin-src/src/http.rs @@ -0,0 +1,266 @@ +//! The HTTP API: a thin layer translating requests into [`OriginService`] +//! calls on the repository they name. Every route is documented with +//! `utoipa`, which generates the OpenAPI document; `origin-client` is the +//! Rust SDK for it. + +use std::convert::Infallible; +use std::sync::Arc; + +use axum::Json; +use axum::body::Bytes; +use axum::extract::{DefaultBodyLimit, FromRequestParts, Path, Query, State}; +use axum::http::request::Parts; +use axum::http::{StatusCode, header}; +use axum::response::{IntoResponse, Response}; +use origin_shared::api::{ + ApiError, ErrorCode, FetchRecords, LogEntry, LogQuery, RepoName, RepoSummary, Stored, + TargetInfo, +}; +use origin_shared::pack::{Pack, PackError}; +use utoipa::OpenApi; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::server::Repositories; +use crate::service::{Caller, OriginService, ServiceError}; + +#[derive(OpenApi)] +#[openapi(info( + title = "origin API", + version = "v1", + description = "The repositories an origin server hosts: their records, targets, landing \ + queues and events.", + license(name = "Apache-2.0") +))] +struct ApiDoc; + +type Repos = State>; + +/// The HTTP API. +pub struct Api; + +impl Api { + /// The largest request accepted, which bounds a batch of records put. + const MAX_REQUEST: usize = 1 << 30; + + fn documented() -> OpenApiRouter> { + OpenApiRouter::with_openapi(ApiDoc::openapi()) + .routes(routes!(list_repos)) + .routes(routes!(fetch_records)) + .routes(routes!(put_records)) + .routes(routes!(targets)) + .routes(routes!(log)) + .routes(routes!(openapi_document)) + } + + /// The router serving `repositories`. + pub fn router(repositories: Repositories) -> axum::Router { + axum::Router::from(Self::documented().with_state(Arc::new(repositories))) + .layer(DefaultBodyLimit::max(Self::MAX_REQUEST)) + } + + /// The OpenAPI document, which `docs/openapi.json` keeps a copy of. + #[must_use] + pub fn openapi() -> utoipa::openapi::OpenApi { + Self::documented().into_openapi() + } +} + +/// Every request is anonymous: nothing authenticates callers yet. +impl FromRequestParts> for Caller { + type Rejection = Infallible; + + fn from_request_parts( + _parts: &mut Parts, + _repositories: &Arc, + ) -> impl Future> + Send { + std::future::ready(Ok(Self::Anonymous)) + } +} + +/// Runs a call on the service of repository `repo`, on the blocking thread +/// pool: service calls do synchronous file system work, and event +/// long-polls wait. +async fn call( + State(repositories): Repos, + repo: RepoName, + caller: Caller, + call: impl FnOnce(&OriginService, &Caller) -> Result + Send + 'static, +) -> Result { + tokio::task::spawn_blocking(move || call(repositories.get(&caller, &repo)?, &caller)) + .await + .map_err(|error| HttpError::Panicked(error.to_string()))? + .map_err(HttpError::Service) +} + +/// A failed request, rendered as an [`ApiError`]. +enum HttpError { + Service(ServiceError), + Pack(PackError), + Panicked(String), +} + +impl IntoResponse for HttpError { + fn into_response(self) -> Response { + let (code, message) = match self { + Self::Service(error) if error.code() == ErrorCode::Internal => { + tracing::error!(error = %anyhow::Error::from(error), "request failed"); + (ErrorCode::Internal, "internal server error".to_owned()) + } + Self::Service(error) => (error.code(), error.to_string()), + Self::Pack(error) => (ErrorCode::BadRequest, format!("invalid pack: {error}")), + Self::Panicked(message) => { + tracing::error!(%message, "request panicked"); + (ErrorCode::Internal, "internal server error".to_owned()) + } + }; + let status = match code { + ErrorCode::BadRequest => StatusCode::BAD_REQUEST, + ErrorCode::NotFound => StatusCode::NOT_FOUND, + ErrorCode::Conflict => StatusCode::CONFLICT, + ErrorCode::Expired => StatusCode::GONE, + ErrorCode::Internal => StatusCode::INTERNAL_SERVER_ERROR, + }; + (status, Json(ApiError { code, message })).into_response() + } +} + +/// Binary content, a pack, in the OpenAPI document: utoipa would describe +/// `Vec` as an array of numbers. +struct Binary; + +impl utoipa::PartialSchema for Binary { + fn schema() -> utoipa::openapi::RefOr { + utoipa::openapi::ObjectBuilder::new() + .schema_type(utoipa::openapi::Type::String) + .content_media_type("application/octet-stream") + .into() + } +} + +impl utoipa::ToSchema for Binary {} + +/// Lists the repositories on the server. +#[utoipa::path( + get, + path = "/api/v1/repos", + operation_id = "list_repos", + responses((status = 200, description = "The repositories, by name", body = Vec)) +)] +async fn list_repos(State(repositories): Repos, caller: Caller) -> Json> { + Json(repositories.list(&caller)) +} + +/// Fetches objects by id, as a pack. +#[utoipa::path( + post, + path = "/api/v1/repos/{repo}/records/fetch", + operation_id = "fetch_records", + params(("repo" = String, Path, description = "The repository")), + request_body = FetchRecords, + responses( + (status = 200, description = "The objects, in the order asked, as a pack: each a 32-byte id, a little-endian u64 length and the object's encoding", content_type = "application/octet-stream", body = Binary), + (status = 404, description = "The repository or an object does not exist", body = ApiError) + ) +)] +async fn fetch_records( + repos: Repos, + Path(repo): Path, + caller: Caller, + Json(request): Json, +) -> Result { + let pack = call(repos, repo, caller, move |service, caller| { + service.records(caller, &request.ids) + }) + .await?; + Ok(( + [(header::CONTENT_TYPE, "application/octet-stream")], + pack.encode(), + ) + .into_response()) +} + +/// Puts a batch of objects, as a pack: snapshots, revisions and +/// statements, each needing only objects the batch or the repository has, +/// of the kinds it names. +#[utoipa::path( + put, + path = "/api/v1/repos/{repo}/records", + operation_id = "put_records", + params(("repo" = String, Path, description = "The repository")), + request_body(content = Binary, content_type = "application/octet-stream", description = "The objects, as a pack"), + responses( + (status = 200, description = "The objects are durable", body = Stored), + (status = 400, description = "The pack is invalid, holds an acceptance, or needs objects the repository doesn't have, or has as another kind", body = ApiError), + (status = 404, description = "The repository does not exist", body = ApiError) + ) +)] +async fn put_records( + repos: Repos, + Path(repo): Path, + caller: Caller, + body: Bytes, +) -> Result, HttpError> { + let pack = Pack::decode(&body).map_err(HttpError::Pack)?; + call(repos, repo, caller, move |service, caller| { + service.put_records(caller, pack) + }) + .await + .map(Json) +} + +/// Lists the targets, with their tips, authorities and requirements. +#[utoipa::path( + get, + path = "/api/v1/repos/{repo}/targets", + operation_id = "targets", + params(("repo" = String, Path, description = "The repository")), + responses( + (status = 200, description = "The targets, by name", body = Vec), + (status = 404, description = "The repository does not exist", body = ApiError) + ) +)] +async fn targets( + repos: Repos, + Path(repo): Path, + caller: Caller, +) -> Result>, HttpError> { + call(repos, repo, caller, OriginService::targets) + .await + .map(Json) +} + +/// Lists the acceptances of a target, oldest first. +#[utoipa::path( + get, + path = "/api/v1/repos/{repo}/log", + operation_id = "log", + params(("repo" = String, Path, description = "The repository"), LogQuery), + responses( + (status = 200, description = "The acceptances from `since` on", body = Vec), + (status = 404, description = "The repository or the target does not exist", body = ApiError) + ) +)] +async fn log( + repos: Repos, + Path(repo): Path, + caller: Caller, + Query(query): Query, +) -> Result>, HttpError> { + call(repos, repo, caller, move |service, caller| { + service.log(caller, &query.target, query.since) + }) + .await + .map(Json) +} + +/// The OpenAPI document of this API. +#[utoipa::path( + get, + path = "/api/v1/openapi.json", + operation_id = "openapi_document", + responses((status = 200, description = "The OpenAPI document", body = Object)) +)] +async fn openapi_document() -> Json { + Json(Api::openapi()) +} diff --git a/apps/origin-src/src/lib.rs b/apps/origin-src/src/lib.rs index 6dffb046..374172ed 100644 --- a/apps/origin-src/src/lib.rs +++ b/apps/origin-src/src/lib.rs @@ -10,11 +10,13 @@ pub mod events; #[cfg(feature = "fixture")] pub mod fixture; mod frames; +pub mod http; pub mod index; pub mod oplog; pub mod output; pub mod policy; pub mod queue; +pub mod server; pub mod service; pub mod store; pub mod targets; diff --git a/apps/origin-src/src/server.rs b/apps/origin-src/src/server.rs new file mode 100644 index 00000000..5b2c3dae --- /dev/null +++ b/apps/origin-src/src/server.rs @@ -0,0 +1,41 @@ +//! The repositories a server hosts. + +use std::collections::BTreeMap; + +use origin_shared::api::{RepoName, RepoSummary}; + +use crate::service::{Caller, OriginService, ServiceError}; + +/// The repositories a server hosts, each served by the server's node and +/// kept open while it runs. +#[derive(Debug, Default)] +pub struct Repositories { + repos: BTreeMap, +} + +impl Repositories { + /// Hosts `service` as `name`. + pub fn insert(&mut self, name: RepoName, service: OriginService) { + self.repos.insert(name, service); + } + + /// Lists the repositories, by name. + #[must_use] + pub fn list(&self, _caller: &Caller) -> Vec { + self.repos + .keys() + .map(|name| RepoSummary { name: name.clone() }) + .collect() + } + + /// The repository `name`. + /// + /// # Errors + /// + /// Fails if the server hosts none by that name. + pub fn get(&self, _caller: &Caller, name: &RepoName) -> Result<&OriginService, ServiceError> { + self.repos + .get(name) + .ok_or_else(|| ServiceError::UnknownRepository(name.clone())) + } +} diff --git a/apps/origin-src/src/service.rs b/apps/origin-src/src/service.rs index 178b6e69..096ebd4b 100644 --- a/apps/origin-src/src/service.rs +++ b/apps/origin-src/src/service.rs @@ -600,6 +600,9 @@ impl Dependencies { /// A failed service call. #[derive(Debug, thiserror::Error)] pub enum ServiceError { + /// The server hosts no such repository. + #[error("repository `{0}` not found")] + UnknownRepository(origin_shared::api::RepoName), /// A directory holds no repository. #[error("{} is not an origin repository", .0.display())] NotARepository(PathBuf), @@ -672,7 +675,9 @@ impl ServiceError { #[must_use] pub fn code(&self) -> ErrorCode { match self { - Self::UnknownChange(_) | Self::UnknownTarget(_) => ErrorCode::NotFound, + Self::UnknownRepository(_) | Self::UnknownChange(_) | Self::UnknownTarget(_) => { + ErrorCode::NotFound + } Self::NoTarget | Self::Malformed { .. } | Self::Acceptance(_) diff --git a/apps/origin-src/tests/http.rs b/apps/origin-src/tests/http.rs new file mode 100644 index 00000000..fed0bd2c --- /dev/null +++ b/apps/origin-src/tests/http.rs @@ -0,0 +1,360 @@ +//! The HTTP API, driven through the SDK against a real server: every SDK +//! method, over the server's own repositories. + +use std::sync::Arc; + +use origin_client::{Client, Error, Repo}; +use origin_shared::api::{ErrorCode, FetchRecords, LogQuery, RepoName}; +use origin_shared::pack::Pack; +use origin_shared::{ + Base, BlobId, ChangeId, Digest, EncodedObject, EntryKind, EntryName, Inputs, Kind, NodeKey, + Record, RecordId, Revision, RevisionId, Statement, TargetName, Tree, TreeEntry, Verdict, +}; +use origin_src::http::Api; +use origin_src::policy::Policy; +use origin_src::server::Repositories; +use origin_src::service::{Node, OriginService}; + +/// A server hosting `demo`, whose policy requires nothing, and `strict`, +/// whose `main` requires a passing `ci.test` from `user:ci`. The server's +/// node, `hosted`, orders both. +struct Server { + _dir: tempfile::TempDir, + client: Client, + demo: Repo, + strict: Repo, +} + +impl Server { + async fn start() -> Self { + let dir = tempfile::tempdir().unwrap(); + let node = Node { + name: "hosted".parse().unwrap(), + key: Arc::new(NodeKey::from_bytes(&[7; 32])), + }; + let open = Policy::initial(&node.name, &node.key.public()); + let strict = format!( + "[nodes]\nhosted = \"{}\"\n[targets.policy]\nauthority = \"node:hosted\"\n\ + [targets.main]\nauthority = \"node:hosted\"\n\ + require = [{{ kind = \"ci.test\", verdict = \"pass\", issuer = \"user:ci\" }}]\n", + node.key.public() + ); + let mut repositories = Repositories::default(); + for (name, policy) in [("demo", open), ("strict", strict)] { + let service = + OriginService::create(dir.path().join(name), node.clone(), &policy).unwrap(); + repositories.insert(name.parse().unwrap(), service); + } + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, Api::router(repositories)).await }); + let client = Client::new(&format!("http://{address}")); + Self { + _dir: dir, + demo: client.repo("demo".parse().unwrap()), + strict: client.repo("strict".parse().unwrap()), + client, + } + } +} + +/// A revision of `change` with `files` and a description, made on `base`, +/// and every object it needs, records last. +struct Made { + id: RevisionId, + objects: Vec, +} + +impl Made { + fn revision( + change: ChangeId, + base: Base, + predecessors: Vec, + files: &[(&str, &str)], + ) -> Self { + let mut objects: Vec<_> = files + .iter() + .map(|(_, content)| EncodedObject::blob(content.as_bytes())) + .collect(); + let tree: Tree = files + .iter() + .zip(&objects) + .map(|((name, _), blob)| { + let entry = TreeEntry { + kind: EntryKind::File, + id: blob.id(), + }; + (EntryName::new(*name).unwrap(), entry) + }) + .collect(); + let tree = tree.encode(); + let description = EncodedObject::blob(b"A change"); + let revision = Revision { + change, + predecessors, + base, + deps: Vec::new(), + snapshot: tree.id().into(), + description: BlobId::from(description.id()), + author: "user:ada".parse().unwrap(), + } + .encode(); + let id = revision.id().into(); + objects.extend([tree, description, revision]); + Self { id, objects } + } + + fn pack(&self) -> Pack { + Pack { + objects: self.objects.clone(), + } + } +} + +/// The tip of `main`, to make revisions on. +async fn main_tip(repo: &Repo) -> Base { + let targets = repo.targets().await.unwrap(); + let main = targets + .iter() + .find(|target| target.name == TargetName::MAIN) + .unwrap(); + Base::Acceptance(main.head.acceptance) +} + +fn change(seed: u8) -> ChangeId { + ChangeId::from_bytes([seed; 16]) +} + +/// The error code of a refused request. +fn code(error: Error) -> ErrorCode { + match error { + Error::Api(error) => error.code, + error => panic!("expected an API error, got {error}"), + } +} + +#[tokio::test] +async fn hosts_several_repositories() { + let server = Server::start().await; + let names: Vec<_> = server.client.repos().await.unwrap(); + let names: Vec<_> = names.iter().map(|repo| repo.name.as_str()).collect(); + assert_eq!(names, ["demo", "strict"]); + + let missing = server.client.repo(RepoName::new("missing").unwrap()); + assert_eq!( + code(missing.targets().await.unwrap_err()), + ErrorCode::NotFound + ); + + // Records put in one repository aren't in the other. + let made = Made::revision(change(1), main_tip(&server.demo).await, vec![], &[]); + server.demo.put_records(&made.pack()).await.unwrap(); + let request = FetchRecords { + ids: vec![made.id.into()], + }; + assert!(server.demo.fetch_records(&request).await.is_ok()); + let error = server.strict.fetch_records(&request).await.unwrap_err(); + assert_eq!(code(error), ErrorCode::NotFound); +} + +#[tokio::test] +async fn puts_and_fetches_records() { + let server = Server::start().await; + let repo = &server.demo; + let made = Made::revision( + change(1), + main_tip(repo).await, + vec![], + &[("a.txt", "a"), ("b.txt", "b")], + ); + let stored = repo.put_records(&made.pack()).await.unwrap(); + assert_eq!( + stored.new, 5, + "two blobs, the tree, the description and the revision" + ); + let again = repo.put_records(&made.pack()).await.unwrap(); + assert_eq!( + again.new, 0, + "records are immutable, so putting them again does nothing" + ); + + let wanted = [made.objects[4].clone(), made.objects[0].clone()]; + let fetched = repo + .fetch_records(&FetchRecords { + ids: wanted.iter().map(EncodedObject::id).collect(), + }) + .await + .unwrap(); + assert_eq!(fetched.objects, wanted, "verified, in the order asked"); + + // A record is refused unless the repository can use it. + let orphan = Made::revision(change(2), main_tip(repo).await, vec![], &[("c.txt", "c")]); + let revision_only = Pack { + objects: vec![orphan.objects.last().unwrap().clone()], + }; + let error = repo.put_records(&revision_only).await.unwrap_err(); + assert_eq!(code(error), ErrorCode::BadRequest); + let log = repo + .log(&LogQuery { + target: TargetName::MAIN, + since: 0, + }) + .await + .unwrap(); + let acceptance = log[0].acceptance.encode(); + let error = repo + .put_records(&Pack { + objects: vec![acceptance], + }) + .await + .unwrap_err(); + assert_eq!( + code(error), + ErrorCode::BadRequest, + "only the authority lands" + ); +} + +#[tokio::test] +async fn puts_refuse_objects_named_as_another_kind() { + let server = Server::start().await; + let repo = &server.demo; + let base = main_tip(repo).await; + let refused = |objects: Vec| async move { + code(repo.put_records(&Pack { objects }).await.unwrap_err()) + }; + + // A revision whose snapshot is a blob, in the batch. + let blob = EncodedObject::blob(b"not a tree"); + let description = EncodedObject::blob(b"A change"); + let revision = Revision { + change: change(1), + predecessors: Vec::new(), + base, + deps: Vec::new(), + snapshot: blob.id().into(), + description: BlobId::from(description.id()), + author: "user:ada".parse().unwrap(), + } + .encode(); + let objects = vec![blob, description, revision]; + assert_eq!(refused(objects).await, ErrorCode::BadRequest); + + // Trees naming a stored blob as a directory, and a stored tree as a + // file. + let made = Made::revision(change(2), base, Vec::new(), &[("lib.rs", "fn a() {}")]); + repo.put_records(&made.pack()).await.unwrap(); + let (file, tree) = (made.objects[0].id(), made.objects[1].id()); + for (kind, id) in [(EntryKind::Tree, file), (EntryKind::File, tree)] { + let tree: Tree = [(EntryName::new("x").unwrap(), TreeEntry { kind, id })] + .into_iter() + .collect(); + assert_eq!(refused(vec![tree.encode()]).await, ErrorCode::BadRequest); + } + + // One stored object needed as two kinds, the right one last: a + // revision's snapshot and description, and a tree's directory and + // file. + let stored = EncodedObject::blob(b"stored"); + repo.put_records(&Pack { + objects: vec![stored.clone()], + }) + .await + .unwrap(); + let both = Revision { + change: change(3), + predecessors: Vec::new(), + base, + deps: Vec::new(), + snapshot: stored.id().into(), + description: BlobId::from(stored.id()), + author: "user:ada".parse().unwrap(), + }; + assert_eq!(refused(vec![both.encode()]).await, ErrorCode::BadRequest); + let entry = |kind| TreeEntry { + kind, + id: stored.id(), + }; + let tree: Tree = [ + (EntryName::new("a").unwrap(), entry(EntryKind::Tree)), + (EntryName::new("b").unwrap(), entry(EntryKind::File)), + ] + .into_iter() + .collect(); + assert_eq!(refused(vec![tree.encode()]).await, ErrorCode::BadRequest); +} + +#[tokio::test] +async fn promotions_must_match_their_original() { + let server = Server::start().await; + let repo = &server.demo; + let made = Made::revision(change(1), main_tip(repo).await, vec![], &[("a.txt", "a")]); + repo.put_records(&made.pack()).await.unwrap(); + // Even when they come together. + let same = Made::revision(change(3), main_tip(repo).await, vec![], &[("a.txt", "a")]); + repo.put_records(&same.pack()).await.unwrap(); + let original = Statement { + subject: RecordId::Revision(made.id), + kind: Kind::new("ci.test").unwrap(), + verdict: Some(Verdict::Pass), + issuer: "user:ci".parse().unwrap(), + inputs: Some(Inputs { + paths: vec!["a.txt".parse().unwrap()], + definition: Digest::of(b"test"), + toolchain: Digest::of(b"rustc"), + external: false, + }), + payload: None, + supersedes: None, + promoted_from: None, + }; + let promotion = Statement { + subject: RecordId::Revision(same.id), + issuer: "user:eve".parse().unwrap(), + promoted_from: Some(original.encode().id().into()), + ..original.clone() + }; + let forged = Statement { + verdict: Some(Verdict::Fail), + ..promotion.clone() + }; + let error = repo + .put_records(&Pack { + objects: vec![original.encode(), forged.encode()], + }) + .await + .unwrap_err(); + assert_eq!(code(error), ErrorCode::BadRequest); + let stored = repo + .put_records(&Pack { + objects: vec![promotion.encode(), original.encode()], + }) + .await + .unwrap(); + assert_eq!(stored.new, 1, "the original was stored with the forgery"); +} + +#[tokio::test] +async fn serves_its_openapi_document() { + let server = Server::start().await; + let document = server.client.openapi().await.unwrap(); + assert_eq!(document, serde_json::to_value(Api::openapi()).unwrap()); +} + +/// `docs/openapi.json` documents the API for other languages. Run `just +/// openapi` to rewrite it after changing the API. +#[test] +fn checked_in_openapi_document_is_current() { + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../docs/openapi.json"); + let document = format!("{}\n", Api::openapi().to_pretty_json().unwrap()); + if std::env::var_os("UPDATE_OPENAPI").is_some() { + std::fs::write(path, document).unwrap(); + } else { + let checked_in = std::fs::read_to_string(path).unwrap(); + assert!( + checked_in == document, + "docs/openapi.json is stale: run `just openapi`" + ); + } +} diff --git a/crates/origin-client/Cargo.toml b/crates/origin-client/Cargo.toml index 130fdbe4..f2fe28e7 100644 --- a/crates/origin-client/Cargo.toml +++ b/crates/origin-client/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "origin-client" -description = "HTTP client for the origin API, generated from its OpenAPI document" +description = "The origin SDK: a typed client for origin servers" version.workspace = true edition.workspace = true rust-version.workspace = true @@ -9,6 +9,10 @@ repository.workspace = true [dependencies] origin-shared.workspace = true +reqwest.workspace = true +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true [lints] workspace = true diff --git a/crates/origin-client/src/lib.rs b/crates/origin-client/src/lib.rs index 7eebb729..046ca71c 100644 --- a/crates/origin-client/src/lib.rs +++ b/crates/origin-client/src/lib.rs @@ -1,2 +1,179 @@ -//! HTTP client for the origin API, generated from the OpenAPI document the -//! server publishes. +//! The origin SDK: a typed client for origin servers. +//! +//! ```no_run +//! use origin_client::Client; +//! use origin_shared::api::RepoName; +//! +//! # async fn example() -> Result<(), Box> { +//! let client = Client::new("http://127.0.0.1:7878"); +//! let repo = client.repo(RepoName::new("demo")?); +//! for target in repo.targets().await? { +//! println!("{} is at #{}", target.name, target.head.seq); +//! } +//! # Ok(()) +//! # } +//! ``` +//! +//! Requests and responses are the `origin-shared` types the server uses, so +//! the two cannot disagree on a contract. The server also describes its API +//! in `docs/openapi.json`, for other languages. + +use origin_shared::api::{ + ApiError, FetchRecords, LogEntry, LogQuery, RepoName, RepoSummary, Stored, TargetInfo, +}; +use origin_shared::pack::{Pack, PackError}; +use reqwest::{Method, RequestBuilder}; +use serde::de::DeserializeOwned; + +/// Defines endpoints as methods. Each sends one request, built from an HTTP +/// method, a path relative to its owner's, which can name the arguments +/// like `format!` does, and optionally a body applied by a +/// [`RequestBuilder`] method (`query`, `json` or `body`), then reads the +/// response with a [`Response`] method. +macro_rules! endpoints { + ($( + impl $owner:ident {$( + $(#[doc = $doc:literal])* + fn $name:ident($($arg:ident: $type:ty),*) -> $output:ty = + $method:ident $path:literal $(, $send:ident($body:expr))? => $read:ident; + )*} + )*) => {$( + impl $owner {$( + $(#[doc = $doc])* + /// + /// # Errors + /// + /// Fails if the server cannot be reached or refuses the request. + pub async fn $name(&self, $($arg: $type),*) -> Result<$output, Error> { + let request = self.request(Method::$method, &format!($path))$(.$send($body))?; + Response::send(request).await?.$read().await + } + )*} + )*}; +} + +endpoints! { + impl Client { + /// Lists the repositories on the server, by name. + fn repos() -> Vec = GET "repos" => json; + /// The server's OpenAPI document. + fn openapi() -> serde_json::Value = GET "openapi.json" => json; + } + + impl Repo { + /// Fetches objects by id, in the order asked. + fn fetch_records(request: &FetchRecords) -> Pack = + POST "records/fetch", json(request) => pack; + /// Puts a batch of objects: snapshots, revisions and statements, + /// each needing only objects the batch or the repository has. + fn put_records(pack: &Pack) -> Stored = PUT "records", body(pack.encode()) => json; + /// Every target, with its tip, authority and requirements. + fn targets() -> Vec = GET "targets" => json; + /// The acceptances of a target, oldest first. + fn log(query: &LogQuery) -> Vec = GET "log", query(query) => json; + } +} + +/// A connection to an origin server. Cloning it is cheap, and clones share +/// their connections. +#[derive(Clone, Debug)] +pub struct Client { + http: reqwest::Client, + /// The API's base URL, ending with a `/`. + api: String, +} + +impl Client { + /// A client for the server at `url`, such as `http://127.0.0.1:7878`. + #[must_use] + pub fn new(url: &str) -> Self { + Self { + http: reqwest::Client::new(), + api: format!("{}/api/v1/", url.trim_end_matches('/')), + } + } + + /// A repository on the server. Sends no request. + #[must_use] + pub fn repo(&self, name: RepoName) -> Repo { + Repo { + client: self.clone(), + name, + } + } + + /// Starts a request to `path`, relative to the API's base URL. + fn request(&self, method: Method, path: &str) -> RequestBuilder { + self.http.request(method, format!("{}{path}", self.api)) + } +} + +/// A repository on a server. +#[derive(Clone, Debug)] +pub struct Repo { + client: Client, + name: RepoName, +} + +impl Repo { + /// The repository's name. + #[must_use] + pub fn name(&self) -> &RepoName { + &self.name + } + + /// Starts a request to `path`, relative to the repository's URL. + fn request(&self, method: Method, path: &str) -> RequestBuilder { + let path = format!("repos/{}/{path}", self.name.as_str()); + self.client.request(method, &path) + } +} + +/// A successful response, read in the form its endpoint answers with. +struct Response(reqwest::Response); + +impl Response { + /// Sends a request, turning error statuses into errors. + async fn send(request: RequestBuilder) -> Result { + let response = request.send().await?; + let status = response.status(); + if status.is_success() { + return Ok(Self(response)); + } + Err(match response.json().await { + Ok(error) => Error::Api(error), + Err(_) => Error::Status(status.as_u16()), + }) + } + + async fn json(self) -> Result { + Ok(self.0.json().await?) + } + + async fn pack(self) -> Result { + Ok(Pack::decode(&self.0.bytes().await?)?) + } +} + +/// A failed request. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// The server refused the request, and said why. + #[error("the server refused: {0}")] + Api(ApiError), + /// The server answered with an error status, without saying why. + #[error("the server answered with status {0}")] + Status(u16), + /// The server cannot be reached, or its response cannot be read. + #[error("cannot reach the server")] + Transport(#[source] Box), + /// The server sent invalid objects. + #[error("the server sent invalid objects")] + Pack(#[from] PackError), +} + +impl From for Error { + fn from(error: reqwest::Error) -> Self { + Self::Transport(Box::new(error)) + } +} diff --git a/deny.toml b/deny.toml index 116e5b4f..9d79bf57 100644 --- a/deny.toml +++ b/deny.toml @@ -4,6 +4,9 @@ unmaintained = "workspace" [bans] multiple-versions = "warn" wildcards = "deny" +skip = [ + { crate = "syn@2.0.119", reason = "divan-macros and tracing-attributes have not moved to syn 3 yet" }, +] [licenses] confidence-threshold = 0.8 diff --git a/docs/openapi.json b/docs/openapi.json new file mode 100644 index 00000000..7e8fc9fe --- /dev/null +++ b/docs/openapi.json @@ -0,0 +1,628 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "origin API", + "description": "The repositories an origin server hosts: their records, targets, landing queues and events.", + "license": { + "name": "Apache-2.0" + }, + "version": "v1" + }, + "paths": { + "/api/v1/openapi.json": { + "get": { + "summary": "The OpenAPI document of this API.", + "operationId": "openapi_document", + "responses": { + "200": { + "description": "The OpenAPI document", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + } + } + } + }, + "/api/v1/repos": { + "get": { + "summary": "Lists the repositories on the server.", + "operationId": "list_repos", + "responses": { + "200": { + "description": "The repositories, by name", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepoSummary" + } + } + } + } + } + } + } + }, + "/api/v1/repos/{repo}/log": { + "get": { + "summary": "Lists the acceptances of a target, oldest first.", + "operationId": "log", + "parameters": [ + { + "name": "repo", + "in": "path", + "description": "The repository", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "target", + "in": "query", + "description": "The target.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "since", + "in": "query", + "description": "The position of the first acceptance to return: 0, the first, by\ndefault.", + "required": false, + "schema": { + "type": "integer", + "format": "int64", + "minimum": 0 + } + } + ], + "responses": { + "200": { + "description": "The acceptances from `since` on", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LogEntry" + } + } + } + } + }, + "404": { + "description": "The repository or the target does not exist", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + } + }, + "/api/v1/repos/{repo}/records": { + "put": { + "summary": "Puts a batch of objects, as a pack: snapshots, revisions and\nstatements, each needing only objects the batch or the repository has,\nof the kinds it names.", + "operationId": "put_records", + "parameters": [ + { + "name": "repo", + "in": "path", + "description": "The repository", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "description": "The objects, as a pack", + "content": { + "application/octet-stream": { + "schema": { + "$ref": "#/components/schemas/Binary" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "The objects are durable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Stored" + } + } + } + }, + "400": { + "description": "The pack is invalid, holds an acceptance, or needs objects the repository doesn't have, or has as another kind", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "The repository does not exist", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + } + }, + "/api/v1/repos/{repo}/records/fetch": { + "post": { + "summary": "Fetches objects by id, as a pack.", + "operationId": "fetch_records", + "parameters": [ + { + "name": "repo", + "in": "path", + "description": "The repository", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FetchRecords" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "The objects, in the order asked, as a pack: each a 32-byte id, a little-endian u64 length and the object's encoding", + "content": { + "application/octet-stream": { + "schema": { + "$ref": "#/components/schemas/Binary" + } + } + } + }, + "404": { + "description": "The repository or an object does not exist", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + } + }, + "/api/v1/repos/{repo}/targets": { + "get": { + "summary": "Lists the targets, with their tips, authorities and requirements.", + "operationId": "targets", + "parameters": [ + { + "name": "repo", + "in": "path", + "description": "The repository", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The targets, by name", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TargetInfo" + } + } + } + } + }, + "404": { + "description": "The repository does not exist", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "Acceptance": { + "allOf": [ + { + "$ref": "#/components/schemas/AcceptanceBody" + }, + { + "type": "object", + "required": [ + "signature" + ], + "properties": { + "signature": { + "type": "string" + } + } + } + ], + "description": "One landing on a target, signed by the target's authority.\n\nAcceptances form a hash chain per target: each names the one before it,\nand its sequence number is its position in the target's log.\n\nIn JSON, the body's fields and the signature, in hex." + }, + "AcceptanceBody": { + "type": "object", + "description": "An acceptance without its signature.", + "required": [ + "target", + "seq", + "state", + "landed", + "evidence" + ], + "properties": { + "evidence": { + "type": "array", + "items": { + "$ref": "#/components/schemas/StatementId" + }, + "description": "The statements the policy relied on." + }, + "landed": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Source" + }, + "description": "What landed." + }, + "policy": { + "oneOf": [ + { + "$ref": "#/components/schemas/AcceptanceId", + "description": "The acceptance of the `policy` target in force when this one landed.\nAbsent only for the first acceptance of `policy`, which nothing\nprecedes." + }, + { + "type": "null" + } + ] + }, + "prev": { + "oneOf": [ + { + "$ref": "#/components/schemas/AcceptanceId", + "description": "The acceptance before this one, absent only for the first." + }, + { + "type": "null" + } + ] + }, + "seq": { + "type": "integer", + "format": "int64", + "description": "The position in the target's log, from 0.", + "minimum": 0 + }, + "state": { + "$ref": "#/components/schemas/TreeId", + "description": "The target's snapshot after this landing." + }, + "target": { + "$ref": "#/components/schemas/TargetId", + "description": "The target landed on." + } + } + }, + "AcceptanceId": { + "type": "string", + "examples": [ + "48fc721fbbc172e0925fa27af1671de225ba927134802998b10a1568a188652b" + ] + }, + "ApiError": { + "type": "object", + "description": "What went wrong with a request.", + "required": [ + "code", + "message" + ], + "properties": { + "code": { + "$ref": "#/components/schemas/ErrorCode", + "description": "The kind of failure." + }, + "message": { + "type": "string", + "description": "A human-readable explanation." + } + } + }, + "Binary": { + "type": "string", + "contentMediaType": "application/octet-stream" + }, + "ErrorCode": { + "type": "string", + "description": "The kind of an [`ApiError`].", + "enum": [ + "bad_request", + "not_found", + "conflict", + "expired", + "internal" + ] + }, + "FetchRecords": { + "type": "object", + "description": "Asks for records, and any other objects, by id.", + "required": [ + "ids" + ], + "properties": { + "ids": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ObjectId" + }, + "description": "The objects, returned in this order." + } + } + }, + "Head": { + "type": "object", + "description": "The latest acceptance of a target.", + "required": [ + "seq", + "acceptance" + ], + "properties": { + "acceptance": { + "$ref": "#/components/schemas/AcceptanceId", + "description": "The acceptance." + }, + "seq": { + "type": "integer", + "format": "int64", + "description": "Its position in the log, from 0.", + "minimum": 0 + } + } + }, + "Kind": { + "type": "string", + "examples": [ + "ci.test" + ] + }, + "LogEntry": { + "type": "object", + "description": "One acceptance of a target's log.", + "required": [ + "id", + "acceptance" + ], + "properties": { + "acceptance": { + "$ref": "#/components/schemas/Acceptance", + "description": "The acceptance, whose `seq` is its position in the log." + }, + "id": { + "$ref": "#/components/schemas/AcceptanceId", + "description": "Its id." + } + } + }, + "ObjectId": { + "type": "string", + "examples": [ + "48fc721fbbc172e0925fa27af1671de225ba927134802998b10a1568a188652b" + ] + }, + "PrincipalName": { + "type": "string", + "examples": [ + "alice" + ] + }, + "Principals": { + "type": "string", + "examples": [ + "group:runners" + ] + }, + "RepoName": { + "type": "string", + "description": "The name of a repository on a server: ASCII letters, digits, `.`, `_`\nand `-`, not starting with `.`.", + "example": "origin" + }, + "RepoSummary": { + "type": "object", + "description": "A repository, as listed by the server.", + "required": [ + "name" + ], + "properties": { + "name": { + "$ref": "#/components/schemas/RepoName", + "description": "The repository's name." + } + } + }, + "Requirement": { + "type": "object", + "description": "A statement that landing needs: of `kind`, with `verdict`, from one of\n`issuer`, about what lands.", + "required": [ + "kind", + "verdict", + "issuer" + ], + "properties": { + "issuer": { + "$ref": "#/components/schemas/Principals", + "description": "Who may issue it." + }, + "kind": { + "$ref": "#/components/schemas/Kind", + "description": "The statement's kind." + }, + "verdict": { + "$ref": "#/components/schemas/Verdict", + "description": "Its verdict." + } + } + }, + "RevisionId": { + "type": "string", + "examples": [ + "48fc721fbbc172e0925fa27af1671de225ba927134802998b10a1568a188652b" + ] + }, + "Source": { + "oneOf": [ + { + "type": "object", + "description": "A revision of a change.", + "required": [ + "revision" + ], + "properties": { + "revision": { + "$ref": "#/components/schemas/RevisionId", + "description": "A revision of a change." + } + } + }, + { + "type": "object", + "description": "Another target, as of one of its acceptances.", + "required": [ + "target" + ], + "properties": { + "target": { + "$ref": "#/components/schemas/AcceptanceId", + "description": "Another target, as of one of its acceptances." + } + } + } + ], + "description": "What an acceptance landed." + }, + "StatementId": { + "type": "string", + "examples": [ + "48fc721fbbc172e0925fa27af1671de225ba927134802998b10a1568a188652b" + ] + }, + "Stored": { + "type": "object", + "description": "What putting a batch of records did.", + "required": [ + "new" + ], + "properties": { + "new": { + "type": "integer", + "format": "int64", + "description": "How many of the objects the repository didn't have yet.", + "minimum": 0 + } + } + }, + "TargetId": { + "type": "string", + "examples": [ + "48fc721fbbc172e0925fa27af1671de225ba927134802998b10a1568a188652b" + ] + }, + "TargetInfo": { + "type": "object", + "description": "A target, where it is, and who orders it under the policy in force.", + "required": [ + "name", + "head", + "requirements" + ], + "properties": { + "authority": { + "oneOf": [ + { + "$ref": "#/components/schemas/PrincipalName", + "description": "The node that orders it, if the policy names one." + }, + { + "type": "null" + } + ] + }, + "head": { + "$ref": "#/components/schemas/Head", + "description": "Its latest acceptance." + }, + "name": { + "$ref": "#/components/schemas/TargetName", + "description": "The target's name." + }, + "requirements": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Requirement" + }, + "description": "The statements landing on it needs." + } + } + }, + "TargetName": { + "type": "string", + "examples": [ + "main" + ] + }, + "TreeId": { + "type": "string", + "examples": [ + "48fc721fbbc172e0925fa27af1671de225ba927134802998b10a1568a188652b" + ] + }, + "Verdict": { + "type": "string", + "examples": [ + "pass" + ] + } + } + } +} diff --git a/justfile b/justfile index dd2d87fa..fabd5c89 100644 --- a/justfile +++ b/justfile @@ -28,6 +28,11 @@ doc-test: deny: @cargo deny check +# Rewrite docs/openapi.json after changing the API. `just test` fails while +# it is stale. +openapi: + @UPDATE_OPENAPI=1 cargo nextest run --locked --package origin-src --test http openapi + # Micro-benchmarks of the hot paths (hashing, storage, snapshots). bench *ARGS: @cargo bench --locked --workspace -- {{ARGS}}