diff --git a/CHANGELOG.md b/CHANGELOG.md index 04fe385..6857ec3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,15 @@ +# 0.14.0 + +- **Breaking:** Remove the `IntoBody` trait. Unwrap body types directly instead, either by pattern matching in the handler arguments (eg `|Capped(FromJson(body)): Capped, N>| ...`) or via `.0`. +- **Breaking:** `Option` is now described as `OneOf [T, Null]` (ie `T | null`) rather than `Optional`, since serde serializes `None` as `null`. Previously, clients generated from the info would wrongly expect the key to be omitted. +- Add `#[api_body(optional)]` for `Option` fields in `ApiBody` structs and enum variants. The field is described as `Optional` (ie `{ key?: T }`), is omitted from the JSON when `None`, and is treated as `None` when missing. +- `#[api_body(flatten)]` on an enum variant field is now a clear compile error rather than a confusing one. +- **Breaking:** `HandlerBody::handler_method()` no longer defaults to POST and must be implemented by every `HandlerBody` type. Custom body types that relied on the default should add `fn handler_method() -> Method { Method::POST }`. +- Fix `Capped` always reporting POST as its handler method; it now uses `T`'s method, so wrapping a body type that expects eg PUT no longer changes the route. +- **Breaking:** Responses can now be streamed. `Api::handle()` and `HandlerResponse::handler_response()` now produce an `http::Response` rather than an `http::Response>`. A `Body` is either a complete set of bytes (use `Body::as_bytes()` or `Body::into_bytes()` to get at them without streaming) or a stream of `bytes::Bytes` chunks (use `Body::into_stream()` to obtain a `BodyStream`, which implements `futures::Stream`). Code which previously used `res.into_body()` as a `Vec` can use `res.into_body().into_vec()` instead, though it's better to pass streaming bodies on to your HTTP framework as streams (see the Axum and Hyper examples). +- Add a `ToBinary` response type, which responds with arbitrary bytes, optionally streamed from a `futures::Stream` or `futures::AsyncRead`, and which allows the `content-type` and `content-length` headers to be set. The `content-length` is set automatically when the body is already in memory. +- `ToJson` no longer panics if the value fails to serialize (eg a map with non-string keys, or a custom `Serialize` impl that errors). A 500 `ApiError` is returned instead, with the serialization error in its `internal_message`. + # 0.13.0 - Upgrade to syn 3. diff --git a/Cargo.lock b/Cargo.lock index 17a4fe7..718f1aa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,61 +2,6 @@ # It is not intended for manual editing. version = 4 -[[package]] -name = "addr2line" -version = "0.24.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1" -dependencies = [ - "gimli", -] - -[[package]] -name = "adler2" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" - -[[package]] -name = "ansi_term" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b" -dependencies = [ - "winapi", -] - -[[package]] -name = "async-trait" -version = "0.1.83" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.90", -] - -[[package]] -name = "atomic" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b88d82667eca772c4aa12f0f1348b3ae643424c8876448f3f7bd5787032e234c" -dependencies = [ - "autocfg", -] - -[[package]] -name = "atty" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" -dependencies = [ - "hermit-abi 0.1.19", - "libc", - "winapi", -] - [[package]] name = "autocfg" version = "1.1.0" @@ -65,19 +10,19 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "axum" -version = "0.7.9" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" dependencies = [ - "async-trait", "axum-core", "axum-macros", "bytes", + "form_urlencoded", "futures-util", - "http 1.2.0", - "http-body 1.0.1", + "http", + "http-body", "http-body-util", - "hyper 1.5.1", + "hyper", "hyper-util", "itoa", "matchit", @@ -85,8 +30,7 @@ dependencies = [ "mime", "percent-encoding", "pin-project-lite", - "rustversion", - "serde", + "serde_core", "serde_json", "serde_path_to_error", "serde_urlencoded", @@ -100,19 +44,17 @@ dependencies = [ [[package]] name = "axum-core" -version = "0.4.5" +version = "0.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09f2bd6146b97ae3359fa0cc6d6b376d9539582c7b4220f041a33ec24c226199" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" dependencies = [ - "async-trait", "bytes", - "futures-util", - "http 1.2.0", - "http-body 1.0.1", + "futures-core", + "http", + "http-body", "http-body-util", "mime", "pin-project-lite", - "rustversion", "sync_wrapper", "tower-layer", "tower-service", @@ -121,54 +63,15 @@ dependencies = [ [[package]] name = "axum-macros" -version = "0.4.2" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57d123550fa8d071b7255cb0cc04dc302baa6c8c4a79f55701552684d8399bce" +checksum = "7aa268c23bfbbd2c4363b9cd302a4f504fb2a9dfe7e3451d66f35dd392e20aca" dependencies = [ "proc-macro2", "quote", "syn 2.0.90", ] -[[package]] -name = "backtrace" -version = "0.3.74" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d82cb332cdfaed17ae235a638438ac4d4839913cc2af585c3c6746e8f8bee1a" -dependencies = [ - "addr2line", - "cfg-if", - "libc", - "miniz_oxide", - "object", - "rustc-demangle", - "windows-targets 0.52.6", -] - -[[package]] -name = "base-x" -version = "0.2.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cbbc9d0964165b47557570cce6c952866c2678457aca742aafc9fb771d30270" - -[[package]] -name = "binascii" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "383d29d513d8764dcdc42ea295d979eb99c3c9f00607b3692cf68a431f7dca72" - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bumpalo" -version = "3.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d261e256854913907f67ed06efbc3338dfe6179796deefc1ff763fc1aee5535" - [[package]] name = "bytes" version = "1.9.0" @@ -182,78 +85,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] -name = "const_fn" -version = "0.4.9" +name = "diff" +version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbdcdcb6d86f71c5e97409ad45898af11cbc995b4ee8112d59095a28d376c935" - -[[package]] -name = "cookie" -version = "0.15.0-dev" -source = "git+https://github.com/SergioBenitez/cookie-rs.git?rev=1c3ca83#1c3ca838543b60a4448d279dc4b903cc7a2bc22a" -dependencies = [ - "percent-encoding", - "time", - "version_check", -] - -[[package]] -name = "ctor" -version = "0.1.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d2301688392eb071b0bf1a37be05c469d3cc4dbbd95df672fe28ab021e6a096" -dependencies = [ - "quote", - "syn 1.0.107", -] - -[[package]] -name = "devise" -version = "0.3.0" -source = "git+https://github.com/SergioBenitez/Devise.git?rev=3648468#3648468a9ede9ca896cd35bc1eb818c7a9fb3047" -dependencies = [ - "devise_codegen", - "devise_core", -] - -[[package]] -name = "devise_codegen" -version = "0.3.0" -source = "git+https://github.com/SergioBenitez/Devise.git?rev=3648468#3648468a9ede9ca896cd35bc1eb818c7a9fb3047" -dependencies = [ - "devise_core", - "quote", -] - -[[package]] -name = "devise_core" -version = "0.3.0" -source = "git+https://github.com/SergioBenitez/Devise.git?rev=3648468#3648468a9ede9ca896cd35bc1eb818c7a9fb3047" -dependencies = [ - "bitflags", - "proc-macro2", - "proc-macro2-diagnostics", - "quote", - "syn 1.0.107", -] - -[[package]] -name = "difference" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "524cbf6897b527295dff137cec09ecf3a05f4fddffd7dfcd1585403449e74198" - -[[package]] -name = "discard" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "212d0f5754cb6769937f4501cc0e67f4f4483c8d2c3e1e922ee9edbe4ab4c7c0" - -[[package]] -name = "either" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90e5c1c8368803113bf0c9584fc495a58b86dc8a29edbf8fe877d21d9507e797" +checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" [[package]] name = "equivalent" @@ -261,20 +96,6 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" -[[package]] -name = "figment" -version = "0.10.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e56602b469b2201400dec66a66aec5a9b8761ee97cd1b8c96ab2483fcc16cc9" -dependencies = [ - "atomic", - "pear", - "serde", - "toml 0.5.11", - "uncased", - "version_check", -] - [[package]] name = "fnv" version = "1.0.7" @@ -292,9 +113,9 @@ dependencies = [ [[package]] name = "futures" -version = "0.3.25" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38390104763dc37a5145a53c29c63c1290b5d316d6086ec32c293f6736051bb0" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" dependencies = [ "futures-channel", "futures-core", @@ -307,9 +128,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.25" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ba265a92256105f45b719605a571ffe2d1f0fea3807304b522c1d778f79eed" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" dependencies = [ "futures-core", "futures-sink", @@ -317,15 +138,15 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.25" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04909a7a7e4633ae6c4a9ab280aeb86da1236243a77b694a49eacd659a4bd3ac" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" [[package]] name = "futures-executor" -version = "0.3.25" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7acc85df6714c176ab5edf386123fafe217be88c0840ec11f199441134a074e2" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" dependencies = [ "futures-core", "futures-task", @@ -334,38 +155,38 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.25" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00f5fb52a06bdcadeb54e8d3671f8888a39697dcb0b81b23b55174030427f4eb" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" [[package]] name = "futures-macro" -version = "0.3.25" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bdfb8ce053d86b91919aad980c220b1fb8401a9394410e1c289ed7e66b61835d" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ "proc-macro2", "quote", - "syn 1.0.107", + "syn 3.0.4", ] [[package]] name = "futures-sink" -version = "0.3.25" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39c15cf1a4aa79df40f1bb462fb39676d0ad9e366c2a33b590d7c66f4f81fcf9" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" [[package]] name = "futures-task" -version = "0.3.25" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ffb393ac5d9a6eaa9d3fdf37ae2776656b706e200c8e16b1bdb227f5198e6ea" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" [[package]] name = "futures-util" -version = "0.3.25" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "197676987abd2f9cadff84926f410af1c183608d36641465df73ae8211dc65d6" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-channel", "futures-core", @@ -375,93 +196,21 @@ dependencies = [ "futures-task", "memchr", "pin-project-lite", - "pin-utils", "slab", ] -[[package]] -name = "getrandom" -version = "0.1.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce" -dependencies = [ - "cfg-if", - "libc", - "wasi 0.9.0+wasi-snapshot-preview1", -] - -[[package]] -name = "gimli" -version = "0.31.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" - [[package]] name = "glob" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" -[[package]] -name = "h2" -version = "0.3.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f9f29bc9dda355256b2916cf526ab02ce0aeaaaf2bad60d65ef3f12f11dd0f4" -dependencies = [ - "bytes", - "fnv", - "futures-core", - "futures-sink", - "futures-util", - "http 0.2.8", - "indexmap 1.9.2", - "slab", - "tokio", - "tokio-util 0.7.4", - "tracing", -] - -[[package]] -name = "hashbrown" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" - [[package]] name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" -[[package]] -name = "hermit-abi" -version = "0.1.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" -dependencies = [ - "libc", -] - -[[package]] -name = "hermit-abi" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7" -dependencies = [ - "libc", -] - -[[package]] -name = "http" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75f43d41e26995c17e71ee126451dd3941010b0514a81a9d11f3b341debc2399" -dependencies = [ - "bytes", - "fnv", - "itoa", -] - [[package]] name = "http" version = "1.2.0" @@ -473,17 +222,6 @@ dependencies = [ "itoa", ] -[[package]] -name = "http-body" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1" -dependencies = [ - "bytes", - "http 0.2.8", - "pin-project-lite", -] - [[package]] name = "http-body" version = "1.0.1" @@ -491,7 +229,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" dependencies = [ "bytes", - "http 1.2.0", + "http", ] [[package]] @@ -502,8 +240,8 @@ checksum = "793429d76616a256bcb62c2a2ec2bed781c8307e797e2598c50010f2bee2544f" dependencies = [ "bytes", "futures-util", - "http 1.2.0", - "http-body 1.0.1", + "http", + "http-body", "pin-project-lite", ] @@ -519,30 +257,6 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421" -[[package]] -name = "hyper" -version = "0.14.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "034711faac9d2166cb1baf1a2fb0b60b1f277f8492fd72176c17f3515e1abd3c" -dependencies = [ - "bytes", - "futures-channel", - "futures-core", - "futures-util", - "h2", - "http 0.2.8", - "http-body 0.4.5", - "httparse", - "httpdate", - "itoa", - "pin-project-lite", - "socket2", - "tokio", - "tower-service", - "tracing", - "want", -] - [[package]] name = "hyper" version = "1.5.1" @@ -552,8 +266,8 @@ dependencies = [ "bytes", "futures-channel", "futures-util", - "http 1.2.0", - "http-body 1.0.1", + "http", + "http-body", "httparse", "httpdate", "itoa", @@ -570,24 +284,14 @@ checksum = "df2dcfbe0677734ab2f3ffa7fa7bfd4706bfdc1ef393f2ee30184aed67e631b4" dependencies = [ "bytes", "futures-util", - "http 1.2.0", - "http-body 1.0.1", - "hyper 1.5.1", + "http", + "http-body", + "hyper", "pin-project-lite", "tokio", "tower-service", ] -[[package]] -name = "indexmap" -version = "1.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1885e79c1fc4b10f0e172c475f458b7f7b93061064d98c3293e98c5ba0c8b399" -dependencies = [ - "autocfg", - "hashbrown 0.12.3", -] - [[package]] name = "indexmap" version = "2.14.1" @@ -595,22 +299,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07aa2048142242915a31d35844fb311e0e53fcca590c3a0a40dcf1b841fa09eb" dependencies = [ "equivalent", - "hashbrown 0.17.1", -] - -[[package]] -name = "inlinable_string" -version = "0.1.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8fae54786f62fb2918dcfae3d568594e50eb9b5c25bf04371af6fe7516452fb" - -[[package]] -name = "instant" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" -dependencies = [ - "cfg-if", + "hashbrown", ] [[package]] @@ -621,19 +310,9 @@ checksum = "fad582f4b9e86b6caa621cabeb0963332d92eea04729ab12892c2533951e6440" [[package]] name = "libc" -version = "0.2.168" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aaeb2981e0606ca11d79718f8bb01164f1d6ed75080182d3abf017e6d244b6d" - -[[package]] -name = "lock_api" -version = "0.4.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "435011366fe56583b16cf956f9df0095b405b82d76425bc8981c0e22e60ec4df" -dependencies = [ - "autocfg", - "scopeguard", -] +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "log" @@ -646,9 +325,9 @@ dependencies = [ [[package]] name = "matchit" -version = "0.7.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" [[package]] name = "memchr" @@ -662,108 +341,23 @@ version = "0.3.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d" -[[package]] -name = "miniz_oxide" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2d80299ef12ff69b16a84bb182e3b9df68b5a91574d3d4fa6e41b65deec4df1" -dependencies = [ - "adler2", -] - [[package]] name = "mio" -version = "0.8.11" +version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", - "wasi 0.11.0+wasi-snapshot-preview1", + "wasi", "windows-sys", ] -[[package]] -name = "num_cpus" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b" -dependencies = [ - "hermit-abi 0.2.6", - "libc", -] - -[[package]] -name = "object" -version = "0.36.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aedf0a2d09c573ed1d8d85b30c119153926a2b36dce0ab28322c09a117a4683e" -dependencies = [ - "memchr", -] - [[package]] name = "once_cell" version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f61fba1741ea2b3d6a1e3178721804bb716a68a6aeba1149b5d52e3d464ea66" -[[package]] -name = "output_vt100" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "628223faebab4e3e40667ee0b2336d34a5b960ff60ea743ddfdbcf7770bcfb66" -dependencies = [ - "winapi", -] - -[[package]] -name = "parking_lot" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99" -dependencies = [ - "instant", - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60a2cfe6f0ad2bfc16aefa463b497d5c7a5ecd44a23efa72aa342d90177356dc" -dependencies = [ - "cfg-if", - "instant", - "libc", - "redox_syscall", - "smallvec", - "winapi", -] - -[[package]] -name = "pear" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15e44241c5e4c868e3eaa78b7c1848cadd6344ed4f54d029832d32b415a58702" -dependencies = [ - "inlinable_string", - "pear_codegen", - "yansi", -] - -[[package]] -name = "pear_codegen" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82a5ca643c2303ecb740d506539deba189e16f2754040a42901cd8105d0282d0" -dependencies = [ - "proc-macro2", - "proc-macro2-diagnostics", - "quote", - "syn 1.0.107", -] - [[package]] name = "percent-encoding" version = "2.2.0" @@ -772,40 +366,20 @@ checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e" [[package]] name = "pin-project-lite" -version = "0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" - -[[package]] -name = "pin-utils" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" - -[[package]] -name = "ppv-lite86" version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" [[package]] name = "pretty_assertions" -version = "0.6.1" +version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f81e1644e1b54f5a68959a29aa86cde704219254669da328ecfdf6a1f09d427" +checksum = "3ae130e2f271fbc2ac3a40fb1d07180839cdbbe443c7a27e1e3c13c5cac0116d" dependencies = [ - "ansi_term", - "ctor", - "difference", - "output_vt100", + "diff", + "yansi", ] -[[package]] -name = "proc-macro-hack" -version = "0.5.20+deprecated" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" - [[package]] name = "proc-macro2" version = "1.0.92" @@ -815,19 +389,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "proc-macro2-diagnostics" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bf29726d67464d49fa6224a1d07936a8c08bb3fba727c7493f6cf1616fdaada" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.107", - "version_check", - "yansi", -] - [[package]] name = "quote" version = "1.0.37" @@ -837,250 +398,46 @@ dependencies = [ "proc-macro2", ] -[[package]] -name = "rand" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" -dependencies = [ - "getrandom", - "libc", - "rand_chacha", - "rand_core", - "rand_hc", -] - -[[package]] -name = "rand_chacha" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" -dependencies = [ - "ppv-lite86", - "rand_core", -] - -[[package]] -name = "rand_core" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" -dependencies = [ - "getrandom", -] - -[[package]] -name = "rand_hc" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" -dependencies = [ - "rand_core", -] - -[[package]] -name = "redox_syscall" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" -dependencies = [ - "bitflags", -] - -[[package]] -name = "ref-cast" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c78fb8c9293bcd48ef6fce7b4ca950ceaf21210de6e105a883ee280c0f7b9ed" -dependencies = [ - "ref-cast-impl", -] - -[[package]] -name = "ref-cast-impl" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f9c0c92af03644e4806106281fe2e068ac5bc0ae74a707266d06ea27bccee5f" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.107", -] - -[[package]] -name = "rocket" -version = "0.5.0-dev" -source = "git+https://github.com/SergioBenitez/Rocket?rev=c24f15c1#c24f15c18f02319be83af4f3c1951dc220b52c5e" -dependencies = [ - "async-trait", - "atomic", - "atty", - "binascii", - "either", - "figment", - "futures", - "log", - "memchr", - "num_cpus", - "parking_lot", - "rand", - "ref-cast", - "rocket_codegen", - "rocket_http", - "serde", - "state", - "time", - "tokio", - "ubyte", - "version_check", - "yansi", -] - -[[package]] -name = "rocket_codegen" -version = "0.5.0-dev" -source = "git+https://github.com/SergioBenitez/Rocket?rev=c24f15c1#c24f15c18f02319be83af4f3c1951dc220b52c5e" -dependencies = [ - "devise", - "glob", - "indexmap 1.9.2", - "quote", - "rocket_http", -] - -[[package]] -name = "rocket_http" -version = "0.5.0-dev" -source = "git+https://github.com/SergioBenitez/Rocket?rev=c24f15c1#c24f15c18f02319be83af4f3c1951dc220b52c5e" -dependencies = [ - "cookie", - "either", - "http 0.2.8", - "hyper 0.14.23", - "indexmap 1.9.2", - "log", - "mime", - "parking_lot", - "pear", - "percent-encoding", - "pin-project-lite", - "ref-cast", - "smallvec", - "state", - "time", - "tokio", - "uncased", - "unicode-xid", - "version_check", -] - -[[package]] -name = "rustc-demangle" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" - -[[package]] -name = "rustc_version" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" -dependencies = [ - "semver", -] - -[[package]] -name = "rustversion" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e819f2bc632f285be6d7cd36e25940d45b2391dd6d9b939e79de557f7014248" - [[package]] name = "ryu" version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b4b9743ed687d4b4bcedf9ff5eaa7398495ae14e61cba0a295704edbc7decde" -[[package]] -name = "scopeguard" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" - -[[package]] -name = "seamless" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95b4c0d07ce823cea659f69eb2d21b08d86f1e50de32e71c6d50e8bbf7821a13" -dependencies = [ - "async-trait", - "futures", - "http 1.2.0", - "seamless_macros 0.12.0", - "serde", - "serde_json", - "uuid", -] - [[package]] name = "seamless" -version = "0.13.0" +version = "0.14.0" dependencies = [ - "async-trait", "axum", "bytes", "futures", - "http 1.2.0", + "http", + "http-body-util", + "hyper", + "hyper-util", "pretty_assertions", - "rocket", - "seamless_macros 0.13.0", + "seamless_macros", "serde", "serde_json", "thiserror", "tokio", - "tokio-util 0.6.10", + "tokio-util", "trybuild", "uuid", ] [[package]] name = "seamless_macros" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad4ae64573f259d12aa88079a6df6dee47fc7eb00d9682d28f8e44add0deba3c" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.107", -] - -[[package]] -name = "seamless_macros" -version = "0.13.0" +version = "0.14.0" dependencies = [ "proc-macro2", "quote", - "seamless 0.12.0", + "seamless", "serde", "serde_json", "syn 3.0.4", ] -[[package]] -name = "semver" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" -dependencies = [ - "semver-parser", -] - -[[package]] -name = "semver-parser" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" - [[package]] name = "serde" version = "1.0.229" @@ -1155,30 +512,6 @@ dependencies = [ "serde", ] -[[package]] -name = "sha1" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1da05c97445caa12d05e848c4a4fcbbea29e748ac28f7e80e9b010392063770" -dependencies = [ - "sha1_smol", -] - -[[package]] -name = "sha1_smol" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae1a47186c03a32177042e55dbc5fd5aee900b8e0069a8d70fba96a9375cd012" - -[[package]] -name = "signal-hook-registry" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e51e73328dc4ac0c7ccbda3a494dfa03df1de2f46018127f60c693f2648455b0" -dependencies = [ - "libc", -] - [[package]] name = "slab" version = "0.4.7" @@ -1196,87 +529,12 @@ checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" [[package]] name = "socket2" -version = "0.4.10" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7916fc008ca5542385b89a3d3ce689953c143e9304a9bf8beec1de48994c0d" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "winapi", -] - -[[package]] -name = "standback" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e113fb6f3de07a243d434a56ec6f186dfd51cb08448239fe7bcae73f87ff28ff" -dependencies = [ - "version_check", -] - -[[package]] -name = "state" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3015a7d0a5fd5105c91c3710d42f9ccf0abfb287d62206484dcc67f9569a6483" - -[[package]] -name = "stdweb" -version = "0.4.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d022496b16281348b52d0e30ae99e01a73d737b2f45d38fed4edf79f9325a1d5" -dependencies = [ - "discard", - "rustc_version", - "stdweb-derive", - "stdweb-internal-macros", - "stdweb-internal-runtime", - "wasm-bindgen", -] - -[[package]] -name = "stdweb-derive" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c87a60a40fccc84bef0652345bbbbbe20a605bf5d0ce81719fc476f5c03b50ef" -dependencies = [ - "proc-macro2", - "quote", - "serde", - "serde_derive", - "syn 1.0.107", -] - -[[package]] -name = "stdweb-internal-macros" -version = "0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58fa5ff6ad0d98d1ffa8cb115892b6e69d67799f6763e162a1c9db421dc22e11" -dependencies = [ - "base-x", - "proc-macro2", - "quote", - "serde", - "serde_derive", - "serde_json", - "sha1", - "syn 1.0.107", -] - -[[package]] -name = "stdweb-internal-runtime" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "213701ba3370744dcd1a12960caa4843b3d68b4d1c0a5d575e0d65b2ee9d16c0" - -[[package]] -name = "syn" -version = "1.0.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f4064b5b16e03ae50984a5a8ed5d4f8803e6bc1fd170a3cda91a1be4b18e3f5" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", + "windows-sys", ] [[package]] @@ -1324,76 +582,33 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.38" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a9cd18aa97d5c45c6603caea1da6628790b37f7a34b6ca89522331c5180fed0" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.38" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fb327af4685e4d03fa8cbcf1716380da910eeb2bb8be417e7f9fd3fb164f36f" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.107", -] - -[[package]] -name = "time" -version = "0.2.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4752a97f8eebd6854ff91f1c1824cd6160626ac4bd44287f7f4ea2035a02a242" -dependencies = [ - "const_fn", - "libc", - "standback", - "stdweb", - "time-macros", - "version_check", - "winapi", -] - -[[package]] -name = "time-macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "957e9c6e26f12cb6d0dd7fc776bb67a706312e7299aed74c8dd5b17ebb27e2f1" -dependencies = [ - "proc-macro-hack", - "time-macros-impl", -] - -[[package]] -name = "time-macros-impl" -version = "0.1.2" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd3c141a1b43194f3f56a1411225df8646c55781d5f26db825b3d98507eb482f" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ - "proc-macro-hack", "proc-macro2", "quote", - "standback", - "syn 1.0.107", + "syn 3.0.4", ] [[package]] name = "tokio" -version = "1.29.1" +version = "1.53.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "532826ff75199d5833b9d2c5fe410f29235e25704ee5f0ef599fb51c21f4a4da" +checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e" dependencies = [ - "autocfg", - "backtrace", - "bytes", "libc", "mio", - "num_cpus", "pin-project-lite", - "signal-hook-registry", "socket2", "tokio-macros", "windows-sys", @@ -1401,13 +616,13 @@ dependencies = [ [[package]] name = "tokio-macros" -version = "2.1.0" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 3.0.4", ] [[package]] @@ -1425,36 +640,13 @@ dependencies = [ "tokio", ] -[[package]] -name = "tokio-util" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bb2e075f03b3d66d8d8785356224ba688d2906a371015e225beeb65ca92c740" -dependencies = [ - "bytes", - "futures-core", - "futures-sink", - "pin-project-lite", - "tokio", - "tracing", -] - -[[package]] -name = "toml" -version = "0.5.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234" -dependencies = [ - "serde", -] - [[package]] name = "toml" version = "1.1.5+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "12c0ba9680044b4ce98d391a62094047eada0d64860b80166c39f4a6b5640785" dependencies = [ - "indexmap 2.14.1", + "indexmap", "serde_core", "serde_spanned", "toml_datetime", @@ -1536,12 +728,6 @@ dependencies = [ "once_cell", ] -[[package]] -name = "try-lock" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3528ecfd12c466c6f163363caf2d02a71161dd5e1cc6ae7b34207ea2d42d81ed" - [[package]] name = "trybuild" version = "1.0.120" @@ -1554,25 +740,7 @@ dependencies = [ "serde_json", "target-triple", "termcolor", - "toml 1.1.5+spec-1.1.0", -] - -[[package]] -name = "ubyte" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c81f0dae7d286ad0d9366d7679a77934cfc3cf3a8d67e82669794412b2368fe6" -dependencies = [ - "serde", -] - -[[package]] -name = "uncased" -version = "0.9.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09b01702b0fd0b3fadcf98e098780badda8742d4f4a7676615cad90e8ac73622" -dependencies = [ - "version_check", + "toml", ] [[package]] @@ -1581,100 +749,18 @@ version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "84a22b9f218b40614adcb3f4ff08b703773ad44fa9423e4e0d346d5db86e4ebc" -[[package]] -name = "unicode-xid" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f962df74c8c05a667b5ee8bcf162993134c104e96440b663c8daa176dc772d8c" - [[package]] name = "uuid" version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "422ee0de9031b5b948b97a8fc04e3aa35230001a722ddd27943e0be31564ce4c" -[[package]] -name = "version_check" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" - -[[package]] -name = "want" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0" -dependencies = [ - "log", - "try-lock", -] - -[[package]] -name = "wasi" -version = "0.9.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" - [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" -[[package]] -name = "wasm-bindgen" -version = "0.2.83" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eaf9f5aceeec8be17c128b2e93e031fb8a4d469bb9c4ae2d7dc1888b26887268" -dependencies = [ - "cfg-if", - "wasm-bindgen-macro", -] - -[[package]] -name = "wasm-bindgen-backend" -version = "0.2.83" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c8ffb332579b0557b52d268b91feab8df3615f265d5270fec2a8c95b17c1142" -dependencies = [ - "bumpalo", - "log", - "once_cell", - "proc-macro2", - "quote", - "syn 1.0.107", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.83" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "052be0f94026e6cbc75cdefc9bae13fd6052cdcaf532fa6c45e7ae33a1e6c810" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.83" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07bc0c051dc5f23e307b13285f9d75df86bfdf816c5721e573dec1f9b8aa193c" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.107", - "wasm-bindgen-backend", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.83" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c38c045535d93ec4f0b4defec448e4291638ee608530863b1e2ba115d4fff7f" - [[package]] name = "winapi" version = "0.3.9" @@ -1707,135 +793,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] -name = "windows-sys" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" -dependencies = [ - "windows-targets 0.48.5", -] - -[[package]] -name = "windows-targets" -version = "0.48.5" +name = "windows-link" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" -dependencies = [ - "windows_aarch64_gnullvm 0.48.5", - "windows_aarch64_msvc 0.48.5", - "windows_i686_gnu 0.48.5", - "windows_i686_msvc 0.48.5", - "windows_x86_64_gnu 0.48.5", - "windows_x86_64_gnullvm 0.48.5", - "windows_x86_64_msvc 0.48.5", -] +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" [[package]] -name = "windows-targets" -version = "0.52.6" +name = "windows-sys" +version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ - "windows_aarch64_gnullvm 0.52.6", - "windows_aarch64_msvc 0.52.6", - "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm", - "windows_i686_msvc 0.52.6", - "windows_x86_64_gnu 0.52.6", - "windows_x86_64_gnullvm 0.52.6", - "windows_x86_64_msvc 0.52.6", + "windows-link", ] -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_i686_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - [[package]] name = "winnow" version = "1.0.4" @@ -1844,9 +815,9 @@ checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" [[package]] name = "yansi" -version = "0.5.1" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec" +checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" [[package]] name = "zmij" diff --git a/Cargo.toml b/Cargo.toml index e5f9738..fd4fd7e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,4 +3,40 @@ members = [ "seamless", "seamless-macros" ] -resolver = "2" \ No newline at end of file +resolver = "3" + +[workspace.package] +version = "0.14.0" +authors = ["James Wilson "] +edition = "2024" +license = "MIT" +repository = "https://github.com/jsdw/seamless" +categories = ["web-programming", "web-programming::http-server", "asynchronous"] +keywords = ["api", "http", "rpc", "json"] + +[workspace.dependencies] +# Workspace crates +seamless = { path = "seamless" } +seamless_macros = { version = "0.14.0", path = "seamless-macros" } + +# Dependencies +serde = { version = "1", features = ["derive"] } +serde_json = "1" +http = "1" +futures = "0.3.34" +bytes = "1" +uuid = "1" +syn = { version = "3", features = ["full", "extra-traits"] } +quote = "1" +proc-macro2 = "1" + +# Dev dependencies +trybuild = "1.0.120" +pretty_assertions = "1" +thiserror = "2" +tokio = { version = "1.1.0", features = ["rt", "rt-multi-thread", "macros", "net"] } +tokio-util = { version = "0.6.7", features = ["compat"] } +axum = { version = "0.8.9", features = ["macros"] } +hyper = { version = "1", features = ["server", "http1"] } +hyper-util = { version = "0.1", features = ["tokio"] } +http-body-util = "0.1" diff --git a/README.md b/README.md index 9b10c3e..503b8e2 100644 --- a/README.md +++ b/README.md @@ -1,33 +1,35 @@ # Seamless -[API Docs](https://docs.rs/seamless/latest/seamless) +[![Crates.io](https://img.shields.io/crates/v/seamless.svg)](https://crates.io/crates/seamless) +[![Docs.rs](https://img.shields.io/docsrs/seamless)](https://docs.rs/seamless) +[![CI](https://github.com/jsdw/seamless/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/jsdw/seamless/actions/workflows/ci.yml) -This library aims to provide an easy-to-use and extensible approach to declaring API routes, and will automatically -keep track of various information surrounding requests and responses so that detailed route information (including type -information) can be generated based on the current state of the API. +[See the examples](./seamless/examples/) -This library is fully async, but totally independent from any particular async implementation (you don't even need to -toggle any feature flags). +Seamless provides a way to declare a simple RPC style HTTP API, and from this declaration can hand back enough +information that we can generate a type safe HTTP client for interacting with it. -Using Seamless, we can write our API in pure Rust, and from that generate a TypeScript based API client (or just the types, -or just documentation) based on the current state of the API. This allows us to achieve type safe communication between the -API and TypeScript-like clients without relying on external specifications like OpenAPI. +Seamless supports async handlers and streaming HTTP requests, but is entirely HTTP framework and async framework +agnostic: it can be wired in to your frameworks of choice. For instance, you could use seamless to handle the +API routes in an Axum app and use normal Axum routes to serve other content alongside this API. -The typical steps for using this library are: +## How does it work? -- Annotate your input and output types for these routes with the [`macro@ApiBody`] macro. -- Derive [`macro@ApiError`] (or manually implement `Into`) on any errors you wish to emit. -- Declare each of your API routes using this library. API handlers can just ask for whatever they need as a - function parameter, including arbitrary state or information based on the incoming request (you decide). -- Once the API routes are declared, use [`Api::info()`] to obtain enough information about the API to - generate fully type safe client code (the information is optimised towards generating TypeScript types/code). -- Integrate this API with something like `warp` or `rocket` so that your `seamless` API routes can live alongside - everything else that you'd like to serve (see the examples for how this can be done). +Each API route that you wish to create exists at some path, and is given a handler function which can expect +a specific shape of request body, and will return a specific shape of response, or else an error if things go wrong. -Have a look at the examples in the `examples` directory to get a proper feel for how this library can be used, or -keep reading! +The expected body and response types must implement the `ApiBody` trait, and any errors that are +used must convert into an `ApiError`. Both can be derived via the provided macros, which under the +hood will: +- Implement the `serde::Serialize` and `serde::Deserialize` traits so that we can receive and respond with + values of the given types. +- Implement `ApiBody` or `Into` so that we know the shape of the incoming and + outgoing types, and how any given error should be presented to the client and with what status code. -# A Basic Example +See the `seamless/examples` folder in the crate repository for working examples demonstrating how to use +seamless with both Hyper and Axum, as well as a couple of more basic examples. + +## A Basic Example Below is a basic self contained example of using this library. @@ -38,17 +40,15 @@ use seamless::{ handler::{ body::FromJson, request::Bytes, response::ToJson } }; -// The API relies on types that have been annotated with `ApiBody` (request and response -// types) or `ApiError` (for any errors we might give back). These annotations do some -// reflection to allow us to get information about the shape of the type and doc comments -// added to it, as well as ensuring that they can be Serialized/Deserialized. - +// This is an input to one of our API routes. We annotate it with the ApiBody +// macro so that it can be worked with by seamless as a request or response body. #[ApiBody] struct DivisionInput { a: usize, b: usize } +// We do the same for the type we expect to hand back in a successful response #[ApiBody] #[derive(PartialEq)] struct DivisionOutput { @@ -57,9 +57,10 @@ struct DivisionOutput { result: usize } -// Any errors that we return must implement `Into`, Display and Debug. We can derive -// `ApiError` to automate this for us. Here we use `thiserror` to derive the Display impl -// for us. See the documentation on the `ApiError` macro for more info. +// If we'd like to return a specific error from one of our API routes, we annotate it +// with ApiError, as well as expecting it to be displayable. This allows seamless to +// set the correct HTTP status code given the error returned, and return them in a +// consistent way. #[derive(ApiError, Debug, thiserror::Error, PartialEq)] enum MathsError { #[error("Division by zero")] @@ -69,9 +70,10 @@ enum MathsError { let mut api = Api::new(); -// We add routes to our new API like so. The handler functions would often be defined -// separately and called from this handler. Handler functions can be async or sync, and can -// return any valid handler::HandlerResponse. +// Now, let's define some routes for our API. Handler functions can be async or sync, +// and can return any valid handler::HandlerResponse. Here we use `ToJson` to return +// JSON responses, and in one case return a Result which is either the error we defined +// above, or the response type we defined above. api.add("/echo") .description("Echoes back a JSON string") .handler(|body: FromJson| ToJson(body.0)); @@ -92,16 +94,238 @@ api.add("/maths.divide") // Once we've added routes to the `api`, we use it by sending `http::Request`s to it. // Since we're expecting JSON to be provided, we need to remember to set the correct -// content-type: - +// content-type so that our FromJson input tries to decode it as valid JSON. let req = Request::post("/maths.divide") .header("content-type", "application/json") .body(Bytes::from_vec(serde_json::to_vec(&DivisionInput { a: 20, b: 10 }).unwrap())) .unwrap(); assert_eq!( - api.handle(req).await.unwrap().into_body(), + api.handle(req).await.unwrap().into_body().into_vec().await.unwrap(), serde_json::to_vec(&DivisionOutput{ a: 20, b: 10, result: 2 }).unwrap() ); ``` -Check out the [API Docs](https://docs.rs/seamless/latest/seamless) for lots more information, or take a look at the examples. +## State + +Most real life use cases will require some sort of state to be accessible inside a handler. + +This library follows an approach a little similar to `Axum`. Any type that implements the +`handler::HandlerParam` trait can be passed into handler functions. Using this trait, you can +inspect the request to do things like obtain user information from a session ID, or you can pull +state out of the `Request` object that was placed there prior to it being handed to this library. + +Here's an example: + +```rust +use seamless::{ + api::{ Api, ApiBody, ApiError }, + handler::{ HandlerParam, body::FromJson, request::Bytes, response::ToJson }, +}; + +// Some example state we want to inject into our handler. +#[derive(Clone)] +struct State { value: usize }; + +// Teach the library how to get hold of our "State" value when asked for it. +impl HandlerParam for State { + type Error = ApiError; + async fn handler_param(req: &http::Request<()>) -> Result { + let state: State = req.extensions().get::() + .expect("State must be injected into the request") + .clone(); + Ok(state) + } +} + +let mut api = Api::new(); + +// We can now ask for `State` as a parameter to the handler, as well as the HTTP body, +// which we extract as JSON using `FromJson`. We must always ask for the body last. +api.add("/echo") + .description("Echoes back a JSON string, plus our state value") + .handler(|state: State, body: FromJson| ToJson(format!("{}, {}", body.0, state.value))); + +// Now, to demo it, we build an HTTP request to send to this route. +let mut req = http::Request::post("/echo") + .header("content-type", "application/json") + .body(Bytes::from_vec(serde_json::to_vec("hello").unwrap())) + .unwrap(); + +// When passing a request into our API, remember to inject `State` too so that +// it's available for our `HandlerParam` trait to extract when asked for. +req.extensions_mut().insert(State { value: 123 }); + +// We can now handle a request that is expecting our `State` to be available. +// The response comes back as a JSON string. +let res = api.handle(req).await.unwrap().into_body().into_vec().await.unwrap(); +assert_eq!(res, "\"hello, 123\"".as_bytes()); +``` + +**Note**: params implementing the `handler::HandlerParam` trait must come before the optional final param +that implements `handler::HandlerBody`. Params are resolved in order, with the first failure short circuiting +the rest. + +## Extracting the request body + +To extract the body from a request, the last parameter passed to a handler must implement `handler::HandlerBody`. +At most one such parameter can be provided to a handler (providing more than 1 will lead to a compile error). If no +parameter implementing `handler::HandlerBody` is provided to a handler, it's assumed that the request method will +be GET, and any body will be ignored. + +Two built-in types that implement `handler::HandlerBody` exist for convenience: + +- `handler::body::FromJson` will assume that the request body is valid JSON that decodes to the type `T` + (or fail with a 400 if not). +- `handler::body::FromBinary` will give you back the request body exactly as it was provided. + +## Responding + +Responses from handlers can be plain old synchronous objects or `std::future::Future`s. The value returned +in either case must implement `handler::HandlerResponse`. This trait determines how to create the response to +hand back to the user. + +For convenience, a couple of types are provided which implement this trait: + +- `handler::response::ToJson` will encode the response as JSON. +- `handler::response::ToBinary` will respond with arbitrary bytes, which can be streamed back (from a + `futures::Stream` or `futures::AsyncRead`) rather than loaded into memory all at once. Note that errors + which occur partway through streaming a response can't be turned into an `api::ApiError`, because the + response status will already have been sent. + +Responses handed back from `Api::handle()` have a `handler::response::Body`. This is either a set of bytes that +are entirely in memory, or a stream of chunks of bytes, and can be handed over to whichever HTTP framework you're +using without needing to buffer streaming responses (see the examples folder for how this is done in Axum and Hyper). + +`handler::HandlerResponse` is also implemented for `Option`s and `Result`s, returning a 404 in the event that the +`Option` is `None`, and returning the error from the `Result` (this must itself implement `Into`) in the +event that the `Result` is `Err`. + +## Info + +At some point, you'll probably want to get information about the shape of the API so that you can go +and generate a typed API client (this is, after all, the main selling point of this library). To do this, +use the `Api::info()` function. + +Probably the best way to see what shapes this info can take is by looking at `api/info.rs`. + +Here's an example: + +```rust +use seamless::{ + api::{ Api, ApiBody, ApiError }, + handler::{ body::FromJson, response::ToJson }, +}; +use serde_json::json; + +#[derive(ApiError, Debug, thiserror::Error)] +enum MathsError { + #[error("Division by zero")] + #[api_error(external, code=400)] + DivideByZero +} + +/// Input consisting of two numbers +#[ApiBody] +struct BinaryInput { + /// Input 'a' + a: usize, + /// Input 'b' + b: usize +} + +/// Output containing the original input and result +#[ApiBody] +#[derive(PartialEq)] +struct BinaryOutput { + a: usize, + b: usize, + /// The result + result: usize +} + +async fn divide(input: BinaryInput) -> Result,MathsError> { + todo!() +} + +// A small API with one route: +let mut api = Api::new(); +api.add("maths/divide") + .description("Divide two numbers by each other") + .handler(|FromJson(body)| divide(body)); + +// Get info about this API: +let info = api.info(); + +// Here's what this will look like when serialized to JSON: +let info_json = json!([ + { + "name": "maths/divide", + "description": "Divide two numbers by each other", + "method": "POST", + "request_type": { + "description": "Input consisting of two numbers", + "shape": { + "type": "Object", + "keys": { + "a": { + "description": "Input 'a'", + "shape": { "type": "Number" } + }, + "b": { + "description": "Input 'b'", + "shape": { "type": "Number" } + } + } + } + }, + "response_type": { + "description": "Output containing the original input and result", + "shape": { + "type": "Object", + "keys": { + "a": { + "description": "", + "shape": { "type": "Number" } + }, + "b": { + "description": "", + "shape": { "type": "Number" } + }, + "result": { + "description": "The result", + "shape": { "type": "Number" } + } + } + } + } + } +]); +``` + +The "shape" object can have one of the following "type" literals: `String`, `Number`, `Boolean`, `Null`, +`Any`, `Unknown`, `Binary`, `ArrayOf`, `TupleOf`, `ObjectOf`, `Object`, `OneOf`, `StringLiteral`, `Optional`. Some +of these will come with an additional property. See `ApiBodyType` to get a better feel for exactly what the possible +responses can be. + +## Integrating with other libraries + +Instead of passing requests in manually, you'll probably want to attach an API you define here to a library like +`Axum` (or perhaps just plain old `Hyper`) so that you can benefit from the full power and flexibility +of a well rounded HTTP library alongside your well typed `seamless` API, and actually make the API available +externally. + +See `examples/axum.rs` and `examples/hyper.rs` for examples of how you might integrate this library with those. +Essentially it boils down to being able to construct an `http::Request` from whatever input the library gives you +access to, and being able to handle the `http::Response` or error that's handed back from Seamless. + +## Limitations + +Seamless is designed to make it easy to create simple RPC style JSON APIs that can be "seamlessly" typed from client +to server without using external tools like OpenAPI. + +- Seamless has not been optimised for building RESTful style APIs. However, the `handler::HandlerBody` and + `handler::HandlerParam` traits in particular provide a bunch of extensibility. +- Some of the flexibility that `Serde` provides for manipulating how types are serialized and deserialized is not + available. This library takes the approach of 'wrapping' serde using the `ApiBody` macro to deliberately restrict + how you can transform types, ensuring that any transformations allowed are properly supported and lead to the correct + type information being generated. diff --git a/seamless-macros/Cargo.toml b/seamless-macros/Cargo.toml index 17d50e6..2b53910 100644 --- a/seamless-macros/Cargo.toml +++ b/seamless-macros/Cargo.toml @@ -1,27 +1,27 @@ [package] name = "seamless_macros" -version = "0.13.0" -authors = ["James Wilson "] -edition = "2024" -license = "MIT" readme = "README.md" -repository = "https://github.com/jsdw/seamless" -categories = ["web-programming", "web-programming::http-server", "asynchronous"] -keywords = ["api", "http", "rpc", "json"] description = """ Macros to complement the 'seamless' library """ +version.workspace = true +authors.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +categories.workspace = true +keywords.workspace = true + [lib] proc-macro = true [dependencies] -syn = { version = "3", features = ["full", "extra-traits"] } -quote = "1" -proc-macro2 = "1" +syn.workspace = true +quote.workspace = true +proc-macro2.workspace = true [dev-dependencies] -# All for doc examples (seamless is a lower version to allow publishing) -seamless = { version = "0.12.0" } -serde = { version = "1", features = ["derive"] } -serde_json = "1" +seamless.workspace = true +serde.workspace = true +serde_json.workspace = true diff --git a/seamless-macros/src/body/attrs.rs b/seamless-macros/src/body/attrs.rs index 0d70d77..1b85661 100644 --- a/seamless-macros/src/body/attrs.rs +++ b/seamless-macros/src/body/attrs.rs @@ -1,17 +1,15 @@ +#[derive(Default)] pub struct Props { pub docs: String, pub tag: Option, pub flatten: bool, + pub optional: bool, } -pub static NAME: &str = "api_body"; +pub const NAME: &str = "api_body"; pub fn parse(attrs: &[syn::Attribute]) -> syn::Result { - let mut props = Props { - docs: String::new(), - tag: None, - flatten: false, - }; + let mut props = Props::default(); for attr in attrs { // If the attr is serde based, error! not allowed @@ -30,7 +28,7 @@ pub fn parse(attrs: &[syn::Attribute]) -> syn::Result { props.docs.push_str(&doc); } - // Ignore attrs we don't care about and copy them for output + // Ignore attrs that aren't ours: if !attr.path().is_ident(NAME) { continue; } @@ -43,6 +41,8 @@ pub fn parse(attrs: &[syn::Attribute]) -> syn::Result { props.tag = Some(lit_string(&value?.parse()?)?); } else if path.is_ident("flatten") { props.flatten = true; + } else if path.is_ident("optional") { + props.optional = true; } else { return Err(syn::Error::new_spanned(path, "unrecognized attribute")); } diff --git a/seamless-macros/src/body/fields.rs b/seamless-macros/src/body/fields.rs index b2df161..4558a46 100644 --- a/seamless-macros/src/body/fields.rs +++ b/seamless-macros/src/body/fields.rs @@ -17,30 +17,44 @@ impl Fields { pub fn from_syn(fields: syn::Fields) -> syn::Result { match fields { syn::Fields::Unnamed(fields) => { - if fields.unnamed.len() == 1 { - let field = process_field(fields.unnamed[0].clone()); - Ok(Fields::Single(field?)) + let mut fields = process_fields(fields.unnamed, false)?; + if fields.len() == 1 { + Ok(Fields::Single(fields.remove(0))) } else { - let fields = process_fields(fields.unnamed); - Ok(Fields::Unnamed(fields?)) + Ok(Fields::Unnamed(fields)) } } - syn::Fields::Named(fields) => { - let fields = process_fields(fields.named); - Ok(Fields::Named(fields?)) - } + syn::Fields::Named(fields) => Ok(Fields::Named(process_fields(fields.named, true)?)), syn::Fields::Unit => Ok(Fields::Unit), } } } -fn process_fields(fields: impl IntoIterator) -> syn::Result> { - fields.into_iter().map(process_field).collect() +fn process_fields( + fields: impl IntoIterator, + named: bool, +) -> syn::Result> { + fields + .into_iter() + .map(|f| process_field(f, named)) + .collect() } -fn process_field(field: syn::Field) -> syn::Result { - match attrs::parse(&field.attrs) { - Ok(attr_props) => Ok(Field { attr_props, field }), - Err(e) => Err(e), +fn process_field(field: syn::Field, named: bool) -> syn::Result { + let attr_props = attrs::parse(&field.attrs)?; + if attr_props.optional { + if !named { + return Err(syn::Error::new_spanned( + &field, + "#[api_body(optional)] can only be used on named fields", + )); + } + if attr_props.flatten { + return Err(syn::Error::new_spanned( + &field, + "the `optional` and `flatten` attrs cannot be used together", + )); + } } + Ok(Field { attr_props, field }) } diff --git a/seamless-macros/src/body/mod.rs b/seamless-macros/src/body/mod.rs index 4d99c86..97c1175 100644 --- a/seamless-macros/src/body/mod.rs +++ b/seamless-macros/src/body/mod.rs @@ -3,12 +3,19 @@ mod fields; use fields::{Field, Fields}; use proc_macro::TokenStream; -use proc_macro2::{Span, TokenStream as TokenStream2}; +use proc_macro2::TokenStream as TokenStream2; use quote::{quote, quote_spanned}; -use syn::{parse::Parser, punctuated::Punctuated}; +use syn::{ext::IdentExt, parse::Parser, punctuated::Punctuated}; -static CRATE_NAME_STR: &str = "seamless"; -static VARIANT_DESCRIPTION: &str = "Variant tag"; +const DEFAULT_TAG: &str = "kind"; +const VARIANT_DESCRIPTION: &str = "Variant tag"; + +/// The name serde uses for this identifier on the wire. Raw identifiers +/// lose their prefix, so `r#type` becomes `"type"`. Only use this for strings +/// describing the JSON; generated Rust code still needs the original `Ident`. +fn wire_name(ident: &syn::Ident) -> String { + ident.unraw().to_string() +} #[derive(Debug)] pub struct Attrs { @@ -17,183 +24,146 @@ pub struct Attrs { } pub fn parse_top_attrs(attrs: TokenStream) -> Attrs { - let attrs = Punctuated::::parse_terminated + let idents = Punctuated::::parse_terminated .parse(attrs) .expect("Invalid Api attributes provided"); - // If Serialize or Deserialize attrs given, only - // do that one. If none given, do both. - let mut se = false; - let mut de = false; - for ident in attrs { - if ident == "Serialize" { - se = true - } else if ident == "Deserialize" { - de = true - } - } - if !se && !de { - se = true; - de = true; + // If Serialize or Deserialize attrs given, only do that one. If none given, do both. + let serialize = idents.iter().any(|ident| ident == "Serialize"); + let deserialize = idents.iter().any(|ident| ident == "Deserialize"); + if !serialize && !deserialize { + return Attrs { + serialize: true, + deserialize: true, + }; } Attrs { - serialize: se, - deserialize: de, + serialize, + deserialize, } } pub fn parse_enum(e: syn::ItemEnum, attrs: Attrs) -> syn::Result { - let crate_name: syn::Ident = syn::Ident::new(CRATE_NAME_STR, Span::call_site()); + let api = crate::seamless_api(); let ident = e.ident.clone(); - let top_level_attr_props = attrs::parse(&e.attrs)?; - let serde_tag = top_level_attr_props.tag.unwrap_or("kind".to_owned()); - let top_level_docs = top_level_attr_props.docs; + let top_level_props = attrs::parse(&e.attrs)?; + let serde_tag = top_level_props + .tag + .unwrap_or_else(|| DEFAULT_TAG.to_owned()); + let top_level_docs = top_level_props.docs; - // Errors we can return during iteration: - let tuple_variants_not_allowed = - || syn::Error::new_spanned(&ident, "Enum tuple variants are not allowed"); - let unit_and_nonunit_cant_be_mixed = - || syn::Error::new_spanned(&ident, "Unit enum fields can't be mixed with named fields"); + // Enums with only unit variants are (de)serialized to plain strings, and other enums are + // tagged like { "kind": "Bar", ...otherfields }, so the two kinds of variant can't be mixed. + let is_unit = |variant: &syn::Variant| matches!(variant.fields, syn::Fields::Unit); + let all_unit = e.variants.iter().all(is_unit); + if !all_unit && e.variants.iter().any(is_unit) { + return Err(syn::Error::new_spanned( + &ident, + "Unit enum fields can't be mixed with named fields", + )); + } - // Iterate variants and generate the inner TypeScript impl for each: - let mut ts_impl_variants = vec![]; - let mut seen_unit_fields = false; - let mut seen_nonunit_fields = false; - for variant in e.variants.iter() { - let variant_ident = &variant.ident; - let variant_ident_string = variant_ident.to_string(); - let attr_props = attrs::parse(&variant.attrs)?; - let variant_docs = attr_props.docs; + // Describe each variant: + let mut variant_infos = Vec::new(); + for variant in &e.variants { + let variant_name = wire_name(&variant.ident); + let variant_docs = attrs::parse(&variant.attrs)?.docs; - // What fields does our enum have in it? - let token_stream = match Fields::from_syn(variant.fields.clone())? { - // Unnamed multiple fields aren't allowed because how do we tag - // them with an inner prop eg "kind": "bar". - Fields::Unnamed(..) => return Err(tuple_variants_not_allowed()), - // Unit fields (no values) can't live alongside other types; enums with _only_ - // unit fields will be flattened, and enums with no unit fields will be tagged - // like { "kind": "Bar", ...otherfields }. - Fields::Unit => { - // Disallow unit + names variants living side by side - seen_unit_fields = true; - if seen_nonunit_fields { - return Err(unit_and_nonunit_cant_be_mixed()); - } + // The type of the tag field, eg "kind": "Bar": + let tag_info = quote! { + #api::ApiBodyInfo { + description: #VARIANT_DESCRIPTION.to_owned(), + ty: #api::ApiBodyType::StringLiteral { literal: #variant_name.to_owned() }, + } + }; - quote! {{ - ::#crate_name::api::ApiBodyInfo { - description: #variant_docs.to_owned(), - ty: ::#crate_name::api::ApiBodyType::StringLiteral{ literal: #variant_ident_string.to_owned() } - } - }} + let variant_info = match Fields::from_syn(variant.fields.clone())? { + // Tuple variants aren't allowed, because how would we tag them with + // an inner prop eg "kind": "bar"? + Fields::Unnamed(..) => { + return Err(syn::Error::new_spanned( + &ident, + "Enum tuple variants are not allowed", + )); } - // Single fields are treated like the inner version, but we need to remember - // to apply our tag to them too. Only inner types that are structs are allowed. - Fields::Single(f) => { - // Disallow unit + names variants living side by side - seen_nonunit_fields = true; - if seen_unit_fields { - return Err(unit_and_nonunit_cant_be_mixed()); + // Unit variants are just the string literal: + Fields::Unit => quote! { + #api::ApiBodyInfo { + description: #variant_docs.to_owned(), + ty: #api::ApiBodyType::StringLiteral { literal: #variant_name.to_owned() }, } - + }, + // Single fields are treated like the inner struct, with our tag added to it. + // Only inner types that are structs are allowed. + Fields::Single(f) => { let ty = &f.field.ty; + // If no variant docs, use the inner struct docs instead: + let description = if variant_docs.is_empty() { + quote! { s.description } + } else { + quote! { #variant_docs.to_owned() } + }; quote! {{ - let mut s = <#ty as ::#crate_name::api::ApiBodyStruct>::api_body_struct_info(); - s.struc.insert(#serde_tag.to_owned(), ::#crate_name::api::ApiBodyInfo { - description: #VARIANT_DESCRIPTION.to_owned(), - ty: ::#crate_name::api::ApiBodyType::StringLiteral{ literal: #variant_ident_string.to_owned() } - }); - let mut t = ::#crate_name::api::ApiBodyInfo { - description: #variant_docs.to_owned(), - ty: ::#crate_name::api::ApiBodyType::Object{ keys: s.struc } - }; - // If no variant docs, use the inner struct docs instead: - if t.description.len() == 0 { t.description = s.description } - t + let s = <#ty as #api::ApiBodyStruct>::api_body_struct_info(); + let mut keys = s.fields; + keys.insert(#serde_tag.to_owned(), #tag_info); + #api::ApiBodyInfo { + description: #description, + ty: #api::ApiBodyType::Object { keys }, + } }} } - // Named fields are merged with the variant tag: + // Named fields are merged with the tag: Fields::Named(fields) => { - // Disallow unit + names variants living side by side - seen_nonunit_fields = true; - if seen_unit_fields { - return Err(unit_and_nonunit_cant_be_mixed()); - } - - // Generate impl for each field: - let entries = fields - .iter() - .map(|f| { - let name = f.field.ident.as_ref().unwrap().to_string(); - let f = quote_field(f); - quote! { m.insert(#name.to_owned(), #f); } - }) - .collect::>(); - - // Generate a match arm for this variant: + let entries = fields.iter().map(|f| { + let name = wire_name(f.field.ident.as_ref().unwrap()); + let info = quote_field(f); + quote! { keys.insert(#name.to_owned(), #info); } + }); quote! {{ - let mut m = std::collections::HashMap::new(); - m.insert(#serde_tag.to_owned(), ::#crate_name::api::ApiBodyInfo { - description: #VARIANT_DESCRIPTION.to_owned(), - ty: ::#crate_name::api::ApiBodyType::StringLiteral{ literal: #variant_ident_string.to_owned() } - }); + let mut keys = std::collections::HashMap::new(); + keys.insert(#serde_tag.to_owned(), #tag_info); #(#entries)* - ::#crate_name::api::ApiBodyInfo { + #api::ApiBodyInfo { description: #variant_docs.to_owned(), - ty: ::#crate_name::api::ApiBodyType::Object{ keys: m } + ty: #api::ApiBodyType::Object { keys }, } }} } }; - ts_impl_variants.push(token_stream); + variant_infos.push(variant_info); } - // Do we want to generate the serialize and deserialize impl? - let serialize_toks = if attrs.serialize { - quote! { #[derive(::#crate_name::serde::Serialize)] } - } else { - TokenStream2::new() - }; - let deserialize_toks = if attrs.deserialize { - quote! { #[derive(::#crate_name::serde::Deserialize)] } - } else { - TokenStream2::new() - }; + let serde_tag_attr = (!all_unit).then(|| quote! { #[serde(tag = #serde_tag)] }); - // Do we want to tag our enum? We tag when all fields are named, - // and don't tag when all fields are unit. We shouldn't have a mix by here. - let serde_tag_attr = if seen_nonunit_fields { - quote! { #[serde(tag = #serde_tag)] } - } else { - TokenStream2::new() - }; - - // "api_body" tag attr, if used, needs stripping before we output the enum: - let mut sanitized_e = e; - sanitized_e - .attrs - .retain(|attr| !attr.path().is_ident(attrs::NAME)); + // Replace our "api_body" attrs with corresponding serde attrs: + let mut item = e; + item.attrs.retain(|attr| !attr.path().is_ident(attrs::NAME)); + for field in item.variants.iter_mut().flat_map(|v| v.fields.iter_mut()) { + let props = attrs::parse(&field.attrs)?; + if props.flatten { + let msg = "#[api_body(flatten)] can't be used on enum variant fields"; + return Err(syn::Error::new_spanned(field, msg)); + } + replace_with_serde_attrs(field, &props); + } - // We tell serde where to look for its crate contents (otherwise it expects `serde::*` - // to exist, which it might not.) - let serde_crate_path = format!("::{}::serde", crate_name); + let serde_attrs = serde_attrs(&attrs); Ok(quote! { - #serialize_toks - #deserialize_toks - #[serde(crate = #serde_crate_path)] + #serde_attrs #serde_tag_attr - #sanitized_e + #item - impl ::#crate_name::api::ApiBody for #ident { - fn api_body_info() -> ::#crate_name::api::ApiBodyInfo { - ::#crate_name::api::ApiBodyInfo { + impl #api::ApiBody for #ident { + fn api_body_info() -> #api::ApiBodyInfo { + #api::ApiBodyInfo { description: #top_level_docs.to_owned(), - ty: ::#crate_name::api::ApiBodyType::OneOf{ - values:vec![ #(#ts_impl_variants),* ] - } + ty: #api::ApiBodyType::OneOf { + values: vec![#(#variant_infos),*], + }, } } } @@ -201,143 +171,163 @@ pub fn parse_enum(e: syn::ItemEnum, attrs: Attrs) -> syn::Result { } pub fn parse_struct(s: syn::ItemStruct, attrs: Attrs) -> syn::Result { - let crate_name: syn::Ident = syn::Ident::new(CRATE_NAME_STR, Span::call_site()); - let ident = s.ident.clone(); - - let top_level_attr_props = attrs::parse(&s.attrs)?; - let top_level_docs = top_level_attr_props.docs; + let api = crate::seamless_api(); + let ident = &s.ident; + let docs = attrs::parse(&s.attrs)?.docs; - // Iterate struct and generate the TypeScript impl: - let ts_impl = match Fields::from_syn(s.fields.clone())? { - // serde deserialises to inner val + let api_body_impl = match Fields::from_syn(s.fields.clone())? { + // Newtype structs (de)serialize to their inner value: Fields::Single(f) => { - let field_toks = quote_field(&f); + let info = with_docs(quote_field(&f), &docs); quote! { - impl ::#crate_name::api::ApiBody for #ident { - fn api_body_info() -> ::#crate_name::api::ApiBodyInfo { - let mut t = #field_toks; - let d = #top_level_docs; - if d.len() > 0 { t.description = d.to_owned() } - t + impl #api::ApiBody for #ident { + fn api_body_info() -> #api::ApiBodyInfo { + #info } } } } - // serde deserialises to [val1, val2..] + // Tuple structs (de)serialize to [val1, val2, ..]: Fields::Unnamed(fields) => { - let types = fields.iter().map(quote_field).collect::>(); + let values = fields.iter().map(quote_field); quote! { - impl ::#crate_name::api::ApiBody for #ident { - fn api_body_info() -> ::#crate_name::api::ApiBodyInfo { - ::#crate_name::api::ApiBodyInfo { - description: #top_level_docs.to_owned(), - ty: ::#crate_name::api::ApiBodyType::TupleOf { - values: vec![ #( #types ),* ] - } + impl #api::ApiBody for #ident { + fn api_body_info() -> #api::ApiBodyInfo { + #api::ApiBodyInfo { + description: #docs.to_owned(), + ty: #api::ApiBodyType::TupleOf { + values: vec![#(#values),*], + }, } } } } } - // serde deserializes to { key: ty,... }. We also impl a - // special ApiStruct trait, which we can try using - // in the enum variant to ensure that we have named structs. + // Structs with named fields (de)serialize to { key: value, .. }. We also implement + // ApiBodyStruct for them, so that they can be flattened into other structs and used + // in newtype enum variants. Fields::Named(fields) => { let entries = fields.iter().map(|f| { - let flatten = f.attr_props.flatten; - if flatten { - // Get the field struct info and append all sub things to the map: + if f.attr_props.flatten { + // Merge the fields of the flattened struct into ours: let ty = &f.field.ty; - quote!{{ - let s = <#ty as ::#crate_name::api::ApiBodyStruct>::api_body_struct_info(); - for (key, val) in s.struc.into_iter() { m.insert(key, val); } - }} + quote! { + fields.extend(<#ty as #api::ApiBodyStruct>::api_body_struct_info().fields); + } } else { - // Just append the api_body info for the field to the map: - let name = f.field.ident.as_ref().unwrap().to_string(); - let f = quote_field(f); - quote!{ m.insert(#name.to_owned(), #f); } + let name = wire_name(f.field.ident.as_ref().unwrap()); + let info = quote_field(f); + quote! { fields.insert(#name.to_owned(), #info); } } - }).collect::>(); + }); quote! { - impl ::#crate_name::api::ApiBodyStruct for #ident { - fn api_body_struct_info() -> ::#crate_name::api::ApiBodyStructInfo { - let mut m = std::collections::HashMap::new(); + impl #api::ApiBodyStruct for #ident { + fn api_body_struct_info() -> #api::ApiBodyStructInfo { + let mut fields = std::collections::HashMap::new(); #(#entries)* - ::#crate_name::api::ApiBodyStructInfo { - description: #top_level_docs.to_owned(), - struc: m + #api::ApiBodyStructInfo { + description: #docs.to_owned(), + fields, } } } - impl ::#crate_name::api::ApiBody for #ident { - fn api_body_info() -> ::#crate_name::api::ApiBodyInfo { - let s = <#ident as ::#crate_name::api::ApiBodyStruct>::api_body_struct_info(); - ::#crate_name::api::ApiBodyInfo { + impl #api::ApiBody for #ident { + fn api_body_info() -> #api::ApiBodyInfo { + let s = ::api_body_struct_info(); + #api::ApiBodyInfo { description: s.description, - ty: ::#crate_name::api::ApiBodyType::Object { keys: s.struc } + ty: #api::ApiBodyType::Object { keys: s.fields }, } } } } } - // Not allowed - Fields::Unit => { - quote_spanned! {s.ident.span() => - compile_error!("TypeScript: unit structs are not supported") - } - } - }; - - // Do we want to generate the serialize and deserialize impl? - let serialize_toks = if attrs.serialize { - quote! { #[derive(::#crate_name::serde::Serialize)] } - } else { - TokenStream2::new() - }; - let deserialize_toks = if attrs.deserialize { - quote! { #[derive(::#crate_name::serde::Deserialize)] } - } else { - TokenStream2::new() + Fields::Unit => quote_spanned! {ident.span() => + compile_error!("ApiBody: unit structs are not supported"); + }, }; - // "api_body" tag attr, if used, needs stripping before we output the enum: - let mut sanitized_s = s; - for field in sanitized_s.fields.iter_mut() { - let attr_props = attrs::parse(&field.attrs)?; - // Keep all attributes that aren't ours: - field - .attrs - .retain(|attr| !attr.path().is_ident(attrs::NAME)); - // Append back on a serde(flatten) attr if the field was marked with api_body(flatten): - if attr_props.flatten { - let new_attr: syn::Attribute = syn::parse_quote! { #[serde(flatten)] }; - field.attrs.push(new_attr); - } + // Replace our "api_body" attrs with corresponding serde attrs: + let mut item = s; + for field in item.fields.iter_mut() { + let props = attrs::parse(&field.attrs)?; + replace_with_serde_attrs(field, &props); } - // We tell serde where to look for its crate contents (otherwise it expects `serde::*` - // to exist, which it might not.) - let serde_crate_path = format!("::{}::serde", crate_name); + let serde_attrs = serde_attrs(&attrs); Ok(quote! { - #serialize_toks - #deserialize_toks - #[serde(crate = #serde_crate_path)] - #sanitized_s + #serde_attrs + #item - #ts_impl + #api_body_impl }) } +/// The serde derives asked for via `#[ApiBody(..)]`. We also tell serde to use our re-export +/// of it (otherwise it expects `serde::*` to exist, which it might not). +fn serde_attrs(attrs: &Attrs) -> TokenStream2 { + let serialize = attrs + .serialize + .then(|| quote! { #[derive(::seamless::serde::Serialize)] }); + let deserialize = attrs + .deserialize + .then(|| quote! { #[derive(::seamless::serde::Deserialize)] }); + quote! { + #serialize + #deserialize + #[serde(crate = "::seamless::serde")] + } +} + +/// The `ApiBodyInfo` for a single field, with any docs on the field used as its description. fn quote_field(f: &Field) -> TokenStream2 { - let crate_name: syn::Ident = syn::Ident::new(CRATE_NAME_STR, Span::call_site()); + let api = crate::seamless_api(); let ty = &f.field.ty; - let docs = &f.attr_props.docs; + // `#[api_body(optional)]` fields are described as `{ key?: T }`. OptionalField is only + // implemented for Option, so this fails to compile if the field isn't an Option. + let info = if f.attr_props.optional { + quote! { + #api::ApiBodyInfo { + description: String::new(), + ty: #api::ApiBodyType::Optional { + value: Box::new(<<#ty as #api::OptionalField>::Inner as #api::ApiBody>::api_body_info()), + }, + } + } + } else { + quote! { <#ty as #api::ApiBody>::api_body_info() } + }; + with_docs(info, &f.attr_props.docs) +} + +/// Wrap an expression producing an `ApiBodyInfo` so that its description is +/// replaced with `docs`, unless `docs` is empty. +fn with_docs(info: TokenStream2, docs: &str) -> TokenStream2 { + if docs.is_empty() { + return info; + } quote! {{ - let mut t = <#ty as ::#crate_name::api::ApiBody>::api_body_info(); - let d = #docs; - if d.len() > 0 { t.description = d.to_owned(); } - t + let mut info = #info; + info.description = #docs.to_owned(); + info }} } + +/// Swap our `api_body` field attrs for the serde attrs that they correspond to. +fn replace_with_serde_attrs(field: &mut syn::Field, props: &attrs::Props) { + field + .attrs + .retain(|attr| !attr.path().is_ident(attrs::NAME)); + + if props.flatten { + field.attrs.push(syn::parse_quote! { #[serde(flatten)] }); + } + + if props.optional { + // Omit the field when it's None, and default it to None when it's missing: + field.attrs.push(syn::parse_quote! { + #[serde(default, skip_serializing_if = "::seamless::api::OptionalField::is_none")] + }); + } +} diff --git a/seamless-macros/src/error/attrs.rs b/seamless-macros/src/error/attrs.rs index 5079437..605fadf 100644 --- a/seamless-macros/src/error/attrs.rs +++ b/seamless-macros/src/error/attrs.rs @@ -1,13 +1,18 @@ -use proc_macro2::Span; - +/// What the generated `From for ApiError` impl should do for a struct or enum variant. #[derive(Debug)] -pub struct FinalApiErrorAttrs { - pub external_message: Option, - pub code: syn::Expr, - pub delegate_to_child: bool, +#[allow(clippy::large_enum_variant)] +pub enum ErrorImpl { + /// Delegate to the `Into` impl of the single unnamed field. + Delegate, + /// Build an `ApiError` using the `Display` impl as the internal message. + Convert { + code: syn::Expr, + /// `None` means that the `Display` impl is used as the external message too. + external_message: Option, + }, } -#[derive(Debug)] +#[derive(Debug, Default)] pub struct ApiErrorAttrs { external_tok: Option, internal_tok: Option, @@ -17,71 +22,36 @@ pub struct ApiErrorAttrs { } impl ApiErrorAttrs { - pub fn finalise(mut self) -> syn::Result { - let code = self.code.unwrap_or(syn::parse_quote!(500u16)); - - let to_external_message_str = |s: Option| { - match s { - Some(s) => { - // Allow arbitrary expressions. - s - } - None => { - let s = syn::LitStr::new("Internal server error", Span::call_site()); - syn::Expr::Lit(syn::ExprLit { - attrs: vec![], - lit: syn::Lit::Str(s), - }) - } - } - }; - - // if there is an inner attr, force delegation to child: + pub fn finalise(self) -> ErrorImpl { if self.inner_tok.is_some() { - self.internal_tok = None; - self.external_tok = None; - self.external_message = None; - self.code = None; + return ErrorImpl::Delegate; } - // Invalid: 'external' and 'external = "foo"' makes no sense (if err is external, can't provide an external msg too!) - if let Some(msg) = &self.external_message && self.external_tok.is_some() { - Err(syn::Error::new_spanned( - msg, - "'external' and 'external = \"foo\"' shouldn't both be provided", - )) - } - // The error will be internal only: - else if self.internal_tok.is_some() || self.external_message.is_some() { - Ok(FinalApiErrorAttrs { - external_message: Some(to_external_message_str(self.external_message)), + let code = self.code.unwrap_or_else(|| syn::parse_quote!(500u16)); + + if self.internal_tok.is_some() || self.external_message.is_some() { + // The error message is for internal eyes only: + let external_message = self + .external_message + .unwrap_or_else(|| syn::parse_quote!(::seamless::api::ApiError::SERVER_ERROR)); + ErrorImpl::Convert { code, - delegate_to_child: false, - }) - } - // Error will be shown externally: - else if self.external_tok.is_some() { - Ok(FinalApiErrorAttrs { - external_message: None, + external_message: Some(external_message), + } + } else if self.external_tok.is_some() { + // The error message will be shown externally: + ErrorImpl::Convert { code, - delegate_to_child: false, - }) - } - // Not internal or external? Delegate to the child impl (enums) or error if we can't: - else { - Ok(FinalApiErrorAttrs { external_message: None, - code: syn::parse_quote!(0u16), - delegate_to_child: true, - }) + } + } else { + // Not internal or external? Delegate to the inner error (or fail if there isn't one): + ErrorImpl::Delegate } } - pub fn finalise_with_parent_attrs( - mut self, - parent: &ApiErrorAttrs, - ) -> syn::Result { - // Only self can have an "inner" attr: + pub fn finalise_with_parent_attrs(mut self, parent: &ApiErrorAttrs) -> syn::Result { + // Only variants can have an "inner" attr: if let Some(t) = &parent.inner_tok { return Err(syn::Error::new_spanned( t, @@ -101,44 +71,32 @@ impl ApiErrorAttrs { if self.code.is_none() { self.code = parent.code.clone(); } - self.finalise() + Ok(self.finalise()) } pub fn parse(attrs: &[syn::Attribute]) -> syn::Result { - let mut internal_tok: Option = None; - let mut external_tok: Option = None; - let mut inner_tok: Option = None; - let mut external_message: Option = None; - let mut code: Option = None; - - for attr in attrs { - // Ignore all attributes we don't care about - if !attr.path().is_ident("api_error") { - continue; - } + let mut out = ApiErrorAttrs::default(); + for attr in attrs + .iter() + .filter(|attr| attr.path().is_ident("api_error")) + { attr.parse_nested_meta(|meta| { let value = meta.value(); let path = meta.path; if path.is_ident("internal") { - internal_tok = Some(path); + out.internal_tok = Some(path); } else if path.is_ident("external") { + // Either `external` or `external = `: match value { - Ok(val) => { - // If `= value`, parse the value as a string - external_message = Some(val.parse()?); - } - Err(_) => { - // If no value, that's all good too. - external_tok = Some(path); - } + Ok(value) => out.external_message = Some(value.parse()?), + Err(_) => out.external_tok = Some(path), } } else if path.is_ident("inner") { - inner_tok = Some(path); + out.inner_tok = Some(path); } else if path.is_ident("code") { - // Here we expect `= number` else we'll error - code = Some(value?.parse()?); + out.code = Some(value?.parse()?); } else { return Err(syn::Error::new_spanned(path, "unrecognized attribute")); } @@ -149,40 +107,38 @@ impl ApiErrorAttrs { // A thing can't be marked "inner" and have any other internal/external/code props, // since we'll be ignoring them all anyway: - if inner_tok.is_some() - && (external_tok.is_some() - || external_message.is_some() - || internal_tok.is_some() - || code.is_some()) + if let Some(inner_tok) = &out.inner_tok + && (out.external_tok.is_some() + || out.external_message.is_some() + || out.internal_tok.is_some() + || out.code.is_some()) { return Err(syn::Error::new_spanned( - external_tok.unwrap(), + inner_tok, "'inner' does not make sense alongside any other attributes", )); } // A thing can't be "external" and "internal" at once: - if let Some(external_tok) = &external_tok && internal_tok.is_some() { + if let Some(external_tok) = &out.external_tok + && out.internal_tok.is_some() + { return Err(syn::Error::new_spanned( external_tok, "'internal' and 'external' can't be declared together", )); } - // Can't have external and exteral = "foo" at once: - if let Some(external_tok) = &external_tok && external_message.is_some() { + // Can't have external and external = "foo" at once: + if let Some(external_tok) = &out.external_tok + && out.external_message.is_some() + { return Err(syn::Error::new_spanned( external_tok, "'external' and 'external = \"foo\"' can't be declared together", )); } - Ok(ApiErrorAttrs { - external_tok, - internal_tok, - inner_tok, - external_message, - code, - }) + Ok(out) } } diff --git a/seamless-macros/src/error/mod.rs b/seamless-macros/src/error/mod.rs index 64b89ee..a643c6a 100644 --- a/seamless-macros/src/error/mod.rs +++ b/seamless-macros/src/error/mod.rs @@ -1,164 +1,130 @@ mod attrs; -use attrs::ApiErrorAttrs; +use attrs::{ApiErrorAttrs, ErrorImpl}; use proc_macro2::{Span, TokenStream as TokenStream2}; -use quote::{quote, quote_spanned}; +use quote::quote; -pub fn parse_struct(s: syn::ItemStruct) -> TokenStream2 { - let struct_name = &s.ident; - let crate_name = syn::Ident::new("seamless", Span::call_site()); +/// The identifier of the struct or enum in our generated methods +/// (ie `fn from(s: ...) -> ...`) +const IDENT: &str = "s"; - // get top level attrs: - let attrs = match ApiErrorAttrs::parse(&s.attrs) { - Ok(attrs) => attrs, - Err(err) => return err.to_compile_error(), - }; - - // finalise them since no other attrs to merge with: - let attrs = match attrs.finalise() { - Ok(attrs) => attrs, - Err(e) => return e.to_compile_error(), - }; +pub fn parse_struct(s: syn::ItemStruct) -> syn::Result { + let name = &s.ident; - // For structs with 1 unnamed field, we can delegate to the inner ApiError, else error: - if attrs.delegate_to_child { - if let Err(e) = one_unnamed_field(&s.ident, &s.fields) { - return e.to_compile_error(); + let body = match ApiErrorAttrs::parse(&s.attrs)?.finalise() { + ErrorImpl::Delegate => { + expect_one_unnamed_field(name, &s.fields)?; + quote! { s.0.into() } } - return quote! { - impl From<#struct_name> for #crate_name::api::ApiError { - fn from(s: #struct_name) -> #crate_name::api::ApiError { - s.0.into() - } + ErrorImpl::Convert { + code, + external_message, + } => { + // We don't know how to handle generics (probably not needed for errors): + if !s.generics.params.is_empty() || s.generics.where_clause.is_some() { + return Err(syn::Error::new_spanned( + name, + "ApiError: Generics are not currently supported", + )); } - }; - } - - // We don't know how to handle generics (prolly not needed for errors..): - if !s.generics.params.is_empty() || s.generics.where_clause.is_some() { - return quote_spanned! { - s.ident.span() => - compile_error!("ApiError: Generics are not currently supported"); - }; - } - - // The external message is either whatever expression we provided to `external = ...`, - // with .to_owned() tagged on to make it an owned string, or it's just the display impl - // of this error struct. - let external_msg_tok = if let Some(msg) = attrs.external_message { - quote! { #msg.to_owned() } - } else { - quote! { format!("{}", s) } + api_error_expr(IDENT, &code, external_message.as_ref()) + } }; - // The error code is whatever expression was given, defaulting to 500. - let code = &attrs.code; - - quote! { - impl From<#struct_name> for #crate_name::api::ApiError { - fn from(s: #struct_name) -> #crate_name::api::ApiError { - #crate_name::api::ApiError { - code: #code, - internal_message: format!("{}", s), - external_message: #external_msg_tok, - value: None - } - } - } - } + Ok(from_impl(IDENT, name, body)) } -pub fn parse_enum(e: syn::ItemEnum) -> TokenStream2 { - let top_level_attrs = match ApiErrorAttrs::parse(&e.attrs) { - Ok(attrs) => attrs, - Err(err) => return err.to_compile_error(), - }; - - let struct_name = &e.ident; - let crate_name = syn::Ident::new("seamless", Span::call_site()); +pub fn parse_enum(e: syn::ItemEnum) -> syn::Result { + let name = &e.ident; + let top_level_attrs = ApiErrorAttrs::parse(&e.attrs)?; if e.variants.is_empty() { - return syn::Error::new_spanned( - e.ident, + return Err(syn::Error::new_spanned( + name, "ApiError: Enums without variants are not supported", - ) - .to_compile_error(); + )); } - let mut enum_items = TokenStream2::new(); - for variant in e.variants { - let inner_attrs = match ApiErrorAttrs::parse(&variant.attrs) { - Ok(attrs) => attrs, - Err(err) => return err.to_compile_error(), - }; - - let attrs = match inner_attrs.finalise_with_parent_attrs(&top_level_attrs) { - Ok(attrs) => attrs, - Err(e) => return e.to_compile_error(), - }; - + let mut match_arms = Vec::new(); + for variant in &e.variants { let ident = &variant.ident; + let error_impl = + ApiErrorAttrs::parse(&variant.attrs)?.finalise_with_parent_attrs(&top_level_attrs)?; - // rely on the inner implementation if attrs not provided and there is one to rely on: - if attrs.delegate_to_child { - if let Err(e) = one_unnamed_field(ident, &variant.fields) { - return e.to_compile_error(); + let arm = match error_impl { + ErrorImpl::Delegate => { + expect_one_unnamed_field(ident, &variant.fields)?; + quote! { #name::#ident(inner) => inner.into(), } + } + ErrorImpl::Convert { + code, + external_message, + } => { + let pattern = match variant.fields { + syn::Fields::Named(..) => quote! { #ident { .. } }, + syn::Fields::Unnamed(..) => quote! { #ident(..) }, + syn::Fields::Unit => quote! { #ident }, + }; + let api_error = api_error_expr(IDENT, &code, external_message.as_ref()); + quote! { #name::#pattern => #api_error, } } - enum_items.extend(quote! { - #struct_name::#ident (inner) => inner.into(), - }) - } - - let full_ident = match variant.fields { - syn::Fields::Named(..) => quote! { #ident {..} }, - syn::Fields::Unnamed(..) => quote! { #ident (..) }, - syn::Fields::Unit => quote! { #ident }, - }; - let code = &attrs.code; - let external_msg_tok = if let Some(msg) = attrs.external_message { - quote! { #msg.to_owned() } - } else { - quote! { format!("{}", s) } }; - - enum_items.extend(quote! { - #struct_name::#full_ident => #crate_name::api::ApiError { - code: #code, - internal_message: format!("{}", s), - external_message: #external_msg_tok, - value: None - }, - }) + match_arms.push(arm); } + Ok(from_impl( + IDENT, + name, + quote! { match s { #(#match_arms)* } }, + )) +} + +/// `impl From<#name> for ApiError`, where `body` converts the value `ident` into an `ApiError`. +fn from_impl(ident: &str, name: &syn::Ident, body: TokenStream2) -> TokenStream2 { + let api = crate::seamless_api(); + let ident = syn::Ident::new(ident, Span::call_site()); + quote! { - impl From<#struct_name> for #crate_name::api::ApiError { - fn from(s: #struct_name) -> #crate_name::api::ApiError { - match s { - #enum_items - } + impl From<#name> for #api::ApiError { + fn from(#ident: #name) -> #api::ApiError { + #body } } } } -fn one_unnamed_field(ident: &syn::Ident, fields: &syn::Fields) -> syn::Result<()> { - let fields: Vec<_> = match fields { - syn::Fields::Unnamed(fields) => fields.unnamed.iter().collect(), - _ => { - return Err(syn::Error::new_spanned( - ident, - "One of '#[api_error(internal)]' or '#[api_error(external)]' or \ - '#[api_error(external = \"foo\")]' is required (1)", - )) - } +/// An `ApiError` built from the `Display` impl of the value `ident`. +fn api_error_expr( + ident: &str, + code: &syn::Expr, + external_message: Option<&syn::Expr>, +) -> TokenStream2 { + let api = crate::seamless_api(); + let ident = syn::Ident::new(ident, Span::call_site()); + + // Without an explicit external message, the `Display` impl is shown externally too: + let external_message = match external_message { + Some(msg) => quote! { #msg.to_owned() }, + None => quote! { s.to_string() }, }; - if fields.len() != 1 { - return Err(syn::Error::new_spanned( + quote! { + #api::ApiError { + code: #code, + internal_message: #ident.to_string(), + external_message: #external_message, + value: None, + } + } +} + +/// Delegating to an inner error is only possible when there is exactly one unnamed field. +fn expect_one_unnamed_field(ident: &syn::Ident, fields: &syn::Fields) -> syn::Result<()> { + match fields { + syn::Fields::Unnamed(fields) if fields.unnamed.len() == 1 => Ok(()), + _ => Err(syn::Error::new_spanned( ident, "One of '#[api_error(internal)]' or '#[api_error(external)]' or \ - '#[api_error(external = \"foo\")]' is required (2)", - )); + '#[api_error(external = \"foo\")]' is required", + )), } - Ok(()) } diff --git a/seamless-macros/src/lib.rs b/seamless-macros/src/lib.rs index 3bad59f..508a9f6 100644 --- a/seamless-macros/src/lib.rs +++ b/seamless-macros/src/lib.rs @@ -2,8 +2,6 @@ mod body; mod error; use proc_macro::TokenStream; -use quote::quote_spanned; -use syn::spanned::Spanned; /// Use this macro to generate serde `Serialize`/`Deserialize` impls in addition /// to an `ApiBody` impl that can hand back information about the shape of the @@ -13,19 +11,22 @@ use syn::spanned::Spanned; /// /// Several attributes can be provided to tweak how this works: /// -/// - `#[ApiBody`]: Generates `serde` Serialize and Deserialize impls for this type. -/// - `#[ApiBody(Serialize,Deserialize`]: The same as above. +/// - `#[ApiBody]`: Generates `serde` Serialize and Deserialize impls for this type. +/// - `#[ApiBody(Serialize, Deserialize)]`: The same as above. /// - `#[ApiBody(Serialize)]`: Only generate the `Serialize` impl for this type. /// - `#[ApiBody(Deserialize)]`: Only generate the `Deserialize` impl for this type. /// - `#[api_body(tag = "foo")]`: Used at the top level, right under `#[ApiBody]`, and /// works the same as `#[serde(tag = "foo")]` would. /// - `#[api_body(flatten)]`: Used on a struct field whose value is itself a struct, and /// works the same as `#[serde(flatten)]` would. +/// - `#[api_body(optional)]`: Used on a field of type `Option`, this will skip serializing +/// the field if the value is `None`, and return the type info `ApiBodyType::Optional` so +/// that clients can properly type this. /// /// # Notes /// /// Unit enums like `enum Foo { A, B, C }` will automatically (de)serialize to one-of the string -/// literals "A", "B" or "C", which slightly differs from how Serde normally apply serialization. +/// literals "A", "B" or "C", which slightly differs from how Serde normally applies serialization. /// Unit and non-unit variants cannot exist in the same enum for this reason, so that it is /// "obvious" how the thing will be (de)serialized. /// @@ -121,32 +122,22 @@ pub fn ApiBody(attrs: TokenStream, input: TokenStream) -> TokenStream { let item = syn::parse_macro_input!(input as syn::Item); let attrs = body::parse_top_attrs(attrs); - let s = match item { - syn::Item::Struct(s) => match body::parse_struct(s, attrs) { - Ok(res) => res, - Err(e) => e.to_compile_error(), - }, - syn::Item::Enum(e) => match body::parse_enum(e, attrs) { - Ok(res) => res, - Err(e) => e.to_compile_error(), - }, - _ => { - // Not applied to struct or enum! Produce compile error at - // position of the non-struct item it's applied to - quote_spanned! { - item.span() => - compile_error!("TypeScript can only be used on structs and enums"); - } - } + let result = match item { + syn::Item::Struct(s) => body::parse_struct(s, attrs), + syn::Item::Enum(e) => body::parse_enum(e, attrs), + other => Err(syn::Error::new_spanned( + other, + "ApiBody can only be used on structs and enums", + )), }; - TokenStream::from(s) + result.unwrap_or_else(syn::Error::into_compile_error).into() } /// Use this macro to generate an `Into` implementation for your custom error /// type. Your custom error type needs to implement `Debug` and `Display` in order to /// derive `ApiError`. `Display` in particular determines what the error message will be. -/// You can then use attribtues to set the status code, and decide on whether the +/// You can then use attributes to set the status code, and decide on whether the /// error message will be `internal`-only or `external`. /// /// If the error is marked as being `internal`, the output from the `Display` impl will be @@ -165,10 +156,10 @@ pub fn ApiBody(attrs: TokenStream, input: TokenStream) -> TokenStream { /// - `#[api_error(internal)]`: At the top of a struct or on an enum variant, this /// denotes that the error message is for internal eyes only, and the external message /// will be set to a sensible default. -/// - `#[api_error(external = "Foo")]`: At the top of a struct of enum variant, this +/// - `#[api_error(external = "Foo")]`: At the top of a struct or enum variant, this /// sets the `external_message` to be "Foo", so that the `Display` impl will be set on /// the `internal_message` field only (similar to `internal`, above). -/// - `#[api_error(code = 401)]`: At the top of a struct of enum variant, this +/// - `#[api_error(code = 401)]`: At the top of a struct or enum variant, this /// sets the status code to be returned in the `ApiError` struct. /// /// These attributes can be combined. @@ -202,20 +193,21 @@ pub fn ApiBody(attrs: TokenStream, input: TokenStream) -> TokenStream { /// ``` #[proc_macro_derive(ApiError, attributes(api_error))] pub fn derive_error(input: TokenStream) -> TokenStream { - let item: syn::Item = syn::parse(input).expect("Item"); + let item = syn::parse_macro_input!(input as syn::Item); - let s = match item { + let result = match item { syn::Item::Struct(s) => error::parse_struct(s), syn::Item::Enum(e) => error::parse_enum(e), - _ => { - // Not applied to struct or enum! Produce compile error at - // position of the non-struct item it's applied to - quote_spanned! { - item.span() => - compile_error!("ApiError can only be used on structs and enums"); - } - } + other => Err(syn::Error::new_spanned( + other, + "ApiError can only be used on structs and enums", + )), }; - TokenStream::from(s) + result.unwrap_or_else(syn::Error::into_compile_error).into() +} + +/// Path to the `seamless::api` module, for use in generated code. +fn seamless_api() -> proc_macro2::TokenStream { + quote::quote!(::seamless::api) } diff --git a/seamless/Cargo.toml b/seamless/Cargo.toml index 65bae41..5f3374d 100644 --- a/seamless/Cargo.toml +++ b/seamless/Cargo.toml @@ -1,41 +1,40 @@ [package] name = "seamless" -version = "0.13.0" -authors = ["James Wilson "] -edition = "2021" -license = "MIT" readme = "README.md" -repository = "https://github.com/jsdw/seamless" -categories = ["web-programming", "web-programming::http-server", "asynchronous"] -keywords = ["api", "http", "rpc", "json"] description = """ An opinionated library to easily create RPC style JSON APIs """ +version.workspace = true +authors.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +categories.workspace = true +keywords.workspace = true + + [features] default = ["uuid"] [dependencies] -async-trait = "0.1.36" -serde = { version = "1", features = ["derive"] } -serde_json = "1" -http = "1" -seamless_macros = { version = "0.13.0", path = "../seamless-macros" } -futures = "0.3.15" +serde.workspace = true +serde_json.workspace = true +http.workspace = true +seamless_macros.workspace = true +futures.workspace = true +bytes.workspace = true # Optional dependencies to impl ApiBody for. -uuid = { version = "1", optional = true } +uuid = { workspace = true, optional = true } [dev-dependencies] -trybuild = "1.0.120" -pretty_assertions = "0.6.1" -serde_json = "1" -thiserror = "1.0.23" -tokio = { version = "1.1.0", features = ["rt", "rt-multi-thread", "macros"] } -tokio-util = { version = "0.6.7", features = ["compat"] } -bytes = "1.0.1" -axum = { version = "0.7.9", features = ["macros"] } - -[dev-dependencies.rocket] -git = "https://github.com/SergioBenitez/Rocket" -rev = "c24f15c1" +trybuild.workspace = true +pretty_assertions.workspace = true +thiserror.workspace = true +tokio.workspace = true +tokio-util.workspace = true +axum.workspace = true +hyper.workspace = true +hyper-util.workspace = true +http-body-util.workspace = true diff --git a/seamless/README.md b/seamless/README.md index 9b10c3e..cb9b44f 100644 --- a/seamless/README.md +++ b/seamless/README.md @@ -1,33 +1,35 @@ # Seamless -[API Docs](https://docs.rs/seamless/latest/seamless) +[![Crates.io](https://img.shields.io/crates/v/seamless.svg)](https://crates.io/crates/seamless) +[![Docs.rs](https://img.shields.io/docsrs/seamless)](https://docs.rs/seamless) +[![CI](https://github.com/jsdw/seamless/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/jsdw/seamless/actions/workflows/ci.yml) -This library aims to provide an easy-to-use and extensible approach to declaring API routes, and will automatically -keep track of various information surrounding requests and responses so that detailed route information (including type -information) can be generated based on the current state of the API. +[See the examples](https://github.com/jsdw/seamless/tree/master/seamless/examples) -This library is fully async, but totally independent from any particular async implementation (you don't even need to -toggle any feature flags). +Seamless provides a way to declare a simple RPC style HTTP API, and from this declaration can hand back enough +information that we can generate a type safe HTTP client for interacting with it. -Using Seamless, we can write our API in pure Rust, and from that generate a TypeScript based API client (or just the types, -or just documentation) based on the current state of the API. This allows us to achieve type safe communication between the -API and TypeScript-like clients without relying on external specifications like OpenAPI. +Seamless supports async handlers and streaming HTTP requests, but is entirely HTTP framework and async framework +agnostic: it can be wired in to your frameworks of choice. For instance, you could use seamless to handle the +API routes in an Axum app and use normal Axum routes to serve other content alongside this API. -The typical steps for using this library are: +## How does it work? -- Annotate your input and output types for these routes with the [`macro@ApiBody`] macro. -- Derive [`macro@ApiError`] (or manually implement `Into`) on any errors you wish to emit. -- Declare each of your API routes using this library. API handlers can just ask for whatever they need as a - function parameter, including arbitrary state or information based on the incoming request (you decide). -- Once the API routes are declared, use [`Api::info()`] to obtain enough information about the API to - generate fully type safe client code (the information is optimised towards generating TypeScript types/code). -- Integrate this API with something like `warp` or `rocket` so that your `seamless` API routes can live alongside - everything else that you'd like to serve (see the examples for how this can be done). +Each API route that you wish to create exists at some path, and is given a handler function which can expect +a specific shape of request body, and will return a specific shape of response, or else an error if things go wrong. -Have a look at the examples in the `examples` directory to get a proper feel for how this library can be used, or -keep reading! +The expected body and response types must implement the `ApiBody` trait, and any errors that are +used must convert into an `ApiError`. Both can be derived via the provided macros, which under the +hood will: +- Implement the `serde::Serialize` and `serde::Deserialize` traits so that we can receive and respond with + values of the given types. +- Implement `ApiBody` or `Into` so that we know the shape of the incoming and + outgoing types, and how any given error should be presented to the client and with what status code. -# A Basic Example +See the `seamless/examples` folder in the crate repository for working examples demonstrating how to use +seamless with both Hyper and Axum, as well as a couple of more basic examples. + +## A Basic Example Below is a basic self contained example of using this library. @@ -38,17 +40,15 @@ use seamless::{ handler::{ body::FromJson, request::Bytes, response::ToJson } }; -// The API relies on types that have been annotated with `ApiBody` (request and response -// types) or `ApiError` (for any errors we might give back). These annotations do some -// reflection to allow us to get information about the shape of the type and doc comments -// added to it, as well as ensuring that they can be Serialized/Deserialized. - +// This is an input to one of our API routes. We annotate it with the ApiBody +// macro so that it can be worked with by seamless as a request or response body. #[ApiBody] struct DivisionInput { a: usize, b: usize } +// We do the same for the type we expect to hand back in a successful response #[ApiBody] #[derive(PartialEq)] struct DivisionOutput { @@ -57,9 +57,10 @@ struct DivisionOutput { result: usize } -// Any errors that we return must implement `Into`, Display and Debug. We can derive -// `ApiError` to automate this for us. Here we use `thiserror` to derive the Display impl -// for us. See the documentation on the `ApiError` macro for more info. +// If we'd like to return a specific error from one of our API routes, we annotate it +// with ApiError, as well as expecting it to be displayable. This allows seamless to +// set the correct HTTP status code given the error returned, and return them in a +// consistent way. #[derive(ApiError, Debug, thiserror::Error, PartialEq)] enum MathsError { #[error("Division by zero")] @@ -69,9 +70,10 @@ enum MathsError { let mut api = Api::new(); -// We add routes to our new API like so. The handler functions would often be defined -// separately and called from this handler. Handler functions can be async or sync, and can -// return any valid handler::HandlerResponse. +// Now, let's define some routes for our API. Handler functions can be async or sync, +// and can return any valid handler::HandlerResponse. Here we use `ToJson` to return +// JSON responses, and in one case return a Result which is either the error we defined +// above, or the response type we defined above. api.add("/echo") .description("Echoes back a JSON string") .handler(|body: FromJson| ToJson(body.0)); @@ -92,16 +94,238 @@ api.add("/maths.divide") // Once we've added routes to the `api`, we use it by sending `http::Request`s to it. // Since we're expecting JSON to be provided, we need to remember to set the correct -// content-type: - +// content-type so that our FromJson input tries to decode it as valid JSON. let req = Request::post("/maths.divide") .header("content-type", "application/json") .body(Bytes::from_vec(serde_json::to_vec(&DivisionInput { a: 20, b: 10 }).unwrap())) .unwrap(); assert_eq!( - api.handle(req).await.unwrap().into_body(), + api.handle(req).await.unwrap().into_body().into_vec().await.unwrap(), serde_json::to_vec(&DivisionOutput{ a: 20, b: 10, result: 2 }).unwrap() ); ``` -Check out the [API Docs](https://docs.rs/seamless/latest/seamless) for lots more information, or take a look at the examples. +## State + +Most real life use cases will require some sort of state to be accessible inside a handler. + +This library follows an approach a little similar to `Axum`. Any type that implements the +`handler::HandlerParam` trait can be passed into handler functions. Using this trait, you can +inspect the request to do things like obtain user information from a session ID, or you can pull +state out of the `Request` object that was placed there prior to it being handed to this library. + +Here's an example: + +```rust +use seamless::{ + api::{ Api, ApiBody, ApiError }, + handler::{ HandlerParam, body::FromJson, request::Bytes, response::ToJson }, +}; + +// Some example state we want to inject into our handler. +#[derive(Clone)] +struct State { value: usize }; + +// Teach the library how to get hold of our "State" value when asked for it. +impl HandlerParam for State { + type Error = ApiError; + async fn handler_param(req: &http::Request<()>) -> Result { + let state: State = req.extensions().get::() + .expect("State must be injected into the request") + .clone(); + Ok(state) + } +} + +let mut api = Api::new(); + +// We can now ask for `State` as a parameter to the handler, as well as the HTTP body, +// which we extract as JSON using `FromJson`. We must always ask for the body last. +api.add("/echo") + .description("Echoes back a JSON string, plus our state value") + .handler(|state: State, body: FromJson| ToJson(format!("{}, {}", body.0, state.value))); + +// Now, to demo it, we build an HTTP request to send to this route. +let mut req = http::Request::post("/echo") + .header("content-type", "application/json") + .body(Bytes::from_vec(serde_json::to_vec("hello").unwrap())) + .unwrap(); + +// When passing a request into our API, remember to inject `State` too so that +// it's available for our `HandlerParam` trait to extract when asked for. +req.extensions_mut().insert(State { value: 123 }); + +// We can now handle a request that is expecting our `State` to be available. +// The response comes back as a JSON string. +let res = api.handle(req).await.unwrap().into_body().into_vec().await.unwrap(); +assert_eq!(res, "\"hello, 123\"".as_bytes()); +``` + +**Note**: params implementing the `handler::HandlerParam` trait must come before the optional final param +that implements `handler::HandlerBody`. Params are resolved in order, with the first failure short circuiting +the rest. + +## Extracting the request body + +To extract the body from a request, the last parameter passed to a handler must implement `handler::HandlerBody`. +At most one such parameter can be provided to a handler (providing more than 1 will lead to a compile error). If no +parameter implementing `handler::HandlerBody` is provided to a handler, it's assumed that the request method will +be GET, and any body will be ignored. + +Two built-in types that implement `handler::HandlerBody` exist for convenience: + +- `handler::body::FromJson` will assume that the request body is valid JSON that decodes to the type `T` + (or fail with a 400 if not). +- `handler::body::FromBinary` will give you back the request body exactly as it was provided. + +## Responding + +Responses from handlers can be plain old synchronous objects or `std::future::Future`s. The value returned +in either case must implement `handler::HandlerResponse`. This trait determines how to create the response to +hand back to the user. + +For convenience, a couple of types are provided which implement this trait: + +- `handler::response::ToJson` will encode the response as JSON. +- `handler::response::ToBinary` will respond with arbitrary bytes, which can be streamed back (from a + `futures::Stream` or `futures::AsyncRead`) rather than loaded into memory all at once. Note that errors + which occur partway through streaming a response can't be turned into an `api::ApiError`, because the + response status will already have been sent. + +Responses handed back from `Api::handle()` have a `handler::response::Body`. This is either a set of bytes that +are entirely in memory, or a stream of chunks of bytes, and can be handed over to whichever HTTP framework you're +using without needing to buffer streaming responses (see the examples folder for how this is done in Axum and Hyper). + +`handler::HandlerResponse` is also implemented for `Option`s and `Result`s, returning a 404 in the event that the +`Option` is `None`, and returning the error from the `Result` (this must itself implement `Into`) in the +event that the `Result` is `Err`. + +## Info + +At some point, you'll probably want to get information about the shape of the API so that you can go +and generate a typed API client (this is, after all, the main selling point of this library). To do this, +use the `Api::info()` function. + +Probably the best way to see what shapes this info can take is by looking at `api/info.rs`. + +Here's an example: + +```rust +use seamless::{ + api::{ Api, ApiBody, ApiError }, + handler::{ body::FromJson, response::ToJson }, +}; +use serde_json::json; + +#[derive(ApiError, Debug, thiserror::Error)] +enum MathsError { + #[error("Division by zero")] + #[api_error(external, code=400)] + DivideByZero +} + +/// Input consisting of two numbers +#[ApiBody] +struct BinaryInput { + /// Input 'a' + a: usize, + /// Input 'b' + b: usize +} + +/// Output containing the original input and result +#[ApiBody] +#[derive(PartialEq)] +struct BinaryOutput { + a: usize, + b: usize, + /// The result + result: usize +} + +async fn divide(input: BinaryInput) -> Result,MathsError> { + todo!() +} + +// A small API with one route: +let mut api = Api::new(); +api.add("maths/divide") + .description("Divide two numbers by each other") + .handler(|FromJson(body)| divide(body)); + +// Get info about this API: +let info = api.info(); + +// Here's what this will look like when serialized to JSON: +let info_json = json!([ + { + "name": "maths/divide", + "description": "Divide two numbers by each other", + "method": "POST", + "request_type": { + "description": "Input consisting of two numbers", + "shape": { + "type": "Object", + "keys": { + "a": { + "description": "Input 'a'", + "shape": { "type": "Number" } + }, + "b": { + "description": "Input 'b'", + "shape": { "type": "Number" } + } + } + } + }, + "response_type": { + "description": "Output containing the original input and result", + "shape": { + "type": "Object", + "keys": { + "a": { + "description": "", + "shape": { "type": "Number" } + }, + "b": { + "description": "", + "shape": { "type": "Number" } + }, + "result": { + "description": "The result", + "shape": { "type": "Number" } + } + } + } + } + } +]); +``` + +The "shape" object can have one of the following "type" literals: `String`, `Number`, `Boolean`, `Null`, +`Any`, `Unknown`, `Binary`, `ArrayOf`, `TupleOf`, `ObjectOf`, `Object`, `OneOf`, `StringLiteral`, `Optional`. Some +of these will come with an additional property. See `ApiBodyType` to get a better feel for exactly what the possible +responses can be. + +## Integrating with other libraries + +Instead of passing requests in manually, you'll probably want to attach an API you define here to a library like +`Axum` (or perhaps just plain old `Hyper`) so that you can benefit from the full power and flexibility +of a well rounded HTTP library alongside your well typed `seamless` API, and actually make the API available +externally. + +See `examples/axum.rs` and `examples/hyper.rs` for examples of how you might integrate this library with those. +Essentially it boils down to being able to construct an `http::Request` from whatever input the library gives you +access to, and being able to handle the `http::Response` or error that's handed back from Seamless. + +## Limitations + +Seamless is designed to make it easy to create simple RPC style JSON APIs that can be "seamlessly" typed from client +to server without using external tools like OpenAPI. + +- Seamless has not been optimised for building RESTful style APIs. However, the `handler::HandlerBody` and + `handler::HandlerParam` traits in particular provide a bunch of extensibility. +- Some of the flexibility that `Serde` provides for manipulating how types are serialized and deserialized is not + available. This library takes the approach of 'wrapping' serde using the `ApiBody` macro to deliberately restrict + how you can transform types, ensuring that any transformations allowed are properly supported and lead to the correct + type information being generated. diff --git a/seamless/examples/axum.rs b/seamless/examples/axum.rs index 109faa0..ffefb30 100644 --- a/seamless/examples/axum.rs +++ b/seamless/examples/axum.rs @@ -4,22 +4,26 @@ //! //! curl localhost:8000/api/echo -H 'content-type: application/json' -d '"hello"' //! curl localhost:8000/api/reverse -H 'content-type: application/json' -d '[1,2,3,4,5]' +//! curl localhost:8000/api/count //! //! To see the API in action. use axum::{ + Router, body::Body, extract::State, routing::{any, get}, - Router, }; use futures::StreamExt; use http::{Request, Response}; use seamless::{ api::{Api, RouteError}, - handler::{body::FromJson, request::Bytes as RequestBytes, response::ToJson}, + handler::{ + body::FromJson, + request::Bytes as RequestBytes, + response::{ToBinary, ToJson}, + }, }; use std::sync::Arc; -use std::usize; #[tokio::main] async fn main() { @@ -36,6 +40,16 @@ async fn main() { .handler(|body: FromJson>| { ToJson(body.0.into_iter().rev().collect::>()) }); + seamless_api + .add("/api/count") + .description("Stream back the numbers 1 to 100,000, one per line") + .handler(|| { + // This response is streamed back to the client one chunk at a time + // rather than being built up in memory first. + let lines = futures::stream::iter(1..=100_000) + .map(|n| Ok::<_, std::io::Error>(format!("{n}\n"))); + ToBinary::stream(lines).content_type("text/plain") + }); // The API can hand back information about itself if we want: let info = seamless_api.info(); @@ -72,7 +86,7 @@ async fn seamless_to_axum(state: State>, request: Request) -> Res // preserving the streaming. let body_stream = body.into_data_stream().map(|bytes| match bytes { Ok(bytes) => Ok(bytes.to_vec()), - Err(e) => Err(std::io::Error::new(std::io::ErrorKind::Other, e)), + Err(e) => Err(std::io::Error::other(e)), }); let body = RequestBytes::from_stream(body_stream); @@ -88,8 +102,13 @@ async fn seamless_to_axum(state: State>, request: Request) -> Res .unwrap(), }, |res| { - let (parts, body_bytes) = res.into_parts(); - Response::from_parts(parts, Body::from(body_bytes)) + // Hand complete bodies over as-is, and stream the rest. + let (parts, body) = res.into_parts(); + let body = match body.into_bytes() { + Ok(bytes) => Body::from(bytes), + Err(body) => Body::from_stream(body.into_stream()), + }; + Response::from_parts(parts, body) }, ) } diff --git a/seamless/examples/basic.rs b/seamless/examples/basic.rs index 06041ff..044be5a 100644 --- a/seamless/examples/basic.rs +++ b/seamless/examples/basic.rs @@ -5,13 +5,13 @@ use seamless::{ api::{Api, ApiBody, ApiError}, handler::{ - body::{Capped, FromJson, IntoBody}, + body::{Capped, FromJson}, request::Bytes, response::ToJson, }, http::Request, }; -use serde_json::{json, Value}; +use serde_json::{Value, json}; #[tokio::main] async fn main() { @@ -28,9 +28,11 @@ async fn main() { .description("Reverse an array of numbers") // We cap the request body to 8kb (8 * 1024 bytes) by wrapping it in // our 'Capped' type: - .handler(|body: Capped>, { 8 * 1024 }>| { - ToJson(body.into_body().into_iter().rev().collect::>()) - }); + .handler( + |Capped(FromJson(body)): Capped>, { 8 * 1024 }>| { + ToJson(body.into_iter().rev().collect::>()) + }, + ); // This route uses custom types (see below): api.add("meta/status") @@ -52,8 +54,15 @@ async fn main() { serde_json::to_vec(&BinaryInput { a: 20, b: 10 }).unwrap(), )) .unwrap(); - let actual: Value = - serde_json::from_slice(&api.handle(req).await.unwrap().into_body()).unwrap(); + let body = api + .handle(req) + .await + .unwrap() + .into_body() + .into_vec() + .await + .unwrap(); + let actual: Value = serde_json::from_slice(&body).unwrap(); let expected = serde_json::to_value(json!({ "a": 20, "b": 10, "result": 2 })).unwrap(); assert_eq!(actual, expected); @@ -79,8 +88,15 @@ async fn main() { .header("content-type", "application/json") .body(Bytes::from_vec(Vec::new())) .unwrap(); - let actual: Value = - serde_json::from_slice(&api.handle(req).await.unwrap().into_body()).unwrap(); + let body = api + .handle(req) + .await + .unwrap() + .into_body() + .into_vec() + .await + .unwrap(); + let actual: Value = serde_json::from_slice(&body).unwrap(); let expected = serde_json::to_value(json!({ "status": "Ok" })).unwrap(); assert_eq!(actual, expected); } diff --git a/seamless/examples/hyper.rs b/seamless/examples/hyper.rs new file mode 100644 index 0000000..3c965b0 --- /dev/null +++ b/seamless/examples/hyper.rs @@ -0,0 +1,160 @@ +//! This is an example of how to integrate a `seamless` Api with `hyper`. +//! +//! Run this with `cargo run --example hyper` and then try: +//! +//! curl localhost:8000/api/echo -H 'content-type: application/json' -d '"hello"' +//! curl localhost:8000/api/reverse -H 'content-type: application/json' -d '[1,2,3,4,5]' +//! curl localhost:8000/api/count +//! curl localhost:8000/api/info +//! +//! To see the API in action. Any request whose path doesn't begin with `/api` +//! will get a 404 response. +use bytes::Bytes; +use futures::{StreamExt, TryStreamExt}; +use http::{Request, Response, StatusCode}; +use http_body_util::{BodyExt, Full, StreamBody, combinators::UnsyncBoxBody}; +use hyper::{ + body::{Frame, Incoming}, + server::conn::http1, + service::service_fn, +}; +use hyper_util::rt::TokioIo; +use seamless::{ + api::{Api, RouteError}, + handler::{ + body::FromJson, + request::Bytes as RequestBytes, + response::{Body as ResponseBody, ToBinary, ToJson}, + }, +}; +use std::{convert::Infallible, sync::Arc}; +use tokio::net::TcpListener; + +#[tokio::main] +async fn main() { + // Define a simple seamless API + let mut seamless_api = Api::new(); + + seamless_api + .add("/api/echo") + .description("Echoes back a JSON string") + .handler(|body: FromJson| ToJson(body.0)); + seamless_api + .add("/api/reverse") + .description("Reverse an array of numbers") + .handler(|body: FromJson>| { + ToJson(body.0.into_iter().rev().collect::>()) + }); + seamless_api + .add("/api/count") + .description("Stream back the numbers 1 to 100,000, one per line") + .handler(|| { + // This response is streamed back to the client one chunk at a time + // rather than being built up in memory first. + let lines = futures::stream::iter(1..=100_000) + .map(|n| Ok::<_, std::io::Error>(format!("{n}\n"))); + ToBinary::stream(lines).content_type("text/plain") + }); + + // The API can hand back information about itself if we want: + let info = seamless_api.info(); + seamless_api + .add("/api/info") + .description("Information about the other routes") + .handler(move || ToJson(serde_json::to_value(&info).unwrap())); + + // Share the API across every connection we accept. + let seamless_api = Arc::new(seamless_api); + + // Run our Hyper server, accepting connections in a loop and + // serving each one on its own task. + println!("Listening on 127.0.0.1:8000"); + let listener = TcpListener::bind("127.0.0.1:8000").await.unwrap(); + loop { + let (stream, _) = match listener.accept().await { + Ok(conn) => conn, + Err(e) => { + eprintln!("Error accepting connection: {e}"); + continue; + } + }; + let io = TokioIo::new(stream); + let api = seamless_api.clone(); + + tokio::spawn(async move { + let service = service_fn(move |req| router(api.clone(), req)); + if let Err(e) = http1::Builder::new().serve_connection(io, service).await { + eprintln!("Error serving connection: {e}"); + } + }); + } +} + +/// The response body we hand to hyper. This lets us respond with either a +/// complete body or a streaming one. +type HyperBody = UnsyncBoxBody; + +/// Forward anything whose path begins with `/api` to seamless, and +/// return a 404 for everything else. +async fn router( + api: Arc, + request: Request, +) -> Result, Infallible> { + if request.uri().path().starts_with("/api") { + Ok(seamless_to_hyper(&api, request).await) + } else { + Ok(not_found()) + } +} + +fn not_found() -> Response { + Response::builder() + .status(StatusCode::NOT_FOUND) + .body(full(Bytes::new())) + .unwrap() +} + +/// A complete (non-streaming) body. +fn full(bytes: Bytes) -> HyperBody { + Full::new(bytes) + .map_err(|never| match never {}) + .boxed_unsync() +} + +/// Convert a seamless response body into a hyper one. Complete bodies are handed +/// over as-is, and streaming bodies are streamed through without being buffered. +fn to_hyper_body(body: ResponseBody) -> HyperBody { + match body.into_bytes() { + Ok(bytes) => full(bytes), + Err(body) => StreamBody::new(body.into_stream().map_ok(Frame::data)).boxed_unsync(), + } +} + +async fn seamless_to_hyper(api: &Api, request: Request) -> Response { + let (parts, body) = request.into_parts(); + + // Convert the body stream into a seamless-compatible format, + // preserving the streaming. + let body_stream = body.into_data_stream().map(|bytes| match bytes { + Ok(bytes) => Ok(bytes.to_vec()), + Err(e) => Err(std::io::Error::other(e)), + }); + + let body = RequestBytes::from_stream(body_stream); + let request = Request::from_parts(parts, body); + + // Have our seamless API handle the request. + api.handle(request).await.map_or_else( + |e| match e { + RouteError::NotFound(_) => not_found(), + RouteError::Err(e) => Response::builder() + .status(e.code) + .body(full(Bytes::from(e.external_message))) + .unwrap(), + }, + |res| { + let (parts, body) = res.into_parts(); + Response::from_parts(parts, to_hyper_body(body)) + }, + ) +} diff --git a/seamless/examples/rocket.rs b/seamless/examples/rocket.rs deleted file mode 100644 index 40457fe..0000000 --- a/seamless/examples/rocket.rs +++ /dev/null @@ -1,108 +0,0 @@ -//! This is an example of how to integrate a `seamless` Api with `rocket` (0.5.0). -//! -//! Run this with `cargo run --example rocket` and then try: -//! -//! curl localhost:8000/api/echo -H 'content-type: application/json' -d '"hello"' -//! curl localhost:8000/api/reverse -H 'content-type: application/json' -d '[1,2,3,4,5]' -//! -//! To see the API in action (assuming port 8000). -use http::header::HeaderName; -use rocket::data::ToByteUnit; -use rocket::handler::{Handler, Outcome}; -use rocket::{ - http::{Method, Status}, - Data, Request, Route, -}; -use seamless::{ - api::{Api, RouteError}, - handler::{body::FromJson, request::Bytes, response::ToJson}, -}; -use std::io::Cursor; -use std::sync::Arc; -use tokio_util::compat::TokioAsyncReadCompatExt; - -#[rocket::launch] -fn rocket() -> rocket::Rocket { - let mut api = Api::new(); - - api.add("/api/echo") - .description("Echoes back a JSON string") - .handler(|body: FromJson| ToJson(body.0)); - api.add("/api/reverse") - .description("Reverse an array of numbers") - .handler(|body: FromJson>| { - ToJson(body.0.into_iter().rev().collect::>()) - }); - - rocket::ignite().mount("/", SeamlessApi(Arc::new(api))) -} - -// Wrap our `seamless::Api` in a thing that Rocket can work with: -#[derive(Clone)] -struct SeamlessApi(Arc); - -#[rocket::async_trait] -impl Handler for SeamlessApi { - async fn handle<'r, 's: 'r>(&'s self, req: &'r Request<'_>, data: Data) -> Outcome<'r> { - // Stream the body into `seamless`. We use the `compat` method from tokio-utils to - // convert from `tokio::AsyncRead` to the `futures::AsyncRead` that seamless - // works with. We could alternately obtain a vector of bytes here, but by streaming - // it into seamless, we can do things like configuring per-request size limits, - // immediately terminating the streaming if reached. - let body_reader = data.open(10.megabytes()).compat(); - let streamed_body = Bytes::from_reader(body_reader); - - // Build an http::Request: - let mut http_req = http::Request::builder() - .method(req.method().as_str()) - .uri(req.uri().path()) - .body(streamed_body) - .unwrap(); - - // Copy headers over: - let new_headers = http_req.headers_mut(); - for header in req.headers().iter() { - let header_name = - HeaderName::from_lowercase(header.name().to_string().to_lowercase().as_bytes()); - if let Ok(header_name) = header_name { - new_headers.insert(header_name, header.value().parse().unwrap()); - } - } - - // Give this to `seamless` and then tell Rocket how to - // handle the result: - match self.0.handle(http_req).await { - Ok(res) => { - let response_body = res.into_body(); - let rocket_response = rocket::Response::build() - .header(rocket::http::ContentType::JSON) - .sized_body(response_body.len(), Cursor::new(response_body)) - .finalize(); - Outcome::Success(rocket_response) - } - Err(RouteError::NotFound(_req)) => Outcome::failure(Status::NotFound), - Err(RouteError::Err(e)) => { - eprintln!("Whoops: {:?}", e); - Outcome::failure(Status::InternalServerError) - } - } - } -} - -impl Into> for SeamlessApi { - fn into(self) -> Vec { - // Show rocket what routes exist in our API - // by inspecting the api info: - self.0 - .info() - .into_iter() - .map(|r| { - let method = match r.method.as_str() { - "GET" => Method::Get, - _ => Method::Post, - }; - Route::new(method, format!("/{}", r.name), self.clone()) - }) - .collect() - } -} diff --git a/seamless/examples/state.rs b/seamless/examples/state.rs index ad59d52..295351d 100644 --- a/seamless/examples/state.rs +++ b/seamless/examples/state.rs @@ -3,7 +3,7 @@ use seamless::{ api::{Api, ApiError}, - handler::{body::FromJson, request::Bytes, response::ToJson, HandlerParam}, + handler::{HandlerParam, body::FromJson, request::Bytes, response::ToJson}, }; // Something we want to inject into our handler. @@ -16,7 +16,6 @@ struct State; // This can inspect the request headers and path as well so that we // can do things like load in a user based on a session cookie and complain // with an ApiError if the user is not found. -#[seamless::async_trait] impl HandlerParam for State { type Error = ApiError; async fn handler_param(req: &http::Request<()>) -> Result { diff --git a/seamless/src/api/api.rs b/seamless/src/api/api.rs index cda8d15..ed6bed6 100644 --- a/seamless/src/api/api.rs +++ b/seamless/src/api/api.rs @@ -1,7 +1,9 @@ use super::error::ApiError; use super::info::ApiBodyInfo; -use crate::handler::{request::AsyncReadBody, Handler, IntoHandler}; -use http::{method::Method, Request, Response}; +use crate::handler::{ + Handler, IntoHandler, request::AsyncReadBody, response::Body as ResponseBody, +}; +use http::{Method, Request, Response}; use serde::Serialize; use std::collections::HashMap; @@ -10,13 +12,13 @@ use std::collections::HashMap; /// using [`Self::info()`], or handle an [`http::Request`] using [`Self::handle()`]. pub struct Api { base_path: String, - routes: HashMap<(Method, String), ResolvedApiRoute>, + routes: HashMap<(Method, String), Route>, } -// An API route has the contents of `ResolvedHandler` but also a description. -struct ResolvedApiRoute { +// A route's handler, along with its description. +struct Route { description: String, - resolved_handler: Handler, + handler: Handler, } impl Default for Api { @@ -38,8 +40,11 @@ impl Api { /// the path "hi" is added, then an incoming [`http::Request`] with the path /// `"/foo/bar/hi"` will match it. pub fn new_with_base_path>(base_path: S) -> Api { + // Store without leading or trailing slashes so that it's ready to + // be matched against request paths in `handle`. + let base_path = base_path.into().trim_matches('/').to_owned(); Api { - base_path: base_path.into(), + base_path, routes: HashMap::new(), } } @@ -48,6 +53,9 @@ impl Api { /// and are given back a [`RouteBuilder`] which can be used to give the route a handler /// and a description. /// + /// If you add a route at the same path and requiring the same method as an existing route, + /// the existing route will be silently overwritten. + /// /// # Examples /// /// ``` @@ -74,79 +82,88 @@ impl Api { } // Add a route given the individual parts (for internal use) - fn add_parts, HandlerFn: IntoHandler>( + fn add_parts>( &mut self, - path: P, + path: String, description: String, handler_fn: HandlerFn, ) { - let resolved_handler = handler_fn.into_handler(); - let mut path: String = path.into(); - path = path.trim_matches('/').to_owned(); + let handler = handler_fn.into_handler(); + let path = path.trim_matches('/').to_owned(); self.routes.insert( - (resolved_handler.method.clone(), path), - ResolvedApiRoute { + (handler.method.clone(), path), + Route { description, - resolved_handler, + handler, }, ); } /// Match an incoming [`http::Request`] against our API routes and run the relevant handler if a - /// matching one is found. We'll get back bytes representing a JSON response back if all goes ok, - /// else we'll get back a [`RouteError`], which will either be [`RouteError::NotFound`] if no matching - /// route was found, or a [`RouteError::Err`] if a matching route was found, but that handler emitted - /// an error. + /// matching one is found. We'll get back an [`http::Response`] whose body is a + /// [`crate::handler::response::Body`] if all goes ok, else we'll get back a [`RouteError`], + /// which will either be [`RouteError::NotFound`] if no matching route was found, or a + /// [`RouteError::Err`] if a matching route was found, but that handler emitted an error. + #[allow(clippy::result_large_err)] pub async fn handle( &self, req: Request, - ) -> Result>, RouteError> { - let base_path = &self.base_path.trim_start_matches('/'); - let req_path = req.uri().path().trim_start_matches('/'); - - if let Some(req_path_tail) = req_path.strip_prefix(base_path) { - // Ensure that the method and path suffix lines up as expected: - let req_method = req.method().into(); - let req_path_tail = req_path_tail - .trim_start_matches('/') - .to_owned(); - - // Turn req body into &mut dyn AsyncReadBody: - let (req_parts, mut req_body) = req.into_parts(); - let dyn_req = Request::from_parts(req_parts, &mut req_body as &mut dyn AsyncReadBody); - - if let Some(route) = self.routes.get(&(req_method, req_path_tail)) { - (route.resolved_handler.handler)(dyn_req) - .await - .map_err(RouteError::Err) - } else { - let (req_parts, _) = dyn_req.into_parts(); - Err(RouteError::NotFound(Request::from_parts( - req_parts, req_body, - ))) - } - } else { - Err(RouteError::NotFound(req)) - } + ) -> Result, RouteError> { + let Some(route) = self.find_route(&req) else { + return Err(RouteError::NotFound(req)); + }; + + // Handlers take the body as a `&mut dyn AsyncReadBody`: + let (parts, mut body) = req.into_parts(); + let req = Request::from_parts(parts, &mut body as &mut dyn AsyncReadBody); + + route.handler.call(req).await.map_err(RouteError::Err) + } + + /// Find the route matching the request's method and path, if there is one. + fn find_route(&self, req: &Request) -> Option<&Route> { + let path = req.uri().path().trim_start_matches('/'); + let path = strip_path_prefix(path, &self.base_path)?.trim_start_matches('/'); + self.routes.get(&(req.method().clone(), path.to_owned())) } /// Return information about the API routes that have been defined so far. + /// Routes are currently sorted by name and then by method, but this order may change. pub fn info(&self) -> Vec { - let mut info = vec![]; - for ((_method, key), val) in &self.routes { - info.push(RouteInfo { - name: key.to_owned(), - method: format!("{}", &val.resolved_handler.method), - description: val.description.clone(), - request_type: val.resolved_handler.request_type.clone(), - response_type: val.resolved_handler.response_type.clone(), - }); - } - info.sort_by(|a, b| a.name.cmp(&b.name)); + let mut info: Vec = self + .routes + .iter() + .map(|((method, path), route)| RouteInfo { + name: path.clone(), + method: method.to_string(), + description: route.description.clone(), + request_type: route.handler.request_type.clone(), + response_type: route.handler.response_type.clone(), + }) + .collect(); + // Sort by name, then by method, so that routes sharing a path come out + // in a stable order rather than in `HashMap` iteration order. + info.sort_by(|a, b| a.name.cmp(&b.name).then_with(|| a.method.cmp(&b.method))); info } } +/// Strip `prefix` from the start of `path`, but only if it matches whole path +/// segments. Neither argument should have a leading slash, and `prefix` should +/// have no trailing slash. For example, with a prefix of `"api"`, the paths +/// `"api"` and `"api/foo"` match, but `"apiv2/foo"` does not. +fn strip_path_prefix<'a>(path: &'a str, prefix: &str) -> Option<&'a str> { + if prefix.is_empty() { + return Some(path); + } + let tail = path.strip_prefix(prefix)?; + if tail.is_empty() || tail.starts_with('/') { + Some(tail) + } else { + None + } +} + /// Add a new API route by providing a description (optional but encouraged) /// and then a handler function. /// @@ -175,6 +192,7 @@ pub struct RouteBuilder<'a> { path: String, description: String, } + impl<'a> RouteBuilder<'a> { fn new(api: &'a mut Api, path: String) -> Self { RouteBuilder { @@ -183,11 +201,13 @@ impl<'a> RouteBuilder<'a> { description: String::new(), } } + /// Add a description to the API route. pub fn description>(mut self, desc: S) -> Self { self.description = desc.into(); self } + /// Add a handler to the API route. Until this has been added, the route /// doesn't "exist". pub fn handler>(self, handler: HandlerFn) { @@ -217,7 +237,7 @@ impl std::fmt::Debug for RouteError { impl RouteError { /// Assume that the `RouteError` contains an error and attempt to - /// unwrap this + /// unwrap it. /// /// # Panics /// @@ -225,7 +245,7 @@ impl RouteError { pub fn unwrap_err(self) -> E { match self { RouteError::Err(e) => e, - _ => panic!("Attempt to unwrap_api_err on RouteError that is NotFound"), + _ => panic!("Attempt to unwrap_err on RouteError that is NotFound"), } } } diff --git a/seamless/src/api/error.rs b/seamless/src/api/error.rs index 2e3c8f9..80b378c 100644 --- a/seamless/src/api/error.rs +++ b/seamless/src/api/error.rs @@ -13,10 +13,25 @@ pub struct ApiError { } impl ApiError { - // Try to keep this the same as seamless-macros::api_error's version: + // Also used as the default external message by the ApiError macro: #[doc(hidden)] pub const SERVER_ERROR: &'static str = "Internal server error"; + /// An error whose message is used as both the internal and the external message. + /// + /// **Note:** the message will be shown to API consumers, so be careful not to include + /// anything sensitive in it. Use [`ApiError::server_error()`] for errors that should + /// only be seen internally. + pub fn external(code: u16, msg: impl Into) -> ApiError { + let msg = msg.into(); + ApiError { + code, + internal_message: msg.clone(), + external_message: msg, + value: None, + } + } + /// A helper to instantiate a server error. pub fn server_error>(msg: S) -> ApiError { ApiError { @@ -29,28 +44,17 @@ impl ApiError { /// A helper to instantiate a 404 not found error. pub fn path_not_found() -> ApiError { - ApiError { - code: 404, - internal_message: "Not found".to_owned(), - external_message: "Not found".to_owned(), - value: None, - } + ApiError::external(404, "Not found") } /// A helper to instantiate a not authorized error. pub fn not_authorized(reason: &str) -> ApiError { - let msg = format!("Not Authorized: {}", reason); - ApiError { - code: 403, - external_message: msg.clone(), - internal_message: msg, - value: None, - } + ApiError::external(403, format!("Not Authorized: {reason}")) } } impl From for ApiError { - fn from(_: std::convert::Infallible) -> ApiError { - unreachable!() + fn from(never: std::convert::Infallible) -> ApiError { + match never {} } } diff --git a/seamless/src/api/info.rs b/seamless/src/api/info.rs index 681c158..1c7b69c 100644 --- a/seamless/src/api/info.rs +++ b/seamless/src/api/info.rs @@ -24,7 +24,7 @@ pub struct ApiBodyInfo { #[doc(hidden)] pub struct ApiBodyStructInfo { pub description: String, - pub struc: HashMap, + pub fields: HashMap, } /// An enum representing the shape of the JSON that is provided or output from the API. @@ -91,8 +91,10 @@ pub enum ApiBodyType { /// The exact string literal that we expect. literal: String, }, - /// The type is optional, and need not be provided. It corresponds to either - /// `{ key?: Foo }` in objects, or `Foo | undefined` in other contexts. + /// The object key may be omitted, eg `{ key?: Foo }`. This is expected to be used + /// on struct fields in conjunction with serde's `skip_serializing_if = Option::is_none` + /// attribute. Adding `#[api_body(optional)]` on a field when using the `ApiBody` macro + /// emits this, as well as the corresponding serde attribute. Optional { /// The type that is optional. value: Box, @@ -100,7 +102,7 @@ pub enum ApiBodyType { } /// Any type that implements this trait can be described in terms of [`ApiBodyInfo`], and -/// can potentially also be serialized or deserizlied from JSON. +/// can potentially also be serialized or deserialized from JSON. /// /// This type should not be manually implemented in most cases; instead the [`ApiBody`](seamless_macros::ApiBody) /// macro should be relied on to ensure that the description and shape of the type are consistent with how @@ -110,44 +112,12 @@ pub enum ApiBodyType { pub trait ApiBody { /// This returns information about the shape of the type and description of parts of it. fn api_body_info() -> ApiBodyInfo; - - /// Serialize the type to JSON. - fn to_json_vec(&self) -> Vec - where - Self: ::serde::Serialize, - { - serde_json::to_vec(self) - .expect("Failed to serialize to JSON due to an invalid manual implementation (1)") - } - - /// Serialize the type to a [`serde_json::Value`]. - fn to_json_value(&self) -> serde_json::Value - where - Self: ::serde::Serialize, - { - serde_json::to_value(self) - .expect("Failed to serialize to JSON due to an invalid manual implementation (2)") - } - - /// Deserialize from bytes containing a JSON value. - fn from_json_slice(bytes: &[u8]) -> serde_json::Result - where - Self: ::serde::de::DeserializeOwned, - { - serde_json::from_slice(bytes) - } - - /// Deserialize from a [`serde_json::Value`]. - fn from_json_value(value: serde_json::Value) -> serde_json::Result - where - Self: ::serde::de::DeserializeOwned, - { - serde_json::from_value(value) - } } -/// This trait is implemented for all struct types, so that we know, at compile time, -/// whether we're working with a struct type that can be flattened or not. +/// The ApiBody macro implements this trait for all struct types, so that we can properly +/// flatten enums or newtypes containing a single struct type. +/// +/// This is not meant to be used by hand. #[doc(hidden)] pub trait ApiBodyStruct { fn api_body_struct_info() -> ApiBodyStructInfo; @@ -189,20 +159,43 @@ impl ApiBody for HashMap { } } } + +// Serde serializes `None` as `null`, so the Option type is `T | null`. impl ApiBody for Option { fn api_body_info() -> ApiBodyInfo { ApiBodyInfo { description: String::new(), - ty: ApiBodyType::Optional { - value: Box::new(T::api_body_info()), + ty: ApiBodyType::OneOf { + values: vec![T::api_body_info(), <()>::api_body_info()], }, } } } +/// The [`ApiBody`](seamless_macros::ApiBody) macro uses this for fields marked with +/// `#[api_body(optional)]`, to get at the inner type of an Option, and confirm that +/// the field is indeed an Option. +/// +/// This is not meant to be used by hand. +#[doc(hidden)] +#[diagnostic::on_unimplemented( + message = "`#[api_body(optional)]` can only be used on fields of type `Option`", + label = "`{Self}` is not an `Option`" +)] +pub trait OptionalField { + type Inner: ApiBody; + fn is_none(&self) -> bool; +} +impl OptionalField for Option { + type Inner = T; + fn is_none(&self) -> bool { + Option::is_none(self) + } +} + // Primitives: macro_rules! impl_api_body { - ( $( $($name:path),+ => $ty:expr ),+ ) => ( + ( $( $($name:ty),+ => $ty:expr );+ ) => ( $($( impl ApiBody for $name { fn api_body_info() -> ApiBodyInfo { @@ -228,30 +221,16 @@ impl_api_body! { std::sync::atomic::AtomicU16, std::sync::atomic::AtomicU32, std::sync::atomic::AtomicU64, - serde_json::Number, - std::sync::atomic::AtomicUsize => ApiBodyType::Number, + std::sync::atomic::AtomicUsize, + serde_json::Number => ApiBodyType::Number; bool, - std::sync::atomic::AtomicBool => ApiBodyType::Boolean, - String => ApiBodyType::String -} -impl ApiBody for &str { - fn api_body_info() -> ApiBodyInfo { - ApiBodyInfo { - description: String::new(), - ty: ApiBodyType::String, - } - } + std::sync::atomic::AtomicBool => ApiBodyType::Boolean; + String, &str => ApiBodyType::String; + () => ApiBodyType::Null; + serde_json::Value => ApiBodyType::Any } // Tuples: -impl ApiBody for () { - fn api_body_info() -> ApiBodyInfo { - ApiBodyInfo { - description: String::new(), - ty: ApiBodyType::Null, - } - } -} macro_rules! impl_api_body_tuples { ( $( $( $name:ident )+ ),+ ) => ( $( @@ -281,15 +260,6 @@ impl_api_body_tuples! { A B C D E F G H I J } -impl ApiBody for serde_json::Value { - fn api_body_info() -> ApiBodyInfo { - ApiBodyInfo { - description: String::new(), - ty: ApiBodyType::Any, - } - } -} - impl ApiBody for serde_json::Map { fn api_body_info() -> ApiBodyInfo { ApiBodyInfo { diff --git a/seamless/src/api/mod.rs b/seamless/src/api/mod.rs index 11682da..e716c77 100644 --- a/seamless/src/api/mod.rs +++ b/seamless/src/api/mod.rs @@ -19,4 +19,4 @@ pub use seamless_macros::{ApiBody, ApiError}; // These are used in seamless_macros but are not expected to // be made use of elsewhere and so are hidden from the docs: #[doc(hidden)] -pub use info::{ApiBodyStruct, ApiBodyStructInfo}; +pub use info::{ApiBodyStruct, ApiBodyStructInfo, OptionalField}; diff --git a/seamless/src/handler/body.rs b/seamless/src/handler/body.rs index 2689dcb..33820e4 100644 --- a/seamless/src/handler/body.rs +++ b/seamless/src/handler/body.rs @@ -1,63 +1,48 @@ -use std::ops::{Deref, DerefMut}; - -use crate::api::{ApiBody, ApiBodyInfo, ApiError}; -use crate::handler::request::{AsyncReadBody, CappedAsyncRead}; -use async_trait::async_trait; +use crate::api::{ApiBody, ApiBodyInfo, ApiBodyType, ApiError}; +use crate::handler::request::{AsyncReadBody, CappedAsyncRead, CappedSizeLimitError}; use futures::AsyncReadExt; -use http::{method::Method, Request}; +use http::{Method, Request}; use serde::de::DeserializeOwned; +use std::future::Future; +use std::ops::{Deref, DerefMut}; /// This trait is implemented by anything that represents the incoming request type. /// Only one argument implementing this can be asked for in a given handler. The type /// that implements this is used to determine the input type expected by the handler /// for the sake of generating API information. -#[async_trait] pub trait HandlerBody: Sized { /// Given a request containing arbitrary bytes, this function needs to return an /// instance of the type that this trait is implemented on (typically by deserializing /// it from the bytes provided), or else it should return an error describing what /// went wrong. - async fn handler_body(req: Request<&mut dyn AsyncReadBody>) -> Result; - /// Which HTTP method is required for this Body to be valid. By default, if a body - /// is present in the handler we'll expect the method to be POST. Implement this function - /// to override that. - fn handler_method() -> Method { - Method::POST - } -} + fn handler_body( + req: Request<&mut dyn AsyncReadBody>, + ) -> impl Future> + Send; -/// A simple trait that makes it a little more ergonomic in some cases to extract the body -/// out of our various types like [`FromJson`] and [`FromBinary`]. Useful when we combine -/// types like [`Capped`] so that we can avoid multiple layers of unwrapping. -pub trait IntoBody { - /// The body type that will be extracted. Whatever we extract should itself implement - /// [`trait@ApiBody`] to correspond to the generated type information. - type Target: ApiBody; - - /// Extract the body of the request with this, unwrapping as many layers of nesting as - /// needed. - fn into_body(self) -> Self::Target; + /// Which HTTP method is required for this Body to be valid. The built-in body types + /// ([`FromJson`] and [`FromBinary`]) expect POST, and wrapper types such as [`Capped`] + /// forward the method of the type they wrap. + fn handler_method() -> Method; } /// If the last argument to a handler is this, we'll assume /// that the user needs to provide JSON that decodes to `T`. /// Notably, `T` needs to implement `ApiBody` with the /// Deserialize option. -pub struct FromJson(pub T); +pub struct FromJson(pub T); -#[async_trait] impl HandlerBody for FromJson { async fn handler_body(req: Request<&mut dyn AsyncReadBody>) -> Result { - let content_type = req + let is_json = req .headers() .get(http::header::CONTENT_TYPE) - .ok_or_else(content_type_not_json_err)?; - let content_type_is_json = content_type - .to_str() - .map(|s| s.eq_ignore_ascii_case("application/json")) - .unwrap_or(false); - if !content_type_is_json { - return Err(content_type_not_json_err()); + .and_then(|value| value.to_str().ok()) + .is_some_and(is_json_content_type); + if !is_json { + return Err(ApiError::external( + 415, + "Content-Type must be application/json", + )); } // Stream our body into a vector of bytes: @@ -65,22 +50,17 @@ impl HandlerBody for FromJson { req.into_body() .read_to_end(&mut body) .await - .map_err(|e| ApiError { - code: 400, - internal_message: e.to_string(), - external_message: e.to_string(), - value: None, - })?; + .map_err(io_error_to_api_error)?; // Assume JSON and parse: - let json = serde_json::from_slice(&body).map_err(|e| ApiError { - code: 400, - internal_message: e.to_string(), - external_message: e.to_string(), - value: None, - })?; + let json = + serde_json::from_slice(&body).map_err(|e| ApiError::external(400, e.to_string()))?; Ok(FromJson(json)) } + + fn handler_method() -> Method { + Method::POST + } } impl ApiBody for FromJson @@ -92,33 +72,24 @@ where } } -impl Deref for FromJson { +impl Deref for FromJson { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } -impl DerefMut for FromJson { +impl DerefMut for FromJson { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } -impl IntoBody for FromJson { - type Target = T; - fn into_body(self) -> Self::Target { - self.0 - } -} - -fn content_type_not_json_err() -> ApiError { - ApiError { - code: 415, - internal_message: "Content-Type must be application/json".to_string(), - external_message: "Content-Type must be application/json".to_string(), - value: None, - } +/// True if a Content-Type header value names application/json, +/// ignoring parameters such as `; charset=utf-8`. +fn is_json_content_type(value: &str) -> bool { + let media_type = value.split(';').next().unwrap_or("").trim(); + media_type.eq_ignore_ascii_case("application/json") } /// If the last argument to a handler is this, we'll assume @@ -126,28 +97,26 @@ fn content_type_not_json_err() -> ApiError { /// we'll make that data available within the handler as bytes. pub struct FromBinary(pub Vec); -#[async_trait] impl HandlerBody for FromBinary { async fn handler_body(req: Request<&mut dyn AsyncReadBody>) -> Result { let mut body = vec![]; req.into_body() .read_to_end(&mut body) .await - .map_err(|e| ApiError { - code: 400, - internal_message: e.to_string(), - external_message: e.to_string(), - value: None, - })?; + .map_err(io_error_to_api_error)?; Ok(FromBinary(body)) } + + fn handler_method() -> Method { + Method::POST + } } impl ApiBody for FromBinary { fn api_body_info() -> ApiBodyInfo { ApiBodyInfo { description: "Binary data".to_owned(), - ty: crate::api::ApiBodyType::Binary, + ty: ApiBodyType::Binary, } } } @@ -171,52 +140,142 @@ impl From for Vec { } } -impl IntoBody for FromBinary { - type Target = Vec; - fn into_body(self) -> Self::Target { - self.0 - } -} - /// This wraps anything implementing [`HandlerBody`] and puts a type level cap on the size /// that the request body is allowed to be before this is rejected. This works best when the /// request body is streamed, as it will stop the streaming once said limit is reached. -pub struct Capped(pub T); +pub struct Capped(pub T); -#[async_trait] -impl HandlerBody for Capped { - async fn handler_body<'a>(req: Request<&'a mut dyn AsyncReadBody>) -> Result { +impl HandlerBody for Capped { + async fn handler_body(req: Request<&mut dyn AsyncReadBody>) -> Result { let (parts, body) = req.into_parts(); let mut body = CappedAsyncRead::<_, MAX_BYTES>::new(body); let req = Request::from_parts(parts, &mut body as &mut dyn AsyncReadBody); - T::handler_body(req).await.map(|res| Capped(res)) + T::handler_body(req).await.map(Capped) + } + + fn handler_method() -> Method { + T::handler_method() } } -impl ApiBody for Capped { +impl ApiBody for Capped { fn api_body_info() -> ApiBodyInfo { T::api_body_info() } } -impl Deref for Capped { +impl Deref for Capped { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } -impl DerefMut for Capped { +impl DerefMut for Capped { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } -impl IntoBody - for Capped -{ - type Target = T::Target; - fn into_body(self) -> Self::Target { - self.0.into_body() +/// Map IO errors from reading HTTP bodies into suitable ApiErrors. +fn io_error_to_api_error(e: std::io::Error) -> ApiError { + match e.downcast::() { + Ok(e) => ApiError::external(413, e.to_string()), + Err(e) => ApiError::external(400, e.to_string()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + struct PutBody; + + impl HandlerBody for PutBody { + async fn handler_body(_req: Request<&mut dyn AsyncReadBody>) -> Result { + Ok(PutBody) + } + fn handler_method() -> Method { + Method::PUT + } + } + + impl ApiBody for PutBody { + fn api_body_info() -> ApiBodyInfo { + FromBinary::api_body_info() + } + } + + #[test] + fn capped_forwards_handler_method() { + assert_eq!(PutBody::handler_method(), Method::PUT); + assert_eq!( + as HandlerBody>::handler_method(), + Method::PUT + ); + assert_eq!( + as HandlerBody>::handler_method(), + Method::POST + ); + assert_eq!( + , 1024> as HandlerBody>::handler_method(), + Method::POST + ); + } + + #[tokio::test] + async fn capped_returns_413_when_body_too_large() { + use crate::handler::request::Bytes; + + // Oversized binary body: + let mut body = Bytes::from_vec(vec![0u8; 11]); + let req = Request::post("/") + .body(&mut body as &mut dyn AsyncReadBody) + .unwrap(); + let err = as HandlerBody>::handler_body(req) + .await + .err() + .expect("body exceeding the cap should be rejected"); + assert_eq!(err.code, 413); + assert_eq!(err.external_message, "Size limit exceeded"); + + // Oversized JSON body: + let mut body = Bytes::from_vec(br#""hello world""#.to_vec()); + let req = Request::post("/") + .header(http::header::CONTENT_TYPE, "application/json") + .body(&mut body as &mut dyn AsyncReadBody) + .unwrap(); + let err = , 10> as HandlerBody>::handler_body(req) + .await + .err() + .expect("body exceeding the cap should be rejected"); + assert_eq!(err.code, 413); + assert_eq!(err.external_message, "Size limit exceeded"); + + // A body exactly at the cap is fine: + let mut body = Bytes::from_vec(vec![1u8; 10]); + let req = Request::post("/") + .body(&mut body as &mut dyn AsyncReadBody) + .unwrap(); + let res = as HandlerBody>::handler_body(req) + .await + .unwrap_or_else(|e| { + panic!( + "body within the cap should be accepted: {}", + e.internal_message + ) + }); + assert_eq!(res.0.0, vec![1u8; 10]); + } + + #[test] + fn json_content_type_matching() { + assert!(is_json_content_type("application/json")); + assert!(is_json_content_type("Application/JSON")); + assert!(is_json_content_type("application/json; charset=utf-8")); + assert!(is_json_content_type("application/json ; charset=UTF-8")); + assert!(!is_json_content_type("text/plain")); + assert!(!is_json_content_type("application/jsonx")); + assert!(!is_json_content_type("")); } } diff --git a/seamless/src/handler/handler.rs b/seamless/src/handler/handler.rs index 81dace7..cc83677 100644 --- a/seamless/src/handler/handler.rs +++ b/seamless/src/handler/handler.rs @@ -1,9 +1,9 @@ #![doc(hidden)] -use super::response::HandlerResponse; +use super::response::{Body, HandlerResponse}; use super::to_async::ToAsync; -use crate::api::{ApiBody, ApiBodyInfo, ApiError}; -use crate::handler::{request::AsyncReadBody, HandlerBody, HandlerParam}; -use http::{method::Method, Request, Response}; +use crate::api::{ApiBody, ApiBodyInfo, ApiBodyType, ApiError}; +use crate::handler::{HandlerBody, HandlerParam, request::AsyncReadBody}; +use http::{Method, Request, Response}; use std::future::Future; use std::pin::Pin; @@ -15,7 +15,7 @@ pub struct Handler { pub handler: Box< dyn for<'a> Fn( Request<&'a mut dyn AsyncReadBody>, - ) -> Fut<'a, Result>, ApiError>> + ) -> Fut<'a, Result, ApiError>> + Send + Sync, >, @@ -23,23 +23,33 @@ pub struct Handler { pub response_type: ApiBodyInfo, } +impl Handler { + /// Run the handler on a request. + pub fn call<'a>( + &self, + req: Request<&'a mut dyn AsyncReadBody>, + ) -> Fut<'a, Result, ApiError>> { + (self.handler)(req) + } +} + // A type alias for an overly complicated boxed Future type that can be sent across threads. type Fut<'a, T> = Pin + Send + 'a>>; /// This trait is implemented for all handler functions which are -/// applicable. Handler functions expect context arguments first, and -/// then optionally an argument that implements `Body` (eg `Json` or -/// `Binary`) if the handler requires a body to be provided. Arguments +/// applicable. Handler functions expect [`HandlerParam`] arguments first, and +/// then optionally an argument that implements [`HandlerBody`] (eg `FromJson` or +/// `FromBinary`) if the handler requires a body to be provided. Arguments /// are resolved in the order that they are provided. #[doc(hidden)] pub trait IntoHandler { fn into_handler(self) -> Handler; } -// We want the handler functions to support different numbers of contexts as well +// We want the handler functions to support different numbers of params as well // as either having a body or not; this macro generates the impls for this. -macro_rules! resolve_for_contexts { - ( $( $($ctx:ident)*, $($err:ident)* ;)* ) => { +macro_rules! impl_into_handler { + ( $( $($param:ident)* ;)* ) => { // Markers to differentiate the trait impls: #[doc(hidden)] @@ -47,24 +57,22 @@ macro_rules! resolve_for_contexts { #[doc(hidden)] pub struct WithoutBody; - // Impl each trait with and without the body, and with each number of contexts provided. + // Impl each trait with and without the body, and with each number of params provided. // The body must always be the last argument. These impls work because the traits in correct // usage will not overlap, and so the correct impl can be chosen. $( - impl - IntoHandler<(WithBody, HandlerFn, BodyParam, Res, Output, $($ctx,)* $($err,)* A)> for HandlerFn + impl + IntoHandler<(WithBody, HandlerFn, BodyParam, Res, Output, $($param,)* A)> for HandlerFn where // This is the rough shape we want a handler function to have: - HandlerFn: Fn($($ctx,)* BodyParam) -> Res + Clone + Sync + Send + 'static, + HandlerFn: Fn($($param,)* BodyParam) -> Res + Clone + Sync + Send + 'static, // The last argument to handler functions should be a HandlerBody: BodyParam: HandlerBody + ApiBody + Send, // Any other argument given must be a HandlerParam: - $( $ctx: HandlerParam + Send, )* - // Each of these params can return a unique error, but it needs to convert into ApiError: - $( $err: Into + Send + 'static, )* + $( $param: HandlerParam + Send, )* // The thing returned from the handler can be sync or async: Res: ToAsync + Send, @@ -84,22 +92,19 @@ macro_rules! resolve_for_contexts { $( #[allow(non_snake_case)] - let $ctx = $ctx::handler_param(&bodyless_req) + let $param = $param::handler_param(&bodyless_req) .await - .map_err(|e| { let e: ApiError = e.into(); e })?; + .map_err(Into::into)?; )* let (parts, _) = bodyless_req.into_parts(); let req = Request::from_parts(parts, body); - let body = BodyParam::handler_body(req).await.map_err(|e| { let e: ApiError = e.into(); e })?; - let response = inner_handler($($ctx,)* body) + let body = BodyParam::handler_body(req).await?; + inner_handler($($param,)* body) .to_async() .await .handler_response() .await - .map_err(|e| { let e: ApiError = e.into(); e })?; - - Ok(response) }) }), request_type: BodyParam::api_body_info(), @@ -108,16 +113,14 @@ macro_rules! resolve_for_contexts { } } - impl - IntoHandler<(WithoutBody, HandlerFn, Res, Output, $($ctx,)* $($err,)* A)> for HandlerFn + impl + IntoHandler<(WithoutBody, HandlerFn, Res, Output, $($param,)* A)> for HandlerFn where // This is the rough shape we want a handler function to have (this time, no "body" at the end): - HandlerFn: Fn($($ctx,)*) -> Res + Clone + Sync + Send + 'static, + HandlerFn: Fn($($param,)*) -> Res + Clone + Sync + Send + 'static, // Any argument given must be a HandlerParam: - $( $ctx: HandlerParam + Send, )* - // Each of these params can return a unique error, but it needs to convert into ApiError: - $( $err: Into + Send + 'static, )* + $( $param: HandlerParam + Send, )* // The thing returned from the handler can be sync or async: Res: ToAsync + Send, @@ -138,24 +141,21 @@ macro_rules! resolve_for_contexts { $( #[allow(non_snake_case)] - let $ctx = $ctx::handler_param(&bodyless_req) + let $param = $param::handler_param(&bodyless_req) .await - .map_err(|e| { let e: ApiError = e.into(); e })?; + .map_err(Into::into)?; )* - let response = inner_handler($($ctx),*) + inner_handler($($param),*) .to_async() .await .handler_response() .await - .map_err(|e| { let e: ApiError = e.into(); e })?; - - Ok(response) }) }), request_type: ApiBodyInfo { description: "No request body is expected".to_owned(), - ty: crate::api::ApiBodyType::Null + ty: ApiBodyType::Null }, response_type: ::ResponseBody::api_body_info() } @@ -165,30 +165,14 @@ macro_rules! resolve_for_contexts { )*} } -resolve_for_contexts!( - ,; - - C1, - E1; - - C1 C2, - E1 E2; - - C1 C2 C3, - E1 E2 E3; - - C1 C2 C3 C4, - E1 E2 E3 E4; - - E1 E2 E3 E4 E5, +impl_into_handler!( + ; + C1; + C1 C2; + C1 C2 C3; + C1 C2 C3 C4; C1 C2 C3 C4 C5; - - C1 C2 C3 C4 C5 C6, - E1 E2 E3 E4 E5 E6; - - C1 C2 C3 C4 C5 C6 C7, - E1 E2 E3 E4 E5 E6 E7; - - C1 C2 C3 C4 C5 C6 C7 C8, - E1 E2 E3 E4 E5 E6 E7 E8; + C1 C2 C3 C4 C5 C6; + C1 C2 C3 C4 C5 C6 C7; + C1 C2 C3 C4 C5 C6 C7 C8; ); diff --git a/seamless/src/handler/param.rs b/seamless/src/handler/param.rs index 61c3811..a7a2bcc 100644 --- a/seamless/src/handler/param.rs +++ b/seamless/src/handler/param.rs @@ -1,6 +1,6 @@ use crate::api::ApiError; -use async_trait::async_trait; use http::Request; +use std::future::Future; /// Implement this for anything that you want to be able to pass into a request /// handler that doesn't want to consume the body of the request. This is @@ -24,7 +24,6 @@ use http::Request; /// pub struct User { pub id: String } /// /// // Make it possible to ask for the current user in a request: -/// #[seamless::async_trait] /// impl HandlerParam for User { /// type Error = ApiError; /// async fn handler_param(req: &Request<()>) -> Result { @@ -38,7 +37,6 @@ use http::Request; /// } /// } /// ``` -#[async_trait] pub trait HandlerParam where Self: Sized, @@ -47,19 +45,18 @@ where /// our parameter from the provided request. /// /// To be usable with [`crate::api::Api`], the error should implement `Into` - /// (the [`macro@crate::ApiError`] macro can be used to gelp with this). + /// (the [`macro@crate::ApiError`] macro can be used to help with this). /// /// It can be simpler just to set this to `ApiError` directly. type Error: Into + 'static; - /// Given a [`http::Request<()>`], return a value of type `T` back, or - /// else return an error of type `E` describing what went wrong. Any errors + /// Given a [`http::Request<()>`], return a value of this type, or + /// else return an [`Self::Error`] describing what went wrong. Any errors /// here will lead to the route bailing out and the handler not being run. - async fn handler_param(req: &Request<()>) -> Result; + fn handler_param(req: &Request<()>) -> impl Future> + Send; } -// Option means we'll return None to the handler if handler_param would fail. +// Option means we'll return None to the handler if handler_param would fail. // This will never error. -#[async_trait] impl HandlerParam for Option { type Error = std::convert::Infallible; async fn handler_param(req: &Request<()>) -> Result { @@ -67,9 +64,8 @@ impl HandlerParam for Option { } } -// Result means we'll return the result of attempting to obtain the context. +// Result means we'll return the result of attempting to obtain the param. // This will never error. -#[async_trait] impl HandlerParam for Result::Error> { type Error = ::Error; async fn handler_param(req: &Request<()>) -> Result { diff --git a/seamless/src/handler/request.rs b/seamless/src/handler/request.rs index ff9c98d..d08815d 100644 --- a/seamless/src/handler/request.rs +++ b/seamless/src/handler/request.rs @@ -5,11 +5,11 @@ provided as a request body, but this module provides a `Bytes` struct which can [`Vec`] or [`futures::Stream`] into such a body. */ use futures::{ - io::{AsyncRead, Cursor}, Stream, TryStreamExt, + io::{AsyncRead, Cursor}, }; use std::pin::Pin; -use std::task::{Context, Poll}; +use std::task::{Context, Poll, ready}; /// Any valid body will implement this trait pub trait AsyncReadBody: AsyncRead + Send + Unpin {} @@ -30,7 +30,7 @@ enum BytesVariant { impl std::fmt::Debug for Bytes { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_tuple("ByteStream").finish() + f.debug_tuple("Bytes").finish() } } @@ -40,16 +40,10 @@ impl AsyncRead for Bytes { cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll> { - // If Bytes is pinned, the enum variant is also pinned, so here - // we just want to convert a Pin<&mut Bytes> into the relevant variant - // to poll it. Very much the same sort of idea as: - // - // https://github.com/rust-lang/futures-rs/blob/0.3.0-alpha.12/futures-core/src/stream/mod.rs#L88-L102 - unsafe { - match &mut Pin::get_unchecked_mut(self).variant { - BytesVariant::FromVec(v) => Pin::new_unchecked(v).poll_read(cx, buf), - BytesVariant::FromReader(r) => Pin::new_unchecked(r).poll_read(cx, buf), - } + // Both variants are Unpin, so Bytes is too. + match &mut self.get_mut().variant { + BytesVariant::FromVec(v) => Pin::new(v).poll_read(cx, buf), + BytesVariant::FromReader(r) => Pin::new(r).poll_read(cx, buf), } } } @@ -76,22 +70,73 @@ impl Bytes { } } /// Turn a thing implementing [`futures::Stream`] into [`Bytes`]. - pub fn from_stream>> + 'static + Send + Unpin>( - stream: S, - ) -> Bytes { + pub fn from_stream(stream: S) -> Bytes + where + S: Stream>> + Send + Unpin + 'static, + { Bytes { variant: BytesVariant::FromReader(Box::new(stream.into_async_read())), } } } +/// This wraps other `AsyncRead` impls and caps how many bytes can be +/// read from the underlying reader before an `UnexpectedEof` error is +/// returned. The cap exists at the type level via `const MAX`. +pub(crate) struct CappedAsyncRead { + inner: T, + bytes_read: usize, +} + +/// The error handed back when the size limit is hit for some request. +#[derive(Debug, Clone, Copy)] +pub(crate) struct CappedSizeLimitError; +impl std::error::Error for CappedSizeLimitError {} +impl std::fmt::Display for CappedSizeLimitError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Size limit exceeded") + } +} + +impl AsyncRead for CappedAsyncRead { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut [u8], + ) -> Poll> { + let this = self.get_mut(); + let new_bytes_read = ready!(Pin::new(&mut this.inner).poll_read(cx, buf))?; + + // Bail if we've read more bytes than our limit allows: + this.bytes_read += new_bytes_read; + if this.bytes_read > MAX { + return Poll::Ready(Err(std::io::Error::new( + std::io::ErrorKind::UnexpectedEof, + CappedSizeLimitError, + ))); + } + + // Return the number of bytes written on this run: + Poll::Ready(Ok(new_bytes_read)) + } +} + +impl CappedAsyncRead { + pub fn new(read: T) -> CappedAsyncRead { + CappedAsyncRead { + inner: read, + bytes_read: 0, + } + } +} + #[cfg(test)] -mod test_bytes { +mod tests { use super::*; use futures::AsyncReadExt; #[tokio::test] - async fn can_read_from_vec() { + async fn bytes_can_read_from_vec() { let mut bytes = Bytes::from_vec(vec![1, 2, 3, 4, 5]); let mut output = vec![]; @@ -105,7 +150,7 @@ mod test_bytes { } #[tokio::test] - async fn can_read_from_reader() { + async fn bytes_can_read_from_reader() { // We use another instance of Bytes as our reader: let mut bytes = Bytes::from_reader(Bytes::from_vec(vec![1, 2, 3, 4, 5])); @@ -120,7 +165,7 @@ mod test_bytes { } #[tokio::test] - async fn can_read_from_stream() { + async fn bytes_can_read_from_stream() { let mut bytes = Bytes::from_stream(futures::stream::iter(vec![ Ok(vec![1]), Ok(vec![2]), @@ -138,61 +183,6 @@ mod test_bytes { assert_eq!(n, 5); assert_eq!(output, vec![1, 2, 3, 4, 5]); } -} - -/// This wraps other `AsyncRead` impls and caps how many bytes can be -/// read from the underlying reader before an `UnexpectedEof` error is -/// returned. The cap exists at the type level via `const MAX`. -pub(crate) struct CappedAsyncRead { - inner: T, - bytes_read: usize, -} - -impl AsyncRead for CappedAsyncRead { - fn poll_read( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - buf: &mut [u8], - ) -> Poll> { - // Structural projection; Pin to Pin. Must not access the field in any other way. - let inner = unsafe { self.as_mut().map_unchecked_mut(|lr| &mut lr.inner) }; - - // Read some bytes into the provided buffer: - let new_bytes_read = match inner.poll_read(cx, buf) { - Poll::Ready(Ok(n)) => n, - Poll::Ready(Err(e)) => return Poll::Ready(Err(e)), - Poll::Pending => return Poll::Pending, - }; - - // Bail if we've read more bytes than our limit allows. Non-structural projection here; - // Pin to &mut usize. - let bytes_read = unsafe { &mut self.as_mut().get_unchecked_mut().bytes_read }; - *bytes_read += new_bytes_read; - if *bytes_read > MAX { - return Poll::Ready(Err(std::io::Error::new( - std::io::ErrorKind::UnexpectedEof, - "Size limit exceeded", - ))); - } - - // Return the number of bytes written on this run: - Poll::Ready(Ok(new_bytes_read)) - } -} - -impl CappedAsyncRead { - pub fn new(read: T) -> CappedAsyncRead { - CappedAsyncRead { - inner: read, - bytes_read: 0, - } - } -} - -#[cfg(test)] -mod test_capped_reader { - use super::*; - use futures::AsyncReadExt; #[tokio::test] async fn capped_reader_ok_with_0_bytes() { diff --git a/seamless/src/handler/response.rs b/seamless/src/handler/response.rs index c509f2f..5b1f2d0 100644 --- a/seamless/src/handler/response.rs +++ b/seamless/src/handler/response.rs @@ -1,33 +1,226 @@ -use crate::api::{ApiBody, ApiBodyInfo, ApiError}; -use async_trait::async_trait; +use crate::api::{ApiBody, ApiBodyInfo, ApiBodyType, ApiError}; +use bytes::Bytes; +use futures::io::{AsyncRead, AsyncReadExt}; +use futures::stream::{self, BoxStream, Stream, StreamExt}; +use http::header::{CONTENT_LENGTH, CONTENT_TYPE}; use serde::Serialize; +use std::borrow::Cow; +use std::future::Future; +use std::pin::Pin; +use std::task::{Context, Poll}; -type HttpResponse = http::Response>; +type HttpResponse = http::Response; /// Anything that you'd like to be able to return from a handler function must implement /// this trait, which decides how to take the result of a handler function and encode it -/// into an [`http::Response>`], or failing to do so, returns an [`struct@ApiError`]. -#[async_trait] +/// into an [`http::Response`], or failing to do so, returns an [`struct@ApiError`]. pub trait HandlerResponse { /// The type that we should look at to work out what the response body will look like. type ResponseBody: ApiBody; /// This describes how the type can be converted into an `http::Response`. - async fn handler_response(self) -> Result; + fn handler_response(self) -> impl Future> + Send; +} + +/// The body of an [`http::Response`] handed back from [`crate::api::Api::handle()`]. +/// +/// A body is either a complete set of bytes that are already in memory, or a stream of +/// chunks of bytes which are handed back as they become available. +/// +/// # Errors while streaming +/// +/// By the time a streaming body is being read from, the response status and headers +/// will likely have been sent already, so any error that the stream emits cannot be turned +/// into a nice [`struct@ApiError`] response. Instead, the HTTP framework you're using will +/// typically abort the response. Anything that might fail in a way that the client should +/// be told about (eg a file not existing) should therefore be checked before a streaming +/// body is handed back. +pub struct Body(Inner); + +enum Inner { + Full(Bytes), + Stream(BoxStream<'static, std::io::Result>), +} + +impl std::fmt::Debug for Body { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match &self.0 { + Inner::Full(bytes) => f.debug_tuple("Body::Full").field(bytes).finish(), + Inner::Stream(_) => f.debug_tuple("Body::Stream").finish(), + } + } +} + +impl Default for Body { + fn default() -> Self { + Body::empty() + } +} + +impl Body { + /// An empty body. + pub fn empty() -> Body { + Body(Inner::Full(Bytes::new())) + } + + /// Create a body from some bytes that are already in memory. + pub fn from_bytes(bytes: impl Into) -> Body { + Body(Inner::Full(bytes.into())) + } + + /// Create a streaming body from a [`futures::Stream`] of chunks of bytes. + pub fn from_stream(stream: S) -> Body + where + S: Stream> + Send + 'static, + B: Into, + { + Body(Inner::Stream(stream.map(|r| r.map(Into::into)).boxed())) + } + + /// Create a streaming body from something implementing [`futures::AsyncRead`]. + /// Bytes are read from it in chunks of up to 8KiB as the body is streamed. + /// The stream ends after the reader returns an error. + pub fn from_reader(reader: R) -> Body + where + R: AsyncRead + Send + 'static, + { + const CHUNK_SIZE: usize = 8 * 1024; + let state = Some((Box::pin(reader), vec![0u8; CHUNK_SIZE])); + let stream = stream::unfold(state, |state| async move { + let (mut reader, mut buf) = state?; + match reader.read(&mut buf).await { + Ok(0) => None, + Ok(n) => { + let chunk = Bytes::copy_from_slice(&buf[..n]); + Some((Ok(chunk), Some((reader, buf)))) + } + // Stop reading after an error by setting state to None: + Err(e) => Some((Err(e), None)), + } + }); + Body(Inner::Stream(stream.boxed())) + } + + /// If the body is entirely in memory already, this returns a reference to the bytes. + /// Else it returns `None` if the body is a stream and thus not yet available. + pub fn as_bytes(&self) -> Option<&Bytes> { + match &self.0 { + Inner::Full(bytes) => Some(bytes), + Inner::Stream(_) => None, + } + } + + /// If the body is entirely in memory already, return it as [`Bytes`]. Otherwise, + /// hand back the streaming body unchanged in the `Err` variant. + pub fn into_bytes(self) -> Result { + match self.0 { + Inner::Full(bytes) => Ok(bytes), + inner @ Inner::Stream(_) => Err(Body(inner)), + } + } + + /// Convert the body into a [`BodyStream`], which implements [`futures::Stream`] and + /// hands back chunks of bytes as they become available. + pub fn into_stream(self) -> BodyStream { + BodyStream(self.0) + } + + /// Read the entire body into a [`Vec`]. This is mostly useful for tests; prefer to + /// stream bodies through to the client where possible. + pub async fn into_vec(self) -> std::io::Result> { + match self.0 { + Inner::Full(bytes) => Ok(bytes.to_vec()), + Inner::Stream(mut stream) => { + let mut out = Vec::new(); + while let Some(chunk) = stream.next().await { + out.extend_from_slice(&chunk?); + } + Ok(out) + } + } + } +} + +/// A [`futures::Stream`] of chunks of bytes, obtained via [`Body::into_stream()`]. +// When streaming, `Inner::Full` is left empty once its bytes have been handed out; +// we never hand back an empty chunk. +pub struct BodyStream(Inner); + +impl std::fmt::Debug for BodyStream { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match &self.0 { + Inner::Full(bytes) => f.debug_tuple("BodyStream::Full").field(bytes).finish(), + Inner::Stream(_) => f.debug_tuple("BodyStream::Stream").finish(), + } + } +} + +impl Stream for BodyStream { + type Item = std::io::Result; + + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + // BodyStream is Unpin, since both Bytes and BoxStream are. + match &mut self.get_mut().0 { + Inner::Full(bytes) if bytes.is_empty() => Poll::Ready(None), + // Taking leaves an empty `Bytes` behind, which doesn't allocate. + Inner::Full(bytes) => Poll::Ready(Some(Ok(std::mem::take(bytes)))), + Inner::Stream(stream) => stream.poll_next_unpin(cx), + } + } + + fn size_hint(&self) -> (usize, Option) { + match &self.0 { + Inner::Full(bytes) => { + let n = usize::from(!bytes.is_empty()); + (n, Some(n)) + } + Inner::Stream(stream) => stream.size_hint(), + } + } +} + +impl From> for Body { + fn from(bytes: Vec) -> Self { + Body::from_bytes(bytes) + } +} + +impl From for Body { + fn from(bytes: Bytes) -> Self { + Body::from_bytes(bytes) + } +} + +impl From for Body { + fn from(s: String) -> Self { + Body::from_bytes(s) + } +} + +impl From<&'static [u8]> for Body { + fn from(bytes: &'static [u8]) -> Self { + Body::from_bytes(bytes) + } +} + +impl From<&'static str> for Body { + fn from(s: &'static str) -> Self { + Body::from_bytes(s) + } } /// Wrap responses in this to return them as JSON -pub struct ToJson(pub T); +pub struct ToJson(pub T); -#[async_trait] impl HandlerResponse for ToJson { type ResponseBody = T; async fn handler_response(self) -> Result { - let body = serde_json::to_vec(&self.0).unwrap(); - let res = http::Response::builder() - .header("content-type", "application/json") - .body(body) - .unwrap(); - Ok(res) + let body = serde_json::to_vec(&self.0).map_err(|e| { + ApiError::server_error(format!("Could not serialize response to JSON: {e}")) + })?; + http::Response::builder() + .header(CONTENT_TYPE, "application/json") + .body(Body::from(body)) + .map_err(|e| ApiError::server_error(format!("Could not build JSON response: {e}"))) } } @@ -40,8 +233,111 @@ where } } -// Options are valid HandlerResponse's if their T's are -#[async_trait] +/// Return this from a handler to respond with arbitrary binary data, which can +/// optionally be streamed rather than being loaded into memory all at once. +/// +/// The `content-type` defaults to `application/octet-stream`, and can be changed +/// with [`ToBinary::content_type()`]. +/// +/// See [`Body`] for a note on how errors that occur while streaming are handled. +/// +/// # Examples +/// +/// ``` +/// # use seamless::{ Api, handler::response::ToBinary }; +/// # let mut api = Api::new(); +/// // Return some bytes that we already have: +/// api.add("hello") +/// .handler(|| ToBinary::new("hello world").content_type("text/plain")); +/// +/// // Stream some bytes back without loading them all into memory first: +/// api.add("count") +/// .handler(|| { +/// let chunks = futures::stream::iter(1..=1000) +/// .map(|n| Ok::<_, std::io::Error>(format!("{n}\n"))); +/// ToBinary::stream(chunks).content_type("text/plain") +/// }); +/// # use futures::StreamExt; +/// ``` +#[derive(Debug)] +pub struct ToBinary { + body: Body, + content_type: Cow<'static, str>, + content_length: Option, +} + +impl ToBinary { + /// Respond with the given body. This can be anything which converts into a [`Body`], + /// including a [`Body`] itself, `Vec`, [`Bytes`] or `String`. + pub fn new(body: impl Into) -> ToBinary { + let body = body.into(); + + // If the body length is known up front, tell the client: + let content_length = body.as_bytes().map(Bytes::len); + + ToBinary { + body, + content_type: Cow::Borrowed("application/octet-stream"), + content_length, + } + } + + /// Respond with a stream of chunks of bytes. Shorthand for + /// `ToBinary::new(Body::from_stream(stream))`. + pub fn stream(stream: S) -> ToBinary + where + S: Stream> + Send + 'static, + B: Into, + { + ToBinary::new(Body::from_stream(stream)) + } + + /// Respond with bytes read from some [`futures::AsyncRead`] implementation. Shorthand + /// for `ToBinary::new(Body::from_reader(reader))`. + pub fn reader(reader: R) -> ToBinary + where + R: AsyncRead + Send + 'static, + { + ToBinary::new(Body::from_reader(reader)) + } + + /// Set the `content-type` header of the response. + pub fn content_type(mut self, content_type: impl Into>) -> ToBinary { + self.content_type = content_type.into(); + self + } + + /// Set the `content-length` header of the response. This is useful when streaming + /// something whose size is known ahead of time (eg a file), so that clients can + /// report progress. It's up to you to ensure that the length is correct. + pub fn content_length(mut self, len: usize) -> ToBinary { + self.content_length = Some(len); + self + } +} + +impl HandlerResponse for ToBinary { + type ResponseBody = ToBinary; + async fn handler_response(self) -> Result { + let mut res = http::Response::builder().header(CONTENT_TYPE, &*self.content_type); + if let Some(len) = self.content_length { + res = res.header(CONTENT_LENGTH, len); + } + res.body(self.body) + .map_err(|e| ApiError::server_error(format!("Could not build binary response: {e}"))) + } +} + +impl ApiBody for ToBinary { + fn api_body_info() -> ApiBodyInfo { + ApiBodyInfo { + description: "Binary data".to_owned(), + ty: ApiBodyType::Binary, + } + } +} + +// Options are valid HandlerResponses if their T's are. `None` becomes a 404. impl HandlerResponse for Option where T: HandlerResponse + Send, @@ -53,8 +349,7 @@ where } } -// Results are valid HandlerResponse's if their T's are, and their E's convert to ApiError -#[async_trait] +// Results are valid HandlerResponses if their T's are, and their E's convert to ApiError impl HandlerResponse for Result where T: HandlerResponse + Send, @@ -62,7 +357,108 @@ where { type ResponseBody = ::ResponseBody; async fn handler_response(self) -> Result { - let res = self.map_err(|e| e.into())?; + let res = self.map_err(Into::into)?; res.handler_response().await } } + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn to_json_serialize_error_is_500() { + struct Bad; + impl Serialize for Bad { + fn serialize(&self, _: S) -> Result { + Err(serde::ser::Error::custom("nope")) + } + } + impl ApiBody for Bad { + fn api_body_info() -> ApiBodyInfo { + ::api_body_info() + } + } + + let err = ToJson(Bad) + .handler_response() + .await + .expect_err("serialization failure should be an error, not a panic"); + assert_eq!(err.code, 500); + assert_eq!(err.external_message, ApiError::SERVER_ERROR); + assert!(err.internal_message.contains("nope")); + } + + #[tokio::test] + async fn full_body_is_bytes() { + let body = Body::from(vec![1, 2, 3]); + assert_eq!(body.as_bytes(), Some(&Bytes::from(vec![1, 2, 3]))); + assert_eq!(body.into_bytes().unwrap(), Bytes::from(vec![1, 2, 3])); + + let body = Body::empty(); + assert_eq!(body.as_bytes(), Some(&Bytes::new())); + assert_eq!(body.into_bytes().unwrap(), Bytes::new()); + } + + #[tokio::test] + async fn full_body_streams_once() { + let chunks: Vec<_> = Body::from(vec![1, 2, 3]) + .into_stream() + .map(|c| c.unwrap()) + .collect() + .await; + assert_eq!(chunks, vec![Bytes::from(vec![1, 2, 3])]); + + let chunks: Vec<_> = Body::empty().into_stream().collect().await; + assert!(chunks.is_empty()); + } + + #[tokio::test] + async fn full_body_stream_size_hint() { + let mut stream = Body::from(vec![1, 2, 3]).into_stream(); + assert_eq!(stream.size_hint(), (1, Some(1))); + assert!(stream.next().await.is_some()); + assert_eq!(stream.size_hint(), (0, Some(0))); + assert!(stream.next().await.is_none()); + + assert_eq!(Body::empty().into_stream().size_hint(), (0, Some(0))); + } + + #[tokio::test] + async fn stream_body_is_not_bytes() { + let body = Body::from_stream(stream::iter(vec![Ok(vec![1]), Ok(vec![2, 3])])); + assert!(body.as_bytes().is_none()); + let body = body + .into_bytes() + .expect_err("stream body should not be bytes"); + assert_eq!(body.into_vec().await.unwrap(), vec![1, 2, 3]); + } + + #[tokio::test] + async fn stream_body_preserves_chunks() { + let body = Body::from_stream(stream::iter(vec![Ok(vec![1]), Ok(vec![2, 3])])); + let chunks: Vec<_> = body.into_stream().map(|c| c.unwrap()).collect().await; + assert_eq!(chunks, vec![Bytes::from(vec![1]), Bytes::from(vec![2, 3])]); + } + + #[tokio::test] + async fn stream_body_propagates_errors() { + let body = Body::from_stream(stream::iter(vec![ + Ok(vec![1]), + Err(std::io::Error::other("boom")), + ])); + let err = body.into_vec().await.expect_err("error expected"); + assert_eq!(err.to_string(), "boom"); + } + + #[tokio::test] + async fn reader_body_reads_everything() { + // More than one chunk's worth of data: + let data: Vec = (0..20_000u32).map(|n| n as u8).collect(); + let body = Body::from_reader(futures::io::Cursor::new(data.clone())); + assert!(body.as_bytes().is_none()); + + let body = Body::from_reader(futures::io::Cursor::new(data.clone())); + assert_eq!(body.into_vec().await.unwrap(), data); + } +} diff --git a/seamless/src/handler/to_async.rs b/seamless/src/handler/to_async.rs index e5c328b..3399e49 100644 --- a/seamless/src/handler/to_async.rs +++ b/seamless/src/handler/to_async.rs @@ -13,9 +13,9 @@ pub trait ToAsync { #[doc(hidden)] pub struct Async; -impl ToAsync for F +impl ToAsync for F where - F: Future + Send + 'static, + F: Future + Send + 'static, { type Output = F; fn to_async(self) -> Self::Output { @@ -25,14 +25,14 @@ where #[doc(hidden)] pub struct Sync; -impl ToAsync for Res +impl ToAsync for T where - // Res has to be constrained to be HandlerResponse + // T has to be constrained to be HandlerResponse // only so that no output can potentially implement both // the Sync and Async version of the trait. - Res: Send + 'static + HandlerResponse, + T: Send + 'static + HandlerResponse, { - type Output = Pin + Send + 'static>>; + type Output = Pin + Send + 'static>>; fn to_async(self) -> Self::Output { Box::pin(async move { self }) } diff --git a/seamless/src/lib.rs b/seamless/src/lib.rs index 77aed14..51f94be 100644 --- a/seamless/src/lib.rs +++ b/seamless/src/lib.rs @@ -1,29 +1,29 @@ #![warn(missing_docs)] /*! -This library aims to provide an easy-to-use and extensible approach to declaring API routes, and will automatically -keep track of various information surrounding requests and responses so that detailed route information (including type -information) can be generated based on the current state of the API. +Seamless provides a way to declare a simple RPC style HTTP API, and from this declaration can hand back enough +information that we can generate a type safe HTTP client for interacting with it. -This library is fully async, but totally independent from any particular async implementation (you don't even need to -toggle any feature flags). +Seamless supports async handlers and streaming HTTP requests, but is entirely HTTP framework and async framework +agnostic: it can be wired in to your frameworks of choice. For instance, you could use seamless to handle the +API routes in an Axum app and use normal Axum routes to serve other content alongside this API. -Using Seamless, we can write our API in pure Rust, and from that generate a TypeScript based API client (or just the types, -or just documentation) based on the current state of the API. This allows us to achieve type safe communication between the -API and TypeScript-like clients without relying on external specifications like OpenAPI. +[See the examples](https://github.com/jsdw/seamless/tree/master/seamless/examples) -The typical steps for using this library are: +# How does it work? -- Annotate your input and output types for these routes with the [`macro@ApiBody`] macro. -- Derive [`macro@ApiError`] (or manually implement `Into`) on any errors you wish to emit. -- Declare each of your API routes using this library. API handlers can just ask for whatever they need as a - function parameter, including arbitrary state or information based on the incoming request (you decide). -- Once the API routes are declared, use [`Api::info()`] to obtain enough information about the API to - generate fully type safe client code (the information is optimised towards generating TypeScript types/code). -- Integrate this API with something like `warp` or `rocket` so that your `seamless` API routes can live alongside - everything else that you'd like to serve (see the examples for how this can be done). +Each API route that you wish to create exists at some path, and is given a handler function which can expect +a specific shape of request body, and will return a specific shape of response, or else an error if things go wrong. -Have a look at the examples in the `examples` directory to get a proper feel for how this library can be used, or -keep reading! +The expected body and response types must implement the [`trait@crate::ApiBody`] trait, and any errors that are +used must convert into an [`struct@crate::ApiError`]. Both can be derived via the provided macros, which under the +hood will: +- Implement the [`serde::Serialize`] and [`serde::Deserialize`] traits so that we can receive and respond with + values of the given types. +- Implement [`trait@crate::ApiBody`] or `Into` so that we know the shape of the incoming and + outgoing types, and how any given error should be presented to the client and with what status code. + +See the `seamless/examples` folder in the crate repository for working examples demonstrating how to use +seamless with both Hyper and Axum, as well as a couple of more basic examples. # A Basic Example @@ -37,17 +37,15 @@ use seamless::{ handler::{ body::FromJson, request::Bytes, response::ToJson } }; -// The API relies on types that have been annotated with `ApiBody` (request and response -// types) or `ApiError` (for any errors we might give back). These annotations do some -// reflection to allow us to get information about the shape of the type and doc comments -// added to it, as well as ensuring that they can be Serialized/Deserialized. - +// This is an input to one of our API routes. We annotate it with the ApiBody +// macro so that it can be worked with by seamless as a request or response body. #[ApiBody] struct DivisionInput { a: usize, b: usize } +// We do the same for the type we expect to hand back in a successful response #[ApiBody] #[derive(PartialEq)] struct DivisionOutput { @@ -56,9 +54,10 @@ struct DivisionOutput { result: usize } -// Any errors that we return must implement `Into`, Display and Debug. We can derive -// `ApiError` to automate this for us. Here we use `thiserror` to derive the Display impl -// for us. See the documentation on the `ApiError` macro for more info. +// If we'd like to return a specific error from one of our API routes, we annotate it +// with ApiError, as well as expecting it to be displayable. This allows seamless to +// set the correct HTTP status code given the error returned, and return them in a +// consistent way. #[derive(ApiError, Debug, thiserror::Error, PartialEq)] enum MathsError { #[error("Division by zero")] @@ -68,9 +67,10 @@ enum MathsError { let mut api = Api::new(); -// We add routes to our new API like so. The handler functions would often be defined -// separately and called from this handler. Handler functions can be async or sync, and can -// return any valid handler::HandlerResponse. +// Now, let's define some routes for our API. Handler functions can be async or sync, +// and can return any valid handler::HandlerResponse. Here we use `ToJson` to return +// JSON responses, and in one case return a Result which is either the error we defined +// above, or the response type we defined above. api.add("/echo") .description("Echoes back a JSON string") .handler(|body: FromJson| ToJson(body.0)); @@ -91,14 +91,13 @@ api.add("/maths.divide") // Once we've added routes to the `api`, we use it by sending `http::Request`s to it. // Since we're expecting JSON to be provided, we need to remember to set the correct -// content-type: - +// content-type so that our FromJson input tries to decode it as valid JSON. let req = Request::post("/maths.divide") .header("content-type", "application/json") .body(Bytes::from_vec(serde_json::to_vec(&DivisionInput { a: 20, b: 10 }).unwrap())) .unwrap(); assert_eq!( - api.handle(req).await.unwrap().into_body(), + api.handle(req).await.unwrap().into_body().into_vec().await.unwrap(), serde_json::to_vec(&DivisionOutput{ a: 20, b: 10, result: 2 }).unwrap() ); # }); @@ -108,7 +107,7 @@ assert_eq!( Most real life use cases will require some sort of state to be accessible inside a handler. -This library follows an approach a little similar to `Rocket`. Any type that implements the +This library follows an approach a little similar to `Axum`. Any type that implements the [`handler::HandlerParam`] trait can be passed into handler functions. Using this trait, you can inspect the request to do things like obtain user information from a session ID, or you can pull state out of the `Request` object that was placed there prior to it being handed to this library. @@ -128,12 +127,11 @@ use seamless::{ # async fn divide(input: BinaryInput) -> Option { Some(BinaryOutput {}) } # tokio::runtime::Runtime::new().unwrap().block_on(async { -// Something we want to inject into our handler. +// Some example state we want to inject into our handler. #[derive(Clone)] -struct State; +struct State { value: usize }; -// Teach the library how to get hold of State when asked for it. -#[seamless::async_trait] +// Teach the library how to get hold of our "State" value when asked for it. impl HandlerParam for State { type Error = ApiError; async fn handler_param(req: &http::Request<()>) -> Result { @@ -146,24 +144,26 @@ impl HandlerParam for State { let mut api = Api::new(); -// Note that we can now ask for `State` as a parameter to the handler. State -// MUST come before our `Json<_>` parameter. `HandlerParam` impls are evaluated -// in the order that arguments appear in the parameter list. +// We can now ask for `State` as a parameter to the handler, as well as the HTTP body, +// which we extract as JSON using `FromJson`. We must always ask for the body last. api.add("/echo") - .description("Echoes back a JSON string") - .handler(|_state: State, body: FromJson| ToJson(body.0)); + .description("Echoes back a JSON string, plus our state value") + .handler(|state: State, body: FromJson| ToJson(format!("{}, {}", body.0, state.value))); +// Now, to demo it, we build an HTTP request to send to this route. let mut req = http::Request::post("/echo") .header("content-type", "application/json") .body(Bytes::from_vec(serde_json::to_vec("hello").unwrap())) .unwrap(); // When passing a request into our API, remember to inject `State` too so that -// it's available for our `HandlerParam` trait to extract: -req.extensions_mut().insert(State); +// it's available for our `HandlerParam` trait to extract when asked for. +req.extensions_mut().insert(State { value: 123 }); -// We can now handle the request without issues: -assert!(api.handle(req).await.is_ok()); +// We can now handle a request that is expecting our `State` to be available. +// The response comes back as a JSON string. +let res = api.handle(req).await.unwrap().into_body().into_vec().await.unwrap(); +assert_eq!(res, "\"hello, 123\"".as_bytes()); # }) ``` @@ -190,7 +190,17 @@ Responses from handlers can be plain old synchronous objects or [`std::future::F in either case must implement [`handler::HandlerResponse`]. This trait determines how to create the response to hand back to the user. -For convenience, a [`handler::response::ToJson`] type is provided that will encode the response as JSON. +For convenience, a couple of types are provided which implement this trait: + +- [`handler::response::ToJson`] will encode the response as JSON. +- [`handler::response::ToBinary`] will respond with arbitrary bytes, which can be streamed back (from a + [`futures::Stream`] or [`futures::AsyncRead`]) rather than loaded into memory all at once. Note that errors + which occur partway through streaming a response can't be turned into an [`struct@api::ApiError`], because the + response status will already have been sent. + +Responses handed back from [`Api::handle()`] have a [`handler::response::Body`]. This is either a set of bytes that +are entirely in memory, or a stream of chunks of bytes, and can be handed over to whichever HTTP framework you're +using without needing to buffer streaming responses (see the examples folder for how this is done in Axum and Hyper). [`handler::HandlerResponse`] is also implemented for `Option`s and `Result`s, returning a 404 in the event that the `Option` is `None`, and returning the error from the `Result` (this must itself implement `Into`) in the @@ -244,7 +254,7 @@ async fn divide(input: BinaryInput) -> Result,MathsError> { todo!() } -// A small APi with one route: +// A small API with one route: let mut api = Api::new(); api.add("maths/divide") .description("Divide two numbers by each other") @@ -302,18 +312,18 @@ let info_json = json!([ ``` The "shape" object can have one of the following "type" literals: `String`, `Number`, `Boolean`, `Null`, -`Any`, `ArrayOf`, `TupleOf`, `ObjectOf`, `Object`, `OneOf`, `StringLiteral`, `Optional`. Some of these will come -with an additional perty. See `seamless/src/api/info.rs` to get a better feel for exactly what the possible responses -can be. +`Any`, `Unknown`, `Binary`, `ArrayOf`, `TupleOf`, `ObjectOf`, `Object`, `OneOf`, `StringLiteral`, `Optional`. Some +of these will come with an additional property. See [`ApiBodyType`] to get a better feel for exactly what the possible +responses can be. # Integrating with other libraries Instead of passing requests in manually, you'll probably want to attach an API you define here to a library like -`Rocket` or `Warp` (or perhaps just plain old `Hyper`) so that you can benefit from the full power and flexibility +`Axum` (or perhaps just plain old `Hyper`) so that you can benefit from the full power and flexibility of a well rounded HTTP library alongside your well typed `seamless` API, and actually make the API available externally. -See `examples/warp.rs` and `examples/rocket.rs` for examples of how you might integrate this library with those. +See `examples/axum.rs` and `examples/hyper.rs` for examples of how you might integrate this library with those. Essentially it boils down to being able to construct an `http::Request` from whatever input the library gives you access to, and being able to handle the `http::Response` or error that's handed back from Seamless. @@ -324,7 +334,7 @@ to server without using external tools like OpenAPI. - Seamless has not been optimised for building RESTful style APIs. However, the [`handler::HandlerBody`] and [`handler::HandlerParam`] traits in particular provide a bunch of extensibility. -- Some of the flexiblity that `Serde` provides for manipulating how types are serialized and deserialized is not +- Some of the flexibility that `Serde` provides for manipulating how types are serialized and deserialized is not available. This library takes the approach of 'wrapping' serde using the [`macro@ApiBody`] macro to deliberately restrict how you can transform types, ensuring that any transformations allowed are properly supported and lead to the correct type information being generated. @@ -339,8 +349,6 @@ pub mod serde { pub use serde::*; } -pub use async_trait::async_trait; - /// A re-export of types from the `http` crate that are useful here. pub mod http { pub use http::{Method, Request, Response}; diff --git a/seamless/tests/aaa_compile_tests.rs b/seamless/tests/aaa_compile_tests.rs index ab08f58..7f55a4c 100644 --- a/seamless/tests/aaa_compile_tests.rs +++ b/seamless/tests/aaa_compile_tests.rs @@ -20,6 +20,12 @@ fn compile_tests() { t.compile_fail("tests/api_body_compile_tests/11_enum_cant_mix_unit_named.rs"); + t.compile_fail("tests/api_body_compile_tests/12_optional_not_option.rs"); + t.compile_fail("tests/api_body_compile_tests/13_optional_unnamed.rs"); + t.compile_fail("tests/api_body_compile_tests/14_optional_flatten.rs"); + t.compile_fail("tests/api_body_compile_tests/15_enum_flatten.rs"); + t.pass("tests/api_body_compile_tests/16_optional_alias.rs"); + /* api_error */ // Structs @@ -36,4 +42,5 @@ fn compile_tests() { t.pass("tests/api_error_compile_tests/09_enum_toplevel_attrs.rs"); t.pass("tests/api_error_compile_tests/10_enum_fields.rs"); t.compile_fail("tests/api_error_compile_tests/11_enum_empty.rs"); + t.compile_fail("tests/api_error_compile_tests/12_inner_with_other_attrs.rs"); } diff --git a/seamless/tests/api_base_path.rs b/seamless/tests/api_base_path.rs new file mode 100644 index 0000000..0837cf0 --- /dev/null +++ b/seamless/tests/api_base_path.rs @@ -0,0 +1,60 @@ +use seamless::{ + api::{Api, RouteError}, + handler::{request::Bytes, response::ToJson}, + http::Request, +}; + +fn get(path: &str) -> Request { + Request::get(path).body(Bytes::from_vec(vec![])).unwrap() +} + +fn api_with_base(base: &str) -> Api { + let mut api = Api::new_with_base_path(base); + api.add("foo").handler(|| ToJson("foo")); + api.add("v2/foo").handler(|| ToJson("v2/foo")); + api +} + +async fn found(api: &Api, path: &str) -> bool { + match api.handle(get(path)).await { + Ok(_) => true, + Err(RouteError::NotFound(_)) => false, + Err(RouteError::Err(e)) => panic!("unexpected handler error for {path}: {e:?}"), + } +} + +#[tokio::test] +async fn base_path_matches_whole_segments_only() { + for base in ["/api", "api", "/api/", "api/"] { + let api = api_with_base(base); + assert!(found(&api, "/api/foo").await, "base {base:?}: /api/foo"); + assert!( + found(&api, "/api/v2/foo").await, + "base {base:?}: /api/v2/foo" + ); + assert!(found(&api, "/api//foo").await, "base {base:?}: /api//foo"); + assert!( + !found(&api, "/apiv2/foo").await, + "base {base:?}: /apiv2/foo" + ); + assert!(!found(&api, "/apifoo").await, "base {base:?}: /apifoo"); + assert!(!found(&api, "/foo").await, "base {base:?}: /foo"); + } +} + +#[tokio::test] +async fn multi_segment_base_path() { + let api = api_with_base("/a/b"); + assert!(found(&api, "/a/b/foo").await); + assert!(!found(&api, "/a/bc/foo").await); + assert!(!found(&api, "/a/foo").await); +} + +#[tokio::test] +async fn empty_base_path_matches_everything() { + for base in ["", "/"] { + let api = api_with_base(base); + assert!(found(&api, "/foo").await, "base {base:?}"); + assert!(found(&api, "/v2/foo").await, "base {base:?}"); + } +} diff --git a/seamless/tests/api_body_02_runtime_tests.rs b/seamless/tests/api_body_02_runtime_tests.rs index 4859763..ed9611c 100644 --- a/seamless/tests/api_body_02_runtime_tests.rs +++ b/seamless/tests/api_body_02_runtime_tests.rs @@ -1,6 +1,6 @@ use pretty_assertions::assert_eq; -use seamless::api::{ApiBodyInfo, ApiBodyType}; use seamless::ApiBody; +use seamless::api::{ApiBodyInfo, ApiBodyType}; macro_rules! map { ( $($key:expr => $val:expr),* ) => ({ @@ -50,11 +50,10 @@ fn has_struct_shape() { // Sanity check that serde outputs a format which aligns with expectation: assert_eq!( - Foo { + to_json_value(Foo { prop: 2, another_prop: true - } - .to_json_value(), + }), serde_json::json!({ "prop": 2, "another_prop": true }) ) } @@ -154,19 +153,19 @@ fn has_enum_shape() { // Sanity check that serde outputs a format which aligns with expectation: assert_eq!( - Foo::Lark { lark1: s("hi") }.to_json_value(), + to_json_value(Foo::Lark { lark1: s("hi") }), serde_json::json!({ "kind": "Lark", "lark1": "hi" }) ); assert_eq!( - Foo::Other(Other { other_prop: true }).to_json_value(), + to_json_value(Foo::Other(Other { other_prop: true })), serde_json::json!({ "kind": "Other", "other_prop": true }) ); assert_eq!( - Foo::AnotherOther(Other { other_prop: true }).to_json_value(), + to_json_value(Foo::AnotherOther(Other { other_prop: true })), serde_json::json!({ "kind": "AnotherOther", "other_prop": true }) ); assert_eq!( - Foo::Bar {}.to_json_value(), + to_json_value(Foo::Bar {}), serde_json::json!({ "kind": "Bar" }) ); } @@ -210,9 +209,9 @@ fn has_enum_shape_unit() { ); // Sanity check that serde outputs a format which aligns with expectation: - assert_eq!(Foo::A.to_json_value(), serde_json::json!("A")); - assert_eq!(Foo::B.to_json_value(), serde_json::json!("B")); - assert_eq!(Foo::C.to_json_value(), serde_json::json!("C")); + assert_eq!(to_json_value(Foo::A), serde_json::json!("A")); + assert_eq!(to_json_value(Foo::B), serde_json::json!("B")); + assert_eq!(to_json_value(Foo::C), serde_json::json!("C")); } #[test] @@ -252,7 +251,7 @@ fn delegates_to_inner() { // Sanity check that serde outputs a format which aligns with expectation: assert_eq!( - Foo(Foo2(Foo3 { hi: 2 })).to_json_value(), + to_json_value(Foo(Foo2(Foo3 { hi: 2 }))), serde_json::json!({ "hi": 2 }) ); } @@ -376,20 +375,21 @@ fn flattens() { // Sanity check that serde outputs a format which aligns with expectation: assert_eq!( - Foo { + to_json_value(Foo { hello: 10, another: Bar { there: true, world: s("w") } - } - .to_json_value(), + }), serde_json::json!({ "hello": 10, "there": true, "world": "w" }) ); // ... and check that flattening works the other way around, too: assert_eq!( - Foo::from_json_value(serde_json::json!({ "hello": 10, "there": true, "world": "w" })) - .unwrap(), + serde_json::from_value::( + serde_json::json!({ "hello": 10, "there": true, "world": "w" }) + ) + .unwrap(), Foo { hello: 10, another: Bar { @@ -399,3 +399,274 @@ fn flattens() { }, ); } + +#[test] +fn raw_identifiers_use_serde_names() { + #[ApiBody] + #[allow(dead_code, non_camel_case_types)] + enum Foo { + r#match { r#in: bool }, + } + + #[ApiBody] + #[allow(dead_code)] + struct Bar { + r#type: String, + } + + assert_eq!( + Foo::api_body_info(), + ApiBodyInfo { + description: s(""), + ty: ApiBodyType::OneOf { + values: vec![ApiBodyInfo { + description: s(""), + ty: ApiBodyType::Object { + keys: map! { + s("kind") => ApiBodyInfo { + description: s("Variant tag"), + ty: ApiBodyType::StringLiteral { literal: s("match") } + }, + s("in") => ApiBodyInfo { + description: s(""), + ty: ApiBodyType::Boolean + } + } + } + }] + } + } + ); + + assert_eq!( + Bar::api_body_info(), + ApiBodyInfo { + description: s(""), + ty: ApiBodyType::Object { + keys: map! { + s("type") => ApiBodyInfo { + description: s(""), + ty: ApiBodyType::String + } + } + } + } + ); + + // Sanity check that serde outputs a format which aligns with expectation: + assert_eq!( + to_json_value(Foo::r#match { r#in: true }), + serde_json::json!({ "kind": "match", "in": true }) + ); + assert_eq!( + to_json_value(Bar { r#type: s("t") }), + serde_json::json!({ "type": "t" }) + ); +} + +#[test] +fn option_is_nullable_by_default() { + #[ApiBody] + #[allow(dead_code)] + struct Foo { + /// Maybe a number + a: Option, + b: Vec>, + } + + #[ApiBody] + #[allow(dead_code)] + struct Bar(Option); + + assert_eq!( + Foo::api_body_info(), + info(ApiBodyType::Object { + keys: map! { + s("a") => ApiBodyInfo { + description: s("Maybe a number"), + ..nullable(ApiBodyType::Number) + }, + s("b") => info(ApiBodyType::ArrayOf { + value: Box::new(nullable(ApiBodyType::Boolean)) + }) + } + }) + ); + assert_eq!(Bar::api_body_info(), nullable(ApiBodyType::Number)); + assert_eq!( + >::api_body_info(), + nullable(ApiBodyType::String) + ); + + // `None` is serialized as `null`, matching the `T | null` description: + assert_eq!( + to_json_value(Foo { + a: None, + b: vec![Some(true), None] + }), + serde_json::json!({ "a": null, "b": [true, null] }) + ); + assert_eq!(to_json_value(Bar(None)), serde_json::json!(null)); +} + +#[test] +fn optional_struct_fields() { + type Maybe = Option; + + #[ApiBody] + #[allow(dead_code)] + struct Foo { + /// Maybe a number + #[api_body(optional)] + a: Option, + #[api_body(optional)] + b: std::option::Option, + #[api_body(optional)] + c: Option>, + d: Maybe, + #[api_body(optional)] + e: Maybe, + } + + assert_eq!( + Foo::api_body_info(), + info(ApiBodyType::Object { + keys: map! { + s("a") => ApiBodyInfo { + description: s("Maybe a number"), + ..optional(info(ApiBodyType::Number)) + }, + s("b") => optional(info(ApiBodyType::String)), + s("c") => optional(nullable(ApiBodyType::Boolean)), + s("d") => nullable(ApiBodyType::Boolean), + s("e") => optional(info(ApiBodyType::Boolean)) + } + }) + ); + + // Marked fields are omitted when `None`, others are `null`: + assert_eq!( + to_json_value(Foo { + a: None, + b: None, + c: None, + d: None, + e: None + }), + serde_json::json!({ "d": null }) + ); + assert_eq!( + to_json_value(Foo { + a: Some(1), + b: Some(s("hi")), + c: Some(None), + d: Some(true), + e: Some(false) + }), + serde_json::json!({ "a": 1, "b": "hi", "c": null, "d": true, "e": false }) + ); + + // Missing keys and `null`s both deserialize to `None`: + let foo: Foo = serde_json::from_value(serde_json::json!({ "b": null, "d": null })).unwrap(); + assert_eq!( + (foo.a, foo.b, foo.c, foo.d, foo.e), + (None, None, None, None, None) + ); +} + +#[test] +fn optional_enum_fields() { + #[ApiBody] + #[allow(dead_code)] + enum Foo { + A { + #[api_body(optional)] + a: Option, + b: Option, + }, + } + + assert_eq!( + Foo::api_body_info(), + info(ApiBodyType::OneOf { + values: vec![info(ApiBodyType::Object { + keys: map! { + s("kind") => ApiBodyInfo { + description: s("Variant tag"), + ty: ApiBodyType::StringLiteral { literal: s("A") } + }, + s("a") => optional(info(ApiBodyType::Number)), + s("b") => nullable(ApiBodyType::Number) + } + })] + }) + ); + + assert_eq!( + to_json_value(Foo::A { a: None, b: None }), + serde_json::json!({ "kind": "A", "b": null }) + ); + assert_eq!( + to_json_value(Foo::A { + a: Some(1), + b: Some(2) + }), + serde_json::json!({ "kind": "A", "a": 1, "b": 2 }) + ); + let Foo::A { a, b } = + serde_json::from_value(serde_json::json!({ "kind": "A", "b": null })).unwrap(); + assert_eq!((a, b), (None, None)); +} + +#[test] +fn optional_deserialize_only() { + #[ApiBody(Deserialize)] + #[allow(dead_code)] + struct Foo { + #[api_body(optional)] + a: Option, + b: bool, + } + + assert_eq!( + Foo::api_body_info(), + info(ApiBodyType::Object { + keys: map! { + s("a") => optional(info(ApiBodyType::Number)), + s("b") => info(ApiBodyType::Boolean) + } + }) + ); + + // The key can be omitted or null: + let foo: Foo = serde_json::from_value(serde_json::json!({ "b": true })).unwrap(); + assert_eq!(foo.a, None); + let foo: Foo = serde_json::from_value(serde_json::json!({ "a": null, "b": true })).unwrap(); + assert_eq!(foo.a, None); + let foo: Foo = serde_json::from_value(serde_json::json!({ "a": 1, "b": true })).unwrap(); + assert_eq!(foo.a, Some(1)); +} + +fn info(ty: ApiBodyType) -> ApiBodyInfo { + ApiBodyInfo { + description: s(""), + ty, + } +} + +fn nullable(ty: ApiBodyType) -> ApiBodyInfo { + info(ApiBodyType::OneOf { + values: vec![info(ty), info(ApiBodyType::Null)], + }) +} + +fn optional(ty: ApiBodyInfo) -> ApiBodyInfo { + info(ApiBodyType::Optional { + value: Box::new(ty), + }) +} + +fn to_json_value(value: impl serde::Serialize) -> serde_json::Value { + serde_json::to_value(value) + .expect("Failed to serialize to JSON due to an invalid manual implementation (2)") +} diff --git a/seamless/tests/api_body_compile_tests/04_serialize_struct_only.rs b/seamless/tests/api_body_compile_tests/04_serialize_struct_only.rs index 891273e..96dcaa5 100644 --- a/seamless/tests/api_body_compile_tests/04_serialize_struct_only.rs +++ b/seamless/tests/api_body_compile_tests/04_serialize_struct_only.rs @@ -8,7 +8,7 @@ struct Foo { fn main() { // This should fail to compile because deserialize not implemented - let f: Foo = ApiBody::from_json_value(json!({ + let f: Foo = serde_json::from_value(json!({ "hello": 10 })).unwrap(); } \ No newline at end of file diff --git a/seamless/tests/api_body_compile_tests/04_serialize_struct_only.stderr b/seamless/tests/api_body_compile_tests/04_serialize_struct_only.stderr index 3d2e65e..36f6688 100644 --- a/seamless/tests/api_body_compile_tests/04_serialize_struct_only.stderr +++ b/seamless/tests/api_body_compile_tests/04_serialize_struct_only.stderr @@ -1,18 +1,18 @@ error[E0277]: the trait bound `Foo: serde::de::DeserializeOwned` is not satisfied --> tests/api_body_compile_tests/04_serialize_struct_only.rs:11:18 | -11 | let f: Foo = ApiBody::from_json_value(json!({ +11 | let f: Foo = serde_json::from_value(json!({ | __________________^ 12 | | "hello": 10 13 | | })).unwrap(); | |_______^ unsatisfied trait bound | -help: the trait `for<'de> seamless::serde::Deserialize<'de>` is not implemented for `Foo` +help: the trait `for<'de> seamless::serde::de::Deserialize<'de>` is not implemented for `Foo` --> tests/api_body_compile_tests/04_serialize_struct_only.rs:5:1 | 5 | struct Foo { | ^^^^^^^^^^ - = help: the following other types implement trait `seamless::serde::Deserialize<'de>`: + = help: the following other types implement trait `seamless::serde::de::Deserialize<'de>`: &'a Path &'a RawValue &'a [u8] @@ -23,10 +23,11 @@ help: the trait `for<'de> seamless::serde::Deserialize<'de>` is not implemented (T0, T1, T2) and $N others = note: required for `Foo` to implement `seamless::serde::de::DeserializeOwned` -note: required by a bound in `from_json_value` - --> src/api/info.rs +note: required by a bound in `from_value` + --> $CARGO/serde_json-$VERSION/src/value/mod.rs | - | fn from_json_value(value: serde_json::Value) -> serde_json::Result - | --------------- required by a bound in this associated function - | where Self: ::serde::de::DeserializeOwned { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `ApiBody::from_json_value` + | pub fn from_value(value: Value) -> Result + | ---------- required by a bound in this function + | where + | T: DeserializeOwned, + | ^^^^^^^^^^^^^^^^ required by this bound in `from_value` diff --git a/seamless/tests/api_body_compile_tests/05_deserialize_struct_only.rs b/seamless/tests/api_body_compile_tests/05_deserialize_struct_only.rs index 5856911..84b0c9f 100644 --- a/seamless/tests/api_body_compile_tests/05_deserialize_struct_only.rs +++ b/seamless/tests/api_body_compile_tests/05_deserialize_struct_only.rs @@ -7,5 +7,5 @@ struct Foo { fn main() { // This should fail to compile because serialize not implemented - let f = Foo { hello: 10 }.to_json_value(); + let _f = serde_json::to_string(&Foo { hello: 10 }).unwrap(); } \ No newline at end of file diff --git a/seamless/tests/api_body_compile_tests/05_deserialize_struct_only.stderr b/seamless/tests/api_body_compile_tests/05_deserialize_struct_only.stderr index 6745ae9..54484ed 100644 --- a/seamless/tests/api_body_compile_tests/05_deserialize_struct_only.stderr +++ b/seamless/tests/api_body_compile_tests/05_deserialize_struct_only.stderr @@ -1,17 +1,19 @@ error[E0277]: the trait bound `Foo: serde::Serialize` is not satisfied - --> tests/api_body_compile_tests/05_deserialize_struct_only.rs:10:31 + --> tests/api_body_compile_tests/05_deserialize_struct_only.rs:10:36 | -10 | let f = Foo { hello: 10 }.to_json_value(); - | ^^^^^^^^^^^^^ unsatisfied trait bound +10 | let _f = serde_json::to_string(&Foo { hello: 10 }).unwrap(); + | --------------------- ^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | | + | required by a bound introduced by this call | -help: the trait `seamless::serde::Serialize` is not implemented for `Foo` +help: the trait `seamless::serde::ser::Serialize` is not implemented for `Foo` --> tests/api_body_compile_tests/05_deserialize_struct_only.rs:4:1 | 4 | struct Foo { | ^^^^^^^^^^ = note: for local types consider adding `#[derive(serde::Serialize)]` to your `Foo` type = note: for types from other crates check whether the crate offers a `serde` feature flag - = help: the following other types implement trait `seamless::serde::Serialize`: + = help: the following other types implement trait `seamless::serde::ser::Serialize`: &'a T &'a mut T () @@ -21,10 +23,11 @@ help: the trait `seamless::serde::Serialize` is not implemented for `Foo` (T0, T1, T2, T3) (T0, T1, T2, T3, T4) and $N others -note: required by a bound in `to_json_value` - --> src/api/info.rs +note: required by a bound in `serde_json::to_string` + --> $CARGO/serde_json-$VERSION/src/ser.rs | - | fn to_json_value(&self) -> serde_json::Value - | ------------- required by a bound in this associated function - | where Self: ::serde::Serialize { - | ^^^^^^^^^^^^^^^^^^ required by this bound in `ApiBody::to_json_value` + | pub fn to_string(value: &T) -> Result + | --------- required by a bound in this function + | where + | T: ?Sized + Serialize, + | ^^^^^^^^^ required by this bound in `to_string` diff --git a/seamless/tests/api_body_compile_tests/06_se_de_struct.rs b/seamless/tests/api_body_compile_tests/06_se_de_struct.rs index 6b9f4dd..e690eac 100644 --- a/seamless/tests/api_body_compile_tests/06_se_de_struct.rs +++ b/seamless/tests/api_body_compile_tests/06_se_de_struct.rs @@ -13,14 +13,14 @@ struct Foo2 { fn main() { // both fine: - let _f: Foo = ApiBody::from_json_value(json!({ + let _f: Foo = serde_json::from_value(json!({ "hello": 10 })).unwrap(); - let _f = Foo { hello: 10 }.to_json_value(); + let _f = serde_json::to_string(&Foo { hello: 10 }); // both fine: - let _f: Foo2 = ApiBody::from_json_value(json!({ + let _f: Foo2 = serde_json::from_value(json!({ "hello": 10 })).unwrap(); - let _f = Foo2 { hello: 10 }.to_json_value(); + let _f = serde_json::to_string(&Foo2 { hello: 10 }); } \ No newline at end of file diff --git a/seamless/tests/api_body_compile_tests/07_serialize_enum_only.rs b/seamless/tests/api_body_compile_tests/07_serialize_enum_only.rs index 8cbbd6d..1d468a0 100644 --- a/seamless/tests/api_body_compile_tests/07_serialize_enum_only.rs +++ b/seamless/tests/api_body_compile_tests/07_serialize_enum_only.rs @@ -8,7 +8,7 @@ enum Foo { fn main() { // This should fail to compile because deserialize not implemented - let f: Foo = ApiBody::from_json_value(json!({ + let f: Foo = serde_json::from_value(json!({ "kind": "Bar", "n": 10 })).unwrap(); diff --git a/seamless/tests/api_body_compile_tests/07_serialize_enum_only.stderr b/seamless/tests/api_body_compile_tests/07_serialize_enum_only.stderr index 61d5d1d..1a381bd 100644 --- a/seamless/tests/api_body_compile_tests/07_serialize_enum_only.stderr +++ b/seamless/tests/api_body_compile_tests/07_serialize_enum_only.stderr @@ -1,19 +1,19 @@ error[E0277]: the trait bound `Foo: serde::de::DeserializeOwned` is not satisfied --> tests/api_body_compile_tests/07_serialize_enum_only.rs:11:18 | -11 | let f: Foo = ApiBody::from_json_value(json!({ +11 | let f: Foo = serde_json::from_value(json!({ | __________________^ 12 | | "kind": "Bar", 13 | | "n": 10 14 | | })).unwrap(); | |_______^ unsatisfied trait bound | -help: the trait `for<'de> seamless::serde::Deserialize<'de>` is not implemented for `Foo` +help: the trait `for<'de> seamless::serde::de::Deserialize<'de>` is not implemented for `Foo` --> tests/api_body_compile_tests/07_serialize_enum_only.rs:5:1 | 5 | enum Foo { | ^^^^^^^^ - = help: the following other types implement trait `seamless::serde::Deserialize<'de>`: + = help: the following other types implement trait `seamless::serde::de::Deserialize<'de>`: &'a Path &'a RawValue &'a [u8] @@ -24,10 +24,11 @@ help: the trait `for<'de> seamless::serde::Deserialize<'de>` is not implemented (T0, T1, T2) and $N others = note: required for `Foo` to implement `seamless::serde::de::DeserializeOwned` -note: required by a bound in `from_json_value` - --> src/api/info.rs +note: required by a bound in `from_value` + --> $CARGO/serde_json-$VERSION/src/value/mod.rs | - | fn from_json_value(value: serde_json::Value) -> serde_json::Result - | --------------- required by a bound in this associated function - | where Self: ::serde::de::DeserializeOwned { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `ApiBody::from_json_value` + | pub fn from_value(value: Value) -> Result + | ---------- required by a bound in this function + | where + | T: DeserializeOwned, + | ^^^^^^^^^^^^^^^^ required by this bound in `from_value` diff --git a/seamless/tests/api_body_compile_tests/08_deserialize_enum_only.rs b/seamless/tests/api_body_compile_tests/08_deserialize_enum_only.rs index 6f3db08..be11773 100644 --- a/seamless/tests/api_body_compile_tests/08_deserialize_enum_only.rs +++ b/seamless/tests/api_body_compile_tests/08_deserialize_enum_only.rs @@ -7,5 +7,5 @@ enum Foo { fn main() { // This should fail to compile because deserialize not implemented - let f = Foo::Bar{ n: 10 }.to_json_value(); + let f = serde_json::to_string(&Foo::Bar{ n: 10 }); } \ No newline at end of file diff --git a/seamless/tests/api_body_compile_tests/08_deserialize_enum_only.stderr b/seamless/tests/api_body_compile_tests/08_deserialize_enum_only.stderr index 70e81a8..8d61fd1 100644 --- a/seamless/tests/api_body_compile_tests/08_deserialize_enum_only.stderr +++ b/seamless/tests/api_body_compile_tests/08_deserialize_enum_only.stderr @@ -1,17 +1,19 @@ error[E0277]: the trait bound `Foo: serde::Serialize` is not satisfied - --> tests/api_body_compile_tests/08_deserialize_enum_only.rs:10:31 + --> tests/api_body_compile_tests/08_deserialize_enum_only.rs:10:35 | -10 | let f = Foo::Bar{ n: 10 }.to_json_value(); - | ^^^^^^^^^^^^^ unsatisfied trait bound +10 | let f = serde_json::to_string(&Foo::Bar{ n: 10 }); + | --------------------- ^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | | + | required by a bound introduced by this call | -help: the trait `seamless::serde::Serialize` is not implemented for `Foo` +help: the trait `seamless::serde::ser::Serialize` is not implemented for `Foo` --> tests/api_body_compile_tests/08_deserialize_enum_only.rs:4:1 | 4 | enum Foo { | ^^^^^^^^ = note: for local types consider adding `#[derive(serde::Serialize)]` to your `Foo` type = note: for types from other crates check whether the crate offers a `serde` feature flag - = help: the following other types implement trait `seamless::serde::Serialize`: + = help: the following other types implement trait `seamless::serde::ser::Serialize`: &'a T &'a mut T () @@ -21,10 +23,11 @@ help: the trait `seamless::serde::Serialize` is not implemented for `Foo` (T0, T1, T2, T3) (T0, T1, T2, T3, T4) and $N others -note: required by a bound in `to_json_value` - --> src/api/info.rs +note: required by a bound in `serde_json::to_string` + --> $CARGO/serde_json-$VERSION/src/ser.rs | - | fn to_json_value(&self) -> serde_json::Value - | ------------- required by a bound in this associated function - | where Self: ::serde::Serialize { - | ^^^^^^^^^^^^^^^^^^ required by this bound in `ApiBody::to_json_value` + | pub fn to_string(value: &T) -> Result + | --------- required by a bound in this function + | where + | T: ?Sized + Serialize, + | ^^^^^^^^^ required by this bound in `to_string` diff --git a/seamless/tests/api_body_compile_tests/09_se_de_enum.rs b/seamless/tests/api_body_compile_tests/09_se_de_enum.rs index 0525480..8722a01 100644 --- a/seamless/tests/api_body_compile_tests/09_se_de_enum.rs +++ b/seamless/tests/api_body_compile_tests/09_se_de_enum.rs @@ -13,16 +13,16 @@ enum Foo2 { fn main() { // both compile fine: - let _f: Foo = ApiBody::from_json_value(json!({ + let _f: Foo = serde_json::from_value(json!({ "kind": "Bar", "n": 10 })).unwrap(); - let _f = Foo::Bar{ n: 10 }.to_json_value(); + let _f = serde_json::to_string(&Foo::Bar{ n: 10 }); // both compile fine: - let _f: Foo2 = ApiBody::from_json_value(json!({ + let _f: Foo2 = serde_json::from_value(json!({ "kind": "Bar", "n": 10 })).unwrap(); - let _f = Foo2::Bar{ n: 10 }.to_json_value(); + let _f = serde_json::to_string(&Foo2::Bar{ n: 10 }); } \ No newline at end of file diff --git a/seamless/tests/api_body_compile_tests/12_optional_not_option.rs b/seamless/tests/api_body_compile_tests/12_optional_not_option.rs new file mode 100644 index 0000000..0faf0de --- /dev/null +++ b/seamless/tests/api_body_compile_tests/12_optional_not_option.rs @@ -0,0 +1,7 @@ +#[seamless::ApiBody] +struct Foo { + #[api_body(optional)] + bar: usize, +} + +fn main() {} diff --git a/seamless/tests/api_body_compile_tests/12_optional_not_option.stderr b/seamless/tests/api_body_compile_tests/12_optional_not_option.stderr new file mode 100644 index 0000000..ca304f9 --- /dev/null +++ b/seamless/tests/api_body_compile_tests/12_optional_not_option.stderr @@ -0,0 +1,26 @@ +error[E0277]: `#[api_body(optional)]` can only be used on fields of type `Option` + --> tests/api_body_compile_tests/12_optional_not_option.rs:1:1 + | +1 | #[seamless::ApiBody] + | ^^^^^^^^^^^^^^^^^^^^ `usize` is not an `Option` + | + = help: the trait `seamless::api::OptionalField` is not implemented for `usize` +help: the trait `seamless::api::OptionalField` is implemented for `Option` + --> src/api/info.rs + | + | impl OptionalField for Option { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: this error originates in the attribute macro `seamless::ApiBody` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: `#[api_body(optional)]` can only be used on fields of type `Option` + --> tests/api_body_compile_tests/12_optional_not_option.rs:4:10 + | +4 | bar: usize, + | ^^^^^ `usize` is not an `Option` + | + = help: the trait `seamless::api::OptionalField` is not implemented for `usize` +help: the trait `seamless::api::OptionalField` is implemented for `Option` + --> src/api/info.rs + | + | impl OptionalField for Option { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/seamless/tests/api_body_compile_tests/13_optional_unnamed.rs b/seamless/tests/api_body_compile_tests/13_optional_unnamed.rs new file mode 100644 index 0000000..da673ec --- /dev/null +++ b/seamless/tests/api_body_compile_tests/13_optional_unnamed.rs @@ -0,0 +1,4 @@ +#[seamless::ApiBody] +struct Foo(#[api_body(optional)] Option, bool); + +fn main() {} diff --git a/seamless/tests/api_body_compile_tests/13_optional_unnamed.stderr b/seamless/tests/api_body_compile_tests/13_optional_unnamed.stderr new file mode 100644 index 0000000..da3438e --- /dev/null +++ b/seamless/tests/api_body_compile_tests/13_optional_unnamed.stderr @@ -0,0 +1,5 @@ +error: #[api_body(optional)] can only be used on named fields + --> tests/api_body_compile_tests/13_optional_unnamed.rs:2:12 + | +2 | struct Foo(#[api_body(optional)] Option, bool); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/seamless/tests/api_body_compile_tests/14_optional_flatten.rs b/seamless/tests/api_body_compile_tests/14_optional_flatten.rs new file mode 100644 index 0000000..a4c9377 --- /dev/null +++ b/seamless/tests/api_body_compile_tests/14_optional_flatten.rs @@ -0,0 +1,12 @@ +#[seamless::ApiBody] +struct Foo { + #[api_body(flatten, optional)] + bar: Option, +} + +#[seamless::ApiBody] +struct Bar { + lark: bool, +} + +fn main() {} diff --git a/seamless/tests/api_body_compile_tests/14_optional_flatten.stderr b/seamless/tests/api_body_compile_tests/14_optional_flatten.stderr new file mode 100644 index 0000000..87a80b3 --- /dev/null +++ b/seamless/tests/api_body_compile_tests/14_optional_flatten.stderr @@ -0,0 +1,6 @@ +error: the `optional` and `flatten` attrs cannot be used together + --> tests/api_body_compile_tests/14_optional_flatten.rs:3:5 + | +3 | / #[api_body(flatten, optional)] +4 | | bar: Option, + | |____________________^ diff --git a/seamless/tests/api_body_compile_tests/15_enum_flatten.rs b/seamless/tests/api_body_compile_tests/15_enum_flatten.rs new file mode 100644 index 0000000..57fc307 --- /dev/null +++ b/seamless/tests/api_body_compile_tests/15_enum_flatten.rs @@ -0,0 +1,14 @@ +#[seamless::ApiBody] +enum Foo { + A { + #[api_body(flatten)] + bar: Bar, + }, +} + +#[seamless::ApiBody] +struct Bar { + lark: bool, +} + +fn main() {} diff --git a/seamless/tests/api_body_compile_tests/15_enum_flatten.stderr b/seamless/tests/api_body_compile_tests/15_enum_flatten.stderr new file mode 100644 index 0000000..2f3ff6d --- /dev/null +++ b/seamless/tests/api_body_compile_tests/15_enum_flatten.stderr @@ -0,0 +1,6 @@ +error: #[api_body(flatten)] can't be used on enum variant fields + --> tests/api_body_compile_tests/15_enum_flatten.rs:4:9 + | +4 | / #[api_body(flatten)] +5 | | bar: Bar, + | |________________^ diff --git a/seamless/tests/api_body_compile_tests/16_optional_alias.rs b/seamless/tests/api_body_compile_tests/16_optional_alias.rs new file mode 100644 index 0000000..dc087bb --- /dev/null +++ b/seamless/tests/api_body_compile_tests/16_optional_alias.rs @@ -0,0 +1,9 @@ +type Maybe = Option; + +#[seamless::ApiBody] +struct Foo { + #[api_body(optional)] + bar: Maybe, +} + +fn main() {} diff --git a/seamless/tests/api_body_json_content_type.rs b/seamless/tests/api_body_json_content_type.rs new file mode 100644 index 0000000..6011c60 --- /dev/null +++ b/seamless/tests/api_body_json_content_type.rs @@ -0,0 +1,56 @@ +use seamless::{ + api::{Api, RouteError}, + handler::{body::FromJson, request::Bytes, response::ToJson}, + http::Request, +}; + +fn post_json(content_type: &str) -> Request { + Request::post("/echo") + .header("content-type", content_type) + .body(Bytes::from_vec(b"[1,2,3]".to_vec())) + .unwrap() +} + +fn echo_api() -> Api { + let mut api = Api::new(); + api.add("echo") + .handler(|body: FromJson>| ToJson(body.0)); + api +} + +#[tokio::test] +async fn json_content_type_with_charset_is_accepted() { + let api = echo_api(); + for ct in [ + "application/json", + "application/json; charset=utf-8", + "Application/JSON;charset=UTF-8", + "application/json ; charset=utf-8", + ] { + let res = api + .handle(post_json(ct)) + .await + .unwrap_or_else(|e| panic!("{ct:?} was rejected: {e:?}")); + assert_eq!( + &*res.into_body().into_bytes().unwrap(), + b"[1,2,3]", + "{ct:?}" + ); + } +} + +#[tokio::test] +async fn non_json_content_type_is_415() { + let api = echo_api(); + for ct in [ + "text/plain", + "application/jsonx", + "text/plain; x=application/json", + ] { + match api.handle(post_json(ct)).await { + Err(RouteError::Err(e)) => assert_eq!(e.code, 415, "{ct:?}"), + Err(RouteError::NotFound(..)) => panic!("{ct:?}: route not found"), + Ok(_) => panic!("{ct:?} should have been rejected"), + } + } +} diff --git a/seamless/tests/api_error_compile_tests/01_basic.stderr b/seamless/tests/api_error_compile_tests/01_basic.stderr index 6bae943..7c78f8a 100644 --- a/seamless/tests/api_error_compile_tests/01_basic.stderr +++ b/seamless/tests/api_error_compile_tests/01_basic.stderr @@ -1,4 +1,4 @@ -error: One of '#[api_error(internal)]' or '#[api_error(external)]' or '#[api_error(external = "foo")]' is required (1) +error: One of '#[api_error(internal)]' or '#[api_error(external)]' or '#[api_error(external = "foo")]' is required --> $DIR/01_basic.rs:4:8 | 4 | struct Foo { diff --git a/seamless/tests/api_error_compile_tests/08_enum_basic.stderr b/seamless/tests/api_error_compile_tests/08_enum_basic.stderr index 7269249..025856c 100644 --- a/seamless/tests/api_error_compile_tests/08_enum_basic.stderr +++ b/seamless/tests/api_error_compile_tests/08_enum_basic.stderr @@ -1,4 +1,4 @@ -error: One of '#[api_error(internal)]' or '#[api_error(external)]' or '#[api_error(external = "foo")]' is required (1) +error: One of '#[api_error(internal)]' or '#[api_error(external)]' or '#[api_error(external = "foo")]' is required --> $DIR/08_enum_basic.rs:5:5 | 5 | Bar, diff --git a/seamless/tests/api_error_compile_tests/12_inner_with_other_attrs.rs b/seamless/tests/api_error_compile_tests/12_inner_with_other_attrs.rs new file mode 100644 index 0000000..4ca13f4 --- /dev/null +++ b/seamless/tests/api_error_compile_tests/12_inner_with_other_attrs.rs @@ -0,0 +1,23 @@ +#[derive(seamless::ApiError)] +#[api_error(external)] +struct Inner; + +impl std::fmt::Display for Inner { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "inner") + } +} + +#[derive(seamless::ApiError)] +enum Foo { + #[api_error(inner, code = 400)] + Bar(Inner), +} + +impl std::fmt::Display for Foo { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "err") + } +} + +fn main() { } diff --git a/seamless/tests/api_error_compile_tests/12_inner_with_other_attrs.stderr b/seamless/tests/api_error_compile_tests/12_inner_with_other_attrs.stderr new file mode 100644 index 0000000..a0c33d6 --- /dev/null +++ b/seamless/tests/api_error_compile_tests/12_inner_with_other_attrs.stderr @@ -0,0 +1,5 @@ +error: 'inner' does not make sense alongside any other attributes + --> tests/api_error_compile_tests/12_inner_with_other_attrs.rs:13:17 + | +13 | #[api_error(inner, code = 400)] + | ^^^^^ diff --git a/seamless/tests/api_info_order.rs b/seamless/tests/api_info_order.rs new file mode 100644 index 0000000..5e56ee0 --- /dev/null +++ b/seamless/tests/api_info_order.rs @@ -0,0 +1,37 @@ +use seamless::{ + api::Api, + handler::{body::FromJson, response::ToJson}, +}; + +// Routes that share a path must come out of `info()` in a stable order +// (by name, then method), not in `HashMap` iteration order. `HashMap` is +// randomly seeded, so build the API many times to catch any instability. +#[test] +fn info_order_is_stable_for_same_path() { + for _ in 0..50 { + let mut api = Api::new(); + api.add("b").handler(|| ToJson("b")); + api.add("a") + .handler(|body: FromJson| ToJson(body.0)); + api.add("a").handler(|| ToJson("a")); + api.add("c") + .handler(|body: FromJson| ToJson(body.0)); + api.add("c").handler(|| ToJson("c")); + + let order: Vec<(String, String)> = + api.info().into_iter().map(|r| (r.name, r.method)).collect(); + + let expected: Vec<(String, String)> = [ + ("a", "GET"), + ("a", "POST"), + ("b", "GET"), + ("c", "GET"), + ("c", "POST"), + ] + .iter() + .map(|(n, m)| (n.to_string(), m.to_string())) + .collect(); + + assert_eq!(order, expected); + } +} diff --git a/seamless/tests/api_response_binary.rs b/seamless/tests/api_response_binary.rs new file mode 100644 index 0000000..bb22b5c --- /dev/null +++ b/seamless/tests/api_response_binary.rs @@ -0,0 +1,117 @@ +use futures::StreamExt; +use seamless::{ + api::{Api, ApiBodyType, ApiError}, + handler::{ + request::Bytes, + response::{Body, ToBinary, ToJson}, + }, + http::Request, +}; + +fn get(path: &str) -> Request { + Request::get(path).body(Bytes::from_vec(vec![])).unwrap() +} + +#[tokio::test] +async fn to_json_bodies_are_full() { + let mut api = Api::new(); + api.add("json").handler(|| ToJson(vec![1, 2, 3])); + + let res = api.handle(get("/json")).await.unwrap(); + assert_eq!(res.headers()["content-type"], "application/json"); + assert_eq!(&*res.into_body().into_bytes().unwrap(), b"[1,2,3]"); +} + +#[tokio::test] +async fn to_binary_full_body() { + let mut api = Api::new(); + api.add("bytes").handler(|| ToBinary::new(vec![1u8, 2, 3])); + + let res = api.handle(get("/bytes")).await.unwrap(); + assert_eq!(res.headers()["content-type"], "application/octet-stream"); + // The length is known up front, so it's set automatically: + assert_eq!(res.headers()["content-length"], "3"); + assert_eq!(&*res.into_body().into_bytes().unwrap(), &[1, 2, 3]); +} + +#[tokio::test] +async fn to_binary_streaming_body() { + let mut api = Api::new(); + api.add("count").handler(|| async { + let lines = futures::stream::iter(1..=3).map(|n| Ok::<_, std::io::Error>(format!("{n}\n"))); + ToBinary::stream(lines) + .content_type("text/plain") + .content_length(6) + }); + + let res = api.handle(get("/count")).await.unwrap(); + assert_eq!(res.headers()["content-type"], "text/plain"); + assert_eq!(res.headers()["content-length"], "6"); + + // The body should come back as a stream, chunk by chunk: + let body = res + .into_body() + .into_bytes() + .expect_err("should be a streaming body"); + let chunks: Vec<_> = body.into_stream().map(|c| c.unwrap()).collect().await; + assert_eq!(chunks, vec!["1\n", "2\n", "3\n"]); +} + +#[tokio::test] +async fn to_binary_from_reader() { + let mut api = Api::new(); + api.add("reader") + .handler(|| ToBinary::reader(futures::io::Cursor::new(b"hello".to_vec()))); + + let res = api.handle(get("/reader")).await.unwrap(); + assert_eq!(res.into_body().into_vec().await.unwrap(), b"hello"); +} + +#[tokio::test] +async fn to_binary_from_body() { + let mut api = Api::new(); + api.add("body").handler(|| ToBinary::new(Body::from("hi"))); + + let res = api.handle(get("/body")).await.unwrap(); + assert_eq!(res.into_body().into_vec().await.unwrap(), b"hi"); +} + +#[tokio::test] +async fn to_binary_errors_before_streaming_are_api_errors() { + let mut api = Api::new(); + api.add("maybe") + .handler(|| -> Result { Err(ApiError::path_not_found()) }); + api.add("none").handler(|| -> Option { None }); + + let err = api.handle(get("/maybe")).await.unwrap_err().unwrap_err(); + assert_eq!(err.code, 404); + let err = api.handle(get("/none")).await.unwrap_err().unwrap_err(); + assert_eq!(err.code, 404); +} + +#[tokio::test] +async fn to_binary_invalid_content_type_is_500() { + let mut api = Api::new(); + api.add("bad") + .handler(|| ToBinary::new("x").content_type("bad\nvalue")); + + let err = api.handle(get("/bad")).await.unwrap_err().unwrap_err(); + assert_eq!(err.code, 500); +} + +#[test] +fn to_binary_info_is_binary() { + let mut api = Api::new(); + api.add("bytes").handler(|| ToBinary::new(vec![1u8])); + api.add("maybe_bytes") + .handler(|| Some(ToBinary::new(vec![1u8]))); + + for route in api.info() { + assert_eq!( + route.response_type.ty, + ApiBodyType::Binary, + "route {}", + route.name + ); + } +}