diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..736190c --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,50 @@ +name: Tests + +on: + push: + pull_request: {} + +env: + CARGO_INCREMENTAL: 0 + CARGO_TERM_COLOR: always + RUST_BACKTRACE: short + CARGO_NET_RETRY: 10 + RUSTUP_MAX_RETRIES: 10 + +# Cancel in-progress runs when a new commit is pushed to the same PR, branch, or tag. +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +# To minimize supply-chain exposure this workflow uses only GitHub's own +# first-party actions. Each job runs a command the README's Building section +# lists, on the toolchain `rust-toolchain.toml` pins. +# +# The workspace patches `cgp` to the repository's `main` branch by git URL, and +# the lockfile pins the resolved commit, so the jobs fetch that commit and need +# network access. +jobs: + build: + name: Build + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + - name: Install the pinned toolchain + run: rustup toolchain install + - name: Build the workspace + run: cargo build --workspace + + test: + name: Test + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + - name: Install the pinned toolchain + run: rustup toolchain install + - name: Test the workspace + run: cargo test --workspace diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..691f900 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,42 @@ +# AGENTS.md: the CGP example crates + +Follow these rules for every change to this repository. Read [README.md](README.md) for what the +crates show and how to build them, and the knowledge base's +[sibling-projects.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/sibling-projects.md) +for the related repositories. + +## Universal rules + +These rules hold in every CGP repository. The +[knowledge base's AGENTS.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/AGENTS.md) +holds their canonical wording: read it first, and change a rule there before updating this block: + +- Learn CGP and its tools from the `/cgp` skill and the knowledge base; never restate them in this + file. +- Prefer the local sibling checkout when reading another project. +- Write a cross-project link as a GitHub URL on `main`. +- Name official release versions only, never a pre-release. +- Commit only when the user explicitly asks, on the current branch. +- Verify a claim against the source before writing it. +- Keep every view of the same truth in sync in the same change. +- Ask the user when a decision is ambiguous. +- Apply point-first writing to internal prose, and natural writing to public-facing documents + such as READMEs, using the optional `/point-first-writing` skill when it is available. + +## Task guides + +The knowledge base documents this project and the website explains it, so a change to what either +describes starts from the document that holds it. Read it before the task: + +- **Changing code the knowledge base describes:** the project's section, + [projects/cgp-examples/](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/projects/cgp-examples/README.md), + and the section's [writing guide](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/projects/writing-guide.md). +- **Changing code a website page explains:** the record of the site's section on it, + [website/projects/cgp-examples.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/website/projects/cgp-examples.md). + +## Checks before committing + +Every commit passes the checks CI runs: + +- Run the build and test commands in [README.md](README.md#building) before committing; + [`.github/workflows/tests.yml`](.github/workflows/tests.yml) runs the same commands. diff --git a/Cargo.lock b/Cargo.lock index 39f8c80..faf3128 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10,9 +10,9 @@ checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" [[package]] name = "anyhow" -version = "1.0.102" +version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "as-any" @@ -39,7 +39,7 @@ checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -59,15 +59,15 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" [[package]] name = "autocfg" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "axum" -version = "0.8.8" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b52af3cb4058c895d37317bb27508dccc8e5f2d39454016b297bf4a400597b8" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" dependencies = [ "axum-core", "bytes", @@ -144,6 +144,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "base64ct" version = "1.8.3" @@ -152,9 +158,9 @@ checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" [[package]] name = "bitflags" -version = "2.11.0" +version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" dependencies = [ "serde_core", ] @@ -170,9 +176,9 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.20.2" +version = "3.20.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" [[package]] name = "byteorder" @@ -182,15 +188,15 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.11.1" +version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] name = "cc" -version = "1.2.56" +version = "1.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aebf35691d1bfb0ac386a69bac2fde4dd276fb618cf8bf4f5318fe285e821bb2" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" dependencies = [ "find-msvc-tools", "shlex", @@ -198,15 +204,15 @@ dependencies = [ [[package]] name = "cfg-if" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" [[package]] name = "cgp" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a2d437a85e5fff058b478d3ebc21e4eef9732caeea448738e73afa116c1fc30" +checksum = "ce6b350c1cf7eabca705457f87021dfa1fbcb5f11037cc7ff0bc231140964741" dependencies = [ "cgp-core", "cgp-extra", @@ -214,28 +220,56 @@ dependencies = [ [[package]] name = "cgp-async-macro" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03ac81c0b822dfe371bb0ff80206a21170860bbd514fcac0daba962ba34e2e35" +checksum = "40e5ae51b899b911147442a1c4b67cddea8de3f40b18437cdae16fc1a2e798f0" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", +] + +[[package]] +name = "cgp-base" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26651c044919d158daa7aa7954e261fa4d143a300e4566e40e84ebb09347b41e" +dependencies = [ + "cgp-base-types", + "cgp-component", + "cgp-macro", ] +[[package]] +name = "cgp-base-extra" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7be769c79b77e2a1e29a578ffc78cc7cad6776ef99706dabc9e3d73bcea73ec" +dependencies = [ + "cgp-base", + "cgp-type", +] + +[[package]] +name = "cgp-base-types" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a71f473b7fae1dccfbe88aa190352290c3991f52242f953138fc77e6b35f1ed5" + [[package]] name = "cgp-component" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39735cd93546a0b4f7183a55172b709c0df893844b41a7117e08583a9da83127" +checksum = "a66541013e9a41b0ea2557f4c942a8dc9113323008276e7f880626d19de01e1b" [[package]] name = "cgp-core" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a0ce263d3cbe6b7048c47dcb99f40852e3c8f5639b9e5dd257889868c902a4c" +checksum = "12182763f179b6adeb9ba0d489d521f797d89a114b122604d868ad14a19a02a8" dependencies = [ "cgp-async-macro", + "cgp-base", "cgp-component", "cgp-error", "cgp-field", @@ -245,9 +279,9 @@ dependencies = [ [[package]] name = "cgp-dispatch" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d39760b78371f2c1c497961b00e8dce8c1c8f16edff8fea5e0433e9ef9d55ffa" +checksum = "4fe2120e1ddc54d90b36a14a17340562ad875ee0dc8e88bdec3848ae850f3a98" dependencies = [ "cgp-core", "cgp-handler", @@ -256,20 +290,21 @@ dependencies = [ [[package]] name = "cgp-error" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d3502be41951b84e3ce40d010cc6ae6bbf24870e46037c459870cccdeffb84" +checksum = "64c48d3e7196024d620e526ee26762fa71c0261e32f327b36db05d3611aed783" dependencies = [ - "cgp-component", + "cgp-base-extra", + "cgp-field", "cgp-macro", "cgp-type", ] [[package]] name = "cgp-error-anyhow" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "627349f2e10a8bd4c2b777ce93fca00cfbfd27ad15b3a186964037dc42634e0e" +checksum = "8c3cc725f39ee2d61334f3b05cf6b0eedeac03aa0d94bb870e06ca22a046c7e5" dependencies = [ "anyhow", "cgp-core", @@ -277,9 +312,9 @@ dependencies = [ [[package]] name = "cgp-error-extra" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0b8b5cbf6677a7fb237fd44245222c47f4ee63e7138d84813724a31f0050962" +checksum = "82e658051d08e24bb1e07f1e08f47f7cb14dffea5e9110d1051a69ece6dc94ab" dependencies = [ "cgp-core", ] @@ -325,101 +360,134 @@ dependencies = [ "tokio", ] +[[package]] +name = "cgp-example-web-app" +version = "0.1.0" +dependencies = [ + "cgp", +] + [[package]] name = "cgp-extra" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc0a18aaebc9a6afefe95d6e3e07894816c2708bd6722c419c974884aa0a30ec" +checksum = "3deddab5d710099a3a48ab1b477106ca18e5de916ba162447655caf6c9152ac2" dependencies = [ "cgp-core", "cgp-dispatch", "cgp-error-extra", - "cgp-extra-macro", "cgp-field-extra", "cgp-handler", + "cgp-macro-extra", "cgp-monad", "cgp-run", "cgp-runtime", ] [[package]] -name = "cgp-extra-macro" -version = "0.7.0" +name = "cgp-field" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83953618e5a9d39f0fdae7d25799ab5c254fa06531441c2c1a5df6535a740a8c" +checksum = "92007d515785395598ee13a14eec5ea29b79f676b1adf8158b85e7d97d716721" dependencies = [ - "cgp-extra-macro-lib", - "syn", + "cgp-base-types", + "cgp-component", + "cgp-type", ] [[package]] -name = "cgp-extra-macro-lib" -version = "0.7.0" +name = "cgp-field-extra" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1800ccf6bd3e3074831b644fc4cdc831d6271d84e68fbd217711c3dfbd85fe42" +checksum = "fe7dc6502715740ed2192ba80441c9fa97e33b40f3e7fc84ccddf61aac099416" +dependencies = [ + "cgp-field", +] + +[[package]] +name = "cgp-handler" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6fcace02fd8c13ec825f9d0e426c007758999583576987719188de107db88d9" +dependencies = [ + "cgp-core", +] + +[[package]] +name = "cgp-macro" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10f0493b83ab856a3f906ca85c16fb5a309e737aaa4e69e0bc4725d54b75868a" dependencies = [ "cgp-macro-lib", - "proc-macro2", - "quote", - "syn", + "syn 2.0.119", ] [[package]] -name = "cgp-field" -version = "0.7.0" +name = "cgp-macro-core" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2412983a507e370aa5d72b8091f9576cf95e58be06bc3233cd91eeb6b6edead" +checksum = "dd31b749396ce3deb60bd6065fe4ff2b1b0b19b4024983b64a65398d1a4c9925" dependencies = [ - "cgp-component", - "cgp-type", + "itertools", + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] -name = "cgp-field-extra" -version = "0.7.0" +name = "cgp-macro-extra" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e6636e484c14fed64533b5f726ca6186493f53218d3975de1437bc76ec72091" +checksum = "a2e66c232209714795356539150ebb1318e74b34aca36d1c22a7fa35443a163c" dependencies = [ - "cgp-field", + "cgp-macro-extra-lib", + "syn 2.0.119", ] [[package]] -name = "cgp-handler" -version = "0.7.0" +name = "cgp-macro-extra-core" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00a2a8574da65309b8b19ba1268953f7d825748b27a921b4d00baa78b2838a97" +checksum = "ae00da280709b157445e58ddd8f5e8670b38c83fb0414494ffe6a88ba6ef3256" dependencies = [ - "cgp-core", + "cgp-macro-core", + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] -name = "cgp-macro" -version = "0.7.0" +name = "cgp-macro-extra-lib" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4f6983bcbc2f08555682f093a56787a4b0b02c63871efc923a0a4f72cda4d68" +checksum = "070e45b0f3d385ad2b7b569cc454716e1b90660da975f800dbbc637cbedeea22" dependencies = [ - "cgp-macro-lib", - "syn", + "cgp-macro-core", + "cgp-macro-extra-core", + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] name = "cgp-macro-lib" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12ec3f9ec29691903cdbf1e82ecc4bb29ab108b306a9826b4d85eaecb6d9d508" +checksum = "cec78890965b839d97bb1170f80ce81e903ee67a83dd6350f0ee7e342202ac92" dependencies = [ + "cgp-macro-core", "itertools", - "prettyplease", "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "cgp-monad" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c313da265af036cefe7307f466c7ae9b26377c4d482172da9d8a1217859482f6" +checksum = "59984f44c7f9b5d9c6587ac1ce5d7c8b07a5661f562da92be16e54cd71066814" dependencies = [ "cgp-core", "cgp-handler", @@ -427,41 +495,33 @@ dependencies = [ [[package]] name = "cgp-run" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b732f6592e4051aa9d43e5ac226c28bb30693c2b92ac1ba7c2a55aa1d757d539" +checksum = "7a30264e7ac9861780b74413700f779cd692da7d5942a80f49f12d0585c36400" dependencies = [ "cgp-core", ] [[package]] name = "cgp-runtime" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45ac97c31acce9ab7d10146c2bd08dbf289c6c533eab1400714dcc9f6c0e85f5" +checksum = "d32c06ed18cd63444f84850a8643c8ff0be33b4ce97f1c2dda551c2fbc0cafd5" dependencies = [ "cgp-core", ] [[package]] name = "cgp-type" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e67030447046e58fd34a8c10d6471eaff67b440ca441cbb01e29211ba29e66da" +checksum = "5e33cef89294ef841c7f877ea1c407ffea14535de835061ba83e25239efa5f41" dependencies = [ + "cgp-base", "cgp-component", "cgp-macro", ] -[[package]] -name = "concurrent-queue" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" -dependencies = [ - "crossbeam-utils", -] - [[package]] name = "const-oid" version = "0.9.6" @@ -494,6 +554,12 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -514,24 +580,24 @@ dependencies = [ [[package]] name = "crc-catalog" -version = "2.4.0" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5" +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" [[package]] name = "crossbeam-queue" -version = "0.3.12" +version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-utils" -version = "0.8.21" +version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" [[package]] name = "crypto-common" @@ -568,13 +634,13 @@ dependencies = [ [[package]] name = "displaydoc" -version = "0.2.5" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] @@ -591,33 +657,38 @@ checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" [[package]] name = "either" -version = "1.15.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" dependencies = [ "serde", ] [[package]] name = "encoding_rs" -version = "0.8.35" +version = "0.8.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" dependencies = [ "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", ] [[package]] name = "equivalent" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "errno" -version = "0.3.14" +version = "0.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" dependencies = [ "libc", "windows-sys 0.61.2", @@ -636,26 +707,25 @@ dependencies = [ [[package]] name = "event-listener" -version = "5.4.1" +version = "5.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" dependencies = [ - "concurrent-queue", "parking", "pin-project-lite", ] [[package]] name = "fastrand" -version = "2.3.0" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" [[package]] name = "find-msvc-tools" -version = "0.1.9" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" [[package]] name = "flume" @@ -706,9 +776,9 @@ dependencies = [ [[package]] name = "futures" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" dependencies = [ "futures-channel", "futures-core", @@ -721,9 +791,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" dependencies = [ "futures-core", "futures-sink", @@ -731,15 +801,15 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" [[package]] name = "futures-executor" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" dependencies = [ "futures-core", "futures-task", @@ -759,38 +829,38 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" [[package]] name = "futures-macro" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] name = "futures-sink" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" [[package]] name = "futures-task" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" [[package]] name = "futures-util" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-channel", "futures-core", @@ -826,28 +896,26 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.4.1" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "139ef39800118c7683f2fd3c98c1b23c09ae076556b435f8e9064ae108aaeeec" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", "libc", "r-efi", - "wasip2", - "wasip3", ] [[package]] name = "glob" -version = "0.3.3" +version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" [[package]] name = "h2" -version = "0.4.13" +version = "0.4.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" dependencies = [ "atomic-waker", "bytes", @@ -875,9 +943,9 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.16.1" +version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" [[package]] name = "hashlink" @@ -890,11 +958,11 @@ dependencies = [ [[package]] name = "headers" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3314d5adb5d94bcdf56771f2e50dbbc80bb4bdf88967526706205ac9eff24eb" +checksum = "fc2700e3fe555c3310aa7286cac6167449f2c87e0eb58769c9208a1c58a1d106" dependencies = [ - "base64", + "base64 0.22.1", "bytes", "headers-core", "http", @@ -953,9 +1021,9 @@ dependencies = [ [[package]] name = "http" -version = "1.4.0" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" dependencies = [ "bytes", "itoa", @@ -963,9 +1031,9 @@ dependencies = [ [[package]] name = "http-body" -version = "1.0.1" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" dependencies = [ "bytes", "http", @@ -973,9 +1041,9 @@ dependencies = [ [[package]] name = "http-body-util" -version = "0.1.3" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" dependencies = [ "bytes", "futures-core", @@ -998,9 +1066,9 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" [[package]] name = "hyper" -version = "1.8.1" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" dependencies = [ "atomic-waker", "bytes", @@ -1013,7 +1081,6 @@ dependencies = [ "httpdate", "itoa", "pin-project-lite", - "pin-utils", "smallvec", "tokio", "want", @@ -1021,15 +1088,14 @@ dependencies = [ [[package]] name = "hyper-rustls" -version = "0.27.7" +version = "0.27.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" dependencies = [ "http", "hyper", "hyper-util", "rustls", - "rustls-pki-types", "tokio", "tokio-rustls", "tower-service", @@ -1053,16 +1119,17 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.20" +version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ - "base64", + "base64 0.23.1", "bytes", "futures-channel", "futures-util", "http", "http-body", + "httparse", "hyper", "ipnet", "libc", @@ -1078,12 +1145,13 @@ dependencies = [ [[package]] name = "icu_collections" -version = "2.1.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" dependencies = [ "displaydoc", "potential_utf", + "utf8_iter", "yoke", "zerofrom", "zerovec", @@ -1091,9 +1159,9 @@ dependencies = [ [[package]] name = "icu_locale_core" -version = "2.1.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" dependencies = [ "displaydoc", "litemap", @@ -1104,9 +1172,9 @@ dependencies = [ [[package]] name = "icu_normalizer" -version = "2.1.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" dependencies = [ "icu_collections", "icu_normalizer_data", @@ -1118,16 +1186,17 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.1.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" [[package]] name = "icu_properties" -version = "2.1.2" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" dependencies = [ + "displaydoc", "icu_collections", "icu_locale_core", "icu_properties_data", @@ -1138,15 +1207,15 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.1.2" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" [[package]] name = "icu_provider" -version = "2.1.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" dependencies = [ "displaydoc", "icu_locale_core", @@ -1157,12 +1226,6 @@ dependencies = [ "zerovec", ] -[[package]] -name = "id-arena" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" - [[package]] name = "idna" version = "1.1.0" @@ -1176,9 +1239,9 @@ dependencies = [ [[package]] name = "idna_adapter" -version = "1.2.1" +version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" dependencies = [ "icu_normalizer", "icu_properties", @@ -1186,31 +1249,19 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.13.0" +version = "2.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", - "hashbrown 0.16.1", - "serde", - "serde_core", + "hashbrown 0.17.1", ] [[package]] name = "ipnet" -version = "2.11.0" +version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130" - -[[package]] -name = "iri-string" -version = "0.7.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c91338f0783edbd6195decb37bae672fd3b165faffb89bf7b9e6942f8b1a731a" -dependencies = [ - "memchr", - "serde", -] +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" [[package]] name = "itertools" @@ -1223,40 +1274,35 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.17" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" [[package]] name = "js-sys" -version = "0.3.88" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7e709f3e3d22866f9c25b3aff01af289b18422cc8b4262fb19103ee80fe513d" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ - "once_cell", + "cfg-if", + "futures-util", "wasm-bindgen", ] [[package]] name = "lazy_static" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" dependencies = [ "spin", ] -[[package]] -name = "leb128fmt" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" - [[package]] name = "libc" -version = "0.2.182" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libm" @@ -1266,13 +1312,14 @@ checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" [[package]] name = "libredox" -version = "0.1.12" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d0b95e02c851351f877147b7deea7b1afb1df71b63aa5f8270716e0c5720616" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" dependencies = [ "bitflags", "libc", - "redox_syscall 0.7.1", + "plain", + "redox_syscall 0.9.5", ] [[package]] @@ -1288,15 +1335,15 @@ dependencies = [ [[package]] name = "linux-raw-sys" -version = "0.11.0" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "litemap" -version = "0.8.1" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" [[package]] name = "lock_api" @@ -1309,9 +1356,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.29" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "matchit" @@ -1331,15 +1378,15 @@ dependencies = [ [[package]] name = "memchr" -version = "2.8.0" +version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "mime" -version = "0.3.17" +version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" [[package]] name = "mime_guess" @@ -1353,15 +1400,21 @@ dependencies = [ [[package]] name = "mio" -version = "1.1.1" +version = "1.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" dependencies = [ "libc", "wasi", "windows-sys 0.61.2", ] +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + [[package]] name = "native-tls" version = "0.2.18" @@ -1397,20 +1450,19 @@ dependencies = [ [[package]] name = "num-integer" -version = "0.1.46" +version = "0.1.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" dependencies = [ "num-traits", ] [[package]] name = "num-iter" -version = "0.1.45" +version = "0.1.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" dependencies = [ - "autocfg", "num-integer", "num-traits", ] @@ -1427,21 +1479,20 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.21.3" +version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] name = "openssl" -version = "0.10.75" +version = "0.10.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08838db121398ad17ab8531ce9de97b244589089e290a384c900cb9ff7434328" +checksum = "4de8111e94a56adca7ebfe6c365b6d42f99deb69b74b6becacd4204e2f193aa2" dependencies = [ "bitflags", "cfg-if", "foreign-types", "libc", - "once_cell", "openssl-macros", "openssl-sys", ] @@ -1454,20 +1505,20 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "openssl-probe" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" [[package]] name = "openssl-sys" -version = "0.9.111" +version = "0.9.118" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82cab2d520aa75e3c58898289429321eb788c3106963d0dc886ec7a5f4adc321" +checksum = "19c413d6ec9ebaf5e1c829d355cb3e9f783778d700f135be0921d52fce3c60ae" dependencies = [ "cc", "libc", @@ -1530,15 +1581,9 @@ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" [[package]] name = "pin-project-lite" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" - -[[package]] -name = "pin-utils" -version = "0.1.0" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" [[package]] name = "pkcs1" @@ -1563,15 +1608,21 @@ dependencies = [ [[package]] name = "pkg-config" -version = "0.3.32" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "plain" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" [[package]] name = "potential_utf" -version = "0.1.4" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" dependencies = [ "zerovec", ] @@ -1585,45 +1636,35 @@ dependencies = [ "zerocopy", ] -[[package]] -name = "prettyplease" -version = "0.2.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" -dependencies = [ - "proc-macro2", - "syn", -] - [[package]] name = "proc-macro2" -version = "1.0.106" +version = "1.0.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.44" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" dependencies = [ "proc-macro2", ] [[package]] name = "r-efi" -version = "5.3.0" +version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "rand" -version = "0.8.5" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" dependencies = [ "libc", "rand_chacha", @@ -1660,9 +1701,9 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.7.1" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35985aa610addc02e24fc232012c86fd11f14111180f902b67e2d5331f8ebf2b" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" dependencies = [ "bitflags", ] @@ -1673,7 +1714,7 @@ version = "0.12.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" dependencies = [ - "base64", + "base64 0.22.1", "bytes", "encoding_rs", "futures-core", @@ -1719,7 +1760,7 @@ checksum = "90771abe32248301b0f95ca4e8a30122e0471b7b778700ca6fd563d3e568e472" dependencies = [ "as-any", "async-stream", - "base64", + "base64 0.22.1", "bytes", "futures", "glob", @@ -1769,9 +1810,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.3" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "146c9e247ccc180c1f61615433868c99f3de3ae256a30a43b49f67c2d9171f34" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags", "errno", @@ -1782,9 +1823,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.36" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c665f33d38cea657d9614f766881e4d510e0eda4239891eea56b4cadcf01801b" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "once_cell", "rustls-pki-types", @@ -1795,18 +1836,18 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.14.0" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" dependencies = [ "zeroize", ] [[package]] name = "rustls-webpki" -version = "0.103.9" +version = "0.103.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" dependencies = [ "ring", "rustls-pki-types", @@ -1815,9 +1856,9 @@ dependencies = [ [[package]] name = "rustversion" -version = "1.0.22" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" [[package]] name = "ryu" @@ -1827,9 +1868,9 @@ checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" [[package]] name = "schannel" -version = "0.1.28" +version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891d81b926048e76efe18581bf793546b4c0eaf8448d72be8de2bbee5fd166e1" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" dependencies = [ "windows-sys 0.61.2", ] @@ -1855,7 +1896,7 @@ dependencies = [ "proc-macro2", "quote", "serde_derive_internals", - "syn", + "syn 2.0.119", ] [[package]] @@ -1887,17 +1928,11 @@ dependencies = [ "libc", ] -[[package]] -name = "semver" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" - [[package]] name = "serde" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", "serde_derive", @@ -1905,22 +1940,22 @@ dependencies = [ [[package]] name = "serde_core" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] @@ -1931,14 +1966,14 @@ checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "serde_json" -version = "1.0.149" +version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ "itoa", "memchr", @@ -1972,9 +2007,9 @@ dependencies = [ [[package]] name = "sha1" -version = "0.10.6" +version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", "cpufeatures", @@ -1994,9 +2029,9 @@ dependencies = [ [[package]] name = "shlex" -version = "1.3.0" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" [[package]] name = "signal-hook-registry" @@ -2018,6 +2053,12 @@ dependencies = [ "rand_core", ] +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + [[package]] name = "slab" version = "0.4.12" @@ -2026,28 +2067,28 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.15.1" +version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" dependencies = [ "serde", ] [[package]] name = "socket2" -version = "0.6.2" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86f4aa3ad99f2088c990dfa82d367e19cb29268ed67c574d10d0a4bfe71f07e0" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] name = "spin" -version = "0.9.8" +version = "0.9.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" dependencies = [ "lock_api", ] @@ -2081,7 +2122,7 @@ version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6" dependencies = [ - "base64", + "base64 0.22.1", "bytes", "crc", "crossbeam-queue", @@ -2102,7 +2143,9 @@ dependencies = [ "serde_json", "sha2", "smallvec", - "thiserror 2.0.18", + "thiserror 2.0.21", + "tokio", + "tokio-stream", "tracing", "url", ] @@ -2117,7 +2160,7 @@ dependencies = [ "quote", "sqlx-core", "sqlx-macros-core", - "syn", + "syn 2.0.119", ] [[package]] @@ -2140,7 +2183,8 @@ dependencies = [ "sqlx-mysql", "sqlx-postgres", "sqlx-sqlite", - "syn", + "syn 2.0.119", + "tokio", "url", ] @@ -2151,7 +2195,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa003f0038df784eb8fecbbac13affe3da23b45194bd57dba231c8f48199c526" dependencies = [ "atoi", - "base64", + "base64 0.22.1", "bitflags", "byteorder", "bytes", @@ -2181,7 +2225,7 @@ dependencies = [ "smallvec", "sqlx-core", "stringprep", - "thiserror 2.0.18", + "thiserror 2.0.21", "tracing", "whoami", ] @@ -2193,7 +2237,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46" dependencies = [ "atoi", - "base64", + "base64 0.22.1", "bitflags", "byteorder", "crc", @@ -2218,7 +2262,7 @@ dependencies = [ "smallvec", "sqlx-core", "stringprep", - "thiserror 2.0.18", + "thiserror 2.0.21", "tracing", "whoami", ] @@ -2242,7 +2286,7 @@ dependencies = [ "serde", "serde_urlencoded", "sqlx-core", - "thiserror 2.0.18", + "thiserror 2.0.21", "tracing", "url", ] @@ -2272,9 +2316,20 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "syn" -version = "2.0.117" +version = "2.0.119" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" dependencies = [ "proc-macro2", "quote", @@ -2292,13 +2347,13 @@ dependencies = [ [[package]] name = "synstructure" -version = "0.13.2" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] @@ -2324,12 +2379,12 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.25.0" +version = "3.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0136791f7c95b1f6dd99f9cc786b91bb81c3800b639b3478e561ddb7be95e5f1" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.1", + "getrandom 0.4.3", "once_cell", "rustix", "windows-sys 0.61.2", @@ -2346,11 +2401,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ - "thiserror-impl 2.0.18", + "thiserror-impl 2.0.21", ] [[package]] @@ -2361,25 +2416,25 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "thiserror-impl" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] name = "tinystr" -version = "0.8.2" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" dependencies = [ "displaydoc", "zerovec", @@ -2387,24 +2442,15 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.10.0" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokio" -version = "1.49.0" +version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ "bytes", "libc", @@ -2419,13 +2465,13 @@ dependencies = [ [[package]] name = "tokio-macros" -version = "2.6.0" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] @@ -2440,23 +2486,35 @@ dependencies = [ [[package]] name = "tokio-rustls" -version = "0.26.4" +version = "0.26.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" dependencies = [ "rustls", "tokio", ] +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + [[package]] name = "tokio-util" -version = "0.7.18" +version = "0.7.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" dependencies = [ "bytes", "futures-core", "futures-sink", + "libc", "pin-project-lite", "tokio", ] @@ -2479,20 +2537,20 @@ dependencies = [ [[package]] name = "tower-http" -version = "0.6.8" +version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" dependencies = [ "bitflags", "bytes", "futures-util", "http", "http-body", - "iri-string", "pin-project-lite", "tower", "tower-layer", "tower-service", + "url", ] [[package]] @@ -2527,7 +2585,7 @@ checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -2547,15 +2605,15 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] name = "typenum" -version = "1.19.0" +version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" [[package]] name = "unicase" -version = "2.9.0" +version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" [[package]] name = "unicode-bidi" @@ -2565,30 +2623,24 @@ checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" [[package]] name = "unicode-ident" -version = "1.0.24" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "unicode-normalization" -version = "0.1.25" +version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" dependencies = [ "tinyvec", ] [[package]] name = "unicode-properties" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" - -[[package]] -name = "unicode-xid" -version = "0.2.6" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" [[package]] name = "untrusted" @@ -2610,9 +2662,18 @@ dependencies = [ [[package]] name = "utf8_iter" -version = "1.0.4" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" [[package]] name = "vcpkg" @@ -2628,9 +2689,9 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "want" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" dependencies = [ "try-lock", ] @@ -2641,24 +2702,6 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" -[[package]] -name = "wasip2" -version = "1.0.2+wasi-0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5" -dependencies = [ - "wit-bindgen", -] - -[[package]] -name = "wasip3" -version = "0.4.0+wasi-0.3.0-rc-2026-01-06" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" -dependencies = [ - "wit-bindgen", -] - [[package]] name = "wasite" version = "0.1.0" @@ -2667,12 +2710,11 @@ checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b" [[package]] name = "wasm-bindgen" -version = "0.2.111" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec1adf1535672f5b7824f817792b1afd731d7e843d2d04ec8f27e8cb51edd8ac" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -2680,23 +2722,20 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.61" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe88540d1c934c4ec8e6db0afa536876c5441289d7f9f9123d4f065ac1250a6b" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ - "cfg-if", - "futures-util", "js-sys", - "once_cell", + "tokio", "wasm-bindgen", - "web-sys", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.111" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19e638317c08b21663aed4d2b9a2091450548954695ff4efa75bff5fa546b3b1" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -2704,48 +2743,26 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.111" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c64760850114d03d5f65457e96fc988f11f01d38fbaa51b254e4ab5809102af" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn", + "syn 3.0.10", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.111" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60eecd4fe26177cfa3339eb00b4a36445889ba3ad37080c2429879718e20ca41" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] -[[package]] -name = "wasm-encoder" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" -dependencies = [ - "leb128fmt", - "wasmparser", -] - -[[package]] -name = "wasm-metadata" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" -dependencies = [ - "anyhow", - "indexmap", - "wasm-encoder", - "wasmparser", -] - [[package]] name = "wasm-streams" version = "0.4.2" @@ -2759,23 +2776,11 @@ dependencies = [ "web-sys", ] -[[package]] -name = "wasmparser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" -dependencies = [ - "bitflags", - "hashbrown 0.15.5", - "indexmap", - "semver", -] - [[package]] name = "web-sys" -version = "0.3.88" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d6bb20ed2d9572df8584f6dc81d68a41a625cadc6f15999d649a70ce7e3597a" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -2844,15 +2849,6 @@ dependencies = [ "windows-targets 0.52.6", ] -[[package]] -name = "windows-sys" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" -dependencies = [ - "windows-targets 0.53.5", -] - [[package]] name = "windows-sys" version = "0.61.2" @@ -2886,30 +2882,13 @@ dependencies = [ "windows_aarch64_gnullvm 0.52.6", "windows_aarch64_msvc 0.52.6", "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm 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", ] -[[package]] -name = "windows-targets" -version = "0.53.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" -dependencies = [ - "windows-link", - "windows_aarch64_gnullvm 0.53.1", - "windows_aarch64_msvc 0.53.1", - "windows_i686_gnu 0.53.1", - "windows_i686_gnullvm 0.53.1", - "windows_i686_msvc 0.53.1", - "windows_x86_64_gnu 0.53.1", - "windows_x86_64_gnullvm 0.53.1", - "windows_x86_64_msvc 0.53.1", -] - [[package]] name = "windows_aarch64_gnullvm" version = "0.48.5" @@ -2922,12 +2901,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" - [[package]] name = "windows_aarch64_msvc" version = "0.48.5" @@ -2940,12 +2913,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" -[[package]] -name = "windows_aarch64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" - [[package]] name = "windows_i686_gnu" version = "0.48.5" @@ -2958,24 +2925,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" -[[package]] -name = "windows_i686_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" - [[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_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" - [[package]] name = "windows_i686_msvc" version = "0.48.5" @@ -2988,12 +2943,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" -[[package]] -name = "windows_i686_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" - [[package]] name = "windows_x86_64_gnu" version = "0.48.5" @@ -3006,12 +2955,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" -[[package]] -name = "windows_x86_64_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" - [[package]] name = "windows_x86_64_gnullvm" version = "0.48.5" @@ -3024,12 +2967,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" - [[package]] name = "windows_x86_64_msvc" version = "0.48.5" @@ -3042,111 +2979,17 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" -[[package]] -name = "windows_x86_64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" - -[[package]] -name = "wit-bindgen" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" -dependencies = [ - "wit-bindgen-rust-macro", -] - -[[package]] -name = "wit-bindgen-core" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" -dependencies = [ - "anyhow", - "heck", - "wit-parser", -] - -[[package]] -name = "wit-bindgen-rust" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" -dependencies = [ - "anyhow", - "heck", - "indexmap", - "prettyplease", - "syn", - "wasm-metadata", - "wit-bindgen-core", - "wit-component", -] - -[[package]] -name = "wit-bindgen-rust-macro" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" -dependencies = [ - "anyhow", - "prettyplease", - "proc-macro2", - "quote", - "syn", - "wit-bindgen-core", - "wit-bindgen-rust", -] - -[[package]] -name = "wit-component" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" -dependencies = [ - "anyhow", - "bitflags", - "indexmap", - "log", - "serde", - "serde_derive", - "serde_json", - "wasm-encoder", - "wasm-metadata", - "wasmparser", - "wit-parser", -] - -[[package]] -name = "wit-parser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" -dependencies = [ - "anyhow", - "id-arena", - "indexmap", - "log", - "semver", - "serde", - "serde_derive", - "serde_json", - "unicode-xid", - "wasmparser", -] - [[package]] name = "writeable" -version = "0.6.2" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" [[package]] name = "yoke" -version = "0.8.1" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -3155,68 +2998,68 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.1" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", "synstructure", ] [[package]] name = "zerocopy" -version = "0.8.39" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db6d35d663eadb6c932438e763b262fe1a70987f9ae936e60158176d710cae4a" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.39" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4122cd3169e94605190e77839c9a40d40ed048d305bfdc146e7df40ab0f3e517" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "zerofrom" -version = "0.1.6" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" dependencies = [ "zerofrom-derive", ] [[package]] name = "zerofrom-derive" -version = "0.1.6" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", "synstructure", ] [[package]] name = "zeroize" -version = "1.8.2" +version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" [[package]] name = "zerotrie" -version = "0.2.3" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" dependencies = [ "displaydoc", "yoke", @@ -3225,9 +3068,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.5" +version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" dependencies = [ "yoke", "zerofrom", @@ -3236,17 +3079,17 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.2" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] name = "zmij" -version = "1.0.21" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index dfee3cc..d8c4cd5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,7 @@ members = [ "greet", "transfer", "builder", + "web-app", ] [workspace.package] @@ -14,13 +15,12 @@ rust-version = "1.90" edition = "2024" license = "MIT" repository = "https://github.com/contextgeneric/cgp-examples" +homepage = "https://contextgeneric.dev/docs/projects/cgp-examples/" +categories = ["rust-patterns"] +description = "Example crates for Context-Generic Programming." authors = ["Soares Chen "] keywords = ["cgp"] [workspace.dependencies] -cgp = { version = "0.7.0" } -cgp-error-anyhow = { version = "0.7.0" } - -[patch.crates-io] -# cgp = { git = "https://github.com/contextgeneric/cgp.git", branch = "v0.7.0" } -# cgp-error-anyhow = { git = "https://github.com/contextgeneric/cgp.git", branch = "v0.7.0" } +cgp = { version = "0.8.0" } +cgp-error-anyhow = { version = "0.8.0" } diff --git a/README.md b/README.md index e69de29..86ebdd4 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,74 @@ +![License](https://img.shields.io/badge/license-MIT-blue.svg) +![Rust 1.90+](https://img.shields.io/badge/rustc-1.90+-blue.svg) +[![Tests](https://github.com/contextgeneric/cgp-examples/actions/workflows/tests.yml/badge.svg)](https://github.com/contextgeneric/cgp-examples/actions/workflows/tests.yml) + +# cgp-examples: example crates for CGP + +**Five independent example crates, each a small program that shows one area of +[Context-Generic Programming (CGP)](https://contextgeneric.dev/) in use.** + +The crates share a workspace and nothing else. Each one is a demonstration rather than a library, and +each is documented on the website, where the code is explained rather than only listed. + +**[Website](https://contextgeneric.dev/) · [CGP quickstart](https://contextgeneric.dev/docs/quickstart) · [Project pages](https://contextgeneric.dev/docs/projects/cgp-examples/) · [Reference](https://contextgeneric.dev/docs/reference/)** + +## The crates + +| Crate | What it shows | Run it | +| --- | --- | --- | +| [`transfer`](transfer) | A money-transfer HTTP service: an environmental context with one handler dispatched per endpoint, and a namespace-organized wiring table | `cargo run -p cgp-example-transfer --bin server` | +| [`expression`](expression) | An arithmetic interpreter open to new variants and operations: a parameter-targeted component with per-type dispatch | `cargo test -p cgp-example-expression` | +| [`builder`](builder) | An application context assembled from per-subsystem builders | `cargo build -p cgp-example-builder` | +| [`web-app`](web-app) | One social-media backend wired four ways, from one trait per domain up to namespace defaults | `cargo build -p cgp-example-web-app` | +| [`greet`](greet) | A greeting written three ways: as a function, as a component, and over an abstract type | `cargo run -p cgp-example-greet --bin greet-function` | + +`transfer` is the only crate with a README of its own: it is a +[walkthrough](transfer/README.md) that teaches the CGP constructs the service uses, and +[`example.sh`](transfer/example.sh) shows a session against a running server. + +Nothing in `web-app` or `builder` runs. Their value is the wiring they compile, so a successful build +is most of their verification, and `check_components!` blocks check the rest. + +Two crates have a page of their own on the website, which explains the code rather than listing it: +[`expression`](https://contextgeneric.dev/docs/projects/cgp-examples/expression) and +[`web-app`](https://contextgeneric.dev/docs/projects/cgp-examples/web-app). + +## Building + +The workspace takes `cgp` and `cgp-error-anyhow` 0.8.0 from crates.io. To build against a local +change to `cgp` instead, point both crates at a checkout in `../cgp` with a `[patch.crates-io]` +section in the root `Cargo.toml`: + +```toml +[patch.crates-io] +cgp = { path = "../cgp/crates/main/cgp" } +cgp-error-anyhow = { path = "../cgp/crates/standalone/error/cgp-error-anyhow" } +``` + +It needs stable Rust 1.90 or later and uses the 2024 edition. The only tests in the workspace are +three unit tests in `expression`; the other crates check their wiring at compile time with +`check_components!` blocks. + +```sh +cargo build --workspace +cargo test --workspace +``` + +Contributors and agents start from [AGENTS.md](AGENTS.md), which names these checks. + +## Learn CGP + +The website is the main documentation: the [quickstart](https://contextgeneric.dev/docs/quickstart), +the [tutorials](https://contextgeneric.dev/docs/tutorials/hello), the +[concepts](https://contextgeneric.dev/docs/concepts/), and the +[construct reference](https://contextgeneric.dev/docs/reference/). The +[project pages](https://contextgeneric.dev/docs/projects/cgp-examples/) explain these crates, and the +[CGP knowledge base](https://github.com/contextgeneric/cgp-knowledge-base) records each crate in depth +for contributors and agents. + +[sibling-projects.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/sibling-projects.md) +lists the related repositories. + +## License + +Licensed under the MIT license. diff --git a/builder/Cargo.toml b/builder/Cargo.toml index d5bbc95..2fbb257 100644 --- a/builder/Cargo.toml +++ b/builder/Cargo.toml @@ -4,6 +4,9 @@ version = "0.1.0" edition = { workspace = true } license = { workspace = true } repository = { workspace = true } +homepage = { workspace = true } +categories = { workspace = true } +description = "An application context assembled from per-subsystem builders." authors = { workspace = true } rust-version = { workspace = true } keywords = { workspace = true } @@ -12,7 +15,7 @@ keywords = { workspace = true } cgp = { workspace = true } cgp-error-anyhow = { workspace = true } -serde = { version = "1.0.219", features = ["derive"] } -sqlx = { version = "0.8.6", features = ["sqlite", "postgres"] } +serde = { version = "1.0.229", features = ["derive"] } +sqlx = { version = "0.8.6", features = ["sqlite", "postgres", "runtime-tokio"] } rig-core = { version = "0.13.0" } -reqwest = { version = "0.12.20" } +reqwest = { version = "0.12.28" } diff --git a/builder/src/contexts/anthropic.rs b/builder/src/contexts/anthropic.rs index e464857..c18cb2e 100644 --- a/builder/src/contexts/anthropic.rs +++ b/builder/src/contexts/anthropic.rs @@ -1,5 +1,6 @@ use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; use cgp::extra::dispatch::BuildAndMergeOutputs; +use cgp::extra::handler::HandlerComponent; use cgp::prelude::*; use cgp_error_anyhow::{RaiseAnyhowError, UseAnyhowError}; use reqwest::Client; @@ -10,7 +11,7 @@ use sqlx::SqlitePool; use crate::providers::{BuildDefaultAnthropicClient, BuildHttpClient, BuildSqliteClient}; -#[derive(HasField, HasFields, BuildField)] +#[derive(CgpData)] pub struct AnthropicApp { pub sqlite_pool: SqlitePool, pub http_client: Client, diff --git a/builder/src/contexts/anthropic_and_chatgpt.rs b/builder/src/contexts/anthropic_and_chatgpt.rs index 7c8c072..6db6846 100644 --- a/builder/src/contexts/anthropic_and_chatgpt.rs +++ b/builder/src/contexts/anthropic_and_chatgpt.rs @@ -1,6 +1,6 @@ use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; use cgp::extra::dispatch::BuildAndMergeOutputs; -use cgp::extra::handler::CanHandle; +use cgp::extra::handler::{CanHandle, HandlerComponent}; use cgp::prelude::*; use cgp_error_anyhow::{Error, RaiseAnyhowError, UseAnyhowError}; use reqwest::Client; @@ -15,7 +15,7 @@ use crate::providers::{ BuildDefaultAnthropicClient, BuildHttpClient, BuildOpenAiClient, BuildSqliteClient, }; -#[derive(HasField, HasFields, BuildField)] +#[derive(CgpData)] pub struct AnthropicAndChatGptApp { pub sqlite_pool: SqlitePool, pub http_client: Client, @@ -36,7 +36,7 @@ pub struct AnthropicAndChatGptAppBuilder { pub llm_preamble: String, } -pub struct BuildAnthroicAndChatGptApp; +pub struct BuildAnthropicAndChatGptApp; pub struct BuildChatGptApp; @@ -44,45 +44,45 @@ pub struct BuildAnthropicApp; delegate_components! { AnthropicAndChatGptAppBuilder { + open HandlerComponent; + ErrorTypeProviderComponent: UseAnyhowError, ErrorRaiserComponent: RaiseAnyhowError, - HandlerComponent: - UseDelegate, - BuildChatGptApp: - BuildAndMergeOutputs< - App, - Product![ - BuildSqliteClient, - BuildHttpClient, - BuildOpenAiClient, - ]>, - BuildAnthropicApp: - BuildAndMergeOutputs< - AnthropicApp, - Product![ - BuildSqliteClient, - BuildHttpClient, - BuildDefaultAnthropicClient, - ]>, - }>, + + @HandlerComponent.BuildAnthropicAndChatGptApp: + BuildAndMergeOutputs< + AnthropicAndChatGptApp, + Product![ + BuildSqliteClient, + BuildHttpClient, + BuildDefaultAnthropicClient, + BuildOpenAiClient, + ]>, + @HandlerComponent.BuildChatGptApp: + BuildAndMergeOutputs< + App, + Product![ + BuildSqliteClient, + BuildHttpClient, + BuildOpenAiClient, + ]>, + @HandlerComponent.BuildAnthropicApp: + BuildAndMergeOutputs< + AnthropicApp, + Product![ + BuildSqliteClient, + BuildHttpClient, + BuildDefaultAnthropicClient, + ]>, } } check_components! { AnthropicAndChatGptAppBuilder { HandlerComponent: [ - (BuildAnthroicAndChatGptApp, ()), + (BuildAnthropicAndChatGptApp, ()), (BuildChatGptApp, ()), (BuildAnthropicApp, ()), ], @@ -91,7 +91,7 @@ check_components! { pub async fn main() -> Result<(), Error> { let builder = AnthropicAndChatGptAppBuilder { - db_options: "file:./db.sqlite".to_owned(), + db_options: "sqlite:./db.sqlite?mode=rwc".to_owned(), db_journal_mode: "WAL".to_owned(), http_user_agent: "SUPER_AI_AGENT".to_owned(), anthropic_key: "1234567890".to_owned(), @@ -103,7 +103,7 @@ pub async fn main() -> Result<(), Error> { let _chat_gpt_app: App = builder.handle(PhantomData::, ()).await?; let _anthropic_app: AnthropicApp = builder.handle(PhantomData::, ()).await?; let _anthropic_and_chat_gpt_app: AnthropicAndChatGptApp = builder - .handle(PhantomData::, ()) + .handle(PhantomData::, ()) .await?; /* Call methods on the apps here */ diff --git a/builder/src/contexts/app.rs b/builder/src/contexts/app.rs index d43e813..bf6ff25 100644 --- a/builder/src/contexts/app.rs +++ b/builder/src/contexts/app.rs @@ -1,16 +1,17 @@ use core::str::FromStr; use core::time::Duration; +use std::env; use cgp::prelude::*; use cgp_error_anyhow::Error; use reqwest::Client; use rig::agent::Agent; -use rig::client::{CompletionClient, ProviderClient}; +use rig::client::CompletionClient; use rig::providers::openai; use sqlx::SqlitePool; use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode}; -#[derive(HasField, HasFields, BuildField)] +#[derive(CgpData)] pub struct App { pub sqlite_pool: SqlitePool, pub http_client: Client, @@ -55,7 +56,7 @@ impl App { pub async fn new_with_default(db_path: &str) -> Result { let http_client = Client::new(); let sqlite_pool = SqlitePool::connect(db_path).await?; - let open_ai_client = openai::Client::from_env(); + let open_ai_client = openai::Client::new(&env::var("OPENAI_API_KEY")?); let open_ai_agent = open_ai_client.agent("gpt-4o").build(); Ok(Self { diff --git a/builder/src/contexts/default_builder.rs b/builder/src/contexts/default_builder.rs index 0bd2105..1360e66 100644 --- a/builder/src/contexts/default_builder.rs +++ b/builder/src/contexts/default_builder.rs @@ -1,5 +1,6 @@ use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; use cgp::extra::dispatch::BuildAndMergeOutputs; +use cgp::extra::handler::HandlerComponent; use cgp::prelude::*; use cgp_error_anyhow::{RaiseAnyhowError, UseAnyhowError}; use serde::Deserialize; diff --git a/builder/src/contexts/full_builder.rs b/builder/src/contexts/full_builder.rs index ba2ec86..e2f125c 100644 --- a/builder/src/contexts/full_builder.rs +++ b/builder/src/contexts/full_builder.rs @@ -1,6 +1,6 @@ use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; use cgp::extra::dispatch::BuildAndMergeOutputs; -use cgp::extra::handler::CanHandle; +use cgp::extra::handler::{CanHandle, HandlerComponent}; use cgp::prelude::*; use cgp_error_anyhow::{Error, RaiseAnyhowError, UseAnyhowError}; use serde::Deserialize; @@ -43,7 +43,7 @@ check_components! { pub async fn main() -> Result<(), Error> { let builder = FullAppBuilder { - db_options: "file:./db.sqlite".to_owned(), + db_options: "sqlite:./db.sqlite?mode=rwc".to_owned(), db_journal_mode: "WAL".to_owned(), http_user_agent: "SUPER_AI_AGENT".to_owned(), open_ai_key: "1234567890".to_owned(), diff --git a/builder/src/contexts/postgres.rs b/builder/src/contexts/postgres.rs index 3566f6c..675d3f5 100644 --- a/builder/src/contexts/postgres.rs +++ b/builder/src/contexts/postgres.rs @@ -1,5 +1,6 @@ use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; use cgp::extra::dispatch::BuildAndMergeOutputs; +use cgp::extra::handler::HandlerComponent; use cgp::prelude::*; use cgp_error_anyhow::{RaiseAnyhowError, UseAnyhowError}; use reqwest::Client; @@ -10,7 +11,7 @@ use sqlx::PgPool; use crate::providers::{BuildHttpClient, BuildOpenAiClient, BuildPostgresClient}; -#[derive(HasField, HasFields, BuildField)] +#[derive(CgpData)] pub struct App { pub postgres_pool: PgPool, pub http_client: Client, diff --git a/builder/src/providers/anthropic.rs b/builder/src/providers/anthropic.rs index 6695ae5..8828fb3 100644 --- a/builder/src/providers/anthropic.rs +++ b/builder/src/providers/anthropic.rs @@ -1,41 +1,36 @@ +use cgp::extra::handler::{Handler, HandlerComponent}; use cgp::prelude::*; use rig::agent::Agent; use rig::client::CompletionClient; use rig::providers::anthropic::completion::CompletionModel; use rig::providers::anthropic::{self, ANTHROPIC_VERSION_LATEST, ClientBuilder}; -#[cgp_auto_getter] -pub trait HasAnthropicConfig { - fn anthropic_key(&self) -> &str; - - fn llm_preamble(&self) -> &str; -} - -#[derive(HasField, HasFields, BuildField)] +#[derive(CgpData)] pub struct AnthropicClient { pub anthropic_client: anthropic::Client, pub anthropic_agent: Agent, } +/// Builds an Anthropic client from the default configuration. #[cgp_impl(new BuildDefaultAnthropicClient)] -impl Handler -where - Self: HasAnthropicConfig + HasErrorType, -{ +#[use_type(HasErrorType.Error)] +impl Handler { type Output = AnthropicClient; async fn handle( &self, _code: PhantomData, _input: Input, - ) -> Result { - let anthropic_client = ClientBuilder::new(self.anthropic_key()) + #[implicit] anthropic_key: &str, + #[implicit] llm_preamble: &str, + ) -> Result { + let anthropic_client = ClientBuilder::new(anthropic_key) .anthropic_version(ANTHROPIC_VERSION_LATEST) .build(); let anthropic_agent = anthropic_client .agent(anthropic::CLAUDE_3_7_SONNET) - .preamble(self.llm_preamble()) + .preamble(llm_preamble) .build(); Ok(AnthropicClient { diff --git a/builder/src/providers/chatgpt.rs b/builder/src/providers/chatgpt.rs index 9e82da9..adb5978 100644 --- a/builder/src/providers/chatgpt.rs +++ b/builder/src/providers/chatgpt.rs @@ -1,39 +1,35 @@ +use std::env::{self, VarError}; + +use cgp::extra::handler::{Handler, HandlerComponent}; use cgp::prelude::*; use rig::agent::Agent; -use rig::client::{CompletionClient, ProviderClient}; +use rig::client::CompletionClient; use rig::providers::openai; -#[cgp_auto_getter] -pub trait HasOpenAiConfig { - fn open_ai_key(&self) -> &str; - - fn open_ai_model(&self) -> &str; - - fn llm_preamble(&self) -> &str; -} - -#[derive(HasField, HasFields, BuildField)] +#[derive(CgpData)] pub struct OpenAiClient { pub open_ai_client: openai::Client, pub open_ai_agent: Agent, } +/// Builds an OpenAI client from the given configuration. #[cgp_impl(new BuildOpenAiClient)] -impl Handler -where - Self: HasOpenAiConfig + HasErrorType, -{ +#[use_type(HasErrorType.Error)] +impl Handler { type Output = OpenAiClient; async fn handle( &self, _code: PhantomData, _input: Input, - ) -> Result { - let open_ai_client = openai::Client::new(self.open_ai_key()); + #[implicit] open_ai_key: &str, + #[implicit] open_ai_model: &str, + #[implicit] llm_preamble: &str, + ) -> Result { + let open_ai_client = openai::Client::new(open_ai_key); let open_ai_agent = open_ai_client - .agent(self.open_ai_model()) - .preamble(self.llm_preamble()) + .agent(open_ai_model) + .preamble(llm_preamble) .build(); Ok(OpenAiClient { @@ -43,19 +39,16 @@ where } } +/// Builds an OpenAI client from the default configuration. #[cgp_impl(new BuildDefaultOpenAiClient)] -impl Handler -where - Self: HasErrorType, -{ +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl Handler { type Output = OpenAiClient; - async fn handle( - &self, - _code: PhantomData, - _input: Input, - ) -> Result { - let open_ai_client = openai::Client::from_env(); + async fn handle(&self, _code: PhantomData, _input: Input) -> Result { + let open_ai_key = env::var("OPENAI_API_KEY").map_err(Self::raise_error)?; + let open_ai_client = openai::Client::new(&open_ai_key); let open_ai_agent = open_ai_client.agent("gpt-4o").build(); Ok(OpenAiClient { diff --git a/builder/src/providers/http_client.rs b/builder/src/providers/http_client.rs index f2d8db1..27dab0b 100644 --- a/builder/src/providers/http_client.rs +++ b/builder/src/providers/http_client.rs @@ -1,33 +1,29 @@ use core::time::Duration; +use cgp::extra::handler::{Handler, HandlerComponent}; use cgp::prelude::*; use reqwest::Client; -#[cgp_auto_getter] -pub trait HasHttpClientConfig { - fn http_user_agent(&self) -> &str; -} - -#[derive(HasField, HasFields, BuildField)] +#[derive(CgpData)] pub struct HttpClient { pub http_client: Client, } +/// Builds an HTTP client from the given configuration. #[cgp_impl(new BuildHttpClient)] -impl Handler -where - Self: HasHttpClientConfig + CanRaiseError, -{ +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl Handler { type Output = HttpClient; async fn handle( &self, - _code: PhantomData, _input: Input, - ) -> Result { + #[implicit] http_user_agent: &str, + ) -> Result { let http_client = Client::builder() - .user_agent(self.http_user_agent()) + .user_agent(http_user_agent) .connect_timeout(Duration::from_secs(5)) .build() .map_err(Self::raise_error)?; @@ -36,18 +32,13 @@ where } } +/// Builds an HTTP client from the default configuration. #[cgp_impl(new BuildDefaultHttpClient)] -impl Handler -where - Self: HasErrorType, -{ +#[use_type(HasErrorType.Error)] +impl Handler { type Output = HttpClient; - async fn handle( - &self, - _code: PhantomData, - _input: Input, - ) -> Result { + async fn handle(&self, _code: PhantomData, _input: Input) -> Result { let http_client = Client::new(); Ok(HttpClient { http_client }) } diff --git a/builder/src/providers/postgres.rs b/builder/src/providers/postgres.rs index 4f73ed3..4411ff7 100644 --- a/builder/src/providers/postgres.rs +++ b/builder/src/providers/postgres.rs @@ -1,29 +1,26 @@ +use cgp::extra::handler::{Handler, HandlerComponent}; use cgp::prelude::*; use sqlx::PgPool; -#[cgp_auto_getter] -pub trait HasPostgresUrl { - fn postgres_url(&self) -> &str; -} - -#[derive(HasField, HasFields, BuildField)] +#[derive(CgpData)] pub struct PostgresClient { pub postgres_pool: PgPool, } +/// Builds a Postgres client from the given configuration. #[cgp_impl(new BuildPostgresClient)] -impl Handler -where - Self: HasPostgresUrl + CanRaiseError, -{ +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl Handler { type Output = PostgresClient; async fn handle( &self, _code: PhantomData, _input: Input, - ) -> Result { - let postgres_pool = PgPool::connect(self.postgres_url()) + #[implicit] postgres_url: &str, + ) -> Result { + let postgres_pool = PgPool::connect(postgres_url) .await .map_err(Self::raise_error)?; diff --git a/builder/src/providers/sqlite.rs b/builder/src/providers/sqlite.rs index 697d046..09da94c 100644 --- a/builder/src/providers/sqlite.rs +++ b/builder/src/providers/sqlite.rs @@ -1,42 +1,33 @@ use core::str::FromStr; +use cgp::extra::handler::{Handler, HandlerComponent}; use cgp::prelude::*; use sqlx::SqlitePool; use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode}; -#[cgp_auto_getter] -pub trait HasSqlitePath { - fn db_path(&self) -> &str; -} - -#[cgp_auto_getter] -pub trait HasSqliteOptions { - fn db_options(&self) -> &str; - - fn db_journal_mode(&self) -> &str; -} - -#[derive(HasField, HasFields, BuildField)] +#[derive(CgpData)] pub struct SqliteClient { pub sqlite_pool: SqlitePool, } +/// Builds a SQLite client from the given configuration. #[cgp_impl(new BuildSqliteClient)] -impl Handler -where - Self: HasSqliteOptions + CanRaiseError, -{ +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl Handler { type Output = SqliteClient; async fn handle( &self, _code: PhantomData, _input: Input, - ) -> Result { + #[implicit] db_options: &str, + #[implicit] db_journal_mode: &str, + ) -> Result { let journal_mode = - SqliteJournalMode::from_str(self.db_journal_mode()).map_err(Self::raise_error)?; + SqliteJournalMode::from_str(db_journal_mode).map_err(Self::raise_error)?; - let db_options = SqliteConnectOptions::from_str(self.db_options()) + let db_options = SqliteConnectOptions::from_str(db_options) .map_err(Self::raise_error)? .journal_mode(journal_mode); @@ -48,19 +39,20 @@ where } } +/// Builds a SQLite client from the default configuration. #[cgp_impl(new BuildDefaultSqliteClient)] -impl Handler -where - Self: HasSqlitePath + CanRaiseError, -{ +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl Handler { type Output = SqliteClient; async fn handle( &self, _code: PhantomData, _input: Input, - ) -> Result { - let sqlite_pool = SqlitePool::connect(self.db_path()) + #[implicit] db_path: &str, + ) -> Result { + let sqlite_pool = SqlitePool::connect(db_path) .await .map_err(Self::raise_error)?; diff --git a/builder/src/providers/sqlite_and_http.rs b/builder/src/providers/sqlite_and_http.rs index ce6739d..1715903 100644 --- a/builder/src/providers/sqlite_and_http.rs +++ b/builder/src/providers/sqlite_and_http.rs @@ -1,29 +1,29 @@ +use cgp::extra::handler::{Handler, HandlerComponent}; use cgp::prelude::*; use reqwest::Client; use sqlx::SqlitePool; -use crate::providers::HasSqlitePath; - -#[derive(HasField, HasFields, BuildField)] +#[derive(CgpData)] pub struct SqliteAndHttpClient { pub sqlite_pool: SqlitePool, pub http_client: Client, } +/// Builds a SQLite and HTTP client from the default configuration. #[cgp_impl(new BuildDefaultSqliteAndHttpClient)] -impl Handler -where - Self: HasSqlitePath + CanRaiseError, -{ +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl Handler { type Output = SqliteAndHttpClient; async fn handle( &self, _code: PhantomData, _input: Input, - ) -> Result { - let sqlite_pool = SqlitePool::connect(self.db_path()) + #[implicit] db_path: &str, + ) -> Result { + let sqlite_pool = SqlitePool::connect(db_path) .await .map_err(Self::raise_error)?; diff --git a/expression/Cargo.toml b/expression/Cargo.toml index 74cf8de..a106e98 100644 --- a/expression/Cargo.toml +++ b/expression/Cargo.toml @@ -4,6 +4,9 @@ version = "0.1.0" edition = { workspace = true } license = { workspace = true } repository = { workspace = true } +homepage = { workspace = true } +categories = { workspace = true } +description = "An arithmetic interpreter open to new variants and operations, built with CGP." authors = { workspace = true } rust-version = { workspace = true } keywords = { workspace = true } diff --git a/expression/src/components/expression.rs b/expression/src/components/expression.rs index 06b2f20..a12d715 100644 --- a/expression/src/components/expression.rs +++ b/expression/src/components/expression.rs @@ -1,10 +1,14 @@ use cgp::prelude::*; +/// A context's abstract Lisp-expression type. See +/// [the add_mult example](https://contextgeneric.dev/docs/projects/cgp-examples/expression/examples/add-mult). #[cgp_type] pub trait HasLispExprType { type LispExpr; } +/// A context's abstract math-expression type. See +/// [the add_mult example](https://contextgeneric.dev/docs/projects/cgp-examples/expression/examples/add-mult). #[cgp_type] pub trait HasMathExprType { type MathExpr; diff --git a/expression/src/contexts/add_mult.rs b/expression/src/contexts/add_mult.rs index a2a02af..ada71ba 100644 --- a/expression/src/contexts/add_mult.rs +++ b/expression/src/contexts/add_mult.rs @@ -1,5 +1,5 @@ use cgp::extra::dispatch::{MatchWithValueHandlers, MatchWithValueHandlersRef}; -use cgp::extra::handler::{ComputerRef, ComputerRefComponent, UseInputDelegate}; +use cgp::extra::handler::{Computer, ComputerComponent, ComputerRef, ComputerRefComponent}; use cgp::prelude::*; use crate::components::{LispExprTypeProviderComponent, MathExprTypeProviderComponent}; @@ -11,14 +11,14 @@ use crate::types::{Ident, List, Literal, Plus, Times}; pub type Value = u64; -#[derive(Debug, HasFields, FromVariant, ExtractField)] +#[derive(Debug, CgpData)] pub enum MathExpr { Plus(Plus), Times(Times), Literal(Literal), } -#[derive(Eq, PartialEq, Debug, HasFields, FromVariant, ExtractField)] +#[derive(Eq, PartialEq, Debug, CgpData)] pub enum LispExpr { List(List), Literal(Literal), @@ -29,31 +29,27 @@ pub struct Interpreter; delegate_components! { Interpreter { + open { ComputerComponent, ComputerRefComponent }; + MathExprTypeProviderComponent: UseType, LispExprTypeProviderComponent: UseType, - ComputerComponent: - UseInputDelegate< - new EvalComponents { - MathExpr: DispatchEval, - Plus: EvalAdd, - Times: EvalMultiply, - Literal: EvalLiteral, - } - >, - ComputerRefComponent: - UseInputDelegate< - new ToLispComponents { - MathExpr: DispatchToLisp, - Literal: LiteralToLisp, - Plus: PlusToLisp, - Times: TimesToLisp, - } - >, + + @ComputerComponent. Code.MathExpr: DispatchEval, + @ComputerComponent. Code.Plus: EvalAdd, + @ComputerComponent. Code.Times: EvalMultiply, + @ComputerComponent. Code.Literal: EvalLiteral, + + @ComputerRefComponent. Code.MathExpr: DispatchToLisp, + @ComputerRefComponent. Code.Literal: LiteralToLisp, + @ComputerRefComponent. Code.Plus: PlusToLisp, + @ComputerRefComponent. Code.Times: TimesToLisp, } } +/// Evaluates the language enum by handing its current variant to the context's evaluation. See +/// [the dispatch layers page](https://contextgeneric.dev/docs/projects/cgp-examples/expression/architecture/dispatch-layers). #[cgp_impl(new DispatchEval)] impl Computer for Interpreter { type Output = Value; @@ -63,6 +59,8 @@ impl Computer for Interpreter { } } +/// Converts the language enum by handing its current variant to the context's conversion. See +/// [the dispatch layers page](https://contextgeneric.dev/docs/projects/cgp-examples/expression/architecture/dispatch-layers). #[cgp_impl(new DispatchToLisp)] impl ComputerRef for Interpreter { type Output = LispExpr; @@ -82,6 +80,7 @@ check_components! { (Eval, MathExpr), (Eval, Literal), (Eval, Plus), + (Eval, Times), ], ComputerRefComponent: [ (ToLisp, MathExpr), diff --git a/expression/src/contexts/add_mult_binary_op.rs b/expression/src/contexts/add_mult_binary_op.rs index 60e8ef1..ed99008 100644 --- a/expression/src/contexts/add_mult_binary_op.rs +++ b/expression/src/contexts/add_mult_binary_op.rs @@ -1,5 +1,5 @@ use cgp::extra::dispatch::{MatchWithValueHandlers, MatchWithValueHandlersRef}; -use cgp::extra::handler::{ComputerRef, ComputerRefComponent, UseInputDelegate}; +use cgp::extra::handler::{Computer, ComputerComponent, ComputerRef, ComputerRefComponent}; use cgp::prelude::*; use crate::components::{LispExprTypeProviderComponent, MathExprTypeProviderComponent}; @@ -9,14 +9,14 @@ use crate::types::{Ident, List, Literal, Plus, Times}; pub type Value = u64; -#[derive(Debug, HasFields, FromVariant, ExtractField)] +#[derive(Debug, CgpData)] pub enum MathExpr { Plus(Plus), Times(Times), Literal(Literal), } -#[derive(Eq, PartialEq, Debug, HasFields, FromVariant, ExtractField)] +#[derive(Eq, PartialEq, Debug, CgpData)] pub enum LispExpr { List(List), Literal(Literal), @@ -27,31 +27,27 @@ pub struct Interpreter; delegate_components! { Interpreter { + open { ComputerComponent, ComputerRefComponent }; + MathExprTypeProviderComponent: UseType, LispExprTypeProviderComponent: UseType, - ComputerComponent: - UseInputDelegate< - new EvalComponents { - MathExpr: DispatchEval, - Plus: EvalAdd, - Times: EvalMultiply, - Literal: EvalLiteral, - } - >, - ComputerRefComponent: - UseInputDelegate< - new ToLispComponents { - MathExpr: DispatchToLisp, - Literal: LiteralToLisp, - Plus: BinaryOpToLisp, - Times: BinaryOpToLisp, - } - >, + + @ComputerComponent. Code.MathExpr: DispatchEval, + @ComputerComponent. Code.Plus: EvalAdd, + @ComputerComponent. Code.Times: EvalMultiply, + @ComputerComponent. Code.Literal: EvalLiteral, + + @ComputerRefComponent. Code.MathExpr: DispatchToLisp, + @ComputerRefComponent. Code.Literal: LiteralToLisp, + @ComputerRefComponent. Code.Plus: BinaryOpToLisp, + @ComputerRefComponent. Code.Times: BinaryOpToLisp, } } +/// Evaluates the language enum by handing its current variant to the context's evaluation. See +/// [the dispatch layers page](https://contextgeneric.dev/docs/projects/cgp-examples/expression/architecture/dispatch-layers). #[cgp_impl(new DispatchEval)] impl Computer for Interpreter { type Output = Value; @@ -61,6 +57,8 @@ impl Computer for Interpreter { } } +/// Converts the language enum by handing its current variant to the context's conversion. See +/// [the dispatch layers page](https://contextgeneric.dev/docs/projects/cgp-examples/expression/architecture/dispatch-layers). #[cgp_impl(new DispatchToLisp)] impl ComputerRef for Interpreter { type Output = LispExpr; @@ -80,6 +78,7 @@ check_components! { (Eval, MathExpr), (Eval, Literal), (Eval, Plus), + (Eval, Times), ], ComputerRefComponent: [ (ToLisp, MathExpr), diff --git a/expression/src/contexts/add_mult_code.rs b/expression/src/contexts/add_mult_code.rs index cd69748..9fa7180 100644 --- a/expression/src/contexts/add_mult_code.rs +++ b/expression/src/contexts/add_mult_code.rs @@ -1,5 +1,5 @@ use cgp::extra::dispatch::MatchWithValueHandlersRef; -use cgp::extra::handler::{ComputerRef, ComputerRefComponent, UseInputDelegate}; +use cgp::extra::handler::{ComputerRef, ComputerRefComponent}; use cgp::prelude::*; use crate::components::{LispExprTypeProviderComponent, MathExprTypeProviderComponent}; @@ -9,14 +9,14 @@ use crate::types::{Ident, List, Literal, Plus, Times}; pub type Value = u64; -#[derive(Debug, HasFields, FromVariant, ExtractField)] +#[derive(Debug, CgpData)] pub enum MathExpr { Plus(Plus), Times(Times), Literal(Literal), } -#[derive(Eq, PartialEq, Debug, HasFields, FromVariant, ExtractField)] +#[derive(Eq, PartialEq, Debug, CgpData)] pub enum LispExpr { List(List), Literal(Literal), @@ -27,62 +27,27 @@ pub struct Interpreter; delegate_components! { Interpreter { + open ComputerRefComponent; + MathExprTypeProviderComponent: UseType, LispExprTypeProviderComponent: UseType, - ComputerRefComponent: - UseInputDelegate< - new ExprComputerComponents { - MathExpr: HandleMathExpr, - Literal: HandleLiteral, - Plus: HandlePlus, - Times: HandleTimes, - } - >, - } -} -delegate_components! { - new HandlePlus { - ComputerRefComponent: UseDelegate< - new PlusHandlers { - Eval: EvalAdd, - ToLisp: BinaryOpToLisp, - }> - } -} + @ComputerRefComponent.Eval.MathExpr: DispatchEval, + @ComputerRefComponent.Eval.Literal: EvalLiteral, + @ComputerRefComponent.Eval.Plus: EvalAdd, + @ComputerRefComponent.Eval.Times: EvalMultiply, -delegate_components! { - new HandleTimes { - ComputerRefComponent: UseDelegate< - new TimesHandlers { - Eval: EvalMultiply, - ToLisp: BinaryOpToLisp, - }> - } -} - -delegate_components! { - new HandleLiteral { - ComputerRefComponent: UseDelegate< - new LiteralHandlers { - Eval: EvalLiteral, - ToLisp: LiteralToLisp, - }> - } -} - -delegate_components! { - new HandleMathExpr { - ComputerRefComponent: UseDelegate< - new MathExprHandlers { - Eval: DispatchEval, - ToLisp: DispatchToLisp, - }> + @ComputerRefComponent.ToLisp.MathExpr: DispatchToLisp, + @ComputerRefComponent.ToLisp.Literal: LiteralToLisp, + @ComputerRefComponent.ToLisp.Plus: BinaryOpToLisp, + @ComputerRefComponent.ToLisp.Times: BinaryOpToLisp, } } +/// Evaluates the language enum for the `Eval` code by handing its current variant to the context. See +/// [the dispatch layers page](https://contextgeneric.dev/docs/projects/cgp-examples/expression/architecture/dispatch-layers). #[cgp_impl(new DispatchEval)] impl ComputerRef for Interpreter { type Output = Value; @@ -96,6 +61,8 @@ impl ComputerRef for Interpreter { } } +/// Converts the language enum for the `ToLisp` code by handing its current variant to the context. See +/// [the dispatch layers page](https://contextgeneric.dev/docs/projects/cgp-examples/expression/architecture/dispatch-layers). #[cgp_impl(new DispatchToLisp)] impl ComputerRef for Interpreter { type Output = LispExpr; @@ -115,6 +82,7 @@ check_components! { (Eval, MathExpr), (Eval, Literal), (Eval, Plus), + (Eval, Times), (ToLisp, MathExpr), (ToLisp, Literal), (ToLisp, Plus), diff --git a/expression/src/contexts/add_mult_neg.rs b/expression/src/contexts/add_mult_neg.rs index b86af01..9f2fdfc 100644 --- a/expression/src/contexts/add_mult_neg.rs +++ b/expression/src/contexts/add_mult_neg.rs @@ -1,5 +1,5 @@ use cgp::extra::dispatch::MatchWithValueHandlersRef; -use cgp::extra::handler::{ComputerRef, ComputerRefComponent, UseInputDelegate}; +use cgp::extra::handler::{ComputerRef, ComputerRefComponent}; use cgp::prelude::*; use crate::dsl::Eval; @@ -8,7 +8,7 @@ use crate::types::{Literal, Minus, Negate, Plus, Times}; pub type Value = i64; -#[derive(Debug, HasFields, FromVariant, ExtractField)] +#[derive(Debug, CgpData)] pub enum MathPlusExpr { Plus(Plus), Times(Times), @@ -21,20 +21,19 @@ pub struct InterpreterPlus; delegate_components! { InterpreterPlus { - ComputerRefComponent: - UseDelegate: EvalAdd, - Times: EvalMultiply, - Literal: EvalLiteral, - Minus: EvalSubtract, - Negate: EvalNegate, - }>, - }> + open ComputerRefComponent; + + @ComputerRefComponent.Eval.MathPlusExpr: DispatchEval, + @ComputerRefComponent.Eval.Plus: EvalAdd, + @ComputerRefComponent.Eval.Times: EvalMultiply, + @ComputerRefComponent.Eval.Literal: EvalLiteral, + @ComputerRefComponent.Eval.Minus: EvalSubtract, + @ComputerRefComponent.Eval.Negate: EvalNegate, } } +/// Evaluates the language enum by handing its current variant to the context's evaluation. See +/// [the dispatch layers page](https://contextgeneric.dev/docs/projects/cgp-examples/expression/architecture/dispatch-layers). #[cgp_impl(new DispatchEval)] impl ComputerRef for InterpreterPlus { type Output = Value; @@ -54,6 +53,7 @@ check_components! { (Eval, MathPlusExpr), (Eval, Literal), (Eval, Plus), + (Eval, Times), (Eval, Negate), (Eval, Minus), ] diff --git a/expression/src/providers/eval/add.rs b/expression/src/providers/eval/add.rs index 1570541..1d714bc 100644 --- a/expression/src/providers/eval/add.rs +++ b/expression/src/providers/eval/add.rs @@ -1,16 +1,18 @@ use core::ops::Add; use cgp::extra::handler::{ - CanCompute, CanComputeRef, ComputerComponent, ComputerRef, ComputerRefComponent, + CanCompute, CanComputeRef, Computer, ComputerComponent, ComputerRef, ComputerRefComponent, }; use cgp::prelude::*; use crate::types::Plus; +/// Evaluates a `Plus` by adding the values its operands evaluate to. See +/// [the add_mult example](https://contextgeneric.dev/docs/projects/cgp-examples/expression/examples/add-mult). #[cgp_impl(new EvalAdd)] +#[uses(CanCompute)] impl Computer> where - Self: CanCompute, Output: Add, { type Output = Output; @@ -28,9 +30,9 @@ where } #[cgp_impl(EvalAdd)] +#[uses(CanComputeRef)] impl ComputerRef> where - Self: CanComputeRef, Output: Add, { type Output = Output; diff --git a/expression/src/providers/eval/literal.rs b/expression/src/providers/eval/literal.rs index 140d042..56bc5f5 100644 --- a/expression/src/providers/eval/literal.rs +++ b/expression/src/providers/eval/literal.rs @@ -1,8 +1,10 @@ -use cgp::extra::handler::{ComputerRef, ComputerRefComponent}; +use cgp::extra::handler::{Computer, ComputerComponent, ComputerRef, ComputerRefComponent}; use cgp::prelude::*; use crate::types::Literal; +/// Evaluates a `Literal` to its value. See +/// [the add_mult example](https://contextgeneric.dev/docs/projects/cgp-examples/expression/examples/add-mult). #[cgp_impl(new EvalLiteral)] impl Computer> { type Output = T; diff --git a/expression/src/providers/eval/multiply.rs b/expression/src/providers/eval/multiply.rs index 3e46601..ebda448 100644 --- a/expression/src/providers/eval/multiply.rs +++ b/expression/src/providers/eval/multiply.rs @@ -1,14 +1,18 @@ use core::ops::Mul; -use cgp::extra::handler::{CanCompute, CanComputeRef, ComputerRef, ComputerRefComponent}; +use cgp::extra::handler::{ + CanCompute, CanComputeRef, Computer, ComputerComponent, ComputerRef, ComputerRefComponent, +}; use cgp::prelude::*; use crate::types::Times; +/// Evaluates a `Times` by multiplying the values its operands evaluate to. See +/// [the add_mult example](https://contextgeneric.dev/docs/projects/cgp-examples/expression/examples/add-mult). #[cgp_impl(new EvalMultiply)] +#[uses(CanCompute)] impl Computer> where - Self: CanCompute, Output: Mul, { type Output = Output; @@ -22,9 +26,9 @@ where } #[cgp_impl(EvalMultiply)] +#[uses(CanComputeRef)] impl ComputerRef> where - Self: CanComputeRef, Output: Mul, { type Output = Output; diff --git a/expression/src/providers/eval/negate.rs b/expression/src/providers/eval/negate.rs index ef56afd..1c14785 100644 --- a/expression/src/providers/eval/negate.rs +++ b/expression/src/providers/eval/negate.rs @@ -5,10 +5,12 @@ use cgp::prelude::*; use crate::types::Negate; +/// Evaluates a `Negate` by negating the value its operand evaluates to. See +/// [the add_mult_neg example](https://contextgeneric.dev/docs/projects/cgp-examples/expression/examples/add-mult-neg). #[cgp_impl(new EvalNegate)] +#[uses(CanComputeRef)] impl ComputerRef> where - Self: CanComputeRef, Output: Neg, { type Output = Output; diff --git a/expression/src/providers/eval/subtract.rs b/expression/src/providers/eval/subtract.rs index a37d7be..f1b2457 100644 --- a/expression/src/providers/eval/subtract.rs +++ b/expression/src/providers/eval/subtract.rs @@ -1,14 +1,19 @@ use core::ops::Sub; -use cgp::extra::handler::{CanCompute, CanComputeRef, ComputerRef, ComputerRefComponent}; +use cgp::core::field::traits::FromVariant; +use cgp::extra::handler::{ + CanCompute, CanComputeRef, Computer, ComputerComponent, ComputerRef, ComputerRefComponent, +}; use cgp::prelude::*; use crate::types::{Minus, Negate, Plus}; +/// Evaluates a `Minus` by subtracting the right operand's value from the left's. See +/// [the add_mult_neg example](https://contextgeneric.dev/docs/projects/cgp-examples/expression/examples/add-mult-neg). #[cgp_impl(new EvalSubtract)] +#[uses(CanComputeRef)] impl ComputerRef> where - Self: CanComputeRef, Output: Sub, { type Output = Output; @@ -25,10 +30,11 @@ where } } +/// Evaluates a `Minus` by rewriting it as a `Plus` of the left operand and a negated right one. #[cgp_impl(new EvalSubtractWithNegate)] +#[uses(CanCompute, Output = Output>)] impl Computer> where - Self: CanCompute, Output = Output>, Expr: FromVariant>, { type Output = Output; diff --git a/expression/src/providers/to_lisp/add.rs b/expression/src/providers/to_lisp/add.rs index 87c9133..a368bfe 100644 --- a/expression/src/providers/to_lisp/add.rs +++ b/expression/src/providers/to_lisp/add.rs @@ -8,16 +8,19 @@ use cgp::prelude::*; use crate::components::HasLispExprType; use crate::types::{Ident, List, Plus}; -#[derive(HasFields, ExtractField, FromVariant)] +#[derive(CgpData)] enum LispSubExpr { List(List), Ident(Ident), } +/// Converts a `Plus` to the list `(+ left right)`. See +/// [the add_mult example](https://contextgeneric.dev/docs/projects/cgp-examples/expression/examples/add-mult). #[cgp_impl(new PlusToLisp)] -impl ComputerRef> +#[use_type(HasLispExprType.LispExpr)] +#[uses(CanComputeRef)] +impl ComputerRef> where - Self: HasLispExprType + CanComputeRef, LispSubExpr: CanUpcast, { type Output = LispExpr; diff --git a/expression/src/providers/to_lisp/binary.rs b/expression/src/providers/to_lisp/binary.rs index 19f8a7a..358a48e 100644 --- a/expression/src/providers/to_lisp/binary.rs +++ b/expression/src/providers/to_lisp/binary.rs @@ -10,24 +10,27 @@ use cgp::prelude::*; use crate::components::{HasLispExprType, HasMathExprType}; use crate::types::{Ident, List}; +/// Reads the left and right operands of a binary expression. See +/// [the add_mult_binary_op example](https://contextgeneric.dev/docs/projects/cgp-examples/expression/examples/add-mult-binary-op). #[cgp_auto_getter] pub trait BinarySubExpression { fn left(&self) -> &Box; fn right(&self) -> &Box; } -#[derive(HasFields, ExtractField, FromVariant)] +#[derive(CgpData)] enum LispSubExpr { List(List), Ident(Ident), } +/// Converts any binary operator to a list headed by the operator's symbol. See +/// [the add_mult_binary_op example](https://contextgeneric.dev/docs/projects/cgp-examples/expression/examples/add-mult-binary-op). #[cgp_impl(new BinaryOpToLisp)] -impl ComputerRef +#[use_type(HasMathExprType.MathExpr, HasLispExprType.LispExpr)] +#[uses(CanComputeRef)] +impl ComputerRef where - Self: HasMathExprType - + HasLispExprType - + CanComputeRef, MathSubExpr: BinarySubExpression, Operator: Default + Display, LispSubExpr: CanUpcast, diff --git a/expression/src/providers/to_lisp/literal.rs b/expression/src/providers/to_lisp/literal.rs index 7d2acf8..22ad981 100644 --- a/expression/src/providers/to_lisp/literal.rs +++ b/expression/src/providers/to_lisp/literal.rs @@ -5,15 +5,17 @@ use cgp::prelude::*; use crate::components::HasLispExprType; use crate::types::Literal; -#[derive(HasFields, ExtractField, FromVariant)] +#[derive(CgpData)] enum LispSubExpr { Literal(Literal), } +/// Converts a `Literal` to the target type's `Literal` variant. See +/// [the add_mult example](https://contextgeneric.dev/docs/projects/cgp-examples/expression/examples/add-mult). #[cgp_impl(new LiteralToLisp)] -impl ComputerRef> +#[use_type(HasLispExprType.LispExpr)] +impl ComputerRef> where - Self: HasLispExprType, LispSubExpr: CanUpcast, T: Clone, { diff --git a/expression/src/providers/to_lisp/multiply.rs b/expression/src/providers/to_lisp/multiply.rs index a7bde8c..186270a 100644 --- a/expression/src/providers/to_lisp/multiply.rs +++ b/expression/src/providers/to_lisp/multiply.rs @@ -8,16 +8,19 @@ use cgp::prelude::*; use crate::components::HasLispExprType; use crate::types::{Ident, List, Times}; -#[derive(HasFields, ExtractField, FromVariant)] +#[derive(CgpData)] enum LispSubExpr { List(List), Ident(Ident), } +/// Converts a `Times` to the list `(* left right)`. See +/// [the add_mult example](https://contextgeneric.dev/docs/projects/cgp-examples/expression/examples/add-mult). #[cgp_impl(new TimesToLisp)] -impl ComputerRef> +#[use_type(HasLispExprType.LispExpr)] +#[uses(CanComputeRef)] +impl ComputerRef> where - Self: HasLispExprType + CanComputeRef, LispSubExpr: CanUpcast, { type Output = LispExpr; diff --git a/greet/Cargo.toml b/greet/Cargo.toml index 0a7913b..22c3457 100644 --- a/greet/Cargo.toml +++ b/greet/Cargo.toml @@ -4,6 +4,9 @@ version = "0.1.0" edition = { workspace = true } license = { workspace = true } repository = { workspace = true } +homepage = { workspace = true } +categories = { workspace = true } +description = "A greeting written as a function, as a component, and over an abstract type." authors = { workspace = true } rust-version = { workspace = true } keywords = { workspace = true } diff --git a/greet/bin/greet_abstract_type.rs b/greet/bin/greet_abstract_type.rs index 17627d2..c33202f 100644 --- a/greet/bin/greet_abstract_type.rs +++ b/greet/bin/greet_abstract_type.rs @@ -2,18 +2,21 @@ use core::fmt::Display; use cgp::prelude::*; +/// Greets a person. #[cgp_component(Greeter)] pub trait CanGreet { fn greet(&self); } +/// A context's abstract name type. #[cgp_type] pub trait HasNameType { type Name; } +/// Greets by printing `Hello, {name}!` for the context's abstract `Name` type. #[cgp_impl(new GreetHello)] -#[use_type(HasNameType::Name)] +#[use_type(HasNameType.Name)] impl Greeter where Name: Display, diff --git a/greet/bin/greet_component.rs b/greet/bin/greet_component.rs index 0363d80..8639683 100644 --- a/greet/bin/greet_component.rs +++ b/greet/bin/greet_component.rs @@ -1,15 +1,18 @@ use cgp::prelude::*; +/// Greets a person. #[cgp_component(Greeter)] pub trait CanGreet { fn greet(&self); } +/// A context's abstract name type. #[cgp_type] pub trait HasNameType { type Name; } +/// Greets by printing `Hello, {name}!` from the context's `name` field. #[cgp_impl(new GreetHello)] impl Greeter { fn greet(&self, #[implicit] name: &str) { @@ -17,6 +20,7 @@ impl Greeter { } } +/// Greets by printing `Hi, {name}!` from the context's `name` field. #[cgp_impl(new GreetHi)] impl Greeter { fn greet(&self, #[implicit] name: &str) { diff --git a/greet/bin/greet_function.rs b/greet/bin/greet_function.rs index efc5154..ba34322 100644 --- a/greet/bin/greet_function.rs +++ b/greet/bin/greet_function.rs @@ -1,5 +1,6 @@ use cgp::prelude::*; +/// Greets a person by name. #[cgp_fn] pub fn greet(&self, #[implicit] name: &str) { println!("Hello, {name}!"); diff --git a/greet/src/greet_expanded.rs b/greet/src/greet_expanded.rs index 38bf837..8517fff 100644 --- a/greet/src/greet_expanded.rs +++ b/greet/src/greet_expanded.rs @@ -1,4 +1,11 @@ -use cgp::prelude::*; +//! A hand-written expansion of what `#[cgp_component]` generates for `CanGreet`. +//! +//! The items here are the macro's output written out by hand, so a reader can see the wiring +//! machinery the component macro adds: the component marker, the provider trait, and the two +//! blanket impls that connect them. They carry no docs of their own, and the file differs from +//! the macro's current output in the details the knowledge base records. + +use cgp::core::component::{DelegateComponent, IsProviderFor}; pub struct GreeterComponent; diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 0000000..3bf2079 --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,5 @@ +# The workspace's declared minimum (`rust-version`), so CI checks that every +# example builds on it and a contributor builds with the same compiler. +[toolchain] +channel = "1.90" +profile = "minimal" diff --git a/transfer/Cargo.toml b/transfer/Cargo.toml index b3fa772..dea71bf 100644 --- a/transfer/Cargo.toml +++ b/transfer/Cargo.toml @@ -4,6 +4,9 @@ version = "0.1.0" edition = { workspace = true } license = { workspace = true } repository = { workspace = true } +homepage = { workspace = true } +categories = { workspace = true } +description = "A money-transfer HTTP service wired with CGP components and namespaces." authors = { workspace = true } rust-version = { workspace = true } keywords = { workspace = true } @@ -15,11 +18,11 @@ path = "bin/server.rs" [dependencies] cgp = { workspace = true } -anyhow = { version = "1.0.95" } -futures = { version = "0.3.31" } +anyhow = { version = "1.0.104" } +futures = { version = "0.3.34" } num-traits = { version = "0.2.19" } -serde = { version = "1.0.217", features = ["derive"] } -axum = { version = "0.8.1" } -axum-extra = { version = "0.10.0", features = ["typed-header"] } -headers = { version = "0.4.0" } -tokio = { version = "1.43.0", features = ["full"] } +serde = { version = "1.0.229", features = ["derive"] } +axum = { version = "0.8.9" } +axum-extra = { version = "0.10.3", features = ["typed-header"] } +headers = { version = "0.4.2" } +tokio = { version = "1.54.1", features = ["full"] } diff --git a/transfer/README.md b/transfer/README.md new file mode 100644 index 0000000..0cc7226 --- /dev/null +++ b/transfer/README.md @@ -0,0 +1,526 @@ +# Money-Transfer API: a Context-Generic Programming walkthrough + +This example is a small money-transfer web service: it lets a user check an account +balance and move funds to another user, served over HTTP. Its real purpose is to teach +**Context-Generic Programming (CGP)**, a modular style of Rust in which a trait is +declared once, implemented many times, and each implementation is chosen per application +by *wiring* rather than by hardcoding. The service is deliberately tiny so that the CGP +techniques, not the business logic, are what you take away. + +The walkthrough assumes you know Rust, including traits, generics, and `async`/`await`, but +nothing about CGP. The website's [quickstart](https://contextgeneric.dev/docs/quickstart) and +[reference](https://contextgeneric.dev/docs/reference/) cover the same constructs from the other +direction, one at a time. Every CGP construct is explained where it first appears, so you can read this +file top to bottom without any other reference. If you only skim, the first sentence of +each section carries the point. + +## What the service does + +The server exposes two endpoints, both authenticated with HTTP Basic auth. `GET /balance` +returns the caller's balance in a given currency, and `POST /transfer` moves a quantity of +one currency from the caller to a named recipient. Failures come back as HTTP status codes: +`401` when you are not logged in, `400` for a bad request such as transferring to yourself, +and `404` when a user is unknown. + +The [example.sh](example.sh) script shows the shape of a session against a running server: + +```bash +export ALICE_AUTH="Authorization: Basic $(echo -n 'alice:wonderland' | base64)" + +# Alice checks her EUR balance +curl -i -H "$ALICE_AUTH" 'http://localhost:8080/balance?currency=EUR' + +# Alice transfers 10 EUR to Bob +curl -i -XPOST -H "$ALICE_AUTH" 'http://localhost:8080/transfer?currency=EUR&recipient=bob&quantity=10' +``` + +The data lives in memory, seeded with two users (Alice and Bob) in +[src/contexts/app.rs](src/contexts/app.rs). A real deployment would swap the in-memory +store for a database, and, as the last section shows, that swap touches none of the +request-handling code. + +## How to run it + +The example is an ordinary Cargo binary. Start the server and then drive it with the +script above: + +```bash +cargo run --bin server # listens on 0.0.0.0:8080 +./example.sh # in another terminal +``` + +## A five-minute CGP primer + +Read this section once and the rest of the walkthrough falls into place. It states the +whole mental model in terms this example uses. + +**CGP exists to get around Rust's coherence rules.** Rust allows at most one implementation +of a trait for a given type, and forbids implementing a foreign trait for a foreign type. +That makes it hard to offer several interchangeable implementations of one interface, or to +let the final application choose an implementation for a type a library defined. CGP +sidesteps both limits, so the same `handle_api` interface can have a mock backend today and +a database backend tomorrow, chosen without editing the interface or its callers. + +**A CGP component is split into two traits: a consumer trait you call, and a provider +trait you implement.** When you write `#[cgp_component(MoneyTransferrer)]` on a trait +`CanTransferMoney`, the macro keeps `CanTransferMoney` as the **consumer trait**, the +one callers use with the familiar `&self` receiver, and generates a matching **provider +trait** `MoneyTransferrer`, where the original `Self` has moved into an explicit +`Context` type parameter. The consumer reads as a verb (`CanTransferMoney`), the provider +as a noun (`MoneyTransferrer`). You call the consumer; you implement the provider. + +**A provider is a zero-sized marker type that implements a provider trait.** `UseMockedApp` +and `NoTransferToSelf` in this example are providers: structs with no fields, existing only +as names at the type level. Because a provider implements `MoneyTransferrer` for +*its own* struct over a generic `Context`, rather than implementing a trait for the context, +Rust's coherence rules never block it, and you can define as many alternative providers +for one component as you like. One consequence trips up every newcomer: inside a provider, +`self` and `Self` refer to the **context**, never to the provider struct. The provider +struct holds no data and is never constructed. + +**Wiring is a per-context, compile-time table that says which provider implements each +component.** The `delegate_components!` macro builds it. An entry like +`MoneyTransferrerComponent: UseMockedApp` means "for this context, the money-transfer +component is supplied by `UseMockedApp`." The table is pure trait resolution: there is no +runtime lookup, no dynamic dispatch, and no vtable. The compiler picks the provider during +type-checking and compiles the call down to a direct, static function call, so all of this +machinery costs nothing at runtime. + +**A provider declares the dependencies it needs in a `where` clause, and those dependencies +stay hidden from callers.** This is CGP's form of dependency injection, and it is the single +most important idea. `UseBasicAuth` needs the ability to look up a hashed password and check +it; it says so with `#[uses(CanQueryUserHashedPassword, CanCheckPassword)]`, which adds those +as bounds on its own implementation. A caller that uses the authenticated handler never sees +those requirements, because they are satisfied one level down, by whatever the context wires +for them. This is why endpoints can be written against abstract traits and stay ignorant +of the concrete backend behind them. + +**Wiring is checked with `check_components!`.** Because wiring is resolved lazily, a missing +dependency would otherwise only surface far away, at the point of use, as a confusing error. +`check_components!` asserts at compile time that a context is fully and correctly wired, +reporting the exact missing piece at the wiring site. A green build *is* the passing test. + +With those six ideas, which are two traits, providers, wiring, impl-side dependencies, and +checking, you can read every construct below. + +## Map of the code + +The crate is organized so that the *interface* of the service is separated from every +*implementation* of it, which is the separation CGP is built to exploit. Five directories +under [src/](src) each hold one kind of thing: + +- [src/interfaces/](src/interfaces) — the CGP components: the consumer traits and abstract + types that define *what* the service can do, naming no concrete type or backend. +- [src/providers/](src/providers) — the providers that implement those components: the + endpoint handlers, the reusable wrappers, the in-memory backend, and the error mapping. +- [src/types/](src/types) — the concrete Rust types a deployment plugs in: the currency + enum, the error struct, and the request structs. +- [src/namespaces/](src/namespaces) — reusable bundles of wiring that a context inherits, + so the application's own wiring stays short. +- [src/contexts/](src/contexts) — the concrete application type, `MockApp`, that ties + everything together by wiring each component to a provider. + +The [bin/server.rs](bin/server.rs) entry point builds a `MockApp`, mounts its endpoints on +an Axum router, and serves them. The sections below follow the data inward: from the +abstract vocabulary, through the handlers and backend, to the wiring and the HTTP layer. + +## 1. Abstract domain types + +The service never names a concrete user id, currency, or amount; it names *abstract types* +that a context supplies later. An abstract type in CGP is a trait carrying a single +associated type, and the `#[cgp_type]` macro is the shorthand for defining one. In +[src/interfaces/types.rs](src/interfaces/types.rs): + +```rust +#[cgp_type] +#[prefix(@app.finance.types in DefaultNamespace)] +pub trait HasCurrencyType { + type Currency: Display; +} +``` + +`HasCurrencyType` says "a context has *some* currency type, and whatever it is, it can be +displayed." Generic code refers to `Self::Currency` without committing to `String`, an enum, +or anything else; the concrete choice is made once, at wiring time. This is what lets a +single balance-query handler serve one deployment whose currency is a rich enum and another +whose currency is a bare string, with no change to the handler. The example defines five +such types, which are user id, quantity, currency, password, and hashed password, each +carrying only the bound the rest of the code actually needs. + +The `#[prefix(...)]` attribute files each component under a dotted path in a shared +namespace. Ignore it for now; it is a wiring-organization detail explained in +[section 7](#7-assembling-the-app-with-namespaces). + +A context supplies a concrete type by wiring the component to `UseType`, a built-in +provider that means "the abstract type is `T`." `MockApp` picks its currency with +`CurrencyTypeProviderComponent: UseType`, and the `Display` bound is checked +against `DemoCurrency` right there at the wiring site. + +## 2. Status-coded errors + +Endpoints fail with an HTTP status code, but the handlers never build one directly; they +raise through an application-specific error component, so the mapping from a domain failure +to a status code lives in exactly one place. That component, in +[src/interfaces/error.rs](src/interfaces/error.rs), is a component: + +```rust +#[cgp_component(HttpErrorRaiser)] +#[prefix(@app.error in DefaultNamespace)] +#[use_type(HasErrorType.Error)] +pub trait CanRaiseHttpError { + fn raise_http_error(_code: Code, detail: Detail) -> Error; +} +``` + +Two CGP features appear here. `CanRaiseHttpError` is generic over a `Code` marker (one of +the zero-sized `ErrUnauthorized`, `ErrBadRequest`, `ErrNotFound` structs) and a `Detail` +value, so `Self::raise_http_error(ErrNotFound, "user not found")` names the status class at +the type level. And `#[use_type(HasErrorType.Error)]` imports the context's *abstract error +type*: `HasErrorType` is CGP's built-in "a context has one shared error type `Error`" +component, and the attribute both makes it a supertrait and rewrites the bare `Error` in the +signature to the fully-qualified associated type. Without the attribute the method would have +to be written `-> ::Error`; the attribute lets it read `-> Error`. + +The status codes come from an ordinary trait that turns each marker into a code, so a provider +can map `ErrUnauthorized` to `401` with no match statement: + +```rust +pub trait IsStatusCode { + fn status_code() -> StatusCode; +} +impl IsStatusCode for ErrUnauthorized { /* UNAUTHORIZED */ } +``` + +The provider that satisfies the component, `DisplayHttpError` in +[src/providers/error.rs](src/providers/error.rs), is generic over both the code and the +detail, so one provider serves every `raise_http_error` call whose detail is `Display`: + +```rust +#[cgp_impl(new DisplayHttpError)] +#[use_type(HasErrorType.{Error = AppError})] +impl HttpErrorRaiser +where + Code: IsStatusCode, + Detail: Display, +{ + fn raise_http_error(_code: Code, detail: Detail) -> AppError { /* ... */ } +} +``` + +`#[cgp_impl(new DisplayHttpError)]` is the idiomatic way to write a provider: you write the +impl in consumer-trait style, and the `new` keyword also declares the `struct DisplayHttpError;` +for you. The `#[use_type(HasErrorType.{Error = AppError})]` equality form goes one step +further than before: it *pins* the abstract error to the concrete `AppError`, which is why +the method body can construct an `AppError` value directly. A sibling provider, +`HandleHttpErrorWithAnyhow`, handles details that are already an `anyhow::Error`; the wiring +picks between the two per detail type. + +## 3. The API-handler component + +Every endpoint is one case of a single component that dispatches on a marker type naming the +API. In [src/interfaces/api.rs](src/interfaces/api.rs): + +```rust +#[cgp_component(ApiHandler)] +#[prefix(@app.api in DefaultNamespace)] +#[async_trait] +#[use_type(HasErrorType.Error)] +pub trait CanHandleApi { + type Request; + type Response; + + async fn handle_api(&self, _api: PhantomData, request: Self::Request) + -> Result; +} + +pub struct TransferApi; +pub struct QueryBalanceApi; +``` + +Because the component is generic over `Api`, a context can bind a *different* provider for +each endpoint marker, `TransferApi` to one and `QueryBalanceApi` to another, while the +`Request` and `Response` associated types let each endpoint fix its own input and output +shape. The `PhantomData` argument carries the endpoint choice at the type level, so the +dispatch is resolved at compile time with no runtime branch. `#[async_trait]` lets the method +be written as a natural `async fn` while generating the lint-clean `-> impl Future` +declaration underneath. + +## 4. The endpoint handlers + +Each endpoint is a provider for `ApiHandler` that depends on business *traits* rather +than on any concrete backend. The transfer endpoint, in +[src/providers/api_handlers/transfer.rs](src/providers/api_handlers/transfer.rs), reads the +logged-in sender and the transfer details from its request, then calls `CanTransferMoney`, +which the context wires to the mock backend. + +```rust +#[cgp_impl(new HandleTransfer)] +#[uses(CanTransferMoney, CanRaiseHttpError)] +#[use_type(HasErrorType.Error)] +impl ApiHandler +where + Request: HasLoggedInUser + HasTransferMoneyFields, +{ + type Request = Request; + type Response = (); + + async fn handle_api(&self, _api: PhantomData, request: Request) -> Result<(), Error> { + let sender = request.logged_in_user().as_ref().ok_or_else(|| { + Self::raise_http_error(ErrUnauthorized, "you must first login".into()) + })?; + self.transfer_money(sender, request.recipient(), request.currency(), request.quantity()) + .await?; + Ok(()) + } +} +``` + +The handler is generic over its request shape: `HandleTransfer` works for any +`Request` that exposes a logged-in user and the transfer fields through the getter traits +named in its `where` clause, so the same logic serves whatever request struct a deployment +decodes. The `#[uses(...)]` attribute is where the impl-side dependencies live: it declares +that the context must provide `CanTransferMoney` and the ability to raise an unauthorized +error, and those requirements never leak into the `ApiHandler` interface. Inside the body, +`self.transfer_money(...)` and `Self::raise_http_error(...)` call those wired traits; +which provider actually runs is decided by the context's wiring. + +The getter traits in the `where` clause, `HasLoggedInUser` and `HasTransferMoneyFields`, are +defined with `#[cgp_auto_getter]`, which turns a trait of `&self` accessors into a blanket +implementation that reads same-named fields off the context. They read fields from the +*request* type (`Request: HasTransferMoneyFields`), which is why they are getter traits +rather than the simpler implicit arguments used elsewhere: an implicit argument can only read +a field from `self`, and here the fields live on a separate request value. + +The balance query in +[src/providers/api_handlers/query_balance.rs](src/providers/api_handlers/query_balance.rs) +has the same shape but returns a value, so it fixes a `Response` type. Its +`QueryBalanceResponse` stays generic over the context's abstract `Quantity`, and +`#[derive(Serialize)]` lets the JSON layer encode it. + +## 5. Reusable wrappers as higher-order providers + +Cross-cutting concerns such as decoding, authentication, and JSON encoding are handlers that +wrap another handler. A provider that takes another provider as a type parameter and delegates +part of its work to it is called a **higher-order provider**, and it is how CGP composes +behavior. Each wrapper implements `ApiHandler` itself, takes an inner handler as a generic +parameter, and threads the call through, transforming the request or response on the way. + +`UseBasicAuth`, in +[src/providers/api_handlers/basic_auth.rs](src/providers/api_handlers/basic_auth.rs), +authenticates before delegating: it resolves a Basic-auth header into a logged-in user, +mutates the request in place, and then calls the inner handler. + +```rust +#[cgp_impl(new UseBasicAuth)] +#[uses(CanQueryUserHashedPassword, CanCheckPassword)] +#[use_type(HasErrorType.Error)] +#[use_provider(InHandler: ApiHandler)] +impl ApiHandler +where + InHandler::Request: HasLoggedInUserMut + HasBasicAuthHeader, + Self::UserId: Clone, +{ + // ... authenticate, then: InHandler::handle_api(self, api, request).await +} +``` + +The `#[use_provider(InHandler: ApiHandler)]` attribute is the key detail. A provider +trait moves `Self` into a leading context parameter, so the inner bound is really +`InHandler: ApiHandler`, with the context slot filled in. Writing that by hand is +easy to get wrong, so `#[use_provider]` lets you write `InHandler: ApiHandler` and +supplies the context argument for you. Note the body calls the inner handler as an +associated function, `InHandler::handle_api(self, ...)`, passing the context explicitly, +not `self.handle_api(...)`, which would route back through the context's own wiring instead +of the named inner provider. + +Two more wrappers complete the set. `HandleFromRequest` in +[src/providers/api_handlers/from_request.rs](src/providers/api_handlers/from_request.rs) +adapts the request type, letting an endpoint that wants a clean domain request sit behind a +handler whose request is the raw type the HTTP layer produces (it requires +`Request: Into`). `ResponseToJson` in +[src/providers/axum/json.rs](src/providers/axum/json.rs) adapts in the other direction, +wrapping whatever the inner handler returns in an Axum `Json` envelope. + +Because each wrapper is itself an `ApiHandler`, they nest into a pipeline. The balance +endpoint is wired to: + +```rust +HandleFromRequest>>> +``` + +which reads outside-in as the stages a request passes through: decode the raw Axum request, +JSON-encode the response, authenticate, run the endpoint. Each layer adds exactly one +concern, and the endpoint at the center is oblivious to all of them. + +## 6. The in-memory backend + +The business traits, which query a balance, transfer money, and check passwords, are +satisfied by a single provider, `UseMockedApp`, that reads its data from context fields. It +lives in [src/providers/mocked.rs](src/providers/mocked.rs) and implements each trait by +reaching into maps stored on the context, pulled in as `#[implicit]` arguments: + +```rust +#[cgp_impl(UseMockedApp)] +#[default_impl(@app.finance.UserBalanceQuerierComponent in MockNamespace)] +#[uses(CanRaiseHttpError)] +#[use_type(HasUserIdType.UserId, HasCurrencyType.Currency, HasQuantityType.Quantity, HasErrorType.Error)] +impl UserBalanceQuerier +where /* ... */ +{ + async fn query_user_balance( + &self, + user: &UserId, + currency: &Currency, + #[implicit] user_balances: &Arc>>, + ) -> Result { /* ... */ } +} +``` + +An `#[implicit]` argument is the preferred way to read a field from a provider's own context. +The macro removes the argument from the public signature, adds a hidden `where` bound saying +the context has a field of that name and type, and binds the value at the top of the body. +Here `user_balances` reads the same-named field off the context by shared reference, with no +clone and no getter trait to declare. The `#[use_type(...)]` attribute imports several +abstract types at once, so the signature can name `UserId`, `Currency`, and `Quantity` +without any `Self::` qualification. + +Swapping this backend for a real one is a one-line wiring change. Because `UseMockedApp` is +selected per context, a `UsePostgres` provider that implements the same traits would +replace it without touching a single endpoint or wrapper, which is the entire point of the +separation. + +A business trait can be wrapped just like an API handler. `NoTransferToSelf` in +[src/providers/finance.rs](src/providers/finance.rs) is a higher-order provider for +`MoneyTransferrer` that rejects a self-transfer and otherwise delegates to an inner transfer +provider, the same wrapping pattern as the HTTP handlers, applied to a domain trait. + +## 7. Assembling the app with namespaces + +A concrete context becomes the running application by resolving every abstract type and every +component. Spelling all of that out on the context would be long and repetitive, so the +example lifts the shared wiring into reusable **namespaces**. A namespace is a named table of +wiring entries that a context inherits wholesale and can then selectively override, which is +CGP's answer to the preset system earlier releases shipped. + +Namespaces are populated from two sides. Components file themselves under a path with the +`#[prefix(@path in DefaultNamespace)]` attribute seen throughout the interfaces, this is +what those attributes were for. Providers register themselves as a namespace's default with +the `#[default_impl(@path in MockNamespace)]` attribute seen on `UseMockedApp` above, which +places the wiring next to the implementation it wires. `MockNamespace` in +[src/namespaces/mock.rs](src/namespaces/mock.rs) then only needs to spell out the entries +that have no `#[cgp_impl]` block to attach to: the concrete error type, the per-detail HTTP +error dispatch, and the abstract type choices: + +```rust +cgp_namespace! { + new MockNamespace: DefaultNamespace { + @cgp.core.error.ErrorTypeProviderComponent: UseType, + @app.finance.types.QuantityTypeProviderComponent: UseType, + @app.finance.types.CurrencyTypeProviderComponent: UseType, + // ... and the HTTP-error dispatch and the auth types + } +} +``` + +The API surface, which is the handler pipeline that serves each endpoint, is a second +reusable table, +keyed by the API marker so any backend can pull it in. + +With the backend defaults in `MockNamespace` and the endpoints in `DefaultApiHandlers`, the +application's own wiring in [src/contexts/app.rs](src/contexts/app.rs) shrinks to three +decisions: + +```rust +delegate_components! { + MockApp { + namespace MockNamespace; + + for in DefaultApiHandlers { + @app.api.ApiHandlerComponent.Key: Value, + } + + @app.finance.MoneyTransferrerComponent: NoTransferToSelf, + } +} +``` + +Each line states a decision, not a mechanical fact. `namespace MockNamespace;` joins the +namespace, inheriting every default backend and type. The `for` loop pulls each entry of +`DefaultApiHandlers` onto the `ApiHandler` dispatch path, wiring both endpoints at once. And +the last line overrides the money-transfer component to wrap the mock backend in +`NoTransferToSelf`, guarding against self-transfers. The override is possible only because +`MockNamespace` deliberately does *not* claim the money-transfer path itself, so a context +can override it. + +Because CGP wiring is checked lazily, a companion `check_components!` block proves at compile +time that every endpoint is fully satisfied, listing the API markers to verify for the +generic `ApiHandler` component: + +```rust +check_components! { + MockApp { + QuantityTypeProviderComponent, + UserBalanceQuerierComponent, + MoneyTransferrerComponent, + ApiHandlerComponent: [QueryBalanceApi, TransferApi], + } +} +``` + +If a provider's transitive dependency were unmet, such as a missing field or an unwired type, +this block would fail to compile and name the exact gap, at the wiring site rather than at some +distant call. + +## 8. Serving over HTTP + +Handing the handlers to Axum needs one bound the component cannot express: that each +handler's future is `Send`. Axum runs on a multi-threaded, work-stealing runtime that may +move a suspended task between threads, so the futures it drives must be `Send`. But the +`async fn` in `CanHandleApi` desugars to a bare `impl Future` with no such bound, and stable +Rust has no way to require it generically through the trait. + +The fix, in [src/contexts/app.rs](src/contexts/app.rs), is a plain trait whose method spells +out `+ Send` on its return type, implemented for the concrete context: + +```rust +pub trait CanHandleApiSend: + CanHandleApi + Send + Sync +{ + fn handle_api_send(&self, _api: PhantomData, request: Self::Request) + -> impl Future> + Send; +} + +impl CanHandleApiSend for MockApp { + async fn handle_api_send(&self, api: PhantomData, request: Self::Request) + -> Result { + self.handle_api(api, request).await + } +} +// ... and the same one-line forwarding impl for TransferApi +``` + +Each impl merely forwards to `handle_api`, but at a *concrete* context and API the awaited +future is a concrete type whose `Send`-ness the compiler can verify on its own, which is why +the impls cannot be folded into one generic blanket impl. The repetition is the price of a +missing language feature (Return Type Notation), not a CGP requirement. + +The Axum routing layer in [src/providers/axum/routes.rs](src/providers/axum/routes.rs) then +bounds `App: CanHandleApiSend` and mounts each endpoint: `add_route` reads the request +out of the HTTP layer, calls `handle_api_send`, and maps a raised `AppError` to its status +code, so a single `add_main_api_routes` assembles the whole service. Finally +[bin/server.rs](bin/server.rs) constructs a `MockApp`, builds the router, and serves it, +completing the path from a request on the wire, through the decode-authenticate-handle-encode +pipeline the namespace wired, to a JSON response or a status-coded error. + +## The payoff + +Read the wiring in [src/contexts/app.rs](src/contexts/app.rs) as the whole specification of +this application, and the shape of CGP comes into focus. Every endpoint, wrapper, backend, +and type is a swappable part, and the context's wiring is the single place that chooses among +them. Adding an endpoint means adding a handler provider and one line to `DefaultApiHandlers`. +Moving to a database means writing one backend provider and changing one wiring entry. In +both cases the interfaces, the endpoints, and the wrappers are untouched, which is the reason +CGP exists, and this small service is a template for any request/response backend whose +endpoints share cross-cutting concerns and whose implementation should stay swappable behind +abstract types. diff --git a/transfer/bin/server.rs b/transfer/bin/server.rs index 17d13bf..bfef6d5 100644 --- a/transfer/bin/server.rs +++ b/transfer/bin/server.rs @@ -5,6 +5,8 @@ use cgp_example_transfer::contexts::MockApp; use cgp_example_transfer::providers::CanAddMainApiRoutes; use tokio::net::TcpListener; +// Entry point: build the wired `MockApp`, mount its endpoints on an Axum router (the routes +// come from the `add_main_api_routes` capability wired in the library), and serve. #[tokio::main] async fn main() { let app = Arc::new(MockApp::new_with_dummy_data()); diff --git a/transfer/src/contexts/app.rs b/transfer/src/contexts/app.rs index 7129e59..98173ac 100644 --- a/transfer/src/contexts/app.rs +++ b/transfer/src/contexts/app.rs @@ -2,18 +2,17 @@ use std::collections::BTreeMap; use std::sync::Arc; use axum::Router; -use cgp::core::component::UseDelegate; -use cgp::core::error::ErrorTypeProviderComponent; use cgp::prelude::*; use futures::lock::Mutex; use crate::interfaces::*; +use crate::namespaces::{DefaultApiHandlers, MockNamespace}; use crate::providers::*; -use crate::types::{ - AppError, AxumQueryBalanceRequest, AxumTransferRequest, DemoCurrency, QueryBalanceRequest, - TransferRequest, -}; +use crate::types::DemoCurrency; +/// The concrete application context — the type all the abstract capabilities are wired onto. +/// Its fields hold the in-memory data the mock backend reads; `#[derive(HasField)]` exposes +/// them by name so `UseMockedApp`'s `#[implicit]` arguments can pull them in. #[derive(HasField, Default)] pub struct MockApp { pub user_balances: Arc>>, @@ -41,63 +40,27 @@ impl MockApp { } } +// The whole application specified as a wiring table. Three decisions: join `MockNamespace` +// to inherit every default backend and abstract type; pull each `DefaultApiHandlers` entry +// onto the `ApiHandler` dispatch path (one entry per endpoint) with the `for` loop; and +// override the money-transfer path to wrap the mock backend in `NoTransferToSelf`. The +// override is legal only because `MockNamespace` does not itself claim that path. delegate_components! { MockApp { - ErrorTypeProviderComponent: UseType, - HttpErrorRaiserComponent: UseDelegate, - [ - UserIdTypeProviderComponent, - PasswordTypeProviderComponent, - HashedPasswordTypeProviderComponent, - ]: - UseType, - QuantityTypeProviderComponent: - UseType, - CurrencyTypeProviderComponent: - UseType, - [ - PasswordCheckerComponent, - UserHashedPasswordQuerierComponent, - UserBalanceQuerierComponent, - ]: - UseMockedApp, - MoneyTransferrerComponent: - NoTransferToSelf, - ApiHandlerComponent: - UseDelegate, - } -} + namespace MockNamespace; -pub struct HandleAppErrors; - -delegate_components! { - HandleAppErrors { - (Code, String): DisplayHttpError, - (Code, anyhow::Error): HandleHttpErrorWithAnyhow, - } -} - -pub struct ApiHandlers; + for in DefaultApiHandlers { + @app.api.ApiHandlerComponent.Key: Value, + } -delegate_components! { - ApiHandlers { - QueryBalanceApi: - HandleFromRequest< - AxumQueryBalanceRequest, - ResponseToJson< - UseBasicAuth< - HandleQueryBalance - >>>, - TransferApi: - HandleFromRequest< - AxumTransferRequest, - UseBasicAuth< - HandleTransfer - > - >, + @app.finance.MoneyTransferrerComponent: + NoTransferToSelf, } } +// Compile-time proof that the wiring above is complete: because CGP resolves wiring lazily, +// this block forces the compiler to check each listed component (and each API marker for the +// generic `ApiHandler`) is fully satisfied, reporting any missing dependency at this site. check_components! { MockApp { @@ -111,6 +74,10 @@ check_components! { } } +// Recover the `Send` bound Axum needs. `CanHandleApiSend` cannot be implemented generically +// on stable Rust, so it is implemented per concrete (context, API) pair: at a fixed type the +// awaited future is concrete and the compiler can confirm it is `Send`. Each impl just +// forwards to `handle_api`. impl CanHandleApiSend for MockApp { async fn handle_api_send( &self, @@ -131,6 +98,8 @@ impl CanHandleApiSend for MockApp { } } +/// Convenience alias binding the generic routing capability to `MockApp`, so `bin/server.rs` +/// can mount the service on a `Router>`. pub trait CanAddApiRoutes: CanAddMainApiRoutes {} impl CanAddApiRoutes for Router> {} diff --git a/transfer/src/interfaces/api.rs b/transfer/src/interfaces/api.rs index 5485fd1..b2989a0 100644 --- a/transfer/src/interfaces/api.rs +++ b/transfer/src/interfaces/api.rs @@ -1,12 +1,16 @@ -use cgp::core::component::UseDelegate; use cgp::prelude::*; -#[cgp_component{ - provider: ApiHandler, - derive_delegate: UseDelegate, -}] +/// The core capability every endpoint is a case of. `#[cgp_component]` splits it into the +/// consumer trait `CanHandleApi` (what callers use) and a provider trait `ApiHandler` +/// (what handlers implement). It is generic over an `Api` marker, so a context can wire a +/// different handler per endpoint; `Request`/`Response` let each endpoint fix its own shapes. +/// `#[async_trait]` makes the async method lint-clean, and `#[use_type(HasErrorType.Error)]` +/// imports the context's abstract error type so the signature can name it as bare `Error`. +#[cgp_component(ApiHandler)] +#[prefix(@app.api in DefaultNamespace)] #[async_trait] -pub trait CanHandleApi: HasErrorType { +#[use_type(HasErrorType.Error)] +pub trait CanHandleApi { type Request; type Response; @@ -15,9 +19,13 @@ pub trait CanHandleApi: HasErrorType { &self, _api: PhantomData, request: Self::Request, - ) -> Result; + ) -> Result; } +/// A `Send`-carrying view of `CanHandleApi`, needed because the async trait method drops the +/// `Send` bound its future would need to be spawned on a multi-threaded runtime. This is a +/// plain (non-CGP) trait whose method spells out `+ Send`; it is implemented per concrete +/// context in `contexts/app.rs`, where the compiler can prove the bound. See the README. pub trait CanHandleApiSend: CanHandleApi + Send + Sync { @@ -28,6 +36,8 @@ pub trait CanHandleApiSend: ) -> impl Future> + Send; } +/// Endpoint marker for `POST /transfer`, used only as a type-level tag on `CanHandleApi`. pub struct TransferApi; +/// Endpoint marker for `GET /balance`, used only as a type-level tag on `CanHandleApi`. pub struct QueryBalanceApi; diff --git a/transfer/src/interfaces/auth.rs b/transfer/src/interfaces/auth.rs index f3a7b12..355e7dc 100644 --- a/transfer/src/interfaces/auth.rs +++ b/transfer/src/interfaces/auth.rs @@ -2,32 +2,43 @@ use cgp::prelude::*; use crate::interfaces::{HasHashedPasswordType, HasPasswordType, HasUserIdType}; +/// Read the already-authenticated user out of a request. `#[cgp_auto_getter]` turns this +/// getter trait into a blanket impl over any type with a matching `logged_in_user` field, +/// so it is implemented on the request struct, not the app context — which is why it is a +/// getter trait rather than an implicit argument (those read only from `self`). #[cgp_auto_getter] -pub trait HasLoggedInUser -where - App: HasUserIdType, -{ - fn logged_in_user(&self) -> &Option; +#[use_type(HasUserIdType.UserId in App)] +pub trait HasLoggedInUser { + fn logged_in_user(&self) -> &Option; } +/// The mutable counterpart, used by the auth wrapper to record the user it just logged in. #[cgp_auto_getter] -pub trait HasLoggedInUserMut -where - App: HasUserIdType, -{ - fn logged_in_user(&mut self) -> &mut Option; +#[use_type(HasUserIdType.UserId in App)] +pub trait HasLoggedInUserMut { + fn logged_in_user(&mut self) -> &mut Option; } +/// Capability to compare a cleartext password against a stored one. A component so a +/// deployment can swap the plain-equality mock for real password hashing without touching +/// callers. `#[use_type]` imports the abstract password types so they read as bare names. #[cgp_component(PasswordChecker)] -pub trait CanCheckPassword: HasPasswordType + HasHashedPasswordType { - fn check_password(password: &Self::Password, hashed_password: &Self::HashedPassword) -> bool; +#[prefix(@app.auth in DefaultNamespace)] +#[use_type(HasPasswordType.Password, HasHashedPasswordType.HashedPassword)] +pub trait CanCheckPassword { + fn check_password(password: &Password, hashed_password: &HashedPassword) -> bool; } +/// Capability to look up a user's stored password. Abstract over the backend: the mock reads +/// an in-memory map, a real deployment would query a database, and the auth wrapper depends +/// only on this trait. #[cgp_component(UserHashedPasswordQuerier)] +#[prefix(@app.auth in DefaultNamespace)] #[async_trait] -pub trait CanQueryUserHashedPassword: HasUserIdType + HasHashedPasswordType + HasErrorType { +#[use_type(HasUserIdType.UserId, HasHashedPasswordType.HashedPassword, HasErrorType.Error)] +pub trait CanQueryUserHashedPassword { async fn query_user_hashed_password( &self, - user_id: &Self::UserId, - ) -> Result, Self::Error>; + user_id: &UserId, + ) -> Result, Error>; } diff --git a/transfer/src/interfaces/error.rs b/transfer/src/interfaces/error.rs index 51844f0..bffb491 100644 --- a/transfer/src/interfaces/error.rs +++ b/transfer/src/interfaces/error.rs @@ -1,11 +1,18 @@ -use cgp::core::component::UseDelegate; use cgp::prelude::*; +/// Capability to build the context's abstract error from a status-code marker and a detail +/// value, so the mapping from a domain failure to an HTTP status lives in one provider. It +/// is generic over the `Code` marker and the `Detail` type; `#[use_type(HasErrorType.Error)]` +/// imports the context's shared error type as the return type. #[cgp_component(HttpErrorRaiser)] -pub trait CanRaiseHttpError: HasErrorType { - fn raise_http_error(_code: Code, detail: Detail) -> Self::Error; +#[prefix(@app.error in DefaultNamespace)] +#[use_type(HasErrorType.Error)] +pub trait CanRaiseHttpError { + fn raise_http_error(_code: Code, detail: Detail) -> Error; } +/// Status-code markers passed as the `Code` argument of `raise_http_error`. Each is a +/// zero-sized type that a provider maps to a concrete HTTP status (see `providers/error.rs`). pub struct ErrUnauthorized; pub struct ErrBadRequest; @@ -13,15 +20,3 @@ pub struct ErrBadRequest; pub struct ErrNotFound; pub struct ErrInternal; - -#[cgp_impl(UseDelegate)] -impl HttpErrorRaiser -where - Self: HasErrorType, - Components: DelegateComponent<(Code, Detail)>, - Components::Delegate: HttpErrorRaiser, -{ - fn raise_http_error(code: Code, detail: Detail) -> Self::Error { - Components::Delegate::raise_http_error(code, detail) - } -} diff --git a/transfer/src/interfaces/finance.rs b/transfer/src/interfaces/finance.rs index fe492a1..ce3e8f3 100644 --- a/transfer/src/interfaces/finance.rs +++ b/transfer/src/interfaces/finance.rs @@ -2,28 +2,35 @@ use cgp::prelude::*; use crate::interfaces::{HasCurrencyType, HasQuantityType, HasUserIdType}; +// The two business capabilities the endpoints call. Each is a component abstract over the +// backend, so the balance-query handler and transfer handler depend only on these traits and +// never on the concrete store behind them. `#[use_type]` imports the domain's abstract types +// so the signatures read in plain names. + +/// Capability to read a user's balance in a currency. #[cgp_component(UserBalanceQuerier)] +#[prefix(@app.finance in DefaultNamespace)] #[async_trait] -pub trait CanQueryUserBalance: - HasUserIdType + HasCurrencyType + HasQuantityType + HasErrorType -{ +#[use_type(HasUserIdType.UserId, HasCurrencyType.Currency, HasQuantityType.Quantity, HasErrorType.Error)] +pub trait CanQueryUserBalance { async fn query_user_balance( &self, - user: &Self::UserId, - currency: &Self::Currency, - ) -> Result; + user: &UserId, + currency: &Currency, + ) -> Result; } +/// Capability to move a quantity of a currency from one user to another. #[cgp_component(MoneyTransferrer)] +#[prefix(@app.finance in DefaultNamespace)] #[async_trait] -pub trait CanTransferMoney: - HasUserIdType + HasCurrencyType + HasQuantityType + HasErrorType -{ +#[use_type(HasUserIdType.UserId, HasCurrencyType.Currency, HasQuantityType.Quantity, HasErrorType.Error)] +pub trait CanTransferMoney { async fn transfer_money( &self, - sender: &Self::UserId, - recipient: &Self::UserId, - currency: &Self::Currency, - quantity: &Self::Quantity, - ) -> Result<(), Self::Error>; + sender: &UserId, + recipient: &UserId, + currency: &Currency, + quantity: &Quantity, + ) -> Result<(), Error>; } diff --git a/transfer/src/interfaces/types.rs b/transfer/src/interfaces/types.rs index 949f818..00f19ee 100644 --- a/transfer/src/interfaces/types.rs +++ b/transfer/src/interfaces/types.rs @@ -2,27 +2,43 @@ use core::fmt::Display; use cgp::prelude::*; +// The domain's abstract types. Each `#[cgp_type]` declares a component whose only +// content is one associated type, so handlers can name `UserId`/`Quantity`/`Currency` +// generically and a context picks the concrete type at wiring time (via `UseType`). +// The `#[prefix(... in DefaultNamespace)]` files each component under a dotted path so +// the wiring can address it by that path; see the namespaces module. + +/// A context's abstract user-identifier type, kept `Display` so it can appear in errors. #[cgp_type] +#[prefix(@app.auth.types in DefaultNamespace)] pub trait HasUserIdType { type UserId: Display; } +/// A context's abstract money-amount type. #[cgp_type] +#[prefix(@app.finance.types in DefaultNamespace)] pub trait HasQuantityType { type Quantity: Display; } +/// A context's abstract currency type. #[cgp_type] +#[prefix(@app.finance.types in DefaultNamespace)] pub trait HasCurrencyType { type Currency: Display; } +/// A context's abstract cleartext-password type (supplied on a login request). #[cgp_type] +#[prefix(@app.auth.types in DefaultNamespace)] pub trait HasPasswordType { type Password; } +/// A context's abstract stored-password type, compared against `Password` to authenticate. #[cgp_type] +#[prefix(@app.auth.types in DefaultNamespace)] pub trait HasHashedPasswordType { type HashedPassword; } diff --git a/transfer/src/lib.rs b/transfer/src/lib.rs index 476eee5..d791f14 100644 --- a/transfer/src/lib.rs +++ b/transfer/src/lib.rs @@ -2,5 +2,6 @@ pub mod contexts; pub mod interfaces; +pub mod namespaces; pub mod providers; pub mod types; diff --git a/transfer/src/namespaces/api_handlers.rs b/transfer/src/namespaces/api_handlers.rs new file mode 100644 index 0000000..8fe10ae --- /dev/null +++ b/transfer/src/namespaces/api_handlers.rs @@ -0,0 +1,29 @@ +use cgp::prelude::*; + +use crate::interfaces::{QueryBalanceApi, TransferApi}; +use crate::providers::{ + HandleFromRequest, HandleQueryBalance, HandleTransfer, ResponseToJson, UseBasicAuth, +}; +use crate::types::{ + AxumQueryBalanceRequest, AxumTransferRequest, QueryBalanceRequest, TransferRequest, +}; + +// The application's API surface: which handler pipeline serves each API. This is +// a plain lookup table keyed by the `Api` marker rather than a namespace a +// context joins, so a context pulls it in with a `for in +// DefaultApiHandlers` loop and maps each entry onto its own `ApiHandlerComponent` +// dispatch path. +cgp_namespace! { + new DefaultApiHandlers { + QueryBalanceApi: + HandleFromRequest< + AxumQueryBalanceRequest, + ResponseToJson>>, + >, + TransferApi: + HandleFromRequest< + AxumTransferRequest, + UseBasicAuth>, + >, + } +} diff --git a/transfer/src/namespaces/mock.rs b/transfer/src/namespaces/mock.rs new file mode 100644 index 0000000..f3082db --- /dev/null +++ b/transfer/src/namespaces/mock.rs @@ -0,0 +1,33 @@ +use cgp::core::error::ErrorTypeProviderComponent; +use cgp::prelude::*; + +use crate::interfaces::*; +use crate::providers::DisplayHttpError; +use crate::types::{AppError, DemoCurrency}; + +// The mock application's namespace. It inherits every default `DefaultNamespace` +// entry — which is how the mock providers register themselves through the +// `#[default_impl(... in MockNamespace)]` attributes in `providers/mocked.rs` — +// and additionally wires the pieces that have no `#[cgp_impl]` block of their own +// to attach a `#[default_impl]` to: the concrete error type, the app's HTTP +// error-raising dispatch, and the abstract type choices. +cgp_namespace! { + new MockNamespace: DefaultNamespace { + @cgp.core.error.ErrorTypeProviderComponent: + UseType, + + @app.error.HttpErrorRaiserComponent. Code.String: + DisplayHttpError, + + @app.auth.types.{ + UserIdTypeProviderComponent, + PasswordTypeProviderComponent, + HashedPasswordTypeProviderComponent, + }: + UseType, + @app.finance.types.QuantityTypeProviderComponent: + UseType, + @app.finance.types.CurrencyTypeProviderComponent: + UseType, + } +} diff --git a/transfer/src/namespaces/mod.rs b/transfer/src/namespaces/mod.rs new file mode 100644 index 0000000..7821449 --- /dev/null +++ b/transfer/src/namespaces/mod.rs @@ -0,0 +1,5 @@ +mod api_handlers; +mod mock; + +pub use api_handlers::*; +pub use mock::*; diff --git a/transfer/src/providers/api_handlers/basic_auth.rs b/transfer/src/providers/api_handlers/basic_auth.rs index bba97af..a0b52a6 100644 --- a/transfer/src/providers/api_handlers/basic_auth.rs +++ b/transfer/src/providers/api_handlers/basic_auth.rs @@ -2,20 +2,27 @@ use cgp::prelude::*; use crate::interfaces::*; +/// Getter for the optional Basic-auth credentials on a request. Implemented on the request +/// struct (not the app), so it is a getter trait: the auth wrapper requires it as +/// `InHandler::Request: HasBasicAuthHeader`. #[cgp_auto_getter] -pub trait HasBasicAuthHeader -where - App: HasUserIdType + HasPasswordType, -{ - fn basic_auth_header(&self) -> &Option<(App::UserId, App::Password)>; +#[use_type(HasUserIdType.UserId in App, HasPasswordType.Password in App)] +pub trait HasBasicAuthHeader { + fn basic_auth_header(&self) -> &Option<(UserId, Password)>; } +/// A higher-order `ApiHandler` provider that authenticates, then delegates. If no user is +/// logged in yet, it resolves the Basic-auth header into a user, verifies the password via the +/// wired capabilities (`#[uses(...)]`), records the user on the request, and calls the inner +/// handler. `#[use_provider(InHandler: ApiHandler)]` supplies the inner handler's hidden +/// context argument, so the body calls it as `InHandler::handle_api(self, ...)`. #[cgp_impl(new UseBasicAuth)] +#[uses(CanQueryUserHashedPassword, CanCheckPassword)] +#[use_type(HasUserIdType.UserId, HasErrorType.Error)] +#[use_provider(InHandler: ApiHandler)] impl ApiHandler where - Self: CanQueryUserHashedPassword + CanCheckPassword, InHandler::Request: HasLoggedInUserMut + HasBasicAuthHeader, - InHandler: ApiHandler, Self::UserId: Clone, { type Request = InHandler::Request; @@ -26,7 +33,7 @@ where &self, api: PhantomData, mut request: Self::Request, - ) -> Result { + ) -> Result { if request.logged_in_user().is_none() && let Some((user_id, password)) = request.basic_auth_header() { diff --git a/transfer/src/providers/api_handlers/from_request.rs b/transfer/src/providers/api_handlers/from_request.rs index 9a2ce88..ccf9cdd 100644 --- a/transfer/src/providers/api_handlers/from_request.rs +++ b/transfer/src/providers/api_handlers/from_request.rs @@ -2,11 +2,15 @@ use cgp::prelude::*; use crate::interfaces::{ApiHandler, ApiHandlerComponent}; +/// A higher-order `ApiHandler` provider that adapts the request type: it accepts an outer +/// `Request` (e.g. the raw type the HTTP layer produces), converts it into the inner handler's +/// request via `Into`, and delegates. This lets an endpoint be written against a clean domain +/// request while sitting behind the raw extractor type. #[cgp_impl(new HandleFromRequest)] +#[use_type(HasErrorType.Error)] +#[use_provider(InHandler: ApiHandler)] impl ApiHandler where - Self: HasErrorType, - InHandler: ApiHandler, Request: Into, { type Request = Request; @@ -17,16 +21,19 @@ where &self, api: PhantomData, request: Self::Request, - ) -> Result { + ) -> Result { InHandler::handle_api(self, api, request.into()).await } } +/// The mirror wrapper that adapts the response type: it runs the inner handler and converts +/// its response into the outer `Response` via `Into`. (Defined for completeness alongside +/// `HandleFromRequest`.) #[cgp_impl(new HandleFromResponse)] +#[use_type(HasErrorType.Error)] +#[use_provider(InHandler: ApiHandler)] impl ApiHandler where - Self: HasErrorType, - InHandler: ApiHandler, InHandler::Response: Into, { type Request = InHandler::Request; @@ -37,7 +44,7 @@ where &self, api: PhantomData, request: Self::Request, - ) -> Result { + ) -> Result { let response = InHandler::handle_api(self, api, request).await?; Ok(response.into()) diff --git a/transfer/src/providers/api_handlers/query_balance.rs b/transfer/src/providers/api_handlers/query_balance.rs index 073d445..3569786 100644 --- a/transfer/src/providers/api_handlers/query_balance.rs +++ b/transfer/src/providers/api_handlers/query_balance.rs @@ -3,14 +3,15 @@ use serde::Serialize; use crate::interfaces::*; +/// Getter for the fields a balance query needs off its request struct. #[cgp_auto_getter] -pub trait HasQueryBalanceFields -where - App: HasCurrencyType, -{ - fn currency(&self) -> &App::Currency; +#[use_type(HasCurrencyType.Currency in App)] +pub trait HasQueryBalanceFields { + fn currency(&self) -> &Currency; } +/// The balance-query response, generic over the context's abstract `Quantity` so it stays +/// backend-independent; `Serialize` lets the JSON wrapper encode it. #[derive(Serialize)] pub struct QueryBalanceResponse where @@ -19,10 +20,15 @@ where pub balance: App::Quantity, } +/// The balance endpoint: an `ApiHandler` provider that requires the caller to be logged in, +/// then queries the balance. It depends only on the `CanQueryUserBalance` capability and +/// error-raising (declared with `#[uses(...)]`), not on any concrete store, and works for any +/// request exposing the fields named in its `where` clause. #[cgp_impl(new HandleQueryBalance)] +#[uses(CanQueryUserBalance, CanRaiseHttpError)] +#[use_type(HasErrorType.Error)] impl ApiHandler where - Self: CanQueryUserBalance + CanRaiseHttpError, Request: HasLoggedInUser + HasQueryBalanceFields, { type Request = Request; @@ -33,7 +39,7 @@ where &self, _api: PhantomData, request: Request, - ) -> Result, Self::Error> { + ) -> Result, Error> { let user = request.logged_in_user().as_ref().ok_or_else(|| { Self::raise_http_error(ErrUnauthorized, "you must first login".into()) })?; diff --git a/transfer/src/providers/api_handlers/transfer.rs b/transfer/src/providers/api_handlers/transfer.rs index a4c8ba1..0d148a7 100644 --- a/transfer/src/providers/api_handlers/transfer.rs +++ b/transfer/src/providers/api_handlers/transfer.rs @@ -2,33 +2,36 @@ use cgp::prelude::*; use crate::interfaces::*; +/// Getter for the fields a transfer needs off its request struct. #[cgp_auto_getter] -pub trait HasTransferMoneyFields -where - App: HasUserIdType + HasCurrencyType + HasQuantityType, -{ - fn currency(&self) -> &App::Currency; +#[use_type( + HasUserIdType.UserId in App, + HasCurrencyType.Currency in App, + HasQuantityType.Quantity in App, +)] +pub trait HasTransferMoneyFields { + fn currency(&self) -> &Currency; - fn recipient(&self) -> &App::UserId; + fn recipient(&self) -> &UserId; - fn quantity(&self) -> &App::Quantity; + fn quantity(&self) -> &Quantity; } +/// The transfer endpoint: an `ApiHandler` provider that requires a logged-in sender, then +/// invokes the `CanTransferMoney` capability. Like the balance handler, it names its +/// dependencies with `#[uses(...)]` and stays ignorant of which backend fulfills them. #[cgp_impl(new HandleTransfer)] +#[uses(CanTransferMoney, CanRaiseHttpError)] +#[use_type(HasErrorType.Error)] impl ApiHandler where - Self: CanTransferMoney + CanRaiseHttpError, Request: HasLoggedInUser + HasTransferMoneyFields, { type Request = Request; type Response = (); - async fn handle_api( - &self, - _api: PhantomData, - request: Request, - ) -> Result<(), Self::Error> { + async fn handle_api(&self, _api: PhantomData, request: Request) -> Result<(), Error> { let sender = request.logged_in_user().as_ref().ok_or_else(|| { Self::raise_http_error( ErrUnauthorized, diff --git a/transfer/src/providers/axum/json.rs b/transfer/src/providers/axum/json.rs index abd3f9d..d9ad361 100644 --- a/transfer/src/providers/axum/json.rs +++ b/transfer/src/providers/axum/json.rs @@ -1,18 +1,15 @@ -use core::marker::PhantomData; - use axum::Json; use cgp::prelude::*; use crate::interfaces::{ApiHandler, ApiHandlerComponent}; -pub struct ResponseToJson(pub PhantomData); - -#[cgp_impl(ResponseToJson)] -impl ApiHandler -where - Self: HasErrorType, - InHandler: ApiHandler, -{ +/// A higher-order `ApiHandler` provider that adapts the response into an Axum `Json` envelope: +/// it runs the inner handler unchanged and wraps whatever it returns in `Json<_>`. Because it +/// is itself an `ApiHandler`, it nests into a handler pipeline like the other wrappers. +#[cgp_impl(new ResponseToJson)] +#[use_type(HasErrorType.Error)] +#[use_provider(InHandler: ApiHandler)] +impl ApiHandler { type Request = InHandler::Request; type Response = Json; @@ -21,7 +18,7 @@ where &self, api: PhantomData, request: Self::Request, - ) -> Result { + ) -> Result { let response = InHandler::handle_api(self, api, request).await?; Ok(Json(response)) } diff --git a/transfer/src/providers/axum/routes.rs b/transfer/src/providers/axum/routes.rs index 8e7f1eb..35fff85 100644 --- a/transfer/src/providers/axum/routes.rs +++ b/transfer/src/providers/axum/routes.rs @@ -11,14 +11,18 @@ use cgp::prelude::HasErrorType; use crate::interfaces::{CanHandleApiSend, QueryBalanceApi, TransferApi}; use crate::types::AppError; +/// HTTP-method markers used as type-level tags when mounting a route. pub struct GetMethod; pub struct PostMethod; +/// Adds one Axum route to a router for a given API and HTTP method. Implemented once per +/// method below; the impls read the request from the HTTP layer and call `handle_api_send`. pub trait CanAddRoute { fn add_route(self, _tag: PhantomData<(Api, Method)>, path: &str) -> Self; } +/// Turns a raised `AppError` into the `(status, body)` pair Axum returns to the client. pub fn handle_api_error(err: AppError) -> (StatusCode, String) { let status_code = err.status_code; @@ -67,6 +71,8 @@ where } } +/// Mounts the whole service: adds every endpoint route in one call. The `where` clause lists +/// the routes it composes, so the router must be able to add each API/method pair. pub trait CanAddMainApiRoutes { fn add_main_api_routes(self) -> Self; } diff --git a/transfer/src/providers/error.rs b/transfer/src/providers/error.rs index 8a9c153..633780b 100644 --- a/transfer/src/providers/error.rs +++ b/transfer/src/providers/error.rs @@ -10,6 +10,8 @@ use crate::interfaces::{ }; use crate::types::AppError; +/// Maps a status-code marker type to its concrete `StatusCode`, so a provider can turn a +/// marker such as `ErrNotFound` into `404` at the type level with no runtime match. pub trait IsStatusCode { fn status_code() -> StatusCode; } @@ -38,12 +40,14 @@ impl IsStatusCode for ErrInternal { } } -pub struct DisplayHttpError; - -#[cgp_impl(DisplayHttpError)] +/// A provider for `CanRaiseHttpError` covering any `Display` detail: it stamps the status +/// code from the `Code` marker and formats the detail into an `AppError`. The +/// `#[use_type(HasErrorType.{Error = AppError})]` equality form pins the abstract error to +/// the concrete `AppError`, so the body can build one directly. `new` also declares the struct. +#[cgp_impl(new DisplayHttpError)] +#[use_type(HasErrorType.{Error = AppError})] impl HttpErrorRaiser where - Self: HasErrorType, Code: IsStatusCode, Detail: Display, { @@ -55,12 +59,13 @@ where } } -pub struct HandleHttpErrorWithAnyhow; - -#[cgp_impl(HandleHttpErrorWithAnyhow)] +/// A sibling provider for details that are already convertible into `anyhow::Error`: it +/// forwards the detail unchanged rather than formatting it, preserving the error chain. The +/// wiring chooses between this and `DisplayHttpError` per detail type. +#[cgp_impl(new HandleHttpErrorWithAnyhow)] +#[use_type(HasErrorType.{Error = AppError})] impl HttpErrorRaiser where - Self: HasErrorType, Code: IsStatusCode, anyhow::Error: From, { diff --git a/transfer/src/providers/finance.rs b/transfer/src/providers/finance.rs index 27bd27c..321fa22 100644 --- a/transfer/src/providers/finance.rs +++ b/transfer/src/providers/finance.rs @@ -2,23 +2,30 @@ use cgp::prelude::*; use crate::interfaces::*; +/// A higher-order provider for `MoneyTransferrer`: it wraps an inner transfer provider, +/// rejecting a self-transfer up front and otherwise delegating. `#[use_provider(InHandler: +/// MoneyTransferrer)]` declares the inner-provider dependency and fills in the hidden context +/// argument, so the body calls it as the associated function `InHandler::transfer_money(self, ...)`. #[cgp_impl(new NoTransferToSelf)] +#[use_type( + HasUserIdType.UserId, + HasCurrencyType.Currency, + HasQuantityType.Quantity, + HasErrorType.Error, +)] +#[uses(CanRaiseHttpError)] +#[use_provider(InHandler: MoneyTransferrer)] impl MoneyTransferrer where - Self: HasUserIdType - + HasCurrencyType - + HasQuantityType - + CanRaiseHttpError, - InHandler: MoneyTransferrer, - Self::UserId: Eq, + UserId: Eq, { async fn transfer_money( &self, - sender: &Self::UserId, - recipient: &Self::UserId, - currency: &Self::Currency, - quantity: &Self::Quantity, - ) -> Result<(), Self::Error> { + sender: &UserId, + recipient: &UserId, + currency: &Currency, + quantity: &Quantity, + ) -> Result<(), Error> { if sender != recipient { InHandler::transfer_money(self, sender, recipient, currency, quantity).await } else { diff --git a/transfer/src/providers/mocked.rs b/transfer/src/providers/mocked.rs index c751451..39daf50 100644 --- a/transfer/src/providers/mocked.rs +++ b/transfer/src/providers/mocked.rs @@ -6,65 +6,73 @@ use futures::lock::Mutex; use num_traits::{CheckedAdd, CheckedSub}; use crate::interfaces::*; +use crate::namespaces::MockNamespace; +/// The in-memory backend provider. One zero-sized marker implements every business and auth +/// capability by reading maps stored on the context, so a deployment swaps the whole backend +/// by wiring these components to a different provider. Each impl below uses `#[default_impl]` +/// to register itself as the `MockNamespace` default for the component it satisfies. pub struct UseMockedApp; -#[cgp_auto_getter] -pub trait HasMockedUserBalances: HasUserIdType + HasCurrencyType + HasQuantityType { - fn user_balances( - &self, - ) -> &Arc>>; -} - -#[cgp_auto_getter] -pub trait HasMockedPasswords: HasUserIdType + HasHashedPasswordType { - fn user_passwords(&self) -> &BTreeMap; -} - +/// Look up a stored password in the in-memory `user_passwords` map. The `#[implicit]` argument +/// reads that same-named field off the context; `#[default_impl(... in MockNamespace)]` +/// registers this provider as the namespace's default for the password-querier component. #[cgp_impl(UseMockedApp)] +#[default_impl(@app.auth.UserHashedPasswordQuerierComponent in MockNamespace)] +#[use_type(HasUserIdType.UserId, HasHashedPasswordType.HashedPassword, HasErrorType.Error)] impl UserHashedPasswordQuerier where - Self: HasMockedPasswords + HasErrorType, - Self::UserId: Ord, - Self::HashedPassword: Clone, + UserId: Ord, + HashedPassword: Clone, { async fn query_user_hashed_password( &self, - user_id: &Self::UserId, - ) -> Result, Self::Error> { - let hashed_password = self.user_passwords().get(user_id).cloned(); + user_id: &UserId, + #[implicit] user_passwords: &BTreeMap, + ) -> Result, Error> { + let hashed_password = user_passwords.get(user_id).cloned(); Ok(hashed_password) } } +/// Check a password by plain equality — the mock stores passwords in the clear. The +/// `#[use_type]` equality form unifies `HashedPassword` with `Password`, so both are the same +/// type and `==` type-checks. A real deployment would swap this for a hashing check. #[cgp_impl(UseMockedApp)] +#[default_impl(@app.auth.PasswordCheckerComponent in MockNamespace)] +#[use_type(HasPasswordType.Password, HasHashedPasswordType.{HashedPassword = Password})] impl PasswordChecker where - Self: HasPasswordType + HasHashedPasswordType, - Self::Password: Eq, + Password: Eq, { - fn check_password(password: &Self::Password, hashed_password: &Self::HashedPassword) -> bool { + fn check_password(password: &Password, hashed_password: &HashedPassword) -> bool { password == hashed_password } } +/// Read a user's balance from the in-memory `user_balances` map, or raise a 404 if absent. +/// The map is pulled in by reference as an `#[implicit]` argument (no clone), and +/// `#[uses(...)]` declares the error-raising dependency the not-found branch needs. #[cgp_impl(UseMockedApp)] +#[default_impl(@app.finance.UserBalanceQuerierComponent in MockNamespace)] +#[uses(CanRaiseHttpError)] +#[use_type(HasUserIdType.UserId, HasCurrencyType.Currency, HasQuantityType.Quantity, HasErrorType.Error)] impl UserBalanceQuerier where - Self: HasMockedUserBalances + CanRaiseHttpError, - Self::UserId: Ord + Clone, - Self::Currency: Ord + Clone, - Self::Quantity: Clone, + UserId: Ord + Clone, + Currency: Ord + Clone, + Quantity: Clone, { async fn query_user_balance( &self, - user: &Self::UserId, - currency: &Self::Currency, - ) -> Result { - let user_balances = self.user_balances().lock().await; + user: &UserId, + currency: &Currency, + #[implicit] user_balances: &Arc>>, + ) -> Result { + let balances = user_balances.lock().await; - let user_balance = user_balances + let user_balance = balances .get(&(user.clone(), currency.clone())) .ok_or_else(|| { Self::raise_http_error( @@ -77,36 +85,45 @@ where } } +/// Move funds between two users in the in-memory map, checking both accounts exist and that +/// the sender has enough balance, raising a 404 or 400 otherwise. A transfer to oneself +/// succeeds and leaves the balance unchanged. +/// +/// Note: `MoneyTransferrer` is deliberately *not* registered into `MockNamespace`. +/// `MockApp` overrides it directly with `NoTransferToSelf` on the +/// `@app.finance.MoneyTransferrerComponent` path, and a context can only wire a +/// path the joined namespace does not itself claim — registering it here too would +/// make the context entry conflict with the namespace's blanket forwarding impl. #[cgp_impl(UseMockedApp)] +#[uses(CanRaiseHttpError, CanRaiseHttpError)] +#[use_type(HasUserIdType.UserId, HasCurrencyType.Currency, HasQuantityType.Quantity, HasErrorType.Error)] impl MoneyTransferrer where - Self: HasMockedUserBalances - + CanRaiseHttpError - + CanRaiseHttpError, - Self::Quantity: CheckedAdd + CheckedSub, - Self::UserId: Ord + Clone, - Self::Currency: Ord + Clone, + Quantity: CheckedAdd + CheckedSub, + UserId: Ord + Clone, + Currency: Ord + Clone, { async fn transfer_money( &self, - sender: &Self::UserId, - recipient: &Self::UserId, - currency: &Self::Currency, - quantity: &Self::Quantity, - ) -> Result<(), Self::Error> { - let mut user_balances = self.user_balances().lock().await; + sender: &UserId, + recipient: &UserId, + currency: &Currency, + quantity: &Quantity, + #[implicit] user_balances: &Arc>>, + ) -> Result<(), Error> { + let mut balances = user_balances.lock().await; let sender_key = (sender.clone(), currency.clone()); let recipient_key = (recipient.clone(), currency.clone()); - let old_sender_balance = user_balances.get(&sender_key).ok_or_else(|| { + let old_sender_balance = balances.get(&sender_key).ok_or_else(|| { Self::raise_http_error( ErrNotFound, format!("sender not found in mocked database: {sender}"), ) })?; - let old_recipient_balance = user_balances.get(&recipient_key).ok_or_else(|| { + let old_recipient_balance = balances.get(&recipient_key).ok_or_else(|| { Self::raise_http_error( ErrNotFound, format!("recipient not found in mocked database: {recipient}"), @@ -116,6 +133,12 @@ where let new_sender_balance = old_sender_balance.checked_sub(quantity) .ok_or_else(|| Self::raise_http_error(ErrBadRequest, format!("sender {sender} has insufficient balance {old_sender_balance} to transfer {quantity}")))?; + // A transfer to oneself moves nothing. Returning here, once the sender is known to + // cover the amount, keeps the credit below from overwriting the debit on the same key. + if sender == recipient { + return Ok(()); + } + let new_recipient_balance = old_recipient_balance.checked_add(quantity).ok_or_else(|| { Self::raise_http_error( @@ -124,8 +147,8 @@ where ) })?; - user_balances.insert(sender_key, new_sender_balance); - user_balances.insert(recipient_key, new_recipient_balance); + balances.insert(sender_key, new_sender_balance); + balances.insert(recipient_key, new_recipient_balance); Ok(()) } diff --git a/transfer/src/types/currency.rs b/transfer/src/types/currency.rs index 512187c..9a1d5b9 100644 --- a/transfer/src/types/currency.rs +++ b/transfer/src/types/currency.rs @@ -2,6 +2,9 @@ use core::fmt::Display; use serde::Deserialize; +/// The concrete currency this deployment uses. `MockApp` wires it as the app's abstract +/// `Currency` type (`CurrencyTypeProviderComponent: UseType`); another +/// deployment could plug in a different type without changing any handler. #[derive(PartialOrd, Ord, PartialEq, Eq, Clone, Deserialize)] pub enum DemoCurrency { EUR, diff --git a/transfer/src/types/error.rs b/transfer/src/types/error.rs index 443e662..3d9a12e 100644 --- a/transfer/src/types/error.rs +++ b/transfer/src/types/error.rs @@ -1,5 +1,7 @@ use axum::http::StatusCode; +/// The concrete error this deployment uses, pairing an HTTP status with a detail. `MockApp` +/// wires it as the app's abstract `Error` type, and the HTTP layer turns it into a response. #[derive(Debug)] pub struct AppError { pub status_code: StatusCode, diff --git a/transfer/src/types/requests/query_balance.rs b/transfer/src/types/requests/query_balance.rs index e6ecabf..bc8b3a5 100644 --- a/transfer/src/types/requests/query_balance.rs +++ b/transfer/src/types/requests/query_balance.rs @@ -7,6 +7,9 @@ use serde::Deserialize; use crate::types::DemoCurrency; +/// The domain request the balance handler works with. `#[derive(HasField)]` exposes each +/// field by name, which is what lets the `HasQueryBalanceFields`/`HasLoggedInUser` getters +/// (and the auth wrapper's `HasBasicAuthHeader`) read it generically. #[derive(HasField)] pub struct QueryBalanceRequest { pub currency: DemoCurrency, @@ -28,11 +31,15 @@ impl From for QueryBalanceRequest { } } +/// The raw type Axum extracts from the wire (query string plus optional auth header). +/// `HandleFromRequest` converts it into `QueryBalanceRequest` via the `From` impl above, so +/// the endpoint handler never sees the HTTP-specific extractor types. pub type AxumQueryBalanceRequest = ( Query, Option>>, ); +/// The query-string fields Axum deserializes for a balance request. #[derive(Deserialize)] pub struct QueryBalanceQuery { pub currency: DemoCurrency, diff --git a/transfer/src/types/requests/transfer.rs b/transfer/src/types/requests/transfer.rs index af5c3fb..b3a61e6 100644 --- a/transfer/src/types/requests/transfer.rs +++ b/transfer/src/types/requests/transfer.rs @@ -7,6 +7,9 @@ use serde::Deserialize; use crate::types::DemoCurrency; +/// The domain request the transfer handler works with. `#[derive(HasField)]` exposes each +/// field by name so the `HasTransferMoneyFields`/`HasLoggedInUser`/`HasBasicAuthHeader` +/// getters can read it generically. #[derive(HasField)] pub struct TransferRequest { pub currency: DemoCurrency, @@ -32,6 +35,7 @@ impl From for TransferRequest { } } +/// The query-string fields Axum deserializes for a transfer request. #[derive(Deserialize)] pub struct TransferQuery { pub currency: DemoCurrency, @@ -39,6 +43,8 @@ pub struct TransferQuery { pub quantity: u64, } +/// The raw type Axum extracts from the wire; `HandleFromRequest` converts it into +/// `TransferRequest` so the endpoint handler stays free of HTTP extractor types. pub type AxumTransferRequest = ( Query, Option>>, diff --git a/web-app/Cargo.toml b/web-app/Cargo.toml new file mode 100644 index 0000000..0b479c3 --- /dev/null +++ b/web-app/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "cgp-example-web-app" +version = "0.1.0" +edition = { workspace = true } +license = { workspace = true } +repository = { workspace = true } +homepage = { workspace = true } +categories = { workspace = true } +description = "One social-media backend wired four ways, up to namespace defaults." +authors = { workspace = true } +rust-version = { workspace = true } +keywords = { workspace = true } + +[dependencies] +cgp = { workspace = true } diff --git a/web-app/src/coarse_grained.rs b/web-app/src/coarse_grained.rs new file mode 100644 index 0000000..8f8373b --- /dev/null +++ b/web-app/src/coarse_grained.rs @@ -0,0 +1,145 @@ +use cgp::prelude::*; + +use crate::types::*; + +/// Manages users. See +/// [the coarse-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/coarse-grained). +#[cgp_component(UserManager)] +pub trait CanManageUser { + fn create_user(&self, username: &str, email: &Email) -> Result; + + fn get_user(&self, user_id: &UserId) -> Result; + + fn update_user_data(&self, user_id: &UserId, user_data: &UserData) -> Result<(), Error>; +} + +/// Manages posts. See +/// [the coarse-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/coarse-grained). +#[cgp_component(PostManager)] +pub trait CanManagePost { + fn create_post(&self, title: &str, content: &str) -> Result; + + fn get_post(&self, post_id: &PostId) -> Result; + + fn update_post(&self, post_id: &PostId, content: &str) -> Result<(), Error>; + + fn delete_post(&self, post_id: &PostId) -> Result<(), Error>; +} + +/// Decides whether a username is censored. See +/// [the coarse-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/coarse-grained). +#[cgp_component(UsernameCensor)] +pub trait CanCensorUsername { + fn username_is_censored(&self, username: &str) -> Probability; +} + +/// Decides whether a message is spam. See +/// [the coarse-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/coarse-grained). +#[cgp_component(SpamMessageDetector)] +pub trait CanDetectSpamMessage { + fn message_is_spam(&self, message: &str) -> Probability; +} + +/// Manages users in Postgres, rejecting a censored username before creating one. See +/// [the coarse-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/coarse-grained). +#[cgp_impl(new PostgresUserManager)] +#[uses(CanCensorUsername)] +impl UserManager { + fn create_user( + &self, + #[implicit] database: &PostgresDb, + username: &str, + email: &Email, + ) -> Result { + if self.username_is_censored(username) > Probability::new(0.8) { + return Err(Error::InvalidUsername); + } + + todo!() + } + + fn get_user(&self, #[implicit] database: &PostgresDb, user_id: &UserId) -> Result { + todo!() + } + + fn update_user_data( + &self, + #[implicit] database: &PostgresDb, + user_id: &UserId, + user_data: &UserData, + ) -> Result<(), Error> { + todo!() + } +} + +/// Manages posts in Postgres, rejecting a spam message before creating one. See +/// [the coarse-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/coarse-grained). +#[cgp_impl(new PostgresPostManager)] +#[uses(CanDetectSpamMessage)] +impl PostManager { + fn create_post( + &self, + #[implicit] database: &PostgresDb, + title: &str, + content: &str, + ) -> Result { + if self.message_is_spam(content) > Probability::new(0.8) { + return Err(Error::InvalidMessage); + } + + todo!() + } + + fn get_post(&self, #[implicit] database: &PostgresDb, post_id: &PostId) -> Result { + todo!() + } + + fn update_post( + &self, + #[implicit] database: &PostgresDb, + post_id: &PostId, + content: &str, + ) -> Result<(), Error> { + todo!() + } + + fn delete_post( + &self, + #[implicit] database: &PostgresDb, + post_id: &PostId, + ) -> Result<(), Error> { + todo!() + } +} + +/// Stands in for a username censor, leaving the score unimplemented. See +/// [the coarse-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/coarse-grained). +#[cgp_impl(new DummyUserCensor)] +impl UsernameCensor { + fn username_is_censored(&self, username: &str) -> Probability { + todo!() + } +} + +/// Stands in for a spam detector, leaving the score unimplemented. See +/// [the coarse-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/coarse-grained). +#[cgp_impl(new DummySpamMessageDetector)] +impl SpamMessageDetector { + fn message_is_spam(&self, message: &str) -> Probability { + todo!() + } +} + +#[derive(HasField)] +pub struct ProductionApp { + pub database: PostgresDb, +} + +delegate_and_check_components! { + ProductionApp { + UserManagerComponent: PostgresUserManager, + PostManagerComponent: PostgresPostManager, + UsernameCensorComponent: DummyUserCensor, + SpamMessageDetectorComponent: DummySpamMessageDetector, + } +} diff --git a/web-app/src/default_impls.rs b/web-app/src/default_impls.rs new file mode 100644 index 0000000..7b9c0f3 --- /dev/null +++ b/web-app/src/default_impls.rs @@ -0,0 +1,283 @@ +use cgp::prelude::*; + +use crate::types::*; + +/// Creates a user. See +/// [the default implementations stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/default-impls). +#[cgp_component(UserCreator)] +#[prefix(@app.core.user in DefaultNamespace)] +pub trait CanCreateUser { + fn create_user(&self, username: &str, email: &Email) -> Result; +} + +/// Reads a user. See +/// [the default implementations stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/default-impls). +#[cgp_component(UserGetter)] +#[prefix(@app.core.user in DefaultNamespace)] +pub trait CanGetUser { + fn get_user(&self, user_id: &UserId) -> Result; +} + +/// Updates a user. See +/// [the default implementations stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/default-impls). +#[cgp_component(UserUpdater)] +#[prefix(@app.core.user in DefaultNamespace)] +pub trait CanUpdateUser { + fn update_user_data(&self, user_id: &UserId, user_data: &UserData) -> Result<(), Error>; +} + +/// Creates a post. See +/// [the default implementations stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/default-impls). +#[cgp_component(PostCreator)] +#[prefix(@app.core.post in DefaultNamespace)] +pub trait CanCreatePost { + fn create_post(&self, title: &str, content: &str) -> Result; +} + +/// Reads a post. See +/// [the default implementations stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/default-impls). +#[cgp_component(PostGetter)] +#[prefix(@app.core.post in DefaultNamespace)] +pub trait CanGetPost { + fn get_post(&self, post_id: &PostId) -> Result; +} + +/// Updates a post. See +/// [the default implementations stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/default-impls). +#[cgp_component(PostUpdater)] +#[prefix(@app.core.post in DefaultNamespace)] +pub trait CanUpdatePost { + fn update_post(&self, post_id: &PostId, content: &str) -> Result<(), Error>; +} + +/// Deletes a post. See +/// [the default implementations stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/default-impls). +#[cgp_component(PostDeleter)] +#[prefix(@app.core.post in DefaultNamespace)] +pub trait CanDeletePost { + fn delete_post(&self, post_id: &PostId) -> Result<(), Error>; +} + +/// Decides whether a username is censored. See +/// [the default implementations stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/default-impls). +#[cgp_component(UsernameCensor)] +#[prefix(@app.extra.content_filter in DefaultNamespace)] +pub trait CanCensorUsername { + fn username_is_censored(&self, username: &str) -> Probability; +} + +/// Decides whether a message is spam. See +/// [the default implementations stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/default-impls). +#[cgp_component(SpamMessageDetector)] +#[prefix(@app.extra.content_filter in DefaultNamespace)] +pub trait CanDetectSpamMessage { + fn message_is_spam(&self, message: &str) -> Probability; +} + +cgp_namespace! { + new DefaultAppComponents: DefaultNamespace +} + +cgp_namespace! { + DefaultAppComponents { + @app.core.user.UserCreatorComponent: + FilterCensoredUsername, + + @app.core.post.PostCreatorComponent: + FilterSpamMessage, + } +} + +/// Rejects a censored username and otherwise forwards to the inner creator. See +/// [the default implementations stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/default-impls). +#[cgp_impl(new FilterCensoredUsername)] +#[uses(CanCensorUsername)] +#[use_provider(InnerCreator: UserCreator)] +impl UserCreator { + fn create_user(&self, username: &str, email: &Email) -> Result { + if self.username_is_censored(username) > Probability::new(0.8) { + return Err(Error::InvalidUsername); + } + + InnerCreator::create_user(self, username, email) + } +} + +/// Creates a user in Postgres. See +/// [the default implementations stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/default-impls). +#[cgp_impl(new CreateUserWithPostgres)] +impl UserCreator { + fn create_user( + &self, + #[implicit] database: &PostgresDb, + username: &str, + email: &Email, + ) -> Result { + todo!() + } +} + +/// Reads a user from Postgres. See +/// [the default implementations stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/default-impls). +#[cgp_impl(new GetUserWithPostgres)] +#[default_impl(@app.core.user.UserGetterComponent in DefaultAppComponents)] +impl UserGetter { + fn get_user(&self, #[implicit] database: &PostgresDb, user_id: &UserId) -> Result { + todo!() + } +} + +/// Updates a user's data in Postgres. See +/// [the default implementations stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/default-impls). +#[cgp_impl(new UpdateUserWithPostgres)] +#[default_impl(@app.core.user.UserUpdaterComponent in DefaultAppComponents)] +impl UserUpdater { + fn update_user_data( + &self, + #[implicit] database: &PostgresDb, + user_id: &UserId, + user_data: &UserData, + ) -> Result<(), Error> { + todo!() + } +} + +/// Rejects a spam message and otherwise forwards to the inner creator. See +/// [the default implementations stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/default-impls). +#[cgp_impl(new FilterSpamMessage)] +#[uses(CanDetectSpamMessage)] +#[use_provider(InnerCreator: PostCreator)] +impl PostCreator { + fn create_post(&self, title: &str, content: &str) -> Result { + if self.message_is_spam(content) > Probability::new(0.8) { + return Err(Error::InvalidMessage); + } + + InnerCreator::create_post(self, title, content) + } +} + +/// Creates a post in Postgres. See +/// [the default implementations stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/default-impls). +#[cgp_impl(new CreatePostWithPostgres)] +impl PostCreator { + fn create_post( + &self, + #[implicit] database: &PostgresDb, + title: &str, + content: &str, + ) -> Result { + todo!() + } +} + +/// Reads a post from Postgres. See +/// [the default implementations stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/default-impls). +#[cgp_impl(new GetPostWithPostgres)] +#[default_impl(@app.core.post.PostGetterComponent in DefaultAppComponents)] +impl PostGetter { + fn get_post(&self, #[implicit] database: &PostgresDb, post_id: &PostId) -> Result { + todo!() + } +} + +/// Updates a post's content in Postgres. See +/// [the default implementations stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/default-impls). +#[cgp_impl(new UpdatePostWithPostgres)] +#[default_impl(@app.core.post.PostUpdaterComponent in DefaultAppComponents)] +impl PostUpdater { + fn update_post( + &self, + #[implicit] database: &PostgresDb, + post_id: &PostId, + content: &str, + ) -> Result<(), Error> { + todo!() + } +} + +/// Deletes a post from Postgres. See +/// [the default implementations stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/default-impls). +#[cgp_impl(new DeletePostWithPostgres)] +#[default_impl(@app.core.post.PostDeleterComponent in DefaultAppComponents)] +impl PostDeleter { + fn delete_post( + &self, + #[implicit] database: &PostgresDb, + post_id: &PostId, + ) -> Result<(), Error> { + todo!() + } +} + +/// Stands in for a username censor, leaving the score unimplemented. See +/// [the default implementations stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/default-impls). +#[cgp_impl(new DummyUserCensor)] +impl UsernameCensor { + fn username_is_censored(&self, username: &str) -> Probability { + todo!() + } +} + +/// Scores a username with a model, leaving the call unimplemented. See +/// [the default implementations stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/default-impls). +#[cgp_impl(new AiUserCensor)] +impl UsernameCensor { + fn username_is_censored(&self, username: &str) -> Probability { + todo!() + } +} + +/// Stands in for a spam detector, leaving the score unimplemented. See +/// [the default implementations stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/default-impls). +#[cgp_impl(new DummySpamMessageDetector)] +impl SpamMessageDetector { + fn message_is_spam(&self, message: &str) -> Probability { + todo!() + } +} + +/// Scores a message with a model, leaving the call unimplemented. See +/// [the default implementations stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/default-impls). +#[cgp_impl(new AiSpamMessageDetector)] +impl SpamMessageDetector { + fn message_is_spam(&self, message: &str) -> Probability { + todo!() + } +} + +#[derive(HasField)] +pub struct ProductionApp { + pub database: PostgresDb, +} + +delegate_components! { + new ContentFilterComponents { + UsernameCensorComponent: + AiUserCensor, + SpamMessageDetectorComponent: + AiSpamMessageDetector, + } +} + +delegate_components! { + ProductionApp { + namespace DefaultAppComponents; + + @app.extra.content_filter: ContentFilterComponents, + } +} + +check_components! { + ProductionApp { + UserCreatorComponent, + UserGetterComponent, + UserUpdaterComponent, + PostCreatorComponent, + PostGetterComponent, + PostUpdaterComponent, + PostDeleterComponent, + UsernameCensorComponent, + SpamMessageDetectorComponent, + } +} diff --git a/web-app/src/fine_grained.rs b/web-app/src/fine_grained.rs new file mode 100644 index 0000000..380a38e --- /dev/null +++ b/web-app/src/fine_grained.rs @@ -0,0 +1,317 @@ +use cgp::prelude::*; + +use crate::types::*; + +/// Creates a user. See +/// [the fine-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/fine-grained). +#[cgp_component(UserCreator)] +pub trait CanCreateUser { + fn create_user(&self, username: &str, email: &Email) -> Result; +} + +/// Reads a user. See +/// [the fine-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/fine-grained). +#[cgp_component(UserGetter)] +pub trait CanGetUser { + fn get_user(&self, user_id: &UserId) -> Result; +} + +/// Updates a user. See +/// [the fine-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/fine-grained). +#[cgp_component(UserUpdater)] +pub trait CanUpdateUser { + fn update_user_data(&self, user_id: &UserId, user_data: &UserData) -> Result<(), Error>; +} + +/// Creates a post. See +/// [the fine-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/fine-grained). +#[cgp_component(PostCreator)] +pub trait CanCreatePost { + fn create_post(&self, title: &str, content: &str) -> Result; +} + +/// Reads a post. See +/// [the fine-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/fine-grained). +#[cgp_component(PostGetter)] +pub trait CanGetPost { + fn get_post(&self, post_id: &PostId) -> Result; +} + +/// Updates a post. See +/// [the fine-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/fine-grained). +#[cgp_component(PostUpdater)] +pub trait CanUpdatePost { + fn update_post(&self, post_id: &PostId, content: &str) -> Result<(), Error>; +} + +/// Deletes a post. See +/// [the fine-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/fine-grained). +#[cgp_component(PostDeleter)] +pub trait CanDeletePost { + fn delete_post(&self, post_id: &PostId) -> Result<(), Error>; +} + +/// Decides whether a username is censored. See +/// [the fine-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/fine-grained). +#[cgp_component(UsernameCensor)] +pub trait CanCensorUsername { + fn username_is_censored(&self, username: &str) -> Probability; +} + +/// Decides whether a message is spam. See +/// [the fine-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/fine-grained). +#[cgp_component(SpamMessageDetector)] +pub trait CanDetectSpamMessage { + fn message_is_spam(&self, message: &str) -> Probability; +} + +/// Rejects a censored username and otherwise forwards to the inner creator. See +/// [the fine-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/fine-grained). +#[cgp_impl(new FilterCensoredUsername)] +#[uses(CanCensorUsername)] +#[use_provider(InnerCreator: UserCreator)] +impl UserCreator { + fn create_user(&self, username: &str, email: &Email) -> Result { + if self.username_is_censored(username) > Probability::new(0.8) { + return Err(Error::InvalidUsername); + } + + InnerCreator::create_user(self, username, email) + } +} + +/// Creates a user in Postgres. See +/// [the fine-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/fine-grained). +#[cgp_impl(new CreateUserWithPostgres)] +impl UserCreator { + fn create_user( + &self, + #[implicit] database: &PostgresDb, + username: &str, + email: &Email, + ) -> Result { + todo!() + } +} + +/// Reads a user from Postgres. See +/// [the fine-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/fine-grained). +#[cgp_impl(new GetUserWithPostgres)] +impl UserGetter { + fn get_user(&self, #[implicit] database: &PostgresDb, user_id: &UserId) -> Result { + todo!() + } +} + +/// Updates a user's data in Postgres. See +/// [the fine-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/fine-grained). +#[cgp_impl(new UpdateUserWithPostgres)] +impl UserUpdater { + fn update_user_data( + &self, + #[implicit] database: &PostgresDb, + user_id: &UserId, + user_data: &UserData, + ) -> Result<(), Error> { + todo!() + } +} + +/// Rejects a spam message and otherwise forwards to the inner creator. See +/// [the fine-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/fine-grained). +#[cgp_impl(new FilterSpamMessage)] +#[uses(CanDetectSpamMessage)] +#[use_provider(InnerCreator: PostCreator)] +impl PostCreator { + fn create_post(&self, title: &str, content: &str) -> Result { + if self.message_is_spam(content) > Probability::new(0.8) { + return Err(Error::InvalidMessage); + } + + InnerCreator::create_post(self, title, content) + } +} + +/// Creates a post in Postgres. See +/// [the fine-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/fine-grained). +#[cgp_impl(new CreatePostWithPostgres)] +impl PostCreator { + fn create_post( + &self, + #[implicit] database: &PostgresDb, + title: &str, + content: &str, + ) -> Result { + todo!() + } +} + +/// Reads a post from Postgres. See +/// [the fine-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/fine-grained). +#[cgp_impl(new GetPostWithPostgres)] +impl PostGetter { + fn get_post(&self, #[implicit] database: &PostgresDb, post_id: &PostId) -> Result { + todo!() + } +} + +/// Updates a post's content in Postgres. See +/// [the fine-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/fine-grained). +#[cgp_impl(new UpdatePostWithPostgres)] +impl PostUpdater { + fn update_post( + &self, + #[implicit] database: &PostgresDb, + post_id: &PostId, + content: &str, + ) -> Result<(), Error> { + todo!() + } +} + +/// Deletes a post from Postgres. See +/// [the fine-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/fine-grained). +#[cgp_impl(new DeletePostWithPostgres)] +impl PostDeleter { + fn delete_post( + &self, + #[implicit] database: &PostgresDb, + post_id: &PostId, + ) -> Result<(), Error> { + todo!() + } +} + +/// Stands in for a username censor, leaving the score unimplemented. See +/// [the fine-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/fine-grained). +#[cgp_impl(new DummyUserCensor)] +impl UsernameCensor { + fn username_is_censored(&self, username: &str) -> Probability { + todo!() + } +} + +/// Scores a username with a model, leaving the call unimplemented. See +/// [the fine-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/fine-grained). +#[cgp_impl(new AiUserCensor)] +impl UsernameCensor { + fn username_is_censored(&self, username: &str) -> Probability { + todo!() + } +} + +/// Stands in for a spam detector, leaving the score unimplemented. See +/// [the fine-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/fine-grained). +#[cgp_impl(new DummySpamMessageDetector)] +impl SpamMessageDetector { + fn message_is_spam(&self, message: &str) -> Probability { + todo!() + } +} + +/// Scores a message with a model, leaving the call unimplemented. See +/// [the fine-grained stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/fine-grained). +#[cgp_impl(new AiSpamMessageDetector)] +impl SpamMessageDetector { + fn message_is_spam(&self, message: &str) -> Probability { + todo!() + } +} + +#[derive(HasField)] +pub struct ProductionApp { + pub database: PostgresDb, +} + +// delegate_components! { +// ProductionApp { +// UserCreatorComponent: +// FilterCensoredUsername, +// UserGetterComponent: +// GetUserWithPostgres, +// UserUpdaterComponent: +// UpdateUserWithPostgres, +// PostCreatorComponent: +// FilterSpamMessage, +// PostGetterComponent: +// GetPostWithPostgres, +// PostUpdaterComponent: +// UpdatePostWithPostgres, +// PostDeleterComponent: +// DeletePostWithPostgres, +// UsernameCensorComponent: +// AiUserCensor, +// SpamMessageDetectorComponent: +// AiSpamMessageDetector, +// } +// } + +delegate_components! { + new PostgresUserComponents { + UserCreatorComponent: + FilterCensoredUsername, + UserGetterComponent: + GetUserWithPostgres, + UserUpdaterComponent: + UpdateUserWithPostgres, + } +} + +delegate_components! { + new PostgresPostComponents { + PostCreatorComponent: + FilterSpamMessage, + PostGetterComponent: + GetPostWithPostgres, + PostUpdaterComponent: + UpdatePostWithPostgres, + PostDeleterComponent: + DeletePostWithPostgres, + } +} + +delegate_components! { + new AiContentFilterComponents { + UsernameCensorComponent: + AiUserCensor, + SpamMessageDetectorComponent: + AiSpamMessageDetector, + } +} + +delegate_components! { + ProductionApp { + [ + UserCreatorComponent, + UserGetterComponent, + UserUpdaterComponent, + ]: + PostgresUserComponents, + [ + PostCreatorComponent, + PostGetterComponent, + PostUpdaterComponent, + PostDeleterComponent, + ]: + PostgresPostComponents, + [ + UsernameCensorComponent, + SpamMessageDetectorComponent, + ]: + AiContentFilterComponents, + } +} + +check_components! { + ProductionApp { + UserCreatorComponent, + UserGetterComponent, + UserUpdaterComponent, + PostCreatorComponent, + PostGetterComponent, + PostUpdaterComponent, + PostDeleterComponent, + UsernameCensorComponent, + SpamMessageDetectorComponent, + } +} diff --git a/web-app/src/lib.rs b/web-app/src/lib.rs new file mode 100644 index 0000000..e11d00b --- /dev/null +++ b/web-app/src/lib.rs @@ -0,0 +1,7 @@ +#![allow(unused)] + +pub mod coarse_grained; +pub mod default_impls; +pub mod fine_grained; +pub mod namespace; +pub mod types; diff --git a/web-app/src/namespace.rs b/web-app/src/namespace.rs new file mode 100644 index 0000000..7e704a7 --- /dev/null +++ b/web-app/src/namespace.rs @@ -0,0 +1,359 @@ +use cgp::prelude::*; + +use crate::types::*; + +/// Creates a user. See +/// [the namespaces stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/namespaces). +#[cgp_component(UserCreator)] +#[prefix(@app.core.user in DefaultNamespace)] +pub trait CanCreateUser { + fn create_user(&self, username: &str, email: &Email) -> Result; +} + +/// Reads a user. See +/// [the namespaces stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/namespaces). +#[cgp_component(UserGetter)] +#[prefix(@app.core.user in DefaultNamespace)] +pub trait CanGetUser { + fn get_user(&self, user_id: &UserId) -> Result; +} + +/// Updates a user. See +/// [the namespaces stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/namespaces). +#[cgp_component(UserUpdater)] +#[prefix(@app.core.user in DefaultNamespace)] +pub trait CanUpdateUser { + fn update_user_data(&self, user_id: &UserId, user_data: &UserData) -> Result<(), Error>; +} + +/// Creates a post. See +/// [the namespaces stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/namespaces). +#[cgp_component(PostCreator)] +#[prefix(@app.core.post in DefaultNamespace)] +pub trait CanCreatePost { + fn create_post(&self, title: &str, content: &str) -> Result; +} + +/// Reads a post. See +/// [the namespaces stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/namespaces). +#[cgp_component(PostGetter)] +#[prefix(@app.core.post in DefaultNamespace)] +pub trait CanGetPost { + fn get_post(&self, post_id: &PostId) -> Result; +} + +/// Updates a post. See +/// [the namespaces stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/namespaces). +#[cgp_component(PostUpdater)] +#[prefix(@app.core.post in DefaultNamespace)] +pub trait CanUpdatePost { + fn update_post(&self, post_id: &PostId, content: &str) -> Result<(), Error>; +} + +/// Deletes a post. See +/// [the namespaces stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/namespaces). +#[cgp_component(PostDeleter)] +#[prefix(@app.core.post in DefaultNamespace)] +pub trait CanDeletePost { + fn delete_post(&self, post_id: &PostId) -> Result<(), Error>; +} + +/// Decides whether a username is censored. See +/// [the namespaces stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/namespaces). +#[cgp_component(UsernameCensor)] +#[prefix(@app.extra.content_filter in DefaultNamespace)] +pub trait CanCensorUsername { + fn username_is_censored(&self, username: &str) -> Probability; +} + +/// Decides whether a message is spam. See +/// [the namespaces stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/namespaces). +#[cgp_component(SpamMessageDetector)] +#[prefix(@app.extra.content_filter in DefaultNamespace)] +pub trait CanDetectSpamMessage { + fn message_is_spam(&self, message: &str) -> Probability; +} + +/// Rejects a censored username and otherwise forwards to the inner creator. See +/// [the namespaces stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/namespaces). +#[cgp_impl(new FilterCensoredUsername)] +#[uses(CanCensorUsername)] +#[use_provider(InnerCreator: UserCreator)] +impl UserCreator { + fn create_user(&self, username: &str, email: &Email) -> Result { + if self.username_is_censored(username) > Probability::new(0.8) { + return Err(Error::InvalidUsername); + } + + InnerCreator::create_user(self, username, email) + } +} + +/// Creates a user in Postgres. See +/// [the namespaces stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/namespaces). +#[cgp_impl(new CreateUserWithPostgres)] +impl UserCreator { + fn create_user( + &self, + #[implicit] database: &PostgresDb, + username: &str, + email: &Email, + ) -> Result { + todo!() + } +} + +/// Reads a user from Postgres. See +/// [the namespaces stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/namespaces). +#[cgp_impl(new GetUserWithPostgres)] +impl UserGetter { + fn get_user(&self, #[implicit] database: &PostgresDb, user_id: &UserId) -> Result { + todo!() + } +} + +/// Updates a user's data in Postgres. See +/// [the namespaces stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/namespaces). +#[cgp_impl(new UpdateUserWithPostgres)] +impl UserUpdater { + fn update_user_data( + &self, + #[implicit] database: &PostgresDb, + user_id: &UserId, + user_data: &UserData, + ) -> Result<(), Error> { + todo!() + } +} + +/// Rejects a spam message and otherwise forwards to the inner creator. See +/// [the namespaces stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/namespaces). +#[cgp_impl(new FilterSpamMessage)] +#[uses(CanDetectSpamMessage)] +#[use_provider(InnerCreator: PostCreator)] +impl PostCreator { + fn create_post(&self, title: &str, content: &str) -> Result { + if self.message_is_spam(content) > Probability::new(0.8) { + return Err(Error::InvalidMessage); + } + + InnerCreator::create_post(self, title, content) + } +} + +/// Creates a post in Postgres. See +/// [the namespaces stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/namespaces). +#[cgp_impl(new CreatePostWithPostgres)] +impl PostCreator { + fn create_post( + &self, + #[implicit] database: &PostgresDb, + title: &str, + content: &str, + ) -> Result { + todo!() + } +} + +/// Reads a post from Postgres. See +/// [the namespaces stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/namespaces). +#[cgp_impl(new GetPostWithPostgres)] +impl PostGetter { + fn get_post(&self, #[implicit] database: &PostgresDb, post_id: &PostId) -> Result { + todo!() + } +} + +/// Updates a post's content in Postgres. See +/// [the namespaces stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/namespaces). +#[cgp_impl(new UpdatePostWithPostgres)] +impl PostUpdater { + fn update_post( + &self, + #[implicit] database: &PostgresDb, + post_id: &PostId, + content: &str, + ) -> Result<(), Error> { + todo!() + } +} + +/// Deletes a post from Postgres. See +/// [the namespaces stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/namespaces). +#[cgp_impl(new DeletePostWithPostgres)] +impl PostDeleter { + fn delete_post( + &self, + #[implicit] database: &PostgresDb, + post_id: &PostId, + ) -> Result<(), Error> { + todo!() + } +} + +/// Stands in for a username censor, leaving the score unimplemented. See +/// [the namespaces stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/namespaces). +#[cgp_impl(new DummyUserCensor)] +impl UsernameCensor { + fn username_is_censored(&self, username: &str) -> Probability { + todo!() + } +} + +/// Scores a username with a model, leaving the call unimplemented. See +/// [the namespaces stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/namespaces). +#[cgp_impl(new AiUserCensor)] +impl UsernameCensor { + fn username_is_censored(&self, username: &str) -> Probability { + todo!() + } +} + +/// Stands in for a spam detector, leaving the score unimplemented. See +/// [the namespaces stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/namespaces). +#[cgp_impl(new DummySpamMessageDetector)] +impl SpamMessageDetector { + fn message_is_spam(&self, message: &str) -> Probability { + todo!() + } +} + +/// Scores a message with a model, leaving the call unimplemented. See +/// [the namespaces stage](https://contextgeneric.dev/docs/projects/cgp-examples/web-app/examples/namespaces). +#[cgp_impl(new AiSpamMessageDetector)] +impl SpamMessageDetector { + fn message_is_spam(&self, message: &str) -> Probability { + todo!() + } +} + +#[derive(HasField)] +pub struct ProductionApp { + pub database: PostgresDb, +} + +#[derive(HasField)] +pub struct TestApp { + pub database: PostgresDb, +} + +delegate_components! { + new PostgresUserComponents { + UserCreatorComponent: + FilterCensoredUsername, + UserGetterComponent: + GetUserWithPostgres, + UserUpdaterComponent: + UpdateUserWithPostgres, + } +} + +delegate_components! { + new PostgresPostComponents { + PostCreatorComponent: + FilterSpamMessage, + PostGetterComponent: + GetPostWithPostgres, + PostUpdaterComponent: + UpdatePostWithPostgres, + PostDeleterComponent: + DeletePostWithPostgres, + } +} + +delegate_components! { + new AiContentFilterComponents { + UsernameCensorComponent: + AiUserCensor, + SpamMessageDetectorComponent: + AiSpamMessageDetector, + } +} + +delegate_components! { + new DummyContentFilterComponents { + UsernameCensorComponent: + DummyUserCensor, + SpamMessageDetectorComponent: + DummySpamMessageDetector, + } +} + +// delegate_components! { +// ProductionApp { +// namespace DefaultNamespace; +// +// @app.core.user: PostgresUserComponents, +// @app.core.post: PostgresPostComponents, +// @app.extra.content_filter: AiContentFilterComponents, +// } +// } + +delegate_components! { + new PostgresCoreComponents { + namespace DefaultNamespace; + + @app.core.user: PostgresUserComponents, + @app.core.post: PostgresPostComponents, + } +} + +delegate_components! { + new ProductionExtraComponents { + namespace DefaultNamespace; + + @app.extra.content_filter: AiContentFilterComponents, + } +} + +delegate_components! { + new DummyExtraComponents { + namespace DefaultNamespace; + + @app.extra.content_filter: DummyContentFilterComponents, + } +} + +delegate_components! { + ProductionApp { + namespace DefaultNamespace; + + @app.core: PostgresCoreComponents, + @app.extra: ProductionExtraComponents, + } +} + +delegate_components! { + TestApp { + namespace DefaultNamespace; + + @app.core: PostgresCoreComponents, + @app.extra: DummyExtraComponents, + } +} + +check_components! { + ProductionApp { + UserCreatorComponent, + UserGetterComponent, + UserUpdaterComponent, + PostCreatorComponent, + PostGetterComponent, + PostUpdaterComponent, + PostDeleterComponent, + UsernameCensorComponent, + SpamMessageDetectorComponent, + } + + TestApp { + UserCreatorComponent, + UserGetterComponent, + UserUpdaterComponent, + PostCreatorComponent, + PostGetterComponent, + PostUpdaterComponent, + PostDeleterComponent, + UsernameCensorComponent, + SpamMessageDetectorComponent, + } +} diff --git a/web-app/src/types.rs b/web-app/src/types.rs new file mode 100644 index 0000000..faeb537 --- /dev/null +++ b/web-app/src/types.rs @@ -0,0 +1,24 @@ +pub struct Email(pub String); + +pub struct User; +pub struct UserData; +pub struct UserId; + +pub struct Post; +pub struct PostId; + +pub enum Error { + InvalidUsername, + InvalidMessage, +} + +pub struct PostgresDb; + +#[derive(PartialOrd, PartialEq)] +pub struct Probability(pub f64); + +impl Probability { + pub const fn new(value: f64) -> Self { + Self(value) + } +}