diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..420f90b --- /dev/null +++ b/.dockerignore @@ -0,0 +1,4 @@ +target +.git +.claude +*.sqlite* diff --git a/.env b/.env deleted file mode 100644 index e770977..0000000 --- a/.env +++ /dev/null @@ -1,2 +0,0 @@ -DATABASE_URL=postgres://postgres@localhost/delayed-queue - diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..3d09fcb --- /dev/null +++ b/.env.example @@ -0,0 +1,22 @@ +# Example environment for local development. Copy it to .env and adjust. +# dally does not read .env itself; load it into your shell first: +# +# set -a; . ./.env; set +a +# +# Settings can also come from a TOML file (dally server --config dally.toml). +# Environment variables win over the file. See docs/operations.md. + +# Where the server listens and stores messages. Without DALLY_STORAGE_URL, +# dally uses a local SQLite file. +DALLY_LISTEN=127.0.0.1:7070 +DALLY_STORAGE_URL=postgres://postgres:dally@localhost:55432/postgres +# DALLY_STORAGE_URL=sqlite://dally.sqlite +# DALLY_STORAGE_URL=redis://localhost:56379 + +# Used by the dally CLI subcommands (queues, schedule, messages, dead). +DALLY_SERVER=http://127.0.0.1:7070 +# DALLY_API_KEY= + +# Databases for the test suite, matching compose.yaml. +DALLY_TEST_POSTGRES_URL=postgres://postgres:dally@localhost:55432/postgres +DALLY_TEST_REDIS_URL=redis://localhost:56379 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..4a5996f --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,54 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +env: + CARGO_TERM_COLOR: always + RUSTFLAGS: -D warnings + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + - uses: Swatinem/rust-cache@v2 + - run: cargo fmt --all --check + - run: cargo clippy --workspace --all-targets --all-features + + test: + runs-on: ubuntu-latest + services: + postgres: + image: postgres:17 + env: + POSTGRES_PASSWORD: dally + ports: ["5432:5432"] + options: >- + --health-cmd pg_isready --health-interval 2s --health-timeout 5s --health-retries 10 + redis: + image: redis:8 + ports: ["6379:6379"] + options: >- + --health-cmd "redis-cli ping" --health-interval 2s --health-timeout 5s --health-retries 10 + env: + DALLY_TEST_POSTGRES_URL: postgres://postgres:dally@localhost:5432/postgres + DALLY_TEST_REDIS_URL: redis://localhost:6379 + steps: + - uses: actions/checkout@v5 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - run: cargo test --workspace --all-features + + msrv: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: dtolnay/rust-toolchain@1.94 + - uses: Swatinem/rust-cache@v2 + - run: cargo check --workspace --all-features diff --git a/.gitignore b/.gitignore index 6985cf1..bde880c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,14 +1,9 @@ -# Generated by Cargo -# will have compiled files and executables -debug/ -target/ +/target +*.sqlite +*.sqlite-shm +*.sqlite-wal -# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries -# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html -Cargo.lock - -# These are backup files generated by rustfmt -**/*.rs.bk - -# MSVC Windows builds of rustc generate these, which store debugging information -*.pdb +# Local environment. Copy .env.example to .env; never commit real values. +.env +.env.* +!.env.example diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..35449e5 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,21 @@ +# Changelog + +All notable changes to dally are listed here. The format follows +[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow +[Semantic Versioning](https://semver.org/). + +## [Unreleased] + +The first release. Highlights: + +- Queues with per-queue settings: visibility timeout, max attempts, backoff, + retention, pause and resume. +- Messages with delays, priorities, idempotency keys, leases, retries with + exponential backoff, and a dead-letter state. +- PostgreSQL, SQLite and Redis backends, all passing one conformance suite. +- HTTP API with long polling, push delivery to webhooks with HMAC signatures, + and recurring jobs from cron expressions. +- API keys with client and admin roles, Prometheus metrics, an OpenAPI spec, + and optional OpenTelemetry tracing. +- A Rust client with a `Worker`, and a `dally` CLI. +- An optional web UI. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..b159820 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,71 @@ +# Contributing to dally + +Thanks for helping. Bug reports, docs fixes and code are all welcome. + +## Before you start + +For anything bigger than a small fix, open an issue first and describe what +you want to change. `docs/design.md` explains how dally is put together and +why. A change that goes against it is not ruled out, but it needs a discussion. + +## Layout + +| Path | What it is | +|-----------------------|---------------------------------------------------------| +| `crates/dally-core` | Domain types, the `Service` rules, the `Storage` trait and backends | +| `crates/dally-server` | HTTP API and background tasks | +| `crates/dally-client` | Rust client and `Worker` | +| `crates/dally-ui` | Web UI, a client of the HTTP API | +| `crates/dally` | The `dally` binary | +| `docs/` | Design notes and user documentation | + +## Running the tests + +The SQLite tests and unit tests need nothing. The PostgreSQL and Redis tests +need running databases and are skipped without them: + +```sh +docker compose up -d +export DALLY_TEST_POSTGRES_URL=postgres://postgres:dally@localhost:55432/postgres +export DALLY_TEST_REDIS_URL=redis://localhost:56379 +cargo test --workspace --all-features +``` + +Before sending a pull request, run what CI runs: + +```sh +cargo fmt --all --check +cargo clippy --workspace --all-targets --all-features -- -D warnings +cargo test --workspace --all-features +``` + +After changing the HTTP API, regenerate the committed OpenAPI spec: + +```sh +UPDATE_OPENAPI=1 cargo test -p dally-server openapi +``` + +## Adding a storage backend + +Implement `dally_core::Storage` behind a cargo feature, then add a test file +that calls `conformance_tests!(setup)` (see `crates/dally-core/tests/postgres.rs`). +The conformance suite is the contract: a backend that passes it behaves like +every other backend. If a test seems wrong for your backend, raise it in the +pull request rather than skipping it. + +## Style + +- Write code for the next reader. Small functions, clear names, and comments + that explain *why* rather than *what*. +- Public items get doc comments. The workspace warns on missing docs. +- No `unwrap()` outside tests. Library crates use `thiserror`; only the binary + uses `anyhow`. +- Behaviour changes come with tests, and with an update to `docs/` if users + would notice. +- Commit messages: a short summary line in the imperative ("Add Redis + backend"), then a body explaining why, if it is not obvious. + +## License + +By contributing, you agree that your contributions will be dual licensed under +the MIT and Apache 2.0 licenses, as described in the README. diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..2189800 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,3670 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "arc-swap" +version = "1.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84a22b5d51209f6de83d37a0b33d320acb8da88823e42a94c075140708f032a5" +dependencies = [ + "rustversion", +] + +[[package]] +name = "arcstr" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03918c3dbd7701a85c6b9887732e2921175f26c350b4563841d0958c21d57e6d" + +[[package]] +name = "askama" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6024d73179f43f15ccd2b881bfea6fee7f3a46ec53f33b52210dea749ebebaa4" +dependencies = [ + "askama_macros", + "itoa", + "percent-encoding", + "serde", + "serde_json", +] + +[[package]] +name = "askama_derive" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071ee5ebf2138e3ad180e0aacf6940c2cab5e6d8333741d9925c7bee2b153f39" +dependencies = [ + "askama_parser", + "basic-toml", + "glob", + "memchr", + "proc-macro2", + "quote", + "rustc-hash", + "serde", + "serde_derive", + "syn 3.0.10", +] + +[[package]] +name = "askama_macros" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "643e1c7cbb6aec1d920332fe51a7c0d8219e273dcb8602db03f5263e4d16487b" +dependencies = [ + "askama_derive", +] + +[[package]] +name = "askama_parser" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c5ae75772275d268b03ab8bdccdd12117b6169ee23256942b34e46c9f476583" +dependencies = [ + "rustc-hash", + "serde", + "serde_derive", + "unicode-ident", + "winnow 1.0.5", +] + +[[package]] +name = "async-lock" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "atoi" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" +dependencies = [ + "num-traits", +] + +[[package]] +name = "atomic" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89cbf775b137e9b968e67227ef7f775587cde3fd31b0d8599dbd0f598a48340" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "aws-lc-rs" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "axum-macros", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-macros" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aa268c23bfbbd2c4363b9cd302a4f504fb2a9dfe7e3451d66f35dd392e20aca" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "backon" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cffb0e931875b666fc4fcb20fee52e9bbd1ef836fd9e9e04ec21555f9f85f7ef" +dependencies = [ + "fastrand", +] + +[[package]] +name = "base64" +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 = "basic-toml" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a" +dependencies = [ + "serde", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +dependencies = [ + "serde_core", +] + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core 0.10.1", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "chrono-tz" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6139a8597ed92cf816dfb33f5dd6cf0bb93a6adc938f11039f371bc5bcd26c3" +dependencies = [ + "chrono", + "phf", +] + +[[package]] +name = "clap" +version = "4.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac230478587d0269d8d6998b82ae69ea51509d55df66d9e92edd1f986904cd4a" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "895c9d8d2ac2dd8b8a29f3724a14e72aaaa6debcf8c38c82f97305c6a172767a" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "futures-core", + "memchr", + "pin-project-lite", + "tokio", + "tokio-util", +] + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" + +[[package]] +name = "croner" +version = "4.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0097e28936e948e8f759478e1b5ec2e5ca70ab62cf38aaa9bd3aa660023e3fca" +dependencies = [ + "chrono", + "derive_builder", + "strum", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + +[[package]] +name = "dally" +version = "0.1.0" +dependencies = [ + "anyhow", + "axum", + "chrono", + "clap", + "dally-client", + "dally-server", + "dally-ui", + "humantime", + "opentelemetry", + "opentelemetry-otlp", + "opentelemetry_sdk", + "serde", + "serde_json", + "tokio", + "tracing", + "tracing-opentelemetry", + "tracing-subscriber", +] + +[[package]] +name = "dally-client" +version = "0.1.0" +dependencies = [ + "axum", + "chrono", + "dally-core", + "dally-server", + "humantime-serde", + "reqwest", + "serde", + "serde_json", + "sqlx", + "thiserror", + "tokio", + "tracing", + "tracing-subscriber", + "uuid", +] + +[[package]] +name = "dally-core" +version = "0.1.0" +dependencies = [ + "async-trait", + "chrono", + "fastrand", + "futures-util", + "humantime-serde", + "redis", + "rustls", + "serde", + "serde_json", + "sqlx", + "tempfile", + "thiserror", + "tokio", + "tracing", + "url", + "utoipa", + "uuid", +] + +[[package]] +name = "dally-server" +version = "0.1.0" +dependencies = [ + "axum", + "chrono", + "chrono-tz", + "croner", + "dally-core", + "figment", + "hex", + "hmac", + "humantime-serde", + "prometheus-client", + "reqwest", + "serde", + "serde_json", + "sha2", + "sqlx", + "subtle", + "tempfile", + "thiserror", + "tokio", + "tokio-util", + "tower-http 0.7.1", + "tracing", + "utoipa", + "uuid", +] + +[[package]] +name = "dally-ui" +version = "0.1.0" +dependencies = [ + "askama", + "axum", + "chrono", + "dally-client", + "dally-core", + "dally-server", + "reqwest", + "serde", + "serde_json", + "tokio", + "tracing", +] + +[[package]] +name = "darling" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.119", +] + +[[package]] +name = "darling_macro" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" +dependencies = [ + "darling_core", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "derive_builder" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947" +dependencies = [ + "derive_builder_macro", +] + +[[package]] +name = "derive_builder_core" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "derive_builder_macro" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" +dependencies = [ + "derive_builder_core", + "syn 2.0.119", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "ctutils", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "dotenvy" +version = "0.15.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + +[[package]] +name = "dtoa" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590" + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" +dependencies = [ + "serde", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "etcetera" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de48cc4d1c1d97a20fd819def54b890cadde72ed3ad0c614822a0a433361be96" +dependencies = [ + "cfg-if", + "windows-sys 0.61.2", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "figment" +version = "0.10.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cb01cd46b0cf372153850f4c6c272d9cbea2da513e07538405148f95bd789f3" +dependencies = [ + "atomic", + "parking_lot", + "pear", + "serde", + "tempfile", + "toml", + "uncased", + "version_check", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flume" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be" +dependencies = [ + "futures-core", + "futures-sink", + "spin", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-intrusive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" +dependencies = [ + "futures-core", + "lock_api", + "parking_lot", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bb6743198531e02858aeaea5398fcc883e71851fcbcb5a2f773e2fb6cb1edf2" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hashlink" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824e001ac4f3012dd16a264bec811403a67ca9deb6c102fc5049b32c4574b35f" +dependencies = [ + "hashbrown 0.16.1", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hkdf" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "humantime" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15" + +[[package]] +name = "humantime-serde" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57a3db5ea5923d99402c94e9feb261dc5ee9b4efa158b0315f788cf549cc200c" +dependencies = [ + "humantime", + "serde", +] + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "inlinable_string" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8fae54786f62fb2918dcfae3d568594e50eb9b5c25bf04371af6fe7516452fb" + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "libc", +] + +[[package]] +name = "libsqlite3-sys" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b06e69070b7e12262b0cd90832f0a7396f142a2b330181255562decf9f0c6215" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "md-5" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" +dependencies = [ + "cfg-if", + "digest", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags", +] + +[[package]] +name = "objc2-system-configuration" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7216bd11cbda54ccabcab84d523dc93b858ec75ecfb3a7d89513fa22464da396" +dependencies = [ + "objc2-core-foundation", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "opentelemetry" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c1f1a6ac9c875a4941e4c7c085b61e8f4daa326de03b4701768c3491a6ad9ee" +dependencies = [ + "futures-core", + "futures-sink", + "js-sys", + "pin-project-lite", + "thiserror", +] + +[[package]] +name = "opentelemetry-http" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "302249bd8ee804789faaa7b5b2cbf79bc61cb864714079c644e3828af5b7e811" +dependencies = [ + "async-trait", + "bytes", + "http", + "opentelemetry", + "reqwest", +] + +[[package]] +name = "opentelemetry-otlp" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0756af24841e367128ef31c831999937b8b5c5197d47914590d8f4e2e88c2e1a" +dependencies = [ + "http", + "httpdate", + "opentelemetry", + "opentelemetry-http", + "opentelemetry-proto", + "opentelemetry_sdk", + "prost", + "reqwest", + "thiserror", +] + +[[package]] +name = "opentelemetry-proto" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d576f5dddc3299341bcd85a04be17b2564844c0c9563214f02d85f2524d1afae" +dependencies = [ + "opentelemetry", + "opentelemetry_sdk", + "prost", +] + +[[package]] +name = "opentelemetry_sdk" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "372a912db2974d1990207006fd0e3aa0ef3fd4ad3be43c65cfaadf2206866061" +dependencies = [ + "futures-channel", + "futures-executor", + "futures-util", + "opentelemetry", + "percent-encoding", + "portable-atomic", + "rand 0.9.5", + "thiserror", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pear" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdeeaa00ce488657faba8ebf44ab9361f9365a97bd39ffb8a60663f57ff4b467" +dependencies = [ + "inlinable_string", + "pear_codegen", + "yansi", +] + +[[package]] +name = "pear_codegen" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bab5b985dc082b345f812b7df84e1bef27e7207b39e448439ba8bd69c93f147" +dependencies = [ + "proc-macro2", + "proc-macro2-diagnostics", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "phf" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7" +dependencies = [ + "phf_shared", +] + +[[package]] +name = "phf_shared" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06005508882fb681fd97892ecff4b7fd0fee13ef1aa569f8695dae7ab9099981" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proc-macro2-diagnostics" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "version_check", + "yansi", +] + +[[package]] +name = "prometheus-client" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f021d42d29841d029b61b45a25a7ef94feaf1d744913e59665103333a56045b8" +dependencies = [ + "dtoa", + "itoa", + "parking_lot", + "prometheus-client-derive-encode", +] + +[[package]] +name = "prometheus-client-derive-encode" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01e34894696ff94f64a20c2c373a6440903e9c2789a303d68ec6e6f953f890e4" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "prost" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ef0b569d1d907ab3a28596aee62cf1f61dacb0529a4bedcd8e7460e2d5228b4" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-derive" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad9c5423459fa2f729b8d9235fab810aa29628b171467744fc86d21460ad70d" +dependencies = [ + "anyhow", + "itertools", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "aws-lc-rs", + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.4", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb95882a1e14462c69aea9984bb261293ccfe6022ef8de0eda18bd5afb0052df" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "redis" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bef8fa589dd53a8a379a7856de1365d0a1be50c6b8aebb5c01c1ec441a2c509" +dependencies = [ + "arc-swap", + "arcstr", + "async-lock", + "backon", + "bytes", + "cfg-if", + "combine", + "futures-channel", + "futures-util", + "itoa", + "percent-encoding", + "pin-project-lite", + "rustls", + "rustls-native-certs", + "ryu", + "sha1_smol", + "socket2", + "tokio", + "tokio-rustls", + "tokio-util", + "url", + "xxhash-rust", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http 0.6.11", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "aws-lc-rs", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sha1_smol" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" +dependencies = [ + "serde", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +dependencies = [ + "lock_api", +] + +[[package]] +name = "sqlx" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edb1dddfbdfe5fb99dba0541a87b2edb8adbd59e45815db22d32d4fbbb8813dd" +dependencies = [ + "sqlx-core", + "sqlx-macros", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", +] + +[[package]] +name = "sqlx-core" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08f9787cc5aff062567dea2205f8ae37a617b04342633ab4f74944858ea6072" +dependencies = [ + "base64 0.22.1", + "bytes", + "cfg-if", + "chrono", + "crc", + "crossbeam-queue", + "either", + "event-listener", + "futures-core", + "futures-intrusive", + "futures-io", + "futures-util", + "hashbrown 0.16.1", + "hashlink", + "indexmap", + "log", + "memchr", + "percent-encoding", + "serde", + "serde_json", + "sha2", + "smallvec", + "thiserror", + "tokio", + "tokio-stream", + "tracing", + "url", + "uuid", +] + +[[package]] +name = "sqlx-macros" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf62c58a1e7fd6031ee684eee21d07572f5aebe71c273a01ae4f04eeeba47c47" +dependencies = [ + "proc-macro2", + "quote", + "sqlx-core", + "sqlx-macros-core", + "syn 2.0.119", +] + +[[package]] +name = "sqlx-macros-core" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1ff75c9d609ac84aa8a3e0d92b5c0c54bf541a7f70db492fb40c9a4bea792c8" +dependencies = [ + "cfg-if", + "dotenvy", + "either", + "heck", + "hex", + "proc-macro2", + "quote", + "serde", + "serde_json", + "sha2", + "sqlx-core", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", + "syn 2.0.119", + "thiserror", + "tokio", + "url", +] + +[[package]] +name = "sqlx-mysql" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19eeb93b96eb10a3a59dfb436f3daf87d2fc41168ed9e9dc153ec8257dd6a761" +dependencies = [ + "bitflags", + "byteorder", + "bytes", + "chrono", + "crc", + "digest", + "dotenvy", + "either", + "futures-core", + "futures-util", + "generic-array", + "log", + "percent-encoding", + "serde", + "sha1", + "sha2", + "sqlx-core", + "thiserror", + "tracing", + "uuid", +] + +[[package]] +name = "sqlx-postgres" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0e9e02f764a1fe640eeefc8eb33eeddd274204654ec9f2db8ff851a1dee2364" +dependencies = [ + "atoi", + "base64 0.22.1", + "bitflags", + "byteorder", + "chrono", + "crc", + "dotenvy", + "etcetera", + "futures-channel", + "futures-core", + "futures-util", + "hex", + "hkdf", + "hmac", + "itoa", + "log", + "md-5", + "memchr", + "rand 0.10.4", + "serde", + "serde_json", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "tracing", + "uuid", + "whoami", +] + +[[package]] +name = "sqlx-sqlite" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b6b78a34ddcb1db4046d462db8f79cee811019d7297b99fca8fac5de26672e" +dependencies = [ + "atoi", + "chrono", + "flume", + "form_urlencoded", + "futures-channel", + "futures-core", + "futures-executor", + "futures-intrusive", + "futures-util", + "libsqlite3-sys", + "log", + "percent-encoding", + "serde", + "sqlx-core", + "thiserror", + "tracing", + "url", + "uuid", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +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.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow 0.7.15", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-http" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08a05a66a4fdd61cbbe0a1d755ffe0ca6aba159dd4820936a0ff8a8278245b9c" +dependencies = [ + "bitflags", + "bytes", + "http", + "http-body", + "http-body-util", + "percent-encoding", + "pin-project-lite", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-opentelemetry" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a904802a1b902f43638b677ff2a650847e3b4404101b6c586d648e8c1e3e8fe" +dependencies = [ + "js-sys", + "opentelemetry", + "tracing", + "tracing-core", + "tracing-subscriber", + "web-time", +] + +[[package]] +name = "tracing-serde" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1" +dependencies = [ + "serde", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "serde", + "serde_json", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", + "tracing-serde", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "uncased" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1b88fcfe09e89d3866a5c11019378088af2d24c3fbd4f0543f96b479ec90697" +dependencies = [ + "version_check", +] + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "utoipa" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8765fe27aeff71012a3f90fa474cf1df863a7d0dd81ed25de4e63fff2544994f" +dependencies = [ + "indexmap", + "serde", + "serde_json", + "utoipa-gen", +] + +[[package]] +name = "utoipa-gen" +version = "6.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d935f1c83fdf8b88f09bbe050d0cea78ea4afee6d7b0317403228c1200b2c8ab" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "uuid", +] + +[[package]] +name = "uuid" +version = "1.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "whoami" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c" +dependencies = [ + "libc", + "libredox", + "objc2-system-configuration", + "web-sys", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "xxhash-rust" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40de123dbb523ebcc00d61ec01840ad192578afc378d859f3429caa38308fad5" + +[[package]] +name = "yansi" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index b5998e3..b7431a3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,19 +1,64 @@ -[package] -name = "delayed-queue-rs" +[workspace] +resolver = "3" +members = ["crates/*"] + +[workspace.package] version = "0.1.0" -edition = "2018" +edition = "2024" +rust-version = "1.94" +license = "MIT OR Apache-2.0" +repository = "https://github.com/platonv/dally" +authors = ["Vlad Platon"] + +[workspace.dependencies] +dally-client = { path = "crates/dally-client", version = "0.1.0" } +dally-core = { path = "crates/dally-core", version = "0.1.0" } +dally-server = { path = "crates/dally-server", version = "0.1.0" } +dally-ui = { path = "crates/dally-ui", version = "0.1.0" } + +anyhow = "1.0.104" +askama = "0.16.1" +async-trait = "0.1.92" +axum = { version = "0.8.9", features = ["macros"] } +chrono = { version = "0.4.45", features = ["serde"] } +chrono-tz = "0.10.4" +clap = { version = "4.6.8", features = ["derive", "env"] } +croner = "4.0.3" +fastrand = "2.5.0" +figment = { version = "0.10.19", features = ["toml", "env"] } +futures-util = { version = "0.3.34", default-features = false } +hex = "0.4.3" +hmac = "0.13.0" +humantime = "2.4.0" +humantime-serde = "1.1.1" +redis = { version = "1.8.2", default-features = false, features = ["script", "tokio-comp", "connection-manager", "tokio-rustls-comp"] } +reqwest = { version = "0.13.5", default-features = false, features = ["json"] } +# Only here to pick a crypto provider for the TLS connections redis makes. +rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.154" +sha2 = "0.11.1" +sqlx = { version = "0.9.1", default-features = false, features = ["runtime-tokio", "macros", "chrono", "uuid", "json", "migrate"] } +tempfile = "3.27.0" +subtle = "2.6.1" +opentelemetry = { version = "0.33.1", default-features = false, features = ["trace"] } +opentelemetry-otlp = { version = "0.33.1", default-features = false, features = ["http-proto", "reqwest-blocking-client", "reqwest-rustls", "trace"] } +opentelemetry_sdk = { version = "0.33.1", default-features = false, features = ["trace"] } +prometheus-client = "0.26.0" +utoipa = { version = "6.0.0", features = ["chrono", "uuid"] } +thiserror = "2.0.21" +tokio = { version = "1.54.1", features = ["sync", "time", "macros"] } +tokio-util = "0.7.20" +tower-http = { version = "0.7.1", features = ["trace", "limit"] } +tracing = "0.1.44" +tracing-opentelemetry = { version = "0.34.0", default-features = false } +tracing-subscriber = { version = "0.3.23", features = ["env-filter", "json"] } +url = "2.5.8" +uuid = { version = "1.29.3", features = ["v4", "v7", "serde"] } + +[workspace.lints.rust] +missing_docs = "warn" +unsafe_code = "forbid" -[dependencies] -uuid = { version = "1.8.0", features = ["v4", "fast-rng", "macro-diagnostics"] } -anyhow = "1.0" -tokio = { version = "1.20.0", features = ["full"]} -dotenvy = "0.15.0" -sqlx = { version = "0.7", features = [ "runtime-tokio", "postgres" ] } -clap = { version = "4.5.4", features = [ "cargo" ] } -actix-web = "4.0.0" -actix-rt = "2.2.0" -env_logger = "0.9.0" -serde = { version = "1.0.172-alpha.0" } -serde_json = { version = "1.0.117" } -derive_more = "0.99.17" -reqwest = "0.11" \ No newline at end of file +[workspace.lints.clippy] +unwrap_used = "warn" diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..854969f --- /dev/null +++ b/Dockerfile @@ -0,0 +1,33 @@ +# Builds a small image with the dally binary and every backend. +# +# docker build -t dally . +# docker run -p 7070:7070 -v dally-data:/data dally +# +# On a machine with little memory, limit parallel compile jobs: +# docker build --build-arg CARGO_BUILD_JOBS=2 -t dally . + +FROM rust:1-bookworm AS build +ARG CARGO_BUILD_JOBS +WORKDIR /src +COPY . . +RUN --mount=type=cache,target=/usr/local/cargo/registry \ + --mount=type=cache,target=/src/target \ + cargo build --release --locked -p dally ${CARGO_BUILD_JOBS:+--jobs $CARGO_BUILD_JOBS} \ + && cp target/release/dally /usr/local/bin/dally + +FROM debian:bookworm-slim +RUN apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates \ + && rm -rf /var/lib/apt/lists/* \ + && useradd --system --uid 10001 --home /data dally \ + && mkdir /data && chown dally /data +COPY --from=build /usr/local/bin/dally /usr/local/bin/dally + +USER dally +WORKDIR /data +ENV DALLY_LISTEN=0.0.0.0:7070 \ + DALLY_STORAGE_URL=sqlite:///data/dally.sqlite \ + DALLY_LOG_FORMAT=json +EXPOSE 7070 +ENTRYPOINT ["dally"] +CMD ["server"] diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..bd64e78 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024-2026 Vlad Platon + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index cc7ca98..ab97bf0 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,372 @@ -# delayed-queue-rs +# dally -Message scheduler written in rust with planned support for Redis and RDBMSs. Could be used as a notification service or job scheduler. +[![CI](https://github.com/platonv/delayed-queue-rs/actions/workflows/ci.yml/badge.svg)](https://github.com/platonv/delayed-queue-rs/actions/workflows/ci.yml) +[![License: MIT OR Apache-2.0](https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-blue.svg)](#license) -Inspired by [this](https://alexn.org/blog/2022/10/21/modeling-queue-for-delayed-messages-via-rdbms/) article. \ No newline at end of file +A job queue server written in Rust. You schedule work over HTTP, and dally +hands it back when it is due, either to workers that poll for it or by POSTing +it to your app. + +```sh +curl -X POST localhost:7070/v1/queues/emails/messages \ + -d '{"payload": {"to": "ana@example.com"}, "delay": "10m"}' +``` + +- **Any language.** If it can make an HTTP request, it can use dally. +- **Your database.** PostgreSQL, SQLite or Redis, all three passing one + shared conformance test suite. +- **Delayed and recurring jobs.** Run in ten minutes, at 3 a.m. tomorrow, or + every night from a cron expression. +- **Retries that make sense.** Exponential backoff, a dead-letter state, and + the error from every failed attempt. +- **No duplicates from retried requests.** Idempotency keys make scheduling + safe to retry. +- **Push or pull.** Let dally call your webhook, or run workers that long-poll. +- **A web UI.** Optional, and built on the same public API. +- **One binary.** With no configuration it starts on a local SQLite file. + +> **Status:** dally works end to end and is covered by about 170 tests, but +> it has not been released or run in production yet. The API may change +> before 1.0. See [Status and roadmap](#status-and-roadmap). + +## Why dally + +Most job queues tie you to a language (Sidekiq, Celery, Oban) or to a broker +you have to run next to your database. dally is a small, separate server with +an HTTP API, so any app can use it, and it keeps its state in a database you +probably already run. + +It started as `delayed-queue-rs`, a prototype of the approach in Alexandru +Nedelcu's article +[Modeling a queue for delayed messages via an RDBMS](https://alexn.org/blog/2022/10/21/modeling-queue-for-delayed-messages-via-rdbms/): +one row per message with a due-time column that also works as the lock, so a +plain SQL table makes a reliable delayed queue. dally keeps that idea and adds +leases, retries, idempotency, per-queue settings and more backends around it. +The name means "to linger, to delay". + +## How it works + +Each message is a row (or a Redis hash) with a `status`, a `run_at` time and a +JSON payload. Scheduling inserts a `scheduled` row with `run_at` set to now +plus the delay. Nothing moves the message until a worker asks for it. + +When a worker polls, dally takes the due messages (`scheduled` with +`run_at <= now()`, or `running` with an expired lease) in priority order, +marks them `running`, and gives each a random lease token that expires after +the queue's visibility timeout. Only the holder of a valid lease can ack or +nack the message, so a slow worker cannot ack a message that was already +handed to someone else. + +```mermaid +sequenceDiagram + participant App + participant dally as dally server + participant DB as Storage + participant Worker + + App->>dally: POST /v1/queues/emails/messages (delay 10m) + dally->>DB: insert status=scheduled, run_at=now()+10m + Worker->>dally: POST /v1/queues/emails/poll (wait 20s) + Note over dally,DB: long poll: wait until a message is due + dally->>DB: lease due rows (FOR UPDATE SKIP LOCKED) + DB-->>dally: status=running, lease token, lease_expires_at + dally-->>Worker: message + lease + Worker->>dally: POST /v1/messages/{id}/ack (lease) + dally->>DB: status=succeeded +``` + +If the worker nacks, the message goes back to `scheduled` with +`run_at = now + backoff(attempt)`. If the lease expires, the message can be +leased again right away. After the last attempt it becomes `dead` and stays +there until you retry it. Finished messages are pruned after the queue's +retention period. + +How each backend does this: + +- **PostgreSQL** (the reference backend) leases in one `UPDATE ... FROM + (SELECT ... FOR UPDATE SKIP LOCKED)` statement, so any number of servers can + poll the same queue without blocking each other or taking the same row. + `LISTEN/NOTIFY` wakes long polls on every server as soon as a message is + scheduled, and a partial index over `status = 'scheduled'` keeps polling + fast. +- **SQLite** runs in WAL mode for a single server process, for local + development and small deployments. +- **Redis** keeps due messages in a sorted set per queue and leases in a + second one scored by expiry. Every multi-key operation is a Lua script, so + it is atomic. + +All timestamps come from the storage clock, never the server process, so +several servers with skewed clocks still agree on what is due. Servers are +stateless: all coordination happens in storage. + +The code is a Cargo workspace: + +| Crate | What it does | +|---|---| +| `dally-core` | Queue rules (`Service`), the `Storage` trait and the three backends | +| `dally-server` | HTTP API (axum), push dispatcher, cron ticker, janitor, auth, metrics | +| `dally-client` | Rust client and a `Worker` that polls and runs a handler | +| `dally-ui` | Optional web UI, a client of the public API | +| `dally` | The binary: `dally server`, `dally ui` and client subcommands | + +[docs/design.md](docs/design.md) goes into the details and the reasons behind +them. + +## Quickstart + +You need Rust 1.94 or later. dally is not on crates.io yet, so build it from +this repository: + +```sh +git clone https://github.com/platonv/delayed-queue-rs dally +cd dally +``` + +The quickest start uses a local SQLite file and needs nothing else: + +```sh +cargo run --release -p dally -- server --ui +``` + +To use PostgreSQL, start one in Docker and point dally at it. Migrations run +automatically when the server starts: + +```sh +docker run --rm -d --name dally-postgres \ + -e POSTGRES_PASSWORD=dally -p 5432:5432 postgres:17 + +DALLY_STORAGE_URL=postgres://postgres:dally@localhost:5432/postgres \ + cargo run --release -p dally -- server --ui +``` + +dally listens on `127.0.0.1:7070`, and the web UI is at +. To install the binary instead, run +`cargo install --git https://github.com/platonv/delayed-queue-rs dally`. There +is also a [Dockerfile](Dockerfile). + +## Usage + +### Over HTTP + +Schedule a message. The queue is created on first use: + +```sh +curl -X POST localhost:7070/v1/queues/emails/messages \ + -H 'content-type: application/json' \ + -d '{"payload": {"to": "ana@example.com"}, "delay": "10m", "idempotency_key": "welcome-42"}' +``` + +Take it, do the work, and ack it: + +```sh +curl -X POST localhost:7070/v1/queues/emails/poll -d '{"wait": "20s"}' +# {"messages": [{"id": "0193...", "payload": {...}, "lease": "4f1c...", ...}]} + +curl -X POST localhost:7070/v1/messages/0193.../ack -d '{"lease": "4f1c..."}' +``` + +If the worker crashes or does not ack within the queue's visibility timeout +(30 seconds by default), the message is handed out again. If the worker +reports a failure with `/nack`, dally retries it with backoff, up to five +attempts, and then marks it dead. + +The whole API is described in [docs/openapi.json](docs/openapi.json), which a +running server also serves at `/v1/openapi.json`. + +### From Rust + +```toml +[dependencies] +dally-client = { git = "https://github.com/platonv/delayed-queue-rs" } +``` + +```rust +use std::time::Duration; + +use dally_client::{Client, Job, Worker}; +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize)] +struct Welcome { + user_id: u64, +} + +#[tokio::main] +async fn main() -> dally_client::Result<()> { + let client = Client::new("http://127.0.0.1:7070")?; + + // Send the welcome email in ten minutes. Signing up twice schedules it once. + client + .schedule("emails", &Welcome { user_id: 42 }) + .delay(Duration::from_secs(600)) + .idempotency_key("welcome-42") + .send() + .await?; + + // Run jobs from the queue until Ctrl+C. Ok acks, an error or panic nacks. + Worker::new(client, "emails") + .concurrency(8) + .run_until( + async { + let _ = tokio::signal::ctrl_c().await; + }, + |job: Job| async move { + println!("welcome, user {}", job.payload.user_id); + Ok::<(), std::io::Error>(()) + }, + ) + .await +} +``` + +### From the command line + +The `dally` binary is also a client for a running server: + +```sh +dally schedule emails --payload '{"to": "ana@example.com"}' --delay 10m +dally queues ls +dally messages ls --queue emails --status dead +dally dead retry emails +``` + +## Two ways to deliver + +**Pull.** Workers call `POST /v1/queues/{queue}/poll` and ack or nack each +message. Long polling means an idle worker makes one request every 20 seconds +or so, not hundreds. + +**Push.** Give a queue an endpoint and dally POSTs each message to it. A 2xx +response acks the message; anything else is retried. Requests are signed with +HMAC-SHA256 so your app can check they came from dally. + +```toml +[queues.emails.push] +url = "https://app.example.com/jobs/emails" +secret = "..." +``` + +Push is the quickest way to add background jobs to an existing web app: the +job handler is just another endpoint. See [docs/push.md](docs/push.md). + +## Recurring jobs + +```toml +[[queues.reports.cron]] +name = "nightly" +schedule = "0 3 * * *" +timezone = "Europe/Bucharest" +payload = { kind = "nightly-report" } +``` + +Every server schedules each run with the idempotency key +`cron:{name}:{run_at}`, so running several servers creates each run once, +without leader election. + +## Web UI + +```sh +dally server --ui # served at http://127.0.0.1:7070/ui +dally ui --server https://dally.internal # or on its own, for a remote server +``` + +The UI shows queues and their counts, lets you browse messages by status, +inspect payloads and errors, retry dead messages, cancel or run waiting ones, +and pause queues. It talks to the server through the public API like any +other client. When the server has API keys, you log in with yours, and the UI +can do exactly what that key allows. Build without the `ui` feature to leave +it out entirely. + +## Configuration + +Settings come from a TOML file (`dally server --config dally.toml`) and +`DALLY_*` environment variables, which win: + +```toml +listen = "0.0.0.0:7070" + +[storage] +url = "postgres://dally@db/dally" # or sqlite://dally.sqlite, redis://cache:6379 + +[defaults] # for queues created on first use +visibility_timeout = "30s" +max_attempts = 5 +retention = "7d" + +[queues.reports] +max_attempts = 3 +backoff = { base = "1m", cap = "1h" } +``` + +```sh +DALLY_STORAGE_URL=postgres://dally@db/dally dally server +``` + +[.env.example](.env.example) lists the environment variables used in +development. API keys, Prometheus metrics and OpenTelemetry tracing are +covered in [docs/operations.md](docs/operations.md). + +## Guarantees + +dally delivers each message **at least once**. A message can be delivered +twice if a worker finishes the work but its ack is lost, so make handlers safe +to run twice. [docs/semantics.md](docs/semantics.md) explains exactly when this +happens and how to deal with it. + +## Status and roadmap + +Implemented and tested: + +- Queues with per-queue visibility timeout, max attempts, backoff, retention, + and pause/resume +- Delays, priorities, idempotency keys, leases, retries and a dead-letter + state +- PostgreSQL, SQLite and Redis backends behind one conformance suite +- HTTP API with long polling, push delivery with HMAC signatures, and cron +- API keys with client and admin roles, Prometheus metrics, OpenAPI, and + optional OpenTelemetry tracing +- Rust client with a `Worker`, the `dally` CLI, and the web UI + +Not done yet: + +- A first release on crates.io and a published Docker image +- Production use. dally has only been run in tests and local setups so far +- A gRPC transport (the design leaves room for it) +- Client SDKs for other languages. Until then, generate one from the OpenAPI + spec +- API keys managed in the database instead of the config file +- Workflows: job dependencies and chains + +Not planned: exactly-once delivery, pub/sub fan-out, and ordered streams. Use +Kafka or NATS for those. + +## Development + +```sh +docker compose up -d # Postgres on 55432, Redis on 56379 +export DALLY_TEST_POSTGRES_URL=postgres://postgres:dally@localhost:55432/postgres +export DALLY_TEST_REDIS_URL=redis://localhost:56379 +cargo test --workspace --all-features +``` + +Without those variables, the Postgres and Redis tests are skipped. CI runs +`cargo fmt`, `cargo clippy` with warnings as errors, and the full test suite +against real Postgres and Redis. See [CONTRIBUTING.md](CONTRIBUTING.md). + +## Documentation + +- [Design](docs/design.md): how dally works and why +- [Delivery semantics](docs/semantics.md) +- [Push delivery](docs/push.md) +- [Running in production](docs/operations.md): storage, API keys, metrics, tracing +- [SQLite](docs/backends/sqlite.md) and [Redis](docs/backends/redis.md) backend notes +- [Changelog](CHANGELOG.md) + +## License + +Licensed under either of [Apache License 2.0](LICENSE-APACHE) or +[MIT license](LICENSE-MIT), at your option. + +Unless you explicitly state otherwise, any contribution you submit for +inclusion in dally shall be dual licensed as above, without any additional +terms or conditions. diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..fc0fc56 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,20 @@ +# Databases for running the test suite locally: +# +# docker compose up -d +# export DALLY_TEST_POSTGRES_URL=postgres://postgres:dally@localhost:55432/postgres +# export DALLY_TEST_REDIS_URL=redis://localhost:56379 +# cargo test --workspace --all-features + +services: + postgres: + image: postgres:17 + environment: + POSTGRES_PASSWORD: dally + ports: + - "55432:5432" + + redis: + image: redis:8 + command: ["redis-server", "--appendonly", "yes"] + ports: + - "56379:6379" diff --git a/crates/dally-client/Cargo.toml b/crates/dally-client/Cargo.toml new file mode 100644 index 0000000..579779a --- /dev/null +++ b/crates/dally-client/Cargo.toml @@ -0,0 +1,35 @@ +[package] +name = "dally-client" +description = "Rust client and worker for the dally job queue" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true +keywords = ["queue", "jobs", "background", "worker", "scheduler"] +categories = ["asynchronous", "web-programming::http-client"] + +[dependencies] +chrono.workspace = true +# No backend features: the client only needs the wire types. +dally-core.workspace = true +humantime-serde.workspace = true +reqwest = { workspace = true, features = ["rustls", "query"] } +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true +tokio = { workspace = true, features = ["rt"] } +tracing.workspace = true + +[dev-dependencies] +axum.workspace = true +dally-core = { workspace = true, features = ["postgres"] } +dally-server.workspace = true +sqlx = { workspace = true, features = ["postgres"] } +tokio = { workspace = true, features = ["full"] } +tracing-subscriber.workspace = true +uuid.workspace = true + +[lints] +workspace = true diff --git a/crates/dally-client/src/client.rs b/crates/dally-client/src/client.rs new file mode 100644 index 0000000..f7c0458 --- /dev/null +++ b/crates/dally-client/src/client.rs @@ -0,0 +1,516 @@ +//! The HTTP client. + +use std::fmt; +use std::sync::Arc; +use std::time::Duration; + +use dally_core::{ + LeaseToken, Leased, Message, MessageFilter, MessageId, NackRequest, Page, Queue, QueueSettings, + QueueSummary, RunAt, ScheduleRequest, Scheduled, +}; +use reqwest::{Method, RequestBuilder, Response, StatusCode, Url}; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; + +use crate::error::{Error, Result}; +use crate::schedule::ScheduleBuilder; + +/// How long a request may take unless [`ClientBuilder::timeout`] says +/// otherwise. +const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30); + +/// A client for the dally HTTP API. +/// +/// Cloning is cheap and clones share one connection pool, so create one client +/// and pass clones around. +/// +/// ```no_run +/// # async fn example() -> dally_client::Result<()> { +/// let client = dally_client::Client::builder("https://dally.internal") +/// .api_key("secret") +/// .build()?; +/// let queues = client.list_queues().await?; +/// # Ok(()) +/// # } +/// ``` +#[derive(Clone)] +pub struct Client { + inner: Arc, +} + +struct Inner { + http: reqwest::Client, + base: Url, + api_key: Option, + timeout: Duration, +} + +impl fmt::Debug for Client { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // The API key is left out on purpose: clients end up in logs. + f.debug_struct("Client") + .field("base", &self.inner.base.as_str()) + .field("timeout", &self.inner.timeout) + .finish_non_exhaustive() + } +} + +/// Configures a [`Client`]. Created with [`Client::builder`]. +#[derive(Debug)] +pub struct ClientBuilder { + base_url: String, + api_key: Option, + timeout: Duration, + http: Option, +} + +impl ClientBuilder { + /// Sends `Authorization: Bearer ` with every request. + pub fn api_key(mut self, key: impl Into) -> Self { + self.api_key = Some(key.into()); + self + } + + /// How long a request may take before it fails with + /// [`Error::Transport`]. Defaults to 30 seconds. + /// + /// Long polls get their wait time on top of this, so a poll that waits 20 + /// seconds for messages does not time out early. + pub fn timeout(mut self, timeout: Duration) -> Self { + self.timeout = timeout; + self + } + + /// Uses this `reqwest` client, for example to share a connection pool or + /// to configure proxies and TLS roots. + pub fn http_client(mut self, http: reqwest::Client) -> Self { + self.http = Some(http); + self + } + + /// Checks the base URL and creates the client. + pub fn build(self) -> Result { + let base = parse_base_url(&self.base_url)?; + let http = match self.http { + Some(http) => http, + None => reqwest::Client::builder() + .build() + .map_err(Error::Transport)?, + }; + Ok(Client { + inner: Arc::new(Inner { + http, + base, + api_key: self.api_key, + timeout: self.timeout, + }), + }) + } +} + +fn parse_base_url(url: &str) -> Result { + let invalid = |reason: &str| Error::InvalidUrl { + url: url.to_owned(), + reason: reason.to_owned(), + }; + let parsed = Url::parse(url).map_err(|err| invalid(&err.to_string()))?; + if !matches!(parsed.scheme(), "http" | "https") { + return Err(invalid("the scheme must be http or https")); + } + if parsed.cannot_be_a_base() { + return Err(invalid("the URL cannot have paths appended to it")); + } + Ok(parsed) +} + +impl Client { + /// A client for the server at `base_url`, such as + /// `http://127.0.0.1:7070`, with default settings. + /// + /// The URL may include a path prefix if dally is mounted below the root, + /// as in `https://example.com/dally`. + pub fn new(base_url: impl Into) -> Result { + Self::builder(base_url).build() + } + + /// Starts configuring a client for the server at `base_url`. + pub fn builder(base_url: impl Into) -> ClientBuilder { + ClientBuilder { + base_url: base_url.into(), + api_key: None, + timeout: DEFAULT_TIMEOUT, + http: None, + } + } + + /// The server's base URL. + pub fn base_url(&self) -> &Url { + &self.inner.base + } + + /// Schedules one message with `payload`, which can be any type that + /// serializes to JSON. Set options on the returned builder, then call + /// [`send`](ScheduleBuilder::send). + /// + /// ```no_run + /// # use std::time::Duration; + /// # #[derive(serde::Serialize)] + /// # struct Welcome { user_id: u64 } + /// # async fn example(client: dally_client::Client) -> dally_client::Result<()> { + /// let scheduled = client + /// .schedule("emails", &Welcome { user_id: 42 }) + /// .delay(Duration::from_secs(600)) + /// .idempotency_key("welcome-42") + /// .send() + /// .await?; + /// println!("scheduled {}", scheduled.message.id); + /// # Ok(()) + /// # } + /// ``` + pub fn schedule<'a, T>(&'a self, queue: &'a str, payload: &T) -> ScheduleBuilder<'a> + where + T: Serialize + ?Sized, + { + ScheduleBuilder::new(self, queue, serde_json::to_value(payload)) + } + + /// Schedules one message described by a full [`ScheduleRequest`]. + /// [`schedule`](Self::schedule) is usually more convenient. + pub async fn schedule_request( + &self, + queue: &str, + request: &ScheduleRequest, + ) -> Result { + let url = self.url(&["v1", "queues", queue, "messages"])?; + let response = self + .execute(self.request(Method::POST, url).json(request)) + .await?; + // The server says whether the message is new through the status code: + // 200 means the idempotency key matched an existing message. + let created = response.status() == StatusCode::CREATED; + let message = read_json(response).await?; + Ok(Scheduled { message, created }) + } + + /// Schedules several messages in one request. The results come back in + /// the same order as the requests. + /// + /// The server accepts at most 100 messages per batch. + pub async fn schedule_batch( + &self, + queue: &str, + requests: &[ScheduleRequest], + ) -> Result> { + #[derive(Deserialize)] + struct Batch { + messages: Vec, + } + + let url = self.url(&["v1", "queues", queue, "messages"])?; + let batch: Batch = self + .send(self.request(Method::POST, url).json(requests)) + .await?; + Ok(batch.messages) + } + + /// Leases up to `limit` due messages from `queue`. If none are due, waits + /// up to `wait` for one to arrive before returning an empty list. The + /// server caps `wait` at 30 seconds and `limit` at 100. + /// + /// Each message must be acked or nacked with its lease before the + /// visibility timeout runs out, or it is handed to another worker. + /// [`Worker`](crate::Worker) does all of this for you. + pub async fn poll(&self, queue: &str, limit: u32, wait: Duration) -> Result> { + #[derive(Serialize)] + struct Body { + limit: u32, + #[serde(with = "humantime_serde")] + wait: Duration, + } + #[derive(Deserialize)] + struct Polled { + messages: Vec, + } + + let url = self.url(&["v1", "queues", queue, "poll"])?; + let request = self + .request(Method::POST, url) + .timeout(self.inner.timeout.saturating_add(wait)) + .json(&Body { limit, wait }); + let polled: Polled = self.send(request).await?; + Ok(polled.messages) + } + + /// Marks a leased message as done. + pub async fn ack(&self, id: MessageId, lease: &LeaseToken) -> Result { + #[derive(Serialize)] + struct Body<'a> { + lease: &'a LeaseToken, + } + + let url = self.url(&["v1", "messages", &id.to_string(), "ack"])?; + self.send(self.request(Method::POST, url).json(&Body { lease })) + .await + } + + /// Reports that an attempt failed. The message is retried after the + /// queue's backoff (or `request.retry_in`), or marked dead if it has no + /// attempts left. + /// + /// ```no_run + /// # use dally_client::NackRequest; + /// # async fn example(client: dally_client::Client, leased: dally_client::Leased) -> dally_client::Result<()> { + /// client + /// .nack( + /// leased.message.id, + /// &NackRequest { + /// lease: leased.lease.clone(), + /// error: Some("SMTP server refused the connection".into()), + /// retry_in: None, + /// }, + /// ) + /// .await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn nack(&self, id: MessageId, request: &NackRequest) -> Result { + let url = self.url(&["v1", "messages", &id.to_string(), "nack"])?; + self.send(self.request(Method::POST, url).json(request)) + .await + } + + /// Fetches a message by id. + pub async fn get_message(&self, id: MessageId) -> Result { + let url = self.url(&["v1", "messages", &id.to_string()])?; + self.send(self.request(Method::GET, url)).await + } + + /// Changes when a scheduled message runs. Only messages that are still + /// `scheduled` can be rescheduled. + pub async fn reschedule(&self, id: MessageId, run_at: RunAt) -> Result { + #[derive(Serialize)] + struct Body { + #[serde(with = "humantime_serde", skip_serializing_if = "Option::is_none")] + delay: Option, + #[serde(skip_serializing_if = "Option::is_none")] + run_at: Option>, + } + + let body = match run_at { + RunAt::Now => Body { + delay: None, + run_at: None, + }, + RunAt::After(delay) => Body { + delay: Some(delay), + run_at: None, + }, + RunAt::At(at) => Body { + delay: None, + run_at: Some(at), + }, + }; + let url = self.url(&["v1", "messages", &id.to_string()])?; + self.send(self.request(Method::PATCH, url).json(&body)) + .await + } + + /// Cancels a scheduled message so it never runs. Messages that are + /// already running or finished cannot be cancelled. + pub async fn cancel(&self, id: MessageId) -> Result { + let url = self.url(&["v1", "messages", &id.to_string()])?; + self.send(self.request(Method::DELETE, url)).await + } + + /// Lists messages, newest first. Pass the returned page's `next` as + /// `filter.before` to get the following page. A `limit` of 0 means the + /// server's default page size. + pub async fn list_messages(&self, filter: &MessageFilter) -> Result> { + #[derive(Serialize)] + struct Params<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + queue: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + status: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + before: Option, + #[serde(skip_serializing_if = "Option::is_none")] + limit: Option, + } + + let params = Params { + queue: filter.queue.as_ref().map(|queue| queue.as_str()), + status: filter.status.as_ref().map(|status| status.as_str()), + before: filter.before, + limit: (filter.limit > 0).then_some(filter.limit), + }; + let url = self.url(&["v1", "messages"])?; + self.send(self.request(Method::GET, url).query(¶ms)) + .await + } + + /// Lists every queue with its message counts. + pub async fn list_queues(&self) -> Result> { + #[derive(Deserialize)] + struct QueueList { + queues: Vec, + } + + let url = self.url(&["v1", "queues"])?; + let list: QueueList = self.send(self.request(Method::GET, url)).await?; + Ok(list.queues) + } + + /// Fetches a queue's settings and message counts. + pub async fn get_queue(&self, queue: &str) -> Result { + let url = self.url(&["v1", "queues", queue])?; + self.send(self.request(Method::GET, url)).await + } + + /// Creates a queue or replaces all of its settings. + pub async fn put_queue(&self, queue: &str, settings: &QueueSettings) -> Result { + let url = self.url(&["v1", "queues", queue])?; + self.send(self.request(Method::PUT, url).json(settings)) + .await + } + + /// Stops delivering messages from a queue. It still accepts new ones. + pub async fn pause(&self, queue: &str) -> Result { + let url = self.url(&["v1", "queues", queue, "pause"])?; + self.send(self.request(Method::POST, url)).await + } + + /// Resumes delivery from a paused queue. + pub async fn resume(&self, queue: &str) -> Result { + let url = self.url(&["v1", "queues", queue, "resume"])?; + self.send(self.request(Method::POST, url)).await + } + + /// Moves dead messages back to `scheduled` so they run again with a fresh + /// set of attempts. With `None`, retries every dead message in the queue. + /// Returns how many messages were retried. + pub async fn retry_dead(&self, queue: &str, ids: Option<&[MessageId]>) -> Result { + #[derive(Serialize)] + struct Body<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + ids: Option<&'a [MessageId]>, + } + #[derive(Deserialize)] + struct Retried { + retried: u64, + } + + let url = self.url(&["v1", "queues", queue, "dead", "retry"])?; + let retried: Retried = self + .send(self.request(Method::POST, url).json(&Body { ids })) + .await?; + Ok(retried.retried) + } + + /// Succeeds if the server process is up. + pub async fn health(&self) -> Result<()> { + let url = self.url(&["healthz"])?; + self.execute(self.request(Method::GET, url)).await?; + Ok(()) + } + + /// Succeeds if the server is up and can reach its storage. + pub async fn ready(&self) -> Result<()> { + let url = self.url(&["readyz"])?; + self.execute(self.request(Method::GET, url)).await?; + Ok(()) + } + + /// The base URL with `segments` appended. Each segment is percent-encoded, + /// so a queue name can never escape its place in the path. + fn url(&self, segments: &[&str]) -> Result { + let mut url = self.inner.base.clone(); + url.path_segments_mut() + .map_err(|()| Error::InvalidUrl { + url: self.inner.base.to_string(), + reason: "the URL cannot have paths appended to it".to_owned(), + })? + .pop_if_empty() + .extend(segments); + Ok(url) + } + + fn request(&self, method: Method, url: Url) -> RequestBuilder { + let request = self + .inner + .http + .request(method, url) + .timeout(self.inner.timeout); + match &self.inner.api_key { + Some(key) => request.bearer_auth(key), + None => request, + } + } + + /// Sends a request and parses its JSON response. + async fn send(&self, request: RequestBuilder) -> Result { + read_json(self.execute(request).await?).await + } + + /// Sends a request and turns error statuses into [`Error`]s. + async fn execute(&self, request: RequestBuilder) -> Result { + let response = request.send().await.map_err(Error::Transport)?; + let status = response.status(); + if status.is_success() { + return Ok(response); + } + let body = response.bytes().await.map_err(Error::Transport)?; + Err(Error::from_body(status, &body)) + } +} + +async fn read_json(response: Response) -> Result { + let body = response.bytes().await.map_err(Error::Transport)?; + serde_json::from_slice(&body).map_err(Error::Json) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn path(base: &str, segments: &[&str]) -> String { + let client = Client::new(base).expect("valid base URL"); + client.url(segments).expect("url").to_string() + } + + #[test] + fn appends_paths_to_the_base_url() { + assert_eq!( + path("http://localhost:7070", &["v1", "queues"]), + "http://localhost:7070/v1/queues" + ); + assert_eq!( + path("https://example.com/dally/", &["v1", "queues"]), + "https://example.com/dally/v1/queues" + ); + } + + #[test] + fn encodes_path_segments() { + assert_eq!( + path("http://localhost", &["v1", "queues", "../x?y"]), + "http://localhost/v1/queues/..%2Fx%3Fy" + ); + } + + #[test] + fn rejects_unusable_base_urls() { + assert!(Client::new("localhost:7070").is_err()); + assert!(Client::new("ftp://localhost").is_err()); + assert!(Client::new("not a url").is_err()); + } + + #[test] + fn debug_hides_the_api_key() { + let client = Client::builder("http://localhost") + .api_key("hunter2") + .build() + .expect("valid client"); + assert!(!format!("{client:?}").contains("hunter2")); + } +} diff --git a/crates/dally-client/src/error.rs b/crates/dally-client/src/error.rs new file mode 100644 index 0000000..5cbe051 --- /dev/null +++ b/crates/dally-client/src/error.rs @@ -0,0 +1,188 @@ +//! The error type returned by [`Client`](crate::Client) and +//! [`Worker`](crate::Worker). + +use reqwest::StatusCode; +use serde::Deserialize; + +/// Shorthand for results in dally-client. +pub type Result = std::result::Result; + +/// Everything that can go wrong when talking to a dally server. +/// +/// [`Error::Api`] means the server understood the request and refused it, so +/// retrying the same request will not help. The other variants are problems +/// on the way there and back. [`Error::is_retryable`] tells the two apart. +#[derive(Debug, thiserror::Error)] +#[non_exhaustive] +pub enum Error { + /// The server rejected the request with one of its documented errors. + #[error("{message} ({code})")] + Api { + /// The HTTP status of the response. + status: StatusCode, + /// A stable, machine-readable code such as `message_not_found` or + /// `lease_mismatch`. + code: String, + /// A description meant for people. It may change between versions. + message: String, + }, + + /// The response had an error status but not dally's error format. This + /// usually comes from something between the client and dally, such as a + /// proxy or load balancer. + #[error("unexpected response with status {status}: {body}")] + UnexpectedResponse { + /// The HTTP status of the response. + status: StatusCode, + /// The start of the response body. + body: String, + }, + + /// The request could not be sent, timed out, or its response could not be + /// read. + #[error("request failed: {0}")] + Transport(#[source] reqwest::Error), + + /// A payload could not be serialized, or a response body was not the JSON + /// the client expected. + #[error("invalid JSON: {0}")] + Json(#[source] serde_json::Error), + + /// The base URL given to [`Client::new`](crate::Client::new) cannot be + /// used. + #[error("invalid server URL {url:?}: {reason}")] + InvalidUrl { + /// The URL as given. + url: String, + /// Why it was rejected. + reason: String, + }, +} + +impl Error { + /// The HTTP status of the response, if the server answered. + pub fn status(&self) -> Option { + match self { + Error::Api { status, .. } | Error::UnexpectedResponse { status, .. } => Some(*status), + Error::Transport(err) => err.status(), + Error::Json(_) | Error::InvalidUrl { .. } => None, + } + } + + /// The server's error code, such as `message_not_found`, for + /// [`Error::Api`] errors. + pub fn code(&self) -> Option<&str> { + match self { + Error::Api { code, .. } => Some(code), + _ => None, + } + } + + /// The message or queue does not exist. A message may also have been + /// pruned after its queue's retention period. + pub fn is_not_found(&self) -> bool { + self.status() == Some(StatusCode::NOT_FOUND) + } + + /// The lease no longer matches: it expired and the message went to another + /// worker, or the message was already acked or nacked. + pub fn is_lease_mismatch(&self) -> bool { + self.code() == Some("lease_mismatch") + } + + /// The message is not in a status that allows the operation, for example + /// cancelling a message that is already running. + pub fn is_invalid_status(&self) -> bool { + self.code() == Some("invalid_status") + } + + /// The request was malformed, for example an invalid queue name. + pub fn is_invalid_input(&self) -> bool { + self.code() == Some("invalid_input") + } + + /// The request might succeed if sent again later: the server could not be + /// reached, timed out, or reported a temporary problem such as storage + /// being unavailable. + pub fn is_retryable(&self) -> bool { + match self { + Error::Transport(_) => true, + Error::Api { status, .. } | Error::UnexpectedResponse { status, .. } => { + status.is_server_error() + || *status == StatusCode::TOO_MANY_REQUESTS + || *status == StatusCode::REQUEST_TIMEOUT + } + Error::Json(_) | Error::InvalidUrl { .. } => false, + } + } + + /// Turns an error response into an [`Error`], keeping the server's code + /// and message when the body has dally's error format. + pub(crate) fn from_body(status: StatusCode, body: &[u8]) -> Self { + #[derive(Deserialize)] + struct Envelope { + error: Body, + } + #[derive(Deserialize)] + struct Body { + code: String, + message: String, + } + + match serde_json::from_slice::(body) { + Ok(Envelope { error }) => Error::Api { + status, + code: error.code, + message: error.message, + }, + Err(_) => Error::UnexpectedResponse { + status, + body: truncate(String::from_utf8_lossy(body).trim(), MAX_BODY_IN_ERROR), + }, + } + } +} + +/// Enough of an unexpected body to recognise it, without pasting a whole +/// HTML error page into a log line. +const MAX_BODY_IN_ERROR: usize = 512; + +fn truncate(text: &str, max: usize) -> String { + if text.len() <= max { + return text.to_owned(); + } + let end = (0..=max) + .rev() + .find(|&i| text.is_char_boundary(i)) + .unwrap_or(0); + format!("{}...", &text[..end]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_api_errors() { + let body = br#"{"error": {"code": "lease_mismatch", "message": "not yours"}}"#; + let err = Error::from_body(StatusCode::CONFLICT, body); + assert!(err.is_lease_mismatch()); + assert!(!err.is_not_found()); + assert!(!err.is_retryable()); + assert_eq!(err.to_string(), "not yours (lease_mismatch)"); + } + + #[test] + fn keeps_other_bodies_as_unexpected() { + let err = Error::from_body(StatusCode::BAD_GATEWAY, b"bad gateway"); + assert!(matches!(err, Error::UnexpectedResponse { .. })); + assert!(err.is_retryable()); + assert_eq!(err.code(), None); + } + + #[test] + fn truncates_on_char_boundaries() { + assert_eq!(truncate("short", 10), "short"); + assert_eq!(truncate("ăăă", 3), "ă..."); + } +} diff --git a/crates/dally-client/src/lib.rs b/crates/dally-client/src/lib.rs new file mode 100644 index 0000000..5676702 --- /dev/null +++ b/crates/dally-client/src/lib.rs @@ -0,0 +1,95 @@ +//! A Rust client for [dally](https://github.com/platonv/dally), a job queue +//! server: schedule jobs from your app, and run them in workers. +//! +//! - [`Client`] covers the whole HTTP API: scheduling, polling, inspecting +//! and managing messages and queues. +//! - [`Worker`] polls a queue and runs an async handler for each message, with +//! bounded concurrency, retries through the server, and graceful shutdown. +//! +//! # Quickstart +//! +//! Start a server with `dally server`, then schedule a job from your app: +//! +//! ```no_run +//! use std::time::Duration; +//! +//! use dally_client::Client; +//! use serde::{Deserialize, Serialize}; +//! +//! #[derive(Serialize, Deserialize)] +//! struct Welcome { +//! user_id: u64, +//! } +//! +//! # async fn example() -> dally_client::Result<()> { +//! let client = Client::new("http://127.0.0.1:7070")?; +//! +//! // Send the welcome email in ten minutes. Signing up twice schedules it once. +//! client +//! .schedule("emails", &Welcome { user_id: 42 }) +//! .delay(Duration::from_secs(600)) +//! .idempotency_key("welcome-42") +//! .send() +//! .await?; +//! # Ok(()) +//! # } +//! ``` +//! +//! And run it in a worker, in the same process or another one: +//! +//! ```no_run +//! use dally_client::{Client, Job, Worker}; +//! # #[derive(serde::Deserialize)] +//! # struct Welcome { user_id: u64 } +//! +//! async fn send_welcome(user_id: u64) -> Result<(), std::io::Error> { +//! println!("welcome, user {user_id}"); +//! Ok(()) +//! } +//! +//! # async fn example() -> dally_client::Result<()> { +//! let client = Client::new("http://127.0.0.1:7070")?; +//! Worker::new(client, "emails") +//! .concurrency(8) +//! .run_until( +//! async { +//! let _ = tokio::signal::ctrl_c().await; +//! }, +//! |job: Job| async move { send_welcome(job.payload.user_id).await }, +//! ) +//! .await?; +//! # Ok(()) +//! # } +//! ``` +//! +//! When the handler returns `Ok`, the message is acked. When it returns an +//! error or panics, the message is nacked and the server retries it with the +//! queue's backoff, until it runs out of attempts and is marked dead. +//! +//! # Delivery guarantees +//! +//! dally delivers every message **at least once**. A worker can crash after +//! doing the work but before acking it, and then the message runs again. +//! Write handlers so that running them twice is harmless, for example by +//! recording [`Job::id`] next to the work they do and skipping ids already +//! recorded. + +mod client; +mod error; +mod schedule; +mod worker; + +pub use client::{Client, ClientBuilder}; +pub use error::{Error, Result}; +pub use schedule::ScheduleBuilder; +pub use worker::{Job, Worker}; + +pub use dally_core::{ + Backoff, LeaseToken, Leased, Message, MessageFilter, MessageId, NackRequest, Page, + PushSettings, Queue, QueueName, QueueSettings, QueueStats, QueueSummary, RunAt, + ScheduleRequest, Scheduled, Status, +}; + +/// The HTTP client library, re-exported so that a custom client passed to +/// [`ClientBuilder::http_client`] comes from a compatible version. +pub use reqwest; diff --git a/crates/dally-client/src/schedule.rs b/crates/dally-client/src/schedule.rs new file mode 100644 index 0000000..72ac81e --- /dev/null +++ b/crates/dally-client/src/schedule.rs @@ -0,0 +1,93 @@ +//! The builder returned by [`Client::schedule`]. + +use std::time::Duration; + +use chrono::{DateTime, Utc}; +use dally_core::{ScheduleRequest, Scheduled}; + +use crate::client::Client; +use crate::error::{Error, Result}; + +/// A message about to be scheduled. Created by [`Client::schedule`]; nothing +/// is sent until [`send`](Self::send). +/// +/// Without [`delay`](Self::delay) or [`run_at`](Self::run_at) the message is +/// due right away. +#[derive(Debug)] +#[must_use = "nothing is scheduled until you call .send().await"] +pub struct ScheduleBuilder<'a> { + client: &'a Client, + queue: &'a str, + // Serialization errors are kept until `send` so the builder chain stays + // free of `?`. + payload: serde_json::Result, + request: ScheduleRequest, +} + +impl<'a> ScheduleBuilder<'a> { + pub(crate) fn new( + client: &'a Client, + queue: &'a str, + payload: serde_json::Result, + ) -> Self { + Self { + client, + queue, + payload, + request: ScheduleRequest::default(), + } + } + + /// Runs the message after this delay, measured by the server's storage + /// clock. Replaces an earlier [`run_at`](Self::run_at). + pub fn delay(mut self, delay: Duration) -> Self { + self.request.delay = Some(delay); + self.request.run_at = None; + self + } + + /// Runs the message at this time. Replaces an earlier + /// [`delay`](Self::delay). + pub fn run_at(mut self, at: DateTime) -> Self { + self.request.run_at = Some(at); + self.request.delay = None; + self + } + + /// Higher priorities are delivered first. Defaults to 0. + pub fn priority(mut self, priority: i32) -> Self { + self.request.priority = priority; + self + } + + /// Scheduling again with the same key in the same queue returns the + /// existing message instead of creating a new one, with + /// [`Scheduled::created`] set to false. Keys are remembered until the + /// message is pruned after the queue's retention period. + pub fn idempotency_key(mut self, key: impl Into) -> Self { + self.request.idempotency_key = Some(key.into()); + self + } + + /// Overrides the queue's `max_attempts` for this message. + pub fn max_attempts(mut self, attempts: u32) -> Self { + self.request.max_attempts = Some(attempts); + self + } + + /// Overrides the queue's `visibility_timeout` for this message: how long a + /// worker has to finish an attempt before the message is handed out again. + pub fn visibility_timeout(mut self, timeout: Duration) -> Self { + self.request.visibility_timeout = Some(timeout); + self + } + + /// Schedules the message. + pub async fn send(self) -> Result { + let request = ScheduleRequest { + payload: self.payload.map_err(Error::Json)?, + ..self.request + }; + self.client.schedule_request(self.queue, &request).await + } +} diff --git a/crates/dally-client/src/worker.rs b/crates/dally-client/src/worker.rs new file mode 100644 index 0000000..8b16634 --- /dev/null +++ b/crates/dally-client/src/worker.rs @@ -0,0 +1,409 @@ +//! Running a handler for every message in a queue. + +use std::any::Any; +use std::fmt::Display; +use std::future::Future; +use std::sync::Arc; +use std::time::Duration; + +use dally_core::service::limits::MAX_POLL; +use dally_core::{LeaseToken, Leased, Message, MessageId, NackRequest}; +use serde::de::DeserializeOwned; +use tokio::task::JoinSet; +use tracing::Instrument; + +use crate::client::Client; +use crate::error::Result; + +/// One message, handed to a [`Worker`]'s handler with its payload already +/// deserialized. +#[derive(Debug, Clone)] +pub struct Job { + /// The message's payload. + pub payload: T, + message: Message, +} + +impl Job { + /// The message's id. Since delivery is at least once, this is a good key + /// for remembering that a job is already done. + pub fn id(&self) -> MessageId { + self.message.id + } + + /// Which attempt this is, counting from 1. + pub fn attempt(&self) -> u32 { + self.message.attempts + } + + /// How many attempts the message gets before it is marked dead. + pub fn max_attempts(&self) -> u32 { + self.message.max_attempts + } + + /// True if a failure now marks the message dead instead of retrying it. + pub fn is_last_attempt(&self) -> bool { + self.attempt() >= self.max_attempts() + } + + /// The full message, including its queue, priority and the error from the + /// previous attempt. + pub fn message(&self) -> &Message { + &self.message + } +} + +/// Polls a queue and runs a handler for each message, with bounded +/// concurrency. +/// +/// For each message the worker: +/// +/// - deserializes the payload into the handler's job type, and nacks the +/// message with the serde error if that fails; +/// - runs the handler in its own task, so a panic only fails that message, +/// which is nacked with `handler panicked: ...`; +/// - acks the message when the handler returns `Ok`, and nacks it with the +/// error's `Display` text when it returns `Err`. The server then retries it +/// with the queue's backoff, or marks it dead after the last attempt. +/// +/// ```no_run +/// use dally_client::{Client, Job, Worker}; +/// +/// #[derive(serde::Deserialize)] +/// struct Welcome { +/// user_id: u64, +/// } +/// +/// # async fn send_welcome(_: u64) -> Result<(), std::io::Error> { Ok(()) } +/// # async fn example() -> dally_client::Result<()> { +/// let client = Client::new("http://127.0.0.1:7070")?; +/// Worker::new(client, "emails") +/// .concurrency(8) +/// .run(|job: Job| async move { send_welcome(job.payload.user_id).await }) +/// .await?; +/// # Ok(()) +/// # } +/// ``` +/// +/// # Long jobs +/// +/// The worker does not extend leases. A job that runs longer than its +/// message's visibility timeout (30 seconds by default) is handed to another +/// worker while the first one is still busy, and the first worker's ack then +/// fails. Give queues with long jobs a `visibility_timeout` comfortably above +/// the longest run, either in the queue settings or per message with +/// [`ScheduleBuilder::visibility_timeout`](crate::ScheduleBuilder::visibility_timeout). +/// +/// # Errors from the server +/// +/// When the server cannot be reached or reports a temporary problem, the +/// worker logs a warning and tries again after a delay that doubles from 1 to +/// 30 seconds. Other errors, such as an invalid queue name or a rejected API +/// key, will not fix themselves: the worker stops polling, waits for running +/// jobs, and returns the error. +#[derive(Debug, Clone)] +pub struct Worker { + client: Client, + queue: String, + concurrency: usize, + poll_wait: Duration, +} + +impl Worker { + /// A worker for `queue` that runs one job at a time. + pub fn new(client: Client, queue: impl Into) -> Self { + Self { + client, + queue: queue.into(), + concurrency: 1, + poll_wait: Duration::from_secs(20), + } + } + + /// How many jobs may run at once. Defaults to 1; 0 is treated as 1. + pub fn concurrency(mut self, concurrency: usize) -> Self { + self.concurrency = concurrency.max(1); + self + } + + /// How long each poll waits for a message when the queue is empty. + /// Defaults to 20 seconds; the server caps it at 30. Shorter waits mean + /// more requests to an idle server, not faster delivery: a waiting poll + /// returns as soon as a message is due. + pub fn poll_wait(mut self, wait: Duration) -> Self { + self.poll_wait = wait; + self + } + + /// Runs `handler` for every message until a non-retryable error occurs. + /// Use [`run_until`](Self::run_until) to stop it cleanly. + pub async fn run(self, handler: F) -> Result<()> + where + T: DeserializeOwned + Send + 'static, + F: Fn(Job) -> Fut + Send + Sync + 'static, + Fut: Future> + Send + 'static, + E: Display + 'static, + { + self.run_until(std::future::pending(), handler).await + } + + /// Runs `handler` for every message until `shutdown` resolves, then stops + /// polling and waits for running jobs to finish before returning. + /// + /// A poll still waiting when `shutdown` resolves is abandoned. If the + /// server leased messages to it at that moment, they are delivered again + /// once their visibility timeout runs out. + /// + /// ```no_run + /// # use dally_client::{Client, Job, Worker}; + /// # async fn example(client: Client) -> dally_client::Result<()> { + /// Worker::new(client, "emails") + /// .run_until( + /// async { + /// let _ = tokio::signal::ctrl_c().await; + /// }, + /// |job: Job| async move { + /// println!("got {}", job.payload); + /// Ok::<_, std::io::Error>(()) + /// }, + /// ) + /// .await + /// # } + /// ``` + pub async fn run_until(self, shutdown: S, handler: F) -> Result<()> + where + T: DeserializeOwned + Send + 'static, + F: Fn(Job) -> Fut + Send + Sync + 'static, + Fut: Future> + Send + 'static, + E: Display + 'static, + S: Future, + { + let handler = Arc::new(handler); + let mut in_flight = JoinSet::new(); + let mut backoff = RetryDelay::default(); + let mut shutdown = std::pin::pin!(shutdown); + + let result = loop { + while let Some(finished) = in_flight.try_join_next() { + log_supervisor_failure(finished); + } + + let free = self.concurrency.saturating_sub(in_flight.len()); + if free == 0 { + tokio::select! { + () = &mut shutdown => break Ok(()), + Some(finished) = in_flight.join_next() => log_supervisor_failure(finished), + } + continue; + } + + let limit = u32::try_from(free).map_or(MAX_POLL, |free| free.min(MAX_POLL)); + let polled = tokio::select! { + () = &mut shutdown => break Ok(()), + polled = self.client.poll(&self.queue, limit, self.poll_wait) => polled, + }; + + match polled { + Ok(messages) => { + backoff.reset(); + for leased in messages { + in_flight.spawn(process(self.client.clone(), handler.clone(), leased)); + } + } + Err(err) if err.is_retryable() => { + let delay = backoff.next(); + tracing::warn!( + queue = %self.queue, + error = %err, + retry_in = ?delay, + "polling failed, retrying" + ); + tokio::select! { + () = &mut shutdown => break Ok(()), + () = tokio::time::sleep(delay) => {} + } + } + Err(err) => break Err(err), + } + }; + + if !in_flight.is_empty() { + tracing::info!( + queue = %self.queue, + jobs = in_flight.len(), + "waiting for running jobs" + ); + } + while let Some(finished) = in_flight.join_next().await { + log_supervisor_failure(finished); + } + result + } +} + +/// Runs one message through the handler and reports the outcome. +async fn process(client: Client, handler: Arc, leased: Leased) +where + T: DeserializeOwned + Send + 'static, + F: Fn(Job) -> Fut + Send + Sync + 'static, + Fut: Future> + Send + 'static, + E: Display + 'static, +{ + let Leased { message, lease } = leased; + let id = message.id; + let span = tracing::info_span!( + "job", + queue = %message.queue, + id = %id, + attempt = message.attempts + ); + + let outcome = match serde_json::from_value::(message.payload.clone()) { + Ok(payload) => { + run_handler(handler, Job { payload, message }) + .instrument(span.clone()) + .await + } + Err(err) => Err(format!("invalid payload: {err}")), + }; + report(&client, id, &lease, outcome).instrument(span).await; +} + +/// Runs the handler in its own task, so that a panic is caught as a +/// [`tokio::task::JoinError`] instead of unwinding through the worker. +async fn run_handler(handler: Arc, job: Job) -> Result<(), String> +where + T: Send + 'static, + F: Fn(Job) -> Fut + Send + Sync + 'static, + Fut: Future> + Send + 'static, + E: Display + 'static, +{ + let task = tokio::spawn( + async move { handler(job).await.map_err(|err| err.to_string()) }.in_current_span(), + ); + match task.await { + Ok(result) => result, + Err(err) if err.is_panic() => { + let reason = panic_message(err.into_panic()); + tracing::error!(panic = %reason, "handler panicked"); + Err(format!("handler panicked: {reason}")) + } + // Tasks are only cancelled when the runtime shuts down under us. + Err(_) => Err("handler was cancelled".to_owned()), + } +} + +fn panic_message(payload: Box) -> String { + if let Some(message) = payload.downcast_ref::<&str>() { + (*message).to_owned() + } else if let Some(message) = payload.downcast_ref::() { + message.clone() + } else { + "unknown panic payload".to_owned() + } +} + +/// Acks or nacks the message. A short retry covers network blips, since a lost +/// ack means the job runs again once its lease expires. +async fn report(client: &Client, id: MessageId, lease: &LeaseToken, outcome: Result<(), String>) { + const ATTEMPTS: u32 = 3; + + let mut delay = Duration::from_millis(200); + for attempt in 1..=ATTEMPTS { + let result = match &outcome { + Ok(()) => client.ack(id, lease).await, + Err(error) => { + let nack = NackRequest { + lease: lease.clone(), + error: Some(error.clone()), + retry_in: None, + }; + client.nack(id, &nack).await + } + }; + match result { + Ok(message) => { + tracing::debug!(status = %message.status, "job finished"); + return; + } + Err(err) if err.is_lease_mismatch() => { + tracing::warn!( + "the lease expired before the job finished, so the message may run again; \ + consider a longer visibility_timeout" + ); + return; + } + Err(err) if err.is_retryable() && attempt < ATTEMPTS => { + tracing::debug!(error = %err, "reporting the job outcome failed, retrying"); + tokio::time::sleep(delay).await; + delay *= 2; + } + Err(err) => { + tracing::warn!( + error = %err, + "could not report the job outcome; the message runs again when its lease expires" + ); + return; + } + } + } +} + +/// `process` catches handler panics itself, so a failure here is a bug in the +/// worker. It is logged rather than propagated so other jobs keep running. +fn log_supervisor_failure(result: std::result::Result<(), tokio::task::JoinError>) { + if let Err(err) = result { + tracing::error!(error = %err, "job supervisor failed"); + } +} + +/// The delay between polls after the server could not be reached: 1 second, +/// doubling up to 30. +#[derive(Debug)] +struct RetryDelay { + next: Duration, +} + +impl RetryDelay { + const INITIAL: Duration = Duration::from_secs(1); + const MAX: Duration = Duration::from_secs(30); + + fn next(&mut self) -> Duration { + let delay = self.next; + self.next = (delay * 2).min(Self::MAX); + delay + } + + fn reset(&mut self) { + self.next = Self::INITIAL; + } +} + +impl Default for RetryDelay { + fn default() -> Self { + Self { + next: Self::INITIAL, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn retry_delay_doubles_up_to_the_cap() { + let mut delay = RetryDelay::default(); + let delays: Vec = (0..7).map(|_| delay.next().as_secs()).collect(); + assert_eq!(delays, [1, 2, 4, 8, 16, 30, 30]); + delay.reset(); + assert_eq!(delay.next(), Duration::from_secs(1)); + } + + #[test] + fn panic_messages() { + assert_eq!(panic_message(Box::new("boom")), "boom"); + assert_eq!(panic_message(Box::new(String::from("bang"))), "bang"); + assert_eq!(panic_message(Box::new(42)), "unknown panic payload"); + } +} diff --git a/crates/dally-client/tests/client.rs b/crates/dally-client/tests/client.rs new file mode 100644 index 0000000..8449ef9 --- /dev/null +++ b/crates/dally-client/tests/client.rs @@ -0,0 +1,455 @@ +//! The client against a real server. + +mod common; + +use std::time::Duration; + +use dally_client::{ + Client, Error, MessageFilter, MessageId, NackRequest, QueueName, QueueSettings, RunAt, + ScheduleRequest, Status, +}; +use serde::{Deserialize, Serialize}; +use serde_json::json; + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +struct Welcome { + user_id: u64, +} + +#[tokio::test] +async fn schedule_poll_ack() { + let client = serve_or_skip!(); + + let scheduled = client + .schedule("emails", &Welcome { user_id: 42 }) + .idempotency_key("welcome-42") + .priority(3) + .send() + .await + .expect("schedule"); + assert!(scheduled.created); + assert_eq!(scheduled.message.status, Status::Scheduled); + assert_eq!(scheduled.message.priority, 3); + assert_eq!(scheduled.message.payload, json!({"user_id": 42})); + + let again = client + .schedule("emails", &Welcome { user_id: 0 }) + .idempotency_key("welcome-42") + .send() + .await + .expect("schedule again"); + assert!( + !again.created, + "a repeated key returns the existing message" + ); + assert_eq!(again.message.id, scheduled.message.id); + + let polled = client + .poll("emails", 10, Duration::from_secs(1)) + .await + .expect("poll"); + assert_eq!(polled.len(), 1); + assert_eq!(polled[0].message.id, scheduled.message.id); + assert_eq!(polled[0].message.status, Status::Running); + + let acked = client + .ack(polled[0].message.id, &polled[0].lease) + .await + .expect("ack"); + assert_eq!(acked.status, Status::Succeeded); +} + +#[tokio::test] +async fn schedule_options_reach_the_server() { + let client = serve_or_skip!(); + + let delayed = client + .schedule("emails", &json!({"to": "ana"})) + .delay(Duration::from_secs(3600)) + .max_attempts(2) + .visibility_timeout(Duration::from_secs(90)) + .send() + .await + .expect("schedule delayed"); + assert_eq!(delayed.message.max_attempts, 2); + assert_eq!(delayed.message.visibility_timeout, Duration::from_secs(90)); + assert!(delayed.message.run_at > delayed.message.created_at + chrono::Duration::minutes(59)); + + let at = chrono::Utc::now() + chrono::Duration::days(1); + let timed = client + .schedule("emails", &1) + .delay(Duration::from_secs(5)) + .run_at(at) + .send() + .await + .expect("run_at replaces delay"); + let drift = (timed.message.run_at - at).num_milliseconds().abs(); + assert!(drift < 1000, "run_at should be kept, drift {drift}ms"); + + let nothing_due = client + .poll("emails", 10, Duration::ZERO) + .await + .expect("poll"); + assert!(nothing_due.is_empty()); +} + +#[tokio::test] +async fn schedule_batch_keeps_order() { + let client = serve_or_skip!(); + + let requests = [ + ScheduleRequest::new(json!(1)), + ScheduleRequest { + idempotency_key: Some("two".into()), + ..ScheduleRequest::new(json!(2)) + }, + ]; + let results = client + .schedule_batch("reports", &requests) + .await + .expect("batch"); + assert_eq!(results.len(), 2); + assert!(results.iter().all(|result| result.created)); + assert_eq!(results[0].message.payload, json!(1)); + assert_eq!(results[1].message.payload, json!(2)); + + let again = client + .schedule_batch("reports", &requests[1..]) + .await + .expect("batch again"); + assert!(!again[0].created); +} + +#[tokio::test] +async fn nack_retries_and_dies() { + let client = serve_or_skip!(); + + let id = client + .schedule("emails", &1) + .max_attempts(2) + .send() + .await + .expect("schedule") + .message + .id; + + for expected in [Status::Scheduled, Status::Dead] { + let leased = client + .poll("emails", 1, Duration::from_secs(1)) + .await + .expect("poll") + .pop() + .expect("a due message"); + let nacked = client + .nack( + id, + &NackRequest { + lease: leased.lease, + error: Some("smtp is down".into()), + retry_in: Some(Duration::ZERO), + }, + ) + .await + .expect("nack"); + assert_eq!(nacked.status, expected); + assert_eq!(nacked.last_error.as_deref(), Some("smtp is down")); + } + + assert_eq!( + client.retry_dead("emails", None).await.expect("retry all"), + 1 + ); + let message = client.get_message(id).await.expect("get"); + assert_eq!(message.status, Status::Scheduled); +} + +#[tokio::test] +async fn retry_dead_by_id() { + let client = serve_or_skip!(); + let mut dead = Vec::new(); + for _ in 0..2 { + let id = client + .schedule("jobs", &0) + .max_attempts(1) + .send() + .await + .expect("schedule") + .message + .id; + let leased = client + .poll("jobs", 1, Duration::from_secs(1)) + .await + .expect("poll") + .pop() + .expect("a due message"); + client + .nack( + id, + &NackRequest { + lease: leased.lease, + ..NackRequest::default() + }, + ) + .await + .expect("nack"); + dead.push(id); + } + + let retried = client + .retry_dead("jobs", Some(&dead[..1])) + .await + .expect("retry one"); + assert_eq!(retried, 1); + let still_dead = client.get_message(dead[1]).await.expect("get"); + assert_eq!(still_dead.status, Status::Dead); +} + +#[tokio::test] +async fn reschedule_and_cancel() { + let client = serve_or_skip!(); + let id = client + .schedule("emails", &1) + .delay(Duration::from_secs(3600)) + .send() + .await + .expect("schedule") + .message + .id; + + let later = client + .reschedule(id, RunAt::After(Duration::from_secs(7200))) + .await + .expect("reschedule after"); + assert!(later.run_at > later.created_at + chrono::Duration::minutes(119)); + + let at = chrono::Utc::now() + chrono::Duration::days(2); + let timed = client + .reschedule(id, RunAt::At(at)) + .await + .expect("reschedule at"); + assert!((timed.run_at - at).num_milliseconds().abs() < 1000); + + client + .reschedule(id, RunAt::Now) + .await + .expect("reschedule now"); + let polled = client + .poll("emails", 1, Duration::from_secs(1)) + .await + .expect("poll"); + assert_eq!(polled.len(), 1, "a message rescheduled to now is due"); + + let err = client + .cancel(id) + .await + .expect_err("a running message cannot be cancelled"); + assert!(err.is_invalid_status(), "{err:?}"); + + let other = client + .schedule("emails", &2) + .delay(Duration::from_secs(60)) + .send() + .await + .expect("schedule"); + let cancelled = client.cancel(other.message.id).await.expect("cancel"); + assert_eq!(cancelled.status, Status::Cancelled); +} + +#[tokio::test] +async fn list_messages_filters_and_pages() { + let client = serve_or_skip!(); + for n in 0..3 { + client.schedule("a", &n).send().await.expect("schedule"); + } + let in_b = client + .schedule("b", &"b") + .delay(Duration::from_secs(60)) + .send() + .await + .expect("schedule"); + client.cancel(in_b.message.id).await.expect("cancel"); + + let all = client + .list_messages(&MessageFilter::default()) + .await + .expect("list all"); + assert_eq!(all.items.len(), 4); + + let first = client + .list_messages(&MessageFilter { + queue: Some(QueueName::new("a").expect("valid name")), + limit: 2, + ..MessageFilter::default() + }) + .await + .expect("first page"); + assert_eq!(first.items.len(), 2); + let next = first.next.expect("a second page"); + + let second = client + .list_messages(&MessageFilter { + queue: Some(QueueName::new("a").expect("valid name")), + before: Some(next), + limit: 2, + ..MessageFilter::default() + }) + .await + .expect("second page"); + assert_eq!(second.items.len(), 1); + + let cancelled = client + .list_messages(&MessageFilter { + status: Some(Status::Cancelled), + ..MessageFilter::default() + }) + .await + .expect("list cancelled"); + assert_eq!(cancelled.items.len(), 1); + assert_eq!(cancelled.items[0].id, in_b.message.id); +} + +#[tokio::test] +async fn queues() { + let client = serve_or_skip!(); + + let settings = QueueSettings { + max_attempts: 9, + visibility_timeout: Duration::from_secs(120), + ..QueueSettings::default() + }; + let queue = client.put_queue("billing", &settings).await.expect("put"); + assert_eq!(queue.settings, settings); + + client + .schedule("billing", &1) + .send() + .await + .expect("schedule"); + + let summary = client.get_queue("billing").await.expect("get"); + assert_eq!(summary.queue.settings.max_attempts, 9); + assert_eq!(summary.stats.scheduled, 1); + + let paused = client.pause("billing").await.expect("pause"); + assert!(paused.settings.paused); + let polled = client + .poll("billing", 1, Duration::ZERO) + .await + .expect("poll"); + assert!(polled.is_empty(), "a paused queue delivers nothing"); + + let resumed = client.resume("billing").await.expect("resume"); + assert!(!resumed.settings.paused); + + let queues = client.list_queues().await.expect("list"); + let names: Vec<&str> = queues + .iter() + .map(|summary| summary.queue.name.as_str()) + .collect(); + assert!(names.contains(&"billing"), "{names:?}"); +} + +#[tokio::test] +async fn health() { + let client = serve_or_skip!(); + client.health().await.expect("healthz"); + client.ready().await.expect("readyz"); +} + +#[tokio::test] +async fn errors_carry_the_server_code() { + let client = serve_or_skip!(); + + let missing = MessageId::generate(); + let err = client + .get_message(missing) + .await + .expect_err("no such message"); + assert!(err.is_not_found()); + assert_eq!(err.code(), Some("message_not_found")); + assert_eq!( + err.status(), + Some(dally_client::reqwest::StatusCode::NOT_FOUND) + ); + assert!(!err.is_retryable()); + + let err = client.get_queue("nope").await.expect_err("no such queue"); + assert!(err.is_not_found()); + assert_eq!(err.code(), Some("queue_not_found")); + + let scheduled = client + .schedule("emails", &1) + .send() + .await + .expect("schedule"); + let wrong = dally_client::LeaseToken::from("not-the-lease".to_owned()); + let err = client + .ack(scheduled.message.id, &wrong) + .await + .expect_err("wrong lease"); + assert!(err.is_lease_mismatch(), "{err:?}"); + assert_eq!( + err.status(), + Some(dally_client::reqwest::StatusCode::CONFLICT) + ); + + let err = client + .schedule("bad name", &1) + .send() + .await + .expect_err("invalid queue name"); + assert!(err.is_invalid_input(), "{err:?}"); + assert!(matches!(err, Error::Api { .. })); +} + +#[tokio::test] +async fn transport_errors_are_retryable() { + // Nothing listens on port 9 (discard) on a test machine. + let client = Client::builder("http://127.0.0.1:9") + .timeout(Duration::from_secs(2)) + .build() + .expect("client"); + let err = client.health().await.expect_err("nothing listens there"); + assert!(matches!(err, Error::Transport(_)), "{err:?}"); + assert!(err.is_retryable()); +} + +#[tokio::test] +async fn sends_the_api_key() { + use axum::http::HeaderMap; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind"); + let address = listener.local_addr().expect("local addr"); + let app = axum::Router::new().route( + "/healthz", + axum::routing::get(|headers: HeaderMap| async move { + let auth = headers + .get("authorization") + .and_then(|value| value.to_str().ok()) + .unwrap_or_default() + .to_owned(); + if auth == "Bearer s3cret" { + Ok("ok") + } else { + Err(( + axum::http::StatusCode::UNAUTHORIZED, + axum::Json(json!({"error": {"code": "unauthorized", "message": auth}})), + )) + } + }), + ); + tokio::spawn(async move { axum::serve(listener, app).await.expect("serve") }); + + let base = format!("http://{address}"); + let with_key = Client::builder(&base) + .api_key("s3cret") + .build() + .expect("client"); + with_key.health().await.expect("the key is sent"); + + let without = Client::new(&base).expect("client"); + let err = without.health().await.expect_err("no key"); + assert_eq!(err.code(), Some("unauthorized")); +} diff --git a/crates/dally-client/tests/common/mod.rs b/crates/dally-client/tests/common/mod.rs new file mode 100644 index 0000000..0817d79 --- /dev/null +++ b/crates/dally-client/tests/common/mod.rs @@ -0,0 +1,84 @@ +//! A real server for the integration tests: the dally server router on a random +//! port, backed by PostgreSQL with a fresh schema per test. The tests need +//! `DALLY_TEST_POSTGRES_URL` and skip themselves without it. + +// Each test binary compiles this module separately and uses only part of it. +#![allow(dead_code)] + +use std::sync::Arc; +use std::time::Duration; + +use dally_client::{Client, Message, MessageId, Status}; +use dally_core::storage::postgres::PostgresStorage; +use dally_core::{ConnectOptions, QueueSettings, Service}; +use sqlx::Connection; +use sqlx::postgres::{PgConnectOptions, PgConnection}; + +/// Serves the API and returns a client for it, or `None` when no test +/// database is configured. +pub async fn serve() -> Option { + let url = std::env::var("DALLY_TEST_POSTGRES_URL").ok()?; + let options: PgConnectOptions = url.parse().expect("valid DALLY_TEST_POSTGRES_URL"); + + let schema = format!("dally_test_{}", uuid::Uuid::new_v4().simple()); + let mut admin = PgConnection::connect_with(&options).await.expect("connect"); + sqlx::raw_sql(sqlx::AssertSqlSafe(format!("CREATE SCHEMA {schema}"))) + .execute(&mut admin) + .await + .expect("create schema"); + + let options = options.options([("search_path", schema.as_str())]); + let storage = PostgresStorage::connect_with(options, &ConnectOptions::default()) + .await + .expect("connect storage"); + let service = Service::new(Arc::new(storage), QueueSettings::default()); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind"); + let address = listener.local_addr().expect("local addr"); + tokio::spawn(async move { + axum::serve( + listener, + dally_server::Server::new(service, dally_server::Config::default()) + .expect("server") + .router(), + ) + .await + .expect("serve"); + }); + Some(Client::new(format!("http://{address}")).expect("client")) +} + +/// Starts a test server, or returns from the test when no database is +/// configured. +#[macro_export] +macro_rules! serve_or_skip { + () => { + match common::serve().await { + Some(client) => client, + None => { + eprintln!("skipping: DALLY_TEST_POSTGRES_URL is not set"); + return; + } + } + }; +} + +/// Waits until the message reaches `status`, failing the test after a few +/// seconds. +pub async fn wait_for_status(client: &Client, id: MessageId, status: Status) -> Message { + let deadline = tokio::time::Instant::now() + Duration::from_secs(10); + loop { + let message = client.get_message(id).await.expect("get message"); + if message.status == status { + return message; + } + assert!( + tokio::time::Instant::now() < deadline, + "message {id} stayed {} instead of becoming {status}", + message.status + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } +} diff --git a/crates/dally-client/tests/worker.rs b/crates/dally-client/tests/worker.rs new file mode 100644 index 0000000..d5166c9 --- /dev/null +++ b/crates/dally-client/tests/worker.rs @@ -0,0 +1,249 @@ +//! The worker against a real server. + +mod common; + +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Duration; + +use dally_client::{Client, Job, MessageId, Status, Worker}; +use serde::{Deserialize, Serialize}; +use tokio::sync::{mpsc, oneshot}; +use tokio::task::JoinHandle; + +use common::wait_for_status; + +#[derive(Debug, Serialize, Deserialize)] +struct Task { + fail: bool, + panic: bool, +} + +impl Task { + const OK: Task = Task { + fail: false, + panic: false, + }; +} + +/// Starts a worker in the background. Dropping or sending on the returned +/// sender stops it; the handle resolves when it has shut down. +fn start( + worker: Worker, + handler: F, +) -> (oneshot::Sender<()>, JoinHandle>) +where + T: serde::de::DeserializeOwned + Send + 'static, + F: Fn(Job) -> Fut + Send + Sync + 'static, + Fut: Future> + Send + 'static, +{ + let (stop, stopped) = oneshot::channel::<()>(); + let handle = tokio::spawn(worker.run_until( + async { + let _ = stopped.await; + }, + handler, + )); + (stop, handle) +} + +async fn schedule(client: &Client, queue: &str, task: &Task) -> MessageId { + client + .schedule(queue, task) + .max_attempts(1) + .send() + .await + .expect("schedule") + .message + .id +} + +async fn handle(job: Job) -> Result<(), String> { + if job.payload.panic { + panic!("boom"); + } + if job.payload.fail { + return Err(format!( + "attempt {} of {} failed", + job.attempt(), + job.max_attempts() + )); + } + Ok(()) +} + +#[tokio::test] +async fn acks_and_nacks() { + let client = serve_or_skip!(); + let ok = schedule(&client, "tasks", &Task::OK).await; + let failing = schedule( + &client, + "tasks", + &Task { + fail: true, + panic: false, + }, + ) + .await; + let bad_payload = client + .schedule("tasks", &"not a task") + .max_attempts(1) + .send() + .await + .expect("schedule") + .message + .id; + + let worker = Worker::new(client.clone(), "tasks") + .concurrency(2) + .poll_wait(Duration::from_secs(1)); + let (stop, handle) = start(worker, handle); + + wait_for_status(&client, ok, Status::Succeeded).await; + let failed = wait_for_status(&client, failing, Status::Dead).await; + assert_eq!(failed.last_error.as_deref(), Some("attempt 1 of 1 failed")); + let invalid = wait_for_status(&client, bad_payload, Status::Dead).await; + let error = invalid.last_error.unwrap_or_default(); + assert!(error.starts_with("invalid payload: "), "{error}"); + + let _ = stop.send(()); + handle.await.expect("join").expect("worker"); +} + +#[tokio::test] +async fn survives_a_panicking_handler() { + let client = serve_or_skip!(); + let panicking = schedule( + &client, + "tasks", + &Task { + fail: false, + panic: true, + }, + ) + .await; + + let worker = Worker::new(client.clone(), "tasks").poll_wait(Duration::from_secs(1)); + let (stop, handle) = start(worker, handle); + + let dead = wait_for_status(&client, panicking, Status::Dead).await; + assert_eq!(dead.last_error.as_deref(), Some("handler panicked: boom")); + + let after = schedule(&client, "tasks", &Task::OK).await; + wait_for_status(&client, after, Status::Succeeded).await; + + let _ = stop.send(()); + handle.await.expect("join").expect("worker"); +} + +#[tokio::test] +async fn respects_concurrency() { + let client = serve_or_skip!(); + for _ in 0..12 { + schedule(&client, "tasks", &Task::OK).await; + } + + let running = Arc::new(AtomicUsize::new(0)); + let most = Arc::new(AtomicUsize::new(0)); + let done = Arc::new(AtomicUsize::new(0)); + let (tx, mut finished) = mpsc::unbounded_channel(); + + let worker = Worker::new(client.clone(), "tasks") + .concurrency(4) + .poll_wait(Duration::from_secs(1)); + let handler = { + let (running, most, done) = (running.clone(), most.clone(), done.clone()); + move |_: Job| { + let (running, most, done, tx) = + (running.clone(), most.clone(), done.clone(), tx.clone()); + async move { + let now = running.fetch_add(1, Ordering::SeqCst) + 1; + most.fetch_max(now, Ordering::SeqCst); + tokio::time::sleep(Duration::from_millis(100)).await; + running.fetch_sub(1, Ordering::SeqCst); + if done.fetch_add(1, Ordering::SeqCst) + 1 == 12 { + let _ = tx.send(()); + } + Ok::<_, String>(()) + } + } + }; + let (stop, handle) = start(worker, handler); + + tokio::time::timeout(Duration::from_secs(10), finished.recv()) + .await + .expect("all jobs ran in time"); + assert_eq!(most.load(Ordering::SeqCst), 4); + + let _ = stop.send(()); + handle.await.expect("join").expect("worker"); +} + +#[tokio::test] +async fn shutdown_waits_for_running_jobs() { + let client = serve_or_skip!(); + let mut ids = Vec::new(); + for _ in 0..3 { + ids.push(schedule(&client, "tasks", &Task::OK).await); + } + + let (started_tx, mut started) = mpsc::unbounded_channel(); + let finished = Arc::new(AtomicUsize::new(0)); + let handler = { + let finished = finished.clone(); + move |_: Job| { + let (started_tx, finished) = (started_tx.clone(), finished.clone()); + async move { + let _ = started_tx.send(()); + tokio::time::sleep(Duration::from_millis(500)).await; + finished.fetch_add(1, Ordering::SeqCst); + Ok::<_, String>(()) + } + } + }; + let worker = Worker::new(client.clone(), "tasks") + .concurrency(3) + .poll_wait(Duration::from_secs(1)); + let (stop, handle) = start(worker, handler); + + for _ in 0..3 { + tokio::time::timeout(Duration::from_secs(10), started.recv()) + .await + .expect("jobs start"); + } + let _ = stop.send(()); + handle.await.expect("join").expect("worker"); + + assert_eq!(finished.load(Ordering::SeqCst), 3); + for id in ids { + let message = client.get_message(id).await.expect("get"); + assert_eq!(message.status, Status::Succeeded, "acked before returning"); + } +} + +#[tokio::test] +async fn returns_errors_that_will_not_fix_themselves() { + let client = serve_or_skip!(); + let result = Worker::new(client, "bad name") + .run(|_: Job| async { Ok::<_, String>(()) }) + .await; + let err = result.expect_err("an invalid queue name stops the worker"); + assert!(err.is_invalid_input(), "{err:?}"); +} + +#[tokio::test] +async fn keeps_retrying_while_the_server_is_down() { + let client = Client::new("http://127.0.0.1:9").expect("client"); + // The first retry delay is a second, so stopping after half of one also + // checks that shutdown interrupts the delay. + let result = tokio::time::timeout( + Duration::from_secs(5), + Worker::new(client, "tasks").run_until( + tokio::time::sleep(Duration::from_millis(500)), + |_: Job| async { Ok::<_, String>(()) }, + ), + ) + .await + .expect("shutdown interrupts the retry delay"); + result.expect("retryable errors do not stop the worker"); +} diff --git a/crates/dally-core/Cargo.toml b/crates/dally-core/Cargo.toml new file mode 100644 index 0000000..2484264 --- /dev/null +++ b/crates/dally-core/Cargo.toml @@ -0,0 +1,42 @@ +[package] +name = "dally-core" +description = "Domain types, rules and storage backends for the dally job queue" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true + +[features] +default = [] +postgres = ["dep:sqlx", "sqlx/postgres"] +redis = ["dep:redis", "dep:futures-util", "dep:rustls", "dep:url"] +sqlite = ["dep:sqlx", "sqlx/sqlite"] +# ToSchema derives on the wire types, for generating an OpenAPI spec. +openapi = ["dep:utoipa"] + +[dependencies] +async-trait.workspace = true +chrono.workspace = true +fastrand.workspace = true +futures-util = { workspace = true, optional = true } +humantime-serde.workspace = true +redis = { workspace = true, optional = true } +rustls = { workspace = true, optional = true } +serde.workspace = true +serde_json.workspace = true +sqlx = { workspace = true, optional = true } +thiserror.workspace = true +tokio.workspace = true +tracing.workspace = true +url = { workspace = true, optional = true } +utoipa = { workspace = true, optional = true } +uuid.workspace = true + +[dev-dependencies] +tempfile.workspace = true +tokio = { workspace = true, features = ["full"] } + +[lints] +workspace = true diff --git a/crates/dally-core/migrations/postgres/20261119000000_init.sql b/crates/dally-core/migrations/postgres/20261119000000_init.sql new file mode 100644 index 0000000..69d5f85 --- /dev/null +++ b/crates/dally-core/migrations/postgres/20261119000000_init.sql @@ -0,0 +1,59 @@ +-- Durations are stored as milliseconds, timestamps as timestamptz. Statuses +-- are plain text with a check constraint rather than an enum type, so adding a +-- status later is a one-line migration. + +CREATE TABLE dally_queues ( + name TEXT PRIMARY KEY, + visibility_timeout_ms BIGINT NOT NULL, + max_attempts INTEGER NOT NULL, + backoff_base_ms BIGINT NOT NULL, + backoff_cap_ms BIGINT NOT NULL, + retention_ms BIGINT NOT NULL, + paused BOOLEAN NOT NULL DEFAULT FALSE, + push JSONB, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE dally_messages ( + id UUID PRIMARY KEY, + queue TEXT NOT NULL REFERENCES dally_queues (name) ON DELETE CASCADE, + payload JSONB NOT NULL, + status TEXT NOT NULL + CHECK (status IN ('scheduled', 'running', 'succeeded', 'cancelled', 'dead')), + priority INTEGER NOT NULL DEFAULT 0, + attempts INTEGER NOT NULL DEFAULT 0, + max_attempts INTEGER NOT NULL, + visibility_timeout_ms BIGINT NOT NULL, + idempotency_key TEXT, + run_at TIMESTAMPTZ NOT NULL, + lease_token TEXT, + lease_expires_at TIMESTAMPTZ, + last_error TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + finished_at TIMESTAMPTZ +); + +-- Idempotency: one message per key per queue, for as long as it is stored. +CREATE UNIQUE INDEX dally_messages_idempotency_key + ON dally_messages (queue, idempotency_key) + WHERE idempotency_key IS NOT NULL; + +-- Polling: due messages in priority order. +CREATE INDEX dally_messages_due + ON dally_messages (queue, priority DESC, run_at) + WHERE status = 'scheduled'; + +-- Polling: running messages whose lease may have expired. +CREATE INDEX dally_messages_leases + ON dally_messages (queue, lease_expires_at) + WHERE status = 'running'; + +-- Listing a queue's messages newest first, optionally by status. +CREATE INDEX dally_messages_listing ON dally_messages (queue, status, id DESC); + +-- Pruning finished messages. +CREATE INDEX dally_messages_finished + ON dally_messages (finished_at) + WHERE finished_at IS NOT NULL; diff --git a/crates/dally-core/migrations/sqlite/20261119000000_init.sql b/crates/dally-core/migrations/sqlite/20261119000000_init.sql new file mode 100644 index 0000000..6a3d1e1 --- /dev/null +++ b/crates/dally-core/migrations/sqlite/20261119000000_init.sql @@ -0,0 +1,63 @@ +-- The same schema as the PostgreSQL backend, in SQLite's types. STRICT tables +-- reject values of the wrong type instead of silently storing them. +-- +-- Durations are stored as milliseconds. Timestamps are milliseconds since the +-- Unix epoch, so they sort and compare as plain integers. Ids are UUIDv7 in +-- their hyphenated text form, which sorts like the UUID itself and stays +-- readable in the sqlite3 shell. JSON columns hold text. + +CREATE TABLE dally_queues ( + name TEXT PRIMARY KEY, + visibility_timeout_ms INTEGER NOT NULL, + max_attempts INTEGER NOT NULL, + backoff_base_ms INTEGER NOT NULL, + backoff_cap_ms INTEGER NOT NULL, + retention_ms INTEGER NOT NULL, + paused INTEGER NOT NULL DEFAULT 0 CHECK (paused IN (0, 1)), + push TEXT, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL +) STRICT; + +CREATE TABLE dally_messages ( + id TEXT PRIMARY KEY, + queue TEXT NOT NULL REFERENCES dally_queues (name) ON DELETE CASCADE, + payload TEXT NOT NULL, + status TEXT NOT NULL + CHECK (status IN ('scheduled', 'running', 'succeeded', 'cancelled', 'dead')), + priority INTEGER NOT NULL DEFAULT 0, + attempts INTEGER NOT NULL DEFAULT 0, + max_attempts INTEGER NOT NULL, + visibility_timeout_ms INTEGER NOT NULL, + idempotency_key TEXT, + run_at INTEGER NOT NULL, + lease_token TEXT, + lease_expires_at INTEGER, + last_error TEXT, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + finished_at INTEGER +) STRICT; + +-- Idempotency: one message per key per queue, for as long as it is stored. +CREATE UNIQUE INDEX dally_messages_idempotency_key + ON dally_messages (queue, idempotency_key) + WHERE idempotency_key IS NOT NULL; + +-- Polling: due messages in priority order. +CREATE INDEX dally_messages_due + ON dally_messages (queue, priority DESC, run_at) + WHERE status = 'scheduled'; + +-- Polling: running messages whose lease may have expired. +CREATE INDEX dally_messages_leases + ON dally_messages (queue, lease_expires_at) + WHERE status = 'running'; + +-- Listing a queue's messages newest first, optionally by status. +CREATE INDEX dally_messages_listing ON dally_messages (queue, status, id DESC); + +-- Pruning finished messages. +CREATE INDEX dally_messages_finished + ON dally_messages (finished_at) + WHERE finished_at IS NOT NULL; diff --git a/crates/dally-core/src/error.rs b/crates/dally-core/src/error.rs new file mode 100644 index 0000000..24b2c67 --- /dev/null +++ b/crates/dally-core/src/error.rs @@ -0,0 +1,74 @@ +//! The error type shared by everything in dally-core. + +use crate::message::{MessageId, Status}; +use crate::queue::QueueName; + +/// Shorthand for results in dally-core. +pub type Result = std::result::Result; + +/// Everything that can go wrong in dally-core. +/// +/// The variants are split by who has to act: invalid requests and state +/// conflicts are the caller's problem, `Storage` is the operator's. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// The request is malformed, for example a queue name with spaces. + #[error("{0}")] + InvalidInput(String), + + /// No queue with this name exists. + #[error("queue {0} not found")] + QueueNotFound(QueueName), + + /// No message with this id exists. It may have been pruned. + #[error("message {0} not found")] + MessageNotFound(MessageId), + + /// The lease token does not match the message's current lease. The lease + /// expired and the message was handed to another worker, or the message + /// was already acked or nacked. + #[error("message {0} is not leased with this token")] + LeaseMismatch(MessageId), + + /// The operation is not allowed in the message's current status, for + /// example cancelling a message that is already running. + #[error("message {id} is {status}, expected {expected}")] + InvalidStatus { + /// The message. + id: MessageId, + /// Its current status. + status: Status, + /// The status the operation needs. + expected: Status, + }, + + /// The storage backend failed. These are not the caller's fault and are + /// usually worth retrying. + #[error("storage error: {0}")] + Storage(#[source] Box), +} + +impl Error { + pub(crate) fn invalid(message: impl Into) -> Self { + Error::InvalidInput(message.into()) + } + + /// Wraps a backend error. + pub fn storage(err: impl std::error::Error + Send + Sync + 'static) -> Self { + Error::Storage(Box::new(err)) + } +} + +#[cfg(any(feature = "postgres", feature = "sqlite"))] +impl From for Error { + fn from(err: sqlx::Error) -> Self { + Error::storage(err) + } +} + +#[cfg(feature = "redis")] +impl From for Error { + fn from(err: redis::RedisError) -> Self { + Error::storage(err) + } +} diff --git a/crates/dally-core/src/lib.rs b/crates/dally-core/src/lib.rs new file mode 100644 index 0000000..23287c3 --- /dev/null +++ b/crates/dally-core/src/lib.rs @@ -0,0 +1,24 @@ +//! The core of [dally](https://github.com/platonv/dally), a job queue server. +//! +//! This crate holds the domain types, the rules in [`Service`], and the +//! [`Storage`] trait with its backends. Each backend sits behind a cargo +//! feature: `postgres`, `sqlite`, `redis`. +//! +//! Most users want the `dally` binary rather than this crate. It is useful if +//! you are writing a new transport or a new storage backend. + +pub mod error; +pub mod message; +pub mod notify; +pub mod queue; +pub mod service; +pub mod storage; + +pub use error::{Error, Result}; +pub use message::{ + LeaseToken, Leased, Message, MessageFilter, MessageId, NackRequest, NewMessage, Page, Retry, + RunAt, ScheduleRequest, Scheduled, Status, +}; +pub use queue::{Backoff, PushSettings, Queue, QueueName, QueueSettings, QueueStats, QueueSummary}; +pub use service::{Observer, PollRequest, Service}; +pub use storage::{ConnectOptions, Storage, connect}; diff --git a/crates/dally-core/src/message.rs b/crates/dally-core/src/message.rs new file mode 100644 index 0000000..83f441b --- /dev/null +++ b/crates/dally-core/src/message.rs @@ -0,0 +1,408 @@ +//! Messages and the requests that create and change them. + +use std::fmt; +use std::str::FromStr; +use std::time::Duration; + +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +use crate::error::{Error, Result}; +use crate::queue::QueueName; + +/// A message id. Ids are UUIDv7, so sorting them sorts messages by creation +/// time. +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))] +#[cfg_attr(feature = "openapi", schema(value_type = String, format = Uuid))] +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(transparent)] +pub struct MessageId(Uuid); + +impl MessageId { + /// A new id for a message created now. + pub fn generate() -> Self { + Self(Uuid::now_v7()) + } + + /// Wraps an existing UUID. + pub fn from_uuid(uuid: Uuid) -> Self { + Self(uuid) + } + + /// The underlying UUID. + pub fn as_uuid(&self) -> Uuid { + self.0 + } +} + +impl fmt::Display for MessageId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +impl FromStr for MessageId { + type Err = Error; + + fn from_str(s: &str) -> Result { + Uuid::parse_str(s) + .map(Self) + .map_err(|_| Error::invalid(format!("invalid message id {s:?}"))) + } +} + +/// The token that proves a worker holds a message. It changes every time the +/// message is leased, so a worker whose lease expired cannot ack a message +/// that was handed to someone else. +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))] +#[cfg_attr(feature = "openapi", schema(value_type = String, example = "0f8e2c4b9d1a4e7f8a3b5c6d7e8f9a0b"))] +#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(transparent)] +pub struct LeaseToken(String); + +impl LeaseToken { + /// A new random token. + pub fn generate() -> Self { + Self(Uuid::new_v4().simple().to_string()) + } + + /// The token as a string slice. + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl From for LeaseToken { + fn from(token: String) -> Self { + Self(token) + } +} + +/// Where a message is in its lifecycle. See `docs/design.md` for the diagram. +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Status { + /// Waiting to run, now or later. + Scheduled, + /// Leased by a worker. + Running, + /// Finished successfully. + Succeeded, + /// Cancelled before running. + Cancelled, + /// Out of attempts. + Dead, +} + +impl Status { + /// Every status, in lifecycle order. + pub const ALL: [Status; 5] = [ + Status::Scheduled, + Status::Running, + Status::Succeeded, + Status::Cancelled, + Status::Dead, + ]; + + /// The status as it is stored and shown in the API. + pub fn as_str(&self) -> &'static str { + match self { + Status::Scheduled => "scheduled", + Status::Running => "running", + Status::Succeeded => "succeeded", + Status::Cancelled => "cancelled", + Status::Dead => "dead", + } + } + + /// Finished messages never change again, and are pruned after the queue's + /// retention period. The exception is dead messages, which can be retried. + pub fn is_finished(&self) -> bool { + matches!(self, Status::Succeeded | Status::Cancelled | Status::Dead) + } +} + +impl fmt::Display for Status { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +impl FromStr for Status { + type Err = Error; + + fn from_str(s: &str) -> Result { + Status::ALL + .into_iter() + .find(|status| status.as_str() == s) + .ok_or_else(|| Error::invalid(format!("unknown status {s:?}"))) + } +} + +/// A message as stored. +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Message { + /// The message's id. + pub id: MessageId, + /// The queue it belongs to. + pub queue: QueueName, + /// What the worker gets. + pub payload: serde_json::Value, + /// Where it is in its lifecycle. + pub status: Status, + /// Higher priorities are delivered first. + pub priority: i32, + /// How many times it has been leased. + pub attempts: u32, + /// How many attempts it gets before it is marked dead. + pub max_attempts: u32, + /// How long each lease lasts. + #[serde(with = "humantime_serde")] + #[cfg_attr(feature = "openapi", schema(value_type = String, example = "30s"))] + pub visibility_timeout: Duration, + /// The key that prevents duplicates, if one was given. + pub idempotency_key: Option, + /// When it is next due. + pub run_at: DateTime, + /// When the current lease expires, while it is running. + pub lease_expires_at: Option>, + /// The error reported by the last failed attempt. + pub last_error: Option, + /// When it was scheduled. + pub created_at: DateTime, + /// When it last changed. + pub updated_at: DateTime, + /// When it reached a finished status. + pub finished_at: Option>, +} + +/// A message handed to a worker, with the token it needs to ack or nack it. +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Leased { + /// The message. + #[serde(flatten)] + pub message: Message, + /// The proof that this worker holds it. + pub lease: LeaseToken, +} + +/// When a message should run. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum RunAt { + /// As soon as possible. + #[default] + Now, + /// After a delay, measured by the storage clock. + After(Duration), + /// At a point in time. + At(DateTime), +} + +/// A request to schedule a message, as clients send it. +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ScheduleRequest { + /// What the worker gets. + pub payload: serde_json::Value, + + /// Run after this delay. Cannot be combined with `run_at`. + #[serde( + default, + with = "humantime_serde", + skip_serializing_if = "Option::is_none" + )] + #[cfg_attr(feature = "openapi", schema(value_type = Option, example = "10m"))] + pub delay: Option, + + /// Run at this time. Cannot be combined with `delay`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub run_at: Option>, + + /// Higher priorities are delivered first. Defaults to 0. + #[serde(default)] + pub priority: i32, + + /// Scheduling twice with the same key in the same queue creates only one + /// message. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub idempotency_key: Option, + + /// Overrides the queue's `max_attempts` for this message. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_attempts: Option, + + /// Overrides the queue's `visibility_timeout` for this message. + #[serde( + default, + with = "humantime_serde", + skip_serializing_if = "Option::is_none" + )] + #[cfg_attr(feature = "openapi", schema(value_type = Option, example = "2m"))] + pub visibility_timeout: Option, +} + +impl ScheduleRequest { + /// The longest allowed idempotency key, in bytes. + pub const MAX_IDEMPOTENCY_KEY_LEN: usize = 200; + + /// A request to run `payload` now with default settings. + pub fn new(payload: serde_json::Value) -> Self { + Self { + payload, + ..Self::default() + } + } + + pub(crate) fn run_at(&self) -> Result { + match (self.delay, self.run_at) { + (Some(_), Some(_)) => Err(Error::invalid("use either delay or run_at, not both")), + (Some(delay), None) => Ok(RunAt::After(delay)), + (None, Some(at)) => Ok(RunAt::At(at)), + (None, None) => Ok(RunAt::Now), + } + } + + pub(crate) fn validate(&self) -> Result<()> { + if let Some(key) = &self.idempotency_key + && (key.is_empty() || key.len() > Self::MAX_IDEMPOTENCY_KEY_LEN) + { + return Err(Error::invalid(format!( + "idempotency_key must be 1 to {} bytes", + Self::MAX_IDEMPOTENCY_KEY_LEN + ))); + } + if self.max_attempts == Some(0) { + return Err(Error::invalid("max_attempts must be at least 1")); + } + if self + .visibility_timeout + .is_some_and(|t| t < Duration::from_secs(1)) + { + return Err(Error::invalid("visibility_timeout must be at least 1s")); + } + self.run_at().map(|_| ()) + } +} + +/// A message ready to be stored: a [`ScheduleRequest`] with the queue's +/// defaults filled in. +#[derive(Debug, Clone, PartialEq)] +pub struct NewMessage { + /// The id to store it under. + pub id: MessageId, + /// What the worker gets. + pub payload: serde_json::Value, + /// When it should run. + pub run_at: RunAt, + /// Higher priorities are delivered first. + pub priority: i32, + /// The key that prevents duplicates. + pub idempotency_key: Option, + /// How many attempts it gets. + pub max_attempts: u32, + /// How long each lease lasts. + pub visibility_timeout: Duration, +} + +/// The result of scheduling one message. +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Scheduled { + /// The stored message: the new one, or the existing one with the same + /// idempotency key. + pub message: Message, + /// False when a message with the same idempotency key already existed. + pub created: bool, +} + +/// What a worker reports when an attempt fails. +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))] +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct NackRequest { + /// The lease that proves the worker holds the message. + pub lease: LeaseToken, + /// What went wrong. Shown in the UI and kept on the message. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, + /// Retry after this delay instead of the queue's backoff. + #[serde( + default, + with = "humantime_serde", + skip_serializing_if = "Option::is_none" + )] + #[cfg_attr(feature = "openapi", schema(value_type = Option, example = "30s"))] + pub retry_in: Option, +} + +/// How a storage backend should record a failed attempt. +#[derive(Debug, Clone, PartialEq)] +pub struct Retry { + /// What went wrong. + pub error: Option, + /// How long to wait before the next attempt, if there is one. + pub delay: Duration, +} + +/// Which messages to list. +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +pub struct MessageFilter { + /// Only messages in this queue. + pub queue: Option, + /// Only messages in this status. + pub status: Option, + /// Only messages created before this one. Pass the previous page's `next` + /// to get the following page. + pub before: Option, + /// At most this many messages. + pub limit: u32, +} + +/// One page of a listing, newest first. +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Page { + /// The items on this page. + pub items: Vec, + /// The cursor for the next page, if there is one. + pub next: Option, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn status_round_trips_through_strings() { + for status in Status::ALL { + assert_eq!(status.as_str().parse::().ok(), Some(status)); + } + assert!("unknown".parse::().is_err()); + } + + #[test] + fn schedule_request_rejects_delay_and_run_at_together() { + let request = ScheduleRequest { + delay: Some(Duration::from_secs(1)), + run_at: Some(Utc::now()), + ..ScheduleRequest::default() + }; + assert!(request.validate().is_err()); + } + + #[test] + fn schedule_request_parses_human_delay() { + let request: ScheduleRequest = + serde_json::from_str(r#"{"payload": {"to": "ana"}, "delay": "10m"}"#) + .expect("valid request"); + assert_eq!( + request.run_at().ok(), + Some(RunAt::After(Duration::from_secs(600))) + ); + } +} diff --git a/crates/dally-core/src/notify.rs b/crates/dally-core/src/notify.rs new file mode 100644 index 0000000..8f9180a --- /dev/null +++ b/crates/dally-core/src/notify.rs @@ -0,0 +1,100 @@ +//! Wake-ups for long polling. +//! +//! When a message is scheduled, the backend calls [`Notifier::notify`] so that +//! requests waiting on that queue look again right away instead of at their +//! next timer tick. Notifications are hints: a waiter may wake up and find +//! nothing, and a missed notification only costs latency, never a message. + +use std::collections::HashMap; +use std::sync::Mutex; + +use tokio::sync::watch; + +use crate::queue::QueueName; + +/// Fans out "something was scheduled in queue X" to everyone waiting on X. +#[derive(Debug, Default)] +pub struct Notifier { + queues: Mutex>>, +} + +impl Notifier { + /// Creates a notifier with no subscribers. + pub fn new() -> Self { + Self::default() + } + + /// Starts listening for notifications on `queue`. Notifications sent + /// after this call are seen by [`Subscription::changed`], even if they + /// arrive before it is awaited. + pub fn subscribe(&self, queue: &QueueName) -> Subscription { + let mut queues = self + .queues + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let sender = queues + .entry(queue.clone()) + .or_insert_with(|| watch::channel(()).0); + Subscription(sender.subscribe()) + } + + /// Wakes everyone waiting on `queue`. + pub fn notify(&self, queue: &QueueName) { + let queues = self + .queues + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(sender) = queues.get(queue) { + sender.send_replace(()); + } + } +} + +/// A handle that resolves when its queue is notified. +#[derive(Debug)] +pub struct Subscription(watch::Receiver<()>); + +impl Subscription { + /// Waits for the next notification. + pub async fn changed(&mut self) { + // The sender lives as long as the notifier, so this only errors while + // shutting down. Waiting forever is right then: the caller's timeout + // ends the wait. + if self.0.changed().await.is_err() { + std::future::pending::<()>().await; + } + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use super::*; + + #[tokio::test] + async fn notifications_sent_before_waiting_are_not_lost() { + let notifier = Notifier::new(); + let queue = QueueName::new("emails").expect("valid name"); + + let mut subscription = notifier.subscribe(&queue); + notifier.notify(&queue); + + tokio::time::timeout(Duration::from_millis(100), subscription.changed()) + .await + .expect("notification should already be pending"); + } + + #[tokio::test] + async fn other_queues_do_not_wake_subscribers() { + let notifier = Notifier::new(); + let emails = QueueName::new("emails").expect("valid name"); + let reports = QueueName::new("reports").expect("valid name"); + + let mut subscription = notifier.subscribe(&emails); + notifier.notify(&reports); + + let woke = tokio::time::timeout(Duration::from_millis(50), subscription.changed()).await; + assert!(woke.is_err()); + } +} diff --git a/crates/dally-core/src/queue.rs b/crates/dally-core/src/queue.rs new file mode 100644 index 0000000..2f35068 --- /dev/null +++ b/crates/dally-core/src/queue.rs @@ -0,0 +1,308 @@ +//! Queues and their settings. + +use std::fmt; +use std::time::Duration; + +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; + +use crate::error::{Error, Result}; + +/// The name of a queue: 1 to 100 ASCII letters, digits, `-`, `_` or `.`. +/// +/// The character set is deliberately small so names are safe in URLs, Redis +/// keys and metric labels without escaping. +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))] +#[cfg_attr( + feature = "openapi", + schema(value_type = String, pattern = "^[A-Za-z0-9._-]{1,100}$", example = "emails") +)] +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(try_from = "String", into = "String")] +pub struct QueueName(String); + +impl QueueName { + /// The longest allowed name, in bytes. + pub const MAX_LEN: usize = 100; + + /// Validates and wraps a queue name. + pub fn new(name: impl Into) -> Result { + let name = name.into(); + let valid_chars = name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')); + + if name.is_empty() || name.len() > Self::MAX_LEN || !valid_chars { + return Err(Error::invalid(format!( + "invalid queue name {name:?}: use 1 to {} letters, digits, '-', '_' or '.'", + Self::MAX_LEN + ))); + } + Ok(Self(name)) + } + + /// The name as a string slice. + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl fmt::Display for QueueName { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl TryFrom for QueueName { + type Error = Error; + + fn try_from(name: String) -> Result { + Self::new(name) + } +} + +impl TryFrom<&str> for QueueName { + type Error = Error; + + fn try_from(name: &str) -> Result { + Self::new(name) + } +} + +impl From for String { + fn from(name: QueueName) -> Self { + name.0 + } +} + +/// A queue as stored, with its settings. +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Queue { + /// The queue's name. + pub name: QueueName, + /// How messages in this queue are delivered. + #[serde(flatten)] + pub settings: QueueSettings, + /// When the queue was created. + pub created_at: DateTime, + /// When the settings last changed. + pub updated_at: DateTime, +} + +/// The settings of a queue. Every field has a default, so a queue created +/// implicitly by scheduling a message works without configuration. +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct QueueSettings { + /// How long a lease lasts. A message that is not acked or nacked in this + /// time is handed to another worker. + #[serde(with = "humantime_serde")] + #[cfg_attr(feature = "openapi", schema(value_type = String, example = "30s"))] + pub visibility_timeout: Duration, + + /// How many times a message is attempted before it is marked dead. + pub max_attempts: u32, + + /// How long to wait before retrying a failed attempt. + pub backoff: Backoff, + + /// How long finished messages are kept before they are deleted. This is + /// also how long idempotency keys are remembered. + #[serde(with = "humantime_serde")] + #[cfg_attr(feature = "openapi", schema(value_type = String, example = "7days"))] + pub retention: Duration, + + /// A paused queue accepts new messages but delivers none. + pub paused: bool, + + /// When set, the server delivers messages by POSTing them to this endpoint + /// instead of waiting for workers to poll. + pub push: Option, +} + +impl Default for QueueSettings { + fn default() -> Self { + Self { + visibility_timeout: Duration::from_secs(30), + max_attempts: 5, + backoff: Backoff::default(), + retention: Duration::from_secs(7 * 24 * 60 * 60), + paused: false, + push: None, + } + } +} + +impl QueueSettings { + /// Checks that the settings make sense together. + pub fn validate(&self) -> Result<()> { + if self.visibility_timeout < Duration::from_secs(1) { + return Err(Error::invalid("visibility_timeout must be at least 1s")); + } + if self.max_attempts == 0 { + return Err(Error::invalid("max_attempts must be at least 1")); + } + if self.backoff.base > self.backoff.cap { + return Err(Error::invalid( + "backoff.base must not be greater than backoff.cap", + )); + } + if let Some(push) = &self.push { + push.validate()?; + } + Ok(()) + } +} + +/// Exponential backoff with jitter: attempt `n` waits about +/// `min(base * 2^(n - 1), cap)`, give or take 20%. +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct Backoff { + /// The delay after the first failed attempt. + #[serde(with = "humantime_serde")] + #[cfg_attr(feature = "openapi", schema(value_type = String, example = "5s"))] + pub base: Duration, + /// The longest delay between attempts. + #[serde(with = "humantime_serde")] + #[cfg_attr(feature = "openapi", schema(value_type = String, example = "1h"))] + pub cap: Duration, +} + +impl Default for Backoff { + fn default() -> Self { + Self { + base: Duration::from_secs(5), + cap: Duration::from_secs(60 * 60), + } + } +} + +impl Backoff { + /// The delay before retrying after `attempt` failed. Attempts count from 1. + pub fn delay(&self, attempt: u32) -> Duration { + // 2^30 times any sensible base is far beyond any sensible cap, so + // clamping the exponent avoids overflow without changing the result. + let exponent = attempt.saturating_sub(1).min(30); + let delay = self.base.saturating_mul(1 << exponent).min(self.cap); + let jitter = 0.8 + fastrand::f64() * 0.4; + delay.mul_f64(jitter) + } +} + +/// Where and how to push messages from a queue. +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PushSettings { + /// The endpoint that receives each message as a POST request. + pub url: String, + + /// When set, each request is signed with HMAC-SHA256 using this secret. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub secret: Option, + + /// How long to wait for the endpoint to respond. + #[serde(default = "PushSettings::default_timeout", with = "humantime_serde")] + #[cfg_attr(feature = "openapi", schema(value_type = String, example = "30s"))] + pub timeout: Duration, + + /// How many requests to have in flight at once, per server. + #[serde(default = "PushSettings::default_concurrency")] + pub concurrency: u32, +} + +impl PushSettings { + fn default_timeout() -> Duration { + Duration::from_secs(30) + } + + fn default_concurrency() -> u32 { + 8 + } + + fn validate(&self) -> Result<()> { + if !(self.url.starts_with("http://") || self.url.starts_with("https://")) { + return Err(Error::invalid( + "push.url must start with http:// or https://", + )); + } + if self.concurrency == 0 { + return Err(Error::invalid("push.concurrency must be at least 1")); + } + Ok(()) + } +} + +/// How many messages a queue holds in each status. +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct QueueStats { + /// Waiting to run, now or later. + pub scheduled: u64, + /// Leased by a worker. + pub running: u64, + /// Finished successfully. + pub succeeded: u64, + /// Cancelled before running. + pub cancelled: u64, + /// Out of attempts. + pub dead: u64, +} + +/// A queue together with its message counts. +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct QueueSummary { + /// The queue. + #[serde(flatten)] + pub queue: Queue, + /// Its message counts. + pub stats: QueueStats, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn queue_names() { + assert!(QueueName::new("emails").is_ok()); + assert!(QueueName::new("billing.invoices-v2_eu").is_ok()); + assert!(QueueName::new("").is_err()); + assert!(QueueName::new("has space").is_err()); + assert!(QueueName::new("slash/name").is_err()); + assert!(QueueName::new("x".repeat(101)).is_err()); + } + + #[test] + fn backoff_grows_and_caps() { + let backoff = Backoff { + base: Duration::from_secs(10), + cap: Duration::from_secs(60), + }; + let within = |d: Duration, expected: u64| { + let expected = Duration::from_secs(expected); + d >= expected.mul_f64(0.8) && d <= expected.mul_f64(1.2) + }; + assert!(within(backoff.delay(1), 10)); + assert!(within(backoff.delay(2), 20)); + assert!(within(backoff.delay(3), 40)); + assert!(within(backoff.delay(4), 60)); + assert!(within(backoff.delay(1000), 60)); + } + + #[test] + fn settings_parse_human_durations() { + let settings: QueueSettings = + serde_json::from_str(r#"{"visibility_timeout": "2m", "backoff": {"base": "1s"}}"#) + .expect("valid settings"); + assert_eq!(settings.visibility_timeout, Duration::from_secs(120)); + assert_eq!(settings.backoff.base, Duration::from_secs(1)); + assert_eq!(settings.backoff.cap, Backoff::default().cap); + assert_eq!(settings.max_attempts, 5); + } +} diff --git a/crates/dally-core/src/service.rs b/crates/dally-core/src/service.rs new file mode 100644 index 0000000..96922c6 --- /dev/null +++ b/crates/dally-core/src/service.rs @@ -0,0 +1,351 @@ +//! The rules of dally, independent of any transport. +//! +//! HTTP handlers, the push dispatcher and the cron ticker all go through +//! [`Service`]. It validates input, fills in queue defaults, computes backoff +//! and turns "nothing matched" from storage into a precise error. + +use std::sync::Arc; +use std::time::Duration; + +use tokio::time::Instant; + +use crate::error::{Error, Result}; +use crate::message::{ + LeaseToken, Leased, Message, MessageFilter, MessageId, NackRequest, NewMessage, Page, Retry, + RunAt, ScheduleRequest, Scheduled, Status, +}; +use crate::queue::{Queue, QueueName, QueueSettings, QueueSummary}; +use crate::storage::Storage; + +/// Limits on what a single request can ask for. +pub mod limits { + use std::time::Duration; + + /// The most messages one schedule request can create. + pub const MAX_BATCH: usize = 100; + /// The most messages one poll can lease. + pub const MAX_POLL: u32 = 100; + /// The longest a poll can wait for messages. + pub const MAX_POLL_WAIT: Duration = Duration::from_secs(30); + /// The most messages one listing can return. + pub const MAX_PAGE: u32 = 500; +} + +/// How often a waiting poll checks storage even without a notification. +/// Notifications only fire for new messages, so this is what picks up delayed +/// messages becoming due and expired leases. +const POLL_RECHECK_INTERVAL: Duration = Duration::from_secs(1); + +/// What a worker asks for when it polls. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PollRequest { + /// Lease at most this many messages. + pub limit: u32, + /// If nothing is due, wait up to this long for something to become due. + pub wait: Duration, +} + +impl Default for PollRequest { + fn default() -> Self { + Self { + limit: 1, + wait: Duration::ZERO, + } + } +} + +/// Hears about every message that moves through a [`Service`], whichever +/// transport or background task moved it. The server uses this for metrics. +/// +/// Every method has an empty default, so an observer only implements what it +/// cares about. Methods are called after the storage operation succeeded and +/// must not block. +pub trait Observer: Send + Sync + 'static { + /// `created` new messages were stored in `queue`. Messages that matched an + /// existing idempotency key are not counted. + fn scheduled(&self, queue: &QueueName, created: usize) { + let _ = (queue, created); + } + + /// `count` messages were leased from `queue`. + fn leased(&self, queue: &QueueName, count: usize) { + let _ = (queue, count); + } + + /// A message was acked. + fn acked(&self, message: &Message) { + let _ = message; + } + + /// A message was nacked. Its status says whether it will be retried + /// (`scheduled`) or is out of attempts (`dead`). + fn nacked(&self, message: &Message) { + let _ = message; + } +} + +/// The observer used when none is set. +struct NoObserver; + +impl Observer for NoObserver {} + +/// The entry point to everything dally does. +#[derive(Clone)] +pub struct Service { + storage: Arc, + defaults: QueueSettings, + observer: Arc, +} + +impl Service { + /// Creates a service. `defaults` are the settings for queues created + /// implicitly, by scheduling into or polling from an unknown queue. + pub fn new(storage: Arc, defaults: QueueSettings) -> Self { + Self { + storage, + defaults, + observer: Arc::new(NoObserver), + } + } + + /// Reports every scheduled, leased, acked and nacked message to `observer`. + pub fn with_observer(mut self, observer: Arc) -> Self { + self.observer = observer; + self + } + + /// The storage this service uses. + pub fn storage(&self) -> &Arc { + &self.storage + } + + /// Schedules messages, creating the queue if needed. The results are in + /// the same order as the requests. + pub async fn schedule( + &self, + queue: &QueueName, + requests: Vec, + ) -> Result> { + if requests.is_empty() { + return Ok(Vec::new()); + } + if requests.len() > limits::MAX_BATCH { + return Err(Error::invalid(format!( + "at most {} messages can be scheduled at once", + limits::MAX_BATCH + ))); + } + for request in &requests { + request.validate()?; + } + + let settings = self + .storage + .ensure_queue(queue, &self.defaults) + .await? + .settings; + let messages = requests + .into_iter() + .map(|request| NewMessage { + id: MessageId::generate(), + run_at: request.run_at().unwrap_or_default(), + max_attempts: request.max_attempts.unwrap_or(settings.max_attempts), + visibility_timeout: request + .visibility_timeout + .unwrap_or(settings.visibility_timeout), + priority: request.priority, + idempotency_key: request.idempotency_key, + payload: request.payload, + }) + .collect(); + + let scheduled = self.storage.schedule(queue, messages).await?; + let created = scheduled.iter().filter(|result| result.created).count(); + self.observer.scheduled(queue, created); + Ok(scheduled) + } + + /// Leases due messages. If none are due and `request.wait` is non-zero, + /// waits until some are or the wait runs out. Polling an unknown queue + /// creates it, so workers can start before anything is scheduled. + pub async fn poll(&self, queue: &QueueName, request: PollRequest) -> Result> { + if request.limit == 0 || request.limit > limits::MAX_POLL { + return Err(Error::invalid(format!( + "limit must be between 1 and {}", + limits::MAX_POLL + ))); + } + let deadline = Instant::now() + request.wait.min(limits::MAX_POLL_WAIT); + self.storage.ensure_queue(queue, &self.defaults).await?; + + loop { + // Subscribe before looking, so a message scheduled between the + // lease and the wait still wakes us. + let mut subscription = self.storage.subscribe(queue); + + if !self.is_paused(queue).await? { + let leased = self.storage.lease(queue, request.limit).await?; + if !leased.is_empty() { + self.observer.leased(queue, leased.len()); + return Ok(leased); + } + } + + let now = Instant::now(); + if now >= deadline { + return Ok(Vec::new()); + } + let recheck_at = deadline.min(now + POLL_RECHECK_INTERVAL); + let _ = tokio::time::timeout_at(recheck_at, subscription.changed()).await; + } + } + + /// Marks a message as succeeded. + pub async fn ack(&self, id: MessageId, lease: &LeaseToken) -> Result { + match self.storage.ack(id, lease).await? { + Some(message) => { + self.observer.acked(&message); + Ok(message) + } + None => Err(self.lease_error(id).await), + } + } + + /// Records a failed attempt. The message is retried after the queue's + /// backoff (or `retry_in`, if given), or marked dead if it is out of + /// attempts. + pub async fn nack(&self, id: MessageId, request: NackRequest) -> Result { + // The backoff depends on the attempt number, so look the message up + // first. The lease check in `storage.nack` keeps this race-free: if + // the message changes in between, the nack matches nothing. + let Some(message) = self.storage.get_message(id).await? else { + return Err(Error::MessageNotFound(id)); + }; + let delay = match request.retry_in { + Some(delay) => delay, + None => self + .settings_of(&message.queue) + .await? + .backoff + .delay(message.attempts), + }; + let retry = Retry { + error: request.error, + delay, + }; + + match self.storage.nack(id, &request.lease, retry).await? { + Some(message) => { + self.observer.nacked(&message); + Ok(message) + } + None => Err(self.lease_error(id).await), + } + } + + /// Returns a message. + pub async fn get_message(&self, id: MessageId) -> Result { + self.storage + .get_message(id) + .await? + .ok_or(Error::MessageNotFound(id)) + } + + /// Lists messages newest first. A limit of 0 means the default page size. + pub async fn list_messages(&self, mut filter: MessageFilter) -> Result> { + filter.limit = match filter.limit { + 0 => 50, + limit => limit.min(limits::MAX_PAGE), + }; + self.storage.list_messages(&filter).await + } + + /// Cancels a scheduled message. + pub async fn cancel(&self, id: MessageId) -> Result { + match self.storage.cancel(id).await? { + Some(message) => Ok(message), + None => Err(self.status_error(id, Status::Scheduled).await), + } + } + + /// Changes when a scheduled message runs. + pub async fn reschedule(&self, id: MessageId, run_at: RunAt) -> Result { + match self.storage.reschedule(id, run_at).await? { + Some(message) => Ok(message), + None => Err(self.status_error(id, Status::Scheduled).await), + } + } + + /// Gives dead messages a fresh set of attempts. With `ids`, only those + /// messages; otherwise every dead message in the queue. + pub async fn retry_dead(&self, queue: &QueueName, ids: Option<&[MessageId]>) -> Result { + self.get_queue(queue).await?; + self.storage.retry_dead(queue, ids).await + } + + /// Returns a queue with its message counts. + pub async fn get_queue(&self, name: &QueueName) -> Result { + self.storage + .get_queue(name) + .await? + .ok_or_else(|| Error::QueueNotFound(name.clone())) + } + + /// Returns every queue with its message counts. + pub async fn list_queues(&self) -> Result> { + self.storage.list_queues().await + } + + /// Creates a queue or replaces its settings. Messages already scheduled + /// keep the `max_attempts` and `visibility_timeout` they were created with. + pub async fn put_queue(&self, name: &QueueName, settings: QueueSettings) -> Result { + settings.validate()?; + self.storage.put_queue(name, &settings).await + } + + /// Pauses or resumes delivery from a queue. + pub async fn set_paused(&self, name: &QueueName, paused: bool) -> Result { + let mut settings = self.get_queue(name).await?.queue.settings; + settings.paused = paused; + self.storage.put_queue(name, &settings).await + } + + /// Deletes finished messages past their queue's retention. + pub async fn prune(&self) -> Result { + self.storage.prune().await + } + + async fn settings_of(&self, queue: &QueueName) -> Result { + Ok(self + .storage + .ensure_queue(queue, &self.defaults) + .await? + .settings) + } + + async fn is_paused(&self, queue: &QueueName) -> Result { + Ok(self.settings_of(queue).await?.paused) + } + + /// Explains why an ack or nack matched nothing. + async fn lease_error(&self, id: MessageId) -> Error { + match self.storage.get_message(id).await { + Ok(Some(_)) => Error::LeaseMismatch(id), + Ok(None) => Error::MessageNotFound(id), + Err(err) => err, + } + } + + /// Explains why an operation that needs a certain status matched nothing. + async fn status_error(&self, id: MessageId, expected: Status) -> Error { + match self.storage.get_message(id).await { + Ok(Some(message)) => Error::InvalidStatus { + id, + status: message.status, + expected, + }, + Ok(None) => Error::MessageNotFound(id), + Err(err) => err, + } + } +} diff --git a/crates/dally-core/src/storage/mod.rs b/crates/dally-core/src/storage/mod.rs new file mode 100644 index 0000000..8f609f8 --- /dev/null +++ b/crates/dally-core/src/storage/mod.rs @@ -0,0 +1,185 @@ +//! The storage trait and its backends. +//! +//! The trait is shaped around what dally needs, not generic CRUD. Each method +//! is atomic: two servers calling `lease` on the same queue at the same time +//! never get the same message. The rules about *what* should happen (defaults, +//! validation, backoff) live in [`Service`](crate::Service); backends only +//! store and fetch. +//! +//! Every backend runs the same conformance tests in `tests/conformance`. + +use std::collections::BTreeMap; +use std::sync::Arc; +use std::time::Duration; + +use async_trait::async_trait; +use chrono::{DateTime, Utc}; + +use crate::error::{Error, Result}; +use crate::message::{ + LeaseToken, Leased, Message, MessageFilter, MessageId, NewMessage, Page, Retry, RunAt, + Scheduled, +}; +use crate::notify::Subscription; +use crate::queue::{Queue, QueueName, QueueSettings, QueueSummary}; + +#[cfg(feature = "postgres")] +pub mod postgres; +#[cfg(feature = "redis")] +pub mod redis; +#[cfg(feature = "sqlite")] +pub mod sqlite; + +/// Where dally keeps queues and messages. +#[async_trait] +pub trait Storage: Send + Sync + 'static { + /// Returns the queue, creating it with `defaults` if it does not exist. + async fn ensure_queue(&self, name: &QueueName, defaults: &QueueSettings) -> Result; + + /// Creates the queue or replaces its settings. + async fn put_queue(&self, name: &QueueName, settings: &QueueSettings) -> Result; + + /// Returns the queue, if it exists. + async fn get_queue(&self, name: &QueueName) -> Result>; + + /// Returns every queue, sorted by name. + async fn list_queues(&self) -> Result>; + + /// Stores messages in an existing queue. A message whose idempotency key + /// is already used in the queue is not stored; the existing message is + /// returned with `created: false` instead. Results are in input order. + async fn schedule( + &self, + queue: &QueueName, + messages: Vec, + ) -> Result>; + + /// Leases up to `limit` due messages, highest priority first, then oldest + /// `run_at` first. Each leased message moves to `running`, its attempt + /// count goes up by one, and it gets a fresh lease token. + /// + /// Running messages whose lease expired count as due, so a crashed + /// worker's messages are picked up again. If an expired message has no + /// attempts left, it moves to `dead` instead of being leased. + async fn lease(&self, queue: &QueueName, limit: u32) -> Result>; + + /// Marks a running message as succeeded. Returns `None` if the message + /// does not exist or is not running under this lease. + async fn ack(&self, id: MessageId, lease: &LeaseToken) -> Result>; + + /// Records a failed attempt. The message goes back to `scheduled` after + /// `retry.delay`, or to `dead` if it has no attempts left. Returns `None` + /// if the message does not exist or is not running under this lease. + async fn nack( + &self, + id: MessageId, + lease: &LeaseToken, + retry: Retry, + ) -> Result>; + + /// Returns the message, if it exists. + async fn get_message(&self, id: MessageId) -> Result>; + + /// Lists messages newest first. + async fn list_messages(&self, filter: &MessageFilter) -> Result>; + + /// Cancels a scheduled message. Returns `None` if the message does not + /// exist or is not scheduled. + async fn cancel(&self, id: MessageId) -> Result>; + + /// Changes when a scheduled message runs. Returns `None` if the message + /// does not exist or is not scheduled. + async fn reschedule(&self, id: MessageId, run_at: RunAt) -> Result>; + + /// Moves dead messages back to `scheduled` with a fresh set of attempts, + /// due now. With `ids`, only those messages; otherwise every dead message + /// in the queue. Returns how many were moved. + async fn retry_dead(&self, queue: &QueueName, ids: Option<&[MessageId]>) -> Result; + + /// Deletes finished messages older than their queue's retention. Returns + /// how many were deleted. + async fn prune(&self) -> Result; + + /// For each queue with due messages, how long the oldest of them has been + /// waiting: the storage clock's now minus the earliest `run_at` among due + /// scheduled messages. Queues with nothing due are left out. Used for the + /// `dally_queue_oldest_due_seconds` metric. + /// + /// Returns `None` when the backend cannot answer this cheaply, which is + /// the default. + async fn oldest_due(&self) -> Result>> { + Ok(None) + } + + /// Starts listening for newly scheduled messages in `queue`. + fn subscribe(&self, queue: &QueueName) -> Subscription; + + /// The current time according to the storage clock. + async fn now(&self) -> Result>; +} + +/// Connection options shared by all backends. +#[derive(Debug, Clone)] +pub struct ConnectOptions { + /// Run pending schema migrations after connecting. + pub migrate: bool, +} + +impl Default for ConnectOptions { + fn default() -> Self { + Self { migrate: true } + } +} + +/// Connects to the backend named by the URL scheme: `postgres://`, `sqlite://` +/// or `redis://`. A backend is only available if its cargo feature is enabled. +// Without any backend compiled in, every scheme is an error and `options` is +// never read. +#[cfg_attr( + not(any(feature = "postgres", feature = "sqlite", feature = "redis")), + allow(unused_variables) +)] +pub async fn connect(url: &str, options: &ConnectOptions) -> Result> { + // Split at the first colon rather than at "://": SQLite's in-memory URL + // is `sqlite::memory:`. + let scheme = url + .split_once(':') + .map(|(scheme, _)| scheme) + .unwrap_or_default(); + + match scheme { + "postgres" | "postgresql" => { + #[cfg(feature = "postgres")] + return Ok(Arc::new( + postgres::PostgresStorage::connect(url, options).await?, + )); + #[cfg(not(feature = "postgres"))] + return Err(missing_feature("postgres")); + } + "sqlite" => { + #[cfg(feature = "sqlite")] + return Ok(Arc::new( + sqlite::SqliteStorage::connect(url, options).await?, + )); + #[cfg(not(feature = "sqlite"))] + return Err(missing_feature("sqlite")); + } + "redis" | "rediss" => { + #[cfg(feature = "redis")] + return Ok(Arc::new(redis::RedisStorage::connect(url, options).await?)); + #[cfg(not(feature = "redis"))] + return Err(missing_feature("redis")); + } + // Only the scheme goes in the message: the URL may contain a password. + _ => Err(Error::invalid(format!( + "unsupported storage URL scheme {scheme:?}: expected postgres://, sqlite:// or redis://" + ))), + } +} + +#[allow(dead_code)] // Unused when every backend is compiled in. +fn missing_feature(backend: &str) -> Error { + Error::invalid(format!( + "dally was built without {backend} support; enable the `{backend}` cargo feature" + )) +} diff --git a/crates/dally-core/src/storage/postgres.rs b/crates/dally-core/src/storage/postgres.rs new file mode 100644 index 0000000..95807ec --- /dev/null +++ b/crates/dally-core/src/storage/postgres.rs @@ -0,0 +1,704 @@ +//! The PostgreSQL backend. Requires PostgreSQL 13 or later. +//! +//! Leasing uses `FOR UPDATE SKIP LOCKED`, so any number of servers can poll +//! the same queue without blocking each other or taking the same row. +//! `LISTEN/NOTIFY` on the `dally_scheduled` channel wakes long polls on every +//! server as soon as a message is scheduled. +//! +//! All timestamps come from the database's `now()`, so servers with skewed +//! clocks still agree on what is due. + +use std::collections::BTreeMap; +use std::sync::Arc; +use std::time::Duration; + +use async_trait::async_trait; +use chrono::{DateTime, Utc}; +use sqlx::postgres::{PgConnectOptions, PgListener, PgPool, PgPoolOptions}; +use sqlx::types::Json; +use sqlx::{FromRow, Postgres, Transaction}; +use tokio::task::JoinHandle; +use uuid::Uuid; + +use super::{ConnectOptions, Storage}; +use crate::error::{Error, Result}; +use crate::message::{ + LeaseToken, Leased, Message, MessageFilter, MessageId, NewMessage, Page, Retry, RunAt, + Scheduled, Status, +}; +use crate::notify::{Notifier, Subscription}; +use crate::queue::{ + Backoff, PushSettings, Queue, QueueName, QueueSettings, QueueStats, QueueSummary, +}; + +static MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate!("./migrations/postgres"); + +const CHANNEL: &str = "dally_scheduled"; + +/// Stores queues and messages in PostgreSQL. +pub struct PostgresStorage { + pool: PgPool, + notifier: Arc, + listener: JoinHandle<()>, +} + +impl PostgresStorage { + /// Connects using a `postgres://` URL. + pub async fn connect(url: &str, options: &ConnectOptions) -> Result { + let connect_options: PgConnectOptions = url.parse()?; + Self::connect_with(connect_options, options).await + } + + /// Connects using explicit connection options, for settings a URL cannot + /// express. + pub async fn connect_with( + connect_options: PgConnectOptions, + options: &ConnectOptions, + ) -> Result { + let pool = PgPoolOptions::new() + .max_connections(16) + .connect_with(connect_options) + .await?; + + if options.migrate { + MIGRATOR.run(&pool).await.map_err(Error::storage)?; + } + + let notifier = Arc::new(Notifier::new()); + let listener = tokio::spawn(listen(pool.clone(), Arc::clone(¬ifier))); + + Ok(Self { + pool, + notifier, + listener, + }) + } +} + +impl Drop for PostgresStorage { + fn drop(&mut self) { + self.listener.abort(); + } +} + +/// Forwards `NOTIFY dally_scheduled, ''` to local subscribers. If the +/// connection drops, polls fall back to their periodic recheck until it is +/// back, so nothing is lost. +async fn listen(pool: PgPool, notifier: Arc) { + loop { + let result: Result<(), sqlx::Error> = async { + let mut listener = PgListener::connect_with(&pool).await?; + listener.listen(CHANNEL).await?; + loop { + let notification = listener.recv().await?; + if let Ok(queue) = QueueName::new(notification.payload()) { + notifier.notify(&queue); + } + } + } + .await; + + if let Err(err) = result { + tracing::warn!(error = %err, "postgres listener failed; retrying in 1s"); + } + tokio::time::sleep(Duration::from_secs(1)).await; + } +} + +#[async_trait] +impl Storage for PostgresStorage { + async fn ensure_queue(&self, name: &QueueName, defaults: &QueueSettings) -> Result { + // Most calls find the queue, so look before trying to insert. + if let Some(queue) = self.find_queue(name).await? { + return Ok(queue); + } + + let row: Option = sqlx::query_as( + "INSERT INTO dally_queues + (name, visibility_timeout_ms, max_attempts, backoff_base_ms, backoff_cap_ms, + retention_ms, paused, push) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + ON CONFLICT (name) DO NOTHING + RETURNING *", + ) + .bind(name.as_str()) + .bind(millis(defaults.visibility_timeout)) + .bind(count(defaults.max_attempts)) + .bind(millis(defaults.backoff.base)) + .bind(millis(defaults.backoff.cap)) + .bind(millis(defaults.retention)) + .bind(defaults.paused) + .bind(defaults.push.clone().map(Json)) + .fetch_optional(&self.pool) + .await?; + + match row { + Some(row) => row.into_queue(), + // Another server created it between our select and insert. + None => self + .find_queue(name) + .await? + .ok_or_else(|| Error::QueueNotFound(name.clone())), + } + } + + async fn put_queue(&self, name: &QueueName, settings: &QueueSettings) -> Result { + let row: QueueRow = sqlx::query_as( + "INSERT INTO dally_queues + (name, visibility_timeout_ms, max_attempts, backoff_base_ms, backoff_cap_ms, + retention_ms, paused, push) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + ON CONFLICT (name) DO UPDATE SET + visibility_timeout_ms = excluded.visibility_timeout_ms, + max_attempts = excluded.max_attempts, + backoff_base_ms = excluded.backoff_base_ms, + backoff_cap_ms = excluded.backoff_cap_ms, + retention_ms = excluded.retention_ms, + paused = excluded.paused, + push = excluded.push, + updated_at = now() + RETURNING *", + ) + .bind(name.as_str()) + .bind(millis(settings.visibility_timeout)) + .bind(count(settings.max_attempts)) + .bind(millis(settings.backoff.base)) + .bind(millis(settings.backoff.cap)) + .bind(millis(settings.retention)) + .bind(settings.paused) + .bind(settings.push.clone().map(Json)) + .fetch_one(&self.pool) + .await?; + + // Resuming a queue makes its messages deliverable again. + if !settings.paused { + notify(&self.pool, name).await?; + } + row.into_queue() + } + + async fn get_queue(&self, name: &QueueName) -> Result> { + let Some(queue) = self.find_queue(name).await? else { + return Ok(None); + }; + + let counts: Vec<(String, i64)> = sqlx::query_as( + "SELECT status, count(*) FROM dally_messages WHERE queue = $1 GROUP BY status", + ) + .bind(name.as_str()) + .fetch_all(&self.pool) + .await?; + + let mut stats = QueueStats::default(); + for (status, count) in counts { + add_count(&mut stats, &status, count)?; + } + Ok(Some(QueueSummary { queue, stats })) + } + + async fn list_queues(&self) -> Result> { + let rows: Vec = sqlx::query_as("SELECT * FROM dally_queues ORDER BY name") + .fetch_all(&self.pool) + .await?; + let counts: Vec<(String, String, i64)> = sqlx::query_as( + "SELECT queue, status, count(*) FROM dally_messages GROUP BY queue, status", + ) + .fetch_all(&self.pool) + .await?; + + let mut summaries = rows + .into_iter() + .map(|row| { + Ok(QueueSummary { + queue: row.into_queue()?, + stats: QueueStats::default(), + }) + }) + .collect::>>()?; + + for (queue, status, count) in counts { + if let Some(summary) = summaries + .iter_mut() + .find(|s| s.queue.name.as_str() == queue) + { + add_count(&mut summary.stats, &status, count)?; + } + } + Ok(summaries) + } + + async fn schedule( + &self, + queue: &QueueName, + messages: Vec, + ) -> Result> { + let mut tx = self.pool.begin().await?; + let mut results = Vec::with_capacity(messages.len()); + + for message in messages { + let (at, delay_ms) = split_run_at(message.run_at); + let inserted: Option = sqlx::query_as( + "INSERT INTO dally_messages + (id, queue, payload, status, priority, max_attempts, visibility_timeout_ms, + idempotency_key, run_at) + VALUES ($1, $2, $3, 'scheduled', $4, $5, $6, $7, + COALESCE($8, now() + $9::float8 * interval '1 millisecond')) + ON CONFLICT (queue, idempotency_key) WHERE idempotency_key IS NOT NULL + DO NOTHING + RETURNING *", + ) + .bind(message.id.as_uuid()) + .bind(queue.as_str()) + .bind(Json(&message.payload)) + .bind(message.priority) + .bind(count(message.max_attempts)) + .bind(millis(message.visibility_timeout)) + .bind(message.idempotency_key.as_deref()) + .bind(at) + .bind(delay_ms) + .fetch_optional(&mut *tx) + .await?; + + let result = match inserted { + Some(row) => Scheduled { + message: row.into_message()?, + created: true, + }, + None => { + let existing: MessageRow = sqlx::query_as( + "SELECT * FROM dally_messages WHERE queue = $1 AND idempotency_key = $2", + ) + .bind(queue.as_str()) + .bind(message.idempotency_key.as_deref()) + .fetch_one(&mut *tx) + .await?; + Scheduled { + message: existing.into_message()?, + created: false, + } + } + }; + results.push(result); + } + + if results.iter().any(|result| result.created) { + notify(&mut *tx, queue).await?; + } + tx.commit().await?; + Ok(results) + } + + async fn lease(&self, queue: &QueueName, limit: u32) -> Result> { + let mut tx = self.pool.begin().await?; + bury_expired(&mut tx, queue).await?; + + let rows: Vec = sqlx::query_as( + "WITH due AS ( + SELECT id FROM dally_messages + WHERE queue = $1 + AND ((status = 'scheduled' AND run_at <= now()) + OR (status = 'running' AND lease_expires_at <= now())) + ORDER BY priority DESC, run_at, id + LIMIT $2 + FOR UPDATE SKIP LOCKED + ) + UPDATE dally_messages AS m SET + status = 'running', + attempts = m.attempts + 1, + lease_token = replace(gen_random_uuid()::text, '-', ''), + lease_expires_at = now() + m.visibility_timeout_ms * interval '1 millisecond', + last_error = CASE WHEN m.status = 'running' THEN 'lease expired' + ELSE m.last_error END, + updated_at = now() + FROM due + WHERE m.id = due.id + RETURNING m.*", + ) + .bind(queue.as_str()) + .bind(i64::from(limit)) + .fetch_all(&mut *tx) + .await?; + tx.commit().await?; + + let mut leased = rows + .into_iter() + .map(MessageRow::into_leased) + .collect::>>()?; + // RETURNING does not keep the CTE's order. + leased.sort_by(|a, b| { + let (a, b) = (&a.message, &b.message); + b.priority + .cmp(&a.priority) + .then(a.run_at.cmp(&b.run_at)) + .then(a.id.cmp(&b.id)) + }); + Ok(leased) + } + + async fn ack(&self, id: MessageId, lease: &LeaseToken) -> Result> { + let row: Option = sqlx::query_as( + "UPDATE dally_messages SET + status = 'succeeded', + lease_token = NULL, + lease_expires_at = NULL, + finished_at = now(), + updated_at = now() + WHERE id = $1 AND status = 'running' AND lease_token = $2 + RETURNING *", + ) + .bind(id.as_uuid()) + .bind(lease.as_str()) + .fetch_optional(&self.pool) + .await?; + + row.map(MessageRow::into_message).transpose() + } + + async fn nack( + &self, + id: MessageId, + lease: &LeaseToken, + retry: Retry, + ) -> Result> { + let row: Option = sqlx::query_as( + "UPDATE dally_messages SET + status = CASE WHEN attempts >= max_attempts THEN 'dead' ELSE 'scheduled' END, + run_at = CASE WHEN attempts >= max_attempts THEN run_at + ELSE now() + $3::float8 * interval '1 millisecond' END, + finished_at = CASE WHEN attempts >= max_attempts THEN now() END, + last_error = $4, + lease_token = NULL, + lease_expires_at = NULL, + updated_at = now() + WHERE id = $1 AND status = 'running' AND lease_token = $2 + RETURNING *", + ) + .bind(id.as_uuid()) + .bind(lease.as_str()) + .bind(millis(retry.delay) as f64) + .bind(retry.error.as_deref()) + .fetch_optional(&self.pool) + .await?; + + row.map(MessageRow::into_message).transpose() + } + + async fn get_message(&self, id: MessageId) -> Result> { + let row: Option = sqlx::query_as("SELECT * FROM dally_messages WHERE id = $1") + .bind(id.as_uuid()) + .fetch_optional(&self.pool) + .await?; + + row.map(MessageRow::into_message).transpose() + } + + async fn list_messages(&self, filter: &MessageFilter) -> Result> { + // Fetch one extra row to learn whether there is another page. + let rows: Vec = sqlx::query_as( + "SELECT * FROM dally_messages + WHERE ($1::text IS NULL OR queue = $1) + AND ($2::text IS NULL OR status = $2) + AND ($3::uuid IS NULL OR id < $3) + ORDER BY id DESC + LIMIT $4", + ) + .bind(filter.queue.as_ref().map(QueueName::as_str)) + .bind(filter.status.map(|status| status.as_str())) + .bind(filter.before.map(|id| id.as_uuid())) + .bind(i64::from(filter.limit) + 1) + .fetch_all(&self.pool) + .await?; + + let mut items = rows + .into_iter() + .map(MessageRow::into_message) + .collect::>>()?; + + let next = if items.len() > filter.limit as usize { + items.truncate(filter.limit as usize); + items.last().map(|message| message.id) + } else { + None + }; + Ok(Page { items, next }) + } + + async fn cancel(&self, id: MessageId) -> Result> { + let row: Option = sqlx::query_as( + "UPDATE dally_messages SET + status = 'cancelled', + finished_at = now(), + updated_at = now() + WHERE id = $1 AND status = 'scheduled' + RETURNING *", + ) + .bind(id.as_uuid()) + .fetch_optional(&self.pool) + .await?; + + row.map(MessageRow::into_message).transpose() + } + + async fn reschedule(&self, id: MessageId, run_at: RunAt) -> Result> { + let (at, delay_ms) = split_run_at(run_at); + let row: Option = sqlx::query_as( + "UPDATE dally_messages SET + run_at = COALESCE($2, now() + $3::float8 * interval '1 millisecond'), + updated_at = now() + WHERE id = $1 AND status = 'scheduled' + RETURNING *", + ) + .bind(id.as_uuid()) + .bind(at) + .bind(delay_ms) + .fetch_optional(&self.pool) + .await?; + + let message = row.map(MessageRow::into_message).transpose()?; + if let Some(message) = &message { + notify(&self.pool, &message.queue).await?; + } + Ok(message) + } + + async fn retry_dead(&self, queue: &QueueName, ids: Option<&[MessageId]>) -> Result { + let ids: Option> = ids.map(|ids| ids.iter().map(MessageId::as_uuid).collect()); + let result = sqlx::query( + "UPDATE dally_messages SET + status = 'scheduled', + attempts = 0, + run_at = now(), + finished_at = NULL, + updated_at = now() + WHERE queue = $1 AND status = 'dead' AND ($2::uuid[] IS NULL OR id = ANY($2))", + ) + .bind(queue.as_str()) + .bind(ids) + .execute(&self.pool) + .await?; + + if result.rows_affected() > 0 { + notify(&self.pool, queue).await?; + } + Ok(result.rows_affected()) + } + + async fn prune(&self) -> Result { + let result = sqlx::query( + "DELETE FROM dally_messages AS m + USING dally_queues AS q + WHERE m.queue = q.name + AND m.finished_at IS NOT NULL + AND m.finished_at < now() - q.retention_ms * interval '1 millisecond'", + ) + .execute(&self.pool) + .await?; + + Ok(result.rows_affected()) + } + + async fn oldest_due(&self) -> Result>> { + let rows: Vec<(String, f64)> = sqlx::query_as( + "SELECT queue, EXTRACT(EPOCH FROM now() - min(run_at))::float8 + FROM dally_messages + WHERE status = 'scheduled' AND run_at <= now() + GROUP BY queue", + ) + .fetch_all(&self.pool) + .await?; + + let oldest = rows + .into_iter() + .map(|(queue, seconds)| { + Ok(( + QueueName::new(queue)?, + Duration::from_secs_f64(seconds.max(0.0)), + )) + }) + .collect::>()?; + Ok(Some(oldest)) + } + + fn subscribe(&self, queue: &QueueName) -> Subscription { + self.notifier.subscribe(queue) + } + + async fn now(&self) -> Result> { + let (now,): (DateTime,) = sqlx::query_as("SELECT now()").fetch_one(&self.pool).await?; + Ok(now) + } +} + +impl PostgresStorage { + async fn find_queue(&self, name: &QueueName) -> Result> { + let row: Option = sqlx::query_as("SELECT * FROM dally_queues WHERE name = $1") + .bind(name.as_str()) + .fetch_optional(&self.pool) + .await?; + + row.map(QueueRow::into_queue).transpose() + } +} + +/// Moves running messages whose lease expired on their last attempt to +/// `dead`. Runs before leasing, so they are never handed out again. +async fn bury_expired(tx: &mut Transaction<'_, Postgres>, queue: &QueueName) -> Result<()> { + sqlx::query( + "UPDATE dally_messages SET + status = 'dead', + last_error = 'lease expired', + lease_token = NULL, + lease_expires_at = NULL, + finished_at = now(), + updated_at = now() + WHERE queue = $1 + AND status = 'running' + AND lease_expires_at <= now() + AND attempts >= max_attempts", + ) + .bind(queue.as_str()) + .execute(&mut **tx) + .await?; + Ok(()) +} + +/// Tells every server's listener that `queue` has new due messages. Inside a +/// transaction, the notification is sent on commit. +async fn notify<'e, E>(executor: E, queue: &QueueName) -> Result<()> +where + E: sqlx::Executor<'e, Database = Postgres>, +{ + sqlx::query("SELECT pg_notify($1, $2)") + .bind(CHANNEL) + .bind(queue.as_str()) + .execute(executor) + .await?; + Ok(()) +} + +/// Splits a [`RunAt`] into the two parameters the SQL expects: an absolute +/// time, or a delay from the database's `now()`. +fn split_run_at(run_at: RunAt) -> (Option>, f64) { + match run_at { + RunAt::Now => (None, 0.0), + RunAt::After(delay) => (None, millis(delay) as f64), + RunAt::At(at) => (Some(at), 0.0), + } +} + +fn add_count(stats: &mut QueueStats, status: &str, count: i64) -> Result<()> { + let count = u64::try_from(count).unwrap_or_default(); + match status.parse::()? { + Status::Scheduled => stats.scheduled = count, + Status::Running => stats.running = count, + Status::Succeeded => stats.succeeded = count, + Status::Cancelled => stats.cancelled = count, + Status::Dead => stats.dead = count, + } + Ok(()) +} + +fn millis(duration: Duration) -> i64 { + i64::try_from(duration.as_millis()).unwrap_or(i64::MAX) +} + +fn from_millis(millis: i64) -> Duration { + Duration::from_millis(u64::try_from(millis).unwrap_or_default()) +} + +fn count(n: u32) -> i32 { + i32::try_from(n).unwrap_or(i32::MAX) +} + +fn from_count(n: i32) -> u32 { + u32::try_from(n).unwrap_or_default() +} + +#[derive(FromRow)] +struct QueueRow { + name: String, + visibility_timeout_ms: i64, + max_attempts: i32, + backoff_base_ms: i64, + backoff_cap_ms: i64, + retention_ms: i64, + paused: bool, + push: Option>, + created_at: DateTime, + updated_at: DateTime, +} + +impl QueueRow { + fn into_queue(self) -> Result { + Ok(Queue { + name: QueueName::new(self.name)?, + settings: QueueSettings { + visibility_timeout: from_millis(self.visibility_timeout_ms), + max_attempts: from_count(self.max_attempts), + backoff: Backoff { + base: from_millis(self.backoff_base_ms), + cap: from_millis(self.backoff_cap_ms), + }, + retention: from_millis(self.retention_ms), + paused: self.paused, + push: self.push.map(|Json(push)| push), + }, + created_at: self.created_at, + updated_at: self.updated_at, + }) + } +} + +#[derive(FromRow)] +struct MessageRow { + id: Uuid, + queue: String, + payload: Json, + status: String, + priority: i32, + attempts: i32, + max_attempts: i32, + visibility_timeout_ms: i64, + idempotency_key: Option, + run_at: DateTime, + lease_token: Option, + lease_expires_at: Option>, + last_error: Option, + created_at: DateTime, + updated_at: DateTime, + finished_at: Option>, +} + +impl MessageRow { + fn into_message(self) -> Result { + Ok(Message { + id: MessageId::from_uuid(self.id), + queue: QueueName::new(self.queue)?, + payload: self.payload.0, + status: self.status.parse()?, + priority: self.priority, + attempts: from_count(self.attempts), + max_attempts: from_count(self.max_attempts), + visibility_timeout: from_millis(self.visibility_timeout_ms), + idempotency_key: self.idempotency_key, + run_at: self.run_at, + lease_expires_at: self.lease_expires_at, + last_error: self.last_error, + created_at: self.created_at, + updated_at: self.updated_at, + finished_at: self.finished_at, + }) + } + + fn into_leased(mut self) -> Result { + let lease = self + .lease_token + .take() + .map(LeaseToken::from) + .ok_or_else(|| Error::invalid("leased message has no lease token"))?; + Ok(Leased { + message: self.into_message()?, + lease, + }) + } +} diff --git a/crates/dally-core/src/storage/redis/lua/ack.lua b/crates/dally-core/src/storage/redis/lua/ack.lua new file mode 100644 index 0000000..38185ef --- /dev/null +++ b/crates/dally-core/src/storage/redis/lua/ack.lua @@ -0,0 +1,12 @@ +-- Marks a running message as succeeded. +-- ARGV: prefix, message id, lease token. +-- Returns the message, or false if it is not running under this lease. + +local message = load_message(ARGV[2]) +if not message or message.status ~= 'running' or message.lease_token ~= ARGV[3] then + return false +end + +release_lease(message) +finish(message, 'succeeded', now_ms()) +return message_reply(message.id) diff --git a/crates/dally-core/src/storage/redis/lua/cancel.lua b/crates/dally-core/src/storage/redis/lua/cancel.lua new file mode 100644 index 0000000..c0fa103 --- /dev/null +++ b/crates/dally-core/src/storage/redis/lua/cancel.lua @@ -0,0 +1,12 @@ +-- Cancels a scheduled message. +-- ARGV: prefix, message id. +-- Returns the message, or false if it is not scheduled. + +local message = load_message(ARGV[2]) +if not message or message.status ~= 'scheduled' then + return false +end + +dequeue(message) +finish(message, 'cancelled', now_ms()) +return message_reply(message.id) diff --git a/crates/dally-core/src/storage/redis/lua/ensure_queue.lua b/crates/dally-core/src/storage/redis/lua/ensure_queue.lua new file mode 100644 index 0000000..6db448c --- /dev/null +++ b/crates/dally-core/src/storage/redis/lua/ensure_queue.lua @@ -0,0 +1,15 @@ +-- Returns a queue's hash, creating the queue with the given settings if it +-- does not exist. +-- ARGV: prefix, queue, then the settings as save_settings reads them. + +local queue = ARGV[2] +local key = queue_key(queue) + +if redis.call('EXISTS', key) == 0 then + save_settings(queue, 3) + local now = int(now_ms()) + redis.call('HSET', key, 'created_at', now, 'updated_at', now) + redis.call('ZADD', queues_key(), 0, queue) +end + +return redis.call('HGETALL', key) diff --git a/crates/dally-core/src/storage/redis/lua/lease.lua b/crates/dally-core/src/storage/redis/lua/lease.lua new file mode 100644 index 0000000..0a39f65 --- /dev/null +++ b/crates/dally-core/src/storage/redis/lua/lease.lua @@ -0,0 +1,58 @@ +-- Leases due messages from a queue, highest priority first, then oldest +-- run_at first. +-- ARGV: prefix, queue, then one fresh lease token per message to lease. +-- Returns the leased messages. + +-- How many delayed messages one call promotes to the ready set. Bounds the +-- work of a single call after a large batch becomes due at once; the rest +-- are promoted by the following polls. +local PROMOTE_LIMIT = 1000 + +local queue = ARGV[2] +local limit = #ARGV - 2 +local now = now_ms() +local running = queue_index(queue, 'running') +local delayed = queue_index(queue, 'delayed') +local ready = queue_index(queue, 'ready') + +local function make_ready(message) + redis.call('ZADD', ready, -tonumber(message.priority), ready_member(message.id, message.run_at)) +end + +-- Expired leases: the worker probably crashed. Retry right away if attempts +-- are left, otherwise the message is dead. +for _, id in ipairs(redis.call('ZRANGE', running, '-inf', now, 'BYSCORE')) do + local message = load_message(id) + release_lease(message) + redis.call('HSET', message_key(id), 'last_error', 'lease expired', 'updated_at', int(now)) + if tonumber(message.attempts) >= tonumber(message.max_attempts) then + finish(message, 'dead', now) + else + set_status(message, 'scheduled') + make_ready(message) + end +end + +for _, id in ipairs(redis.call('ZRANGE', delayed, '-inf', now, 'BYSCORE', 'LIMIT', 0, PROMOTE_LIMIT)) do + redis.call('ZREM', delayed, id) + make_ready(load_message(id)) +end + +local leased = {} +for i, member in ipairs(redis.call('ZRANGE', ready, 0, limit - 1)) do + local id = ready_member_id(member) + local message = load_message(id) + local expires = now + tonumber(message.visibility_timeout_ms) + + redis.call('ZREM', ready, member) + set_status(message, 'running') + redis.call('HSET', message_key(id), + 'attempts', int(tonumber(message.attempts) + 1), + 'lease_token', ARGV[2 + i], + 'lease_expires_at', int(expires), + 'updated_at', int(now)) + redis.call('ZADD', running, expires, id) + + leased[#leased + 1] = message_reply(id) +end +return leased diff --git a/crates/dally-core/src/storage/redis/lua/lib.lua b/crates/dally-core/src/storage/redis/lua/lib.lua new file mode 100644 index 0000000..3792a2d --- /dev/null +++ b/crates/dally-core/src/storage/redis/lua/lib.lua @@ -0,0 +1,138 @@ +-- Helpers shared by every script. Each script is this file followed by the +-- script's own body, so the helpers are plain locals. +-- +-- ARGV[1] is always the key prefix. Keys are built here rather than passed in +-- KEYS because most of them depend on data read inside the script, such as +-- the queue a message belongs to. This is fine on a single Redis server, but +-- it is why dally does not support Redis Cluster. + +local prefix = ARGV[1] + +-- In the order the Rust side expects counts. +local STATUSES = { 'scheduled', 'running', 'succeeded', 'cancelled', 'dead' } + +local function queues_key() + return prefix .. 'queues' +end + +local function queue_key(queue) + return prefix .. 'queue:' .. queue +end + +local function queue_index(queue, name) + return prefix .. 'queue:' .. queue .. ':' .. name +end + +local function status_index(queue, status) + return queue_index(queue, 'status:' .. status) +end + +local function message_key(id) + return prefix .. 'message:' .. id +end + +local function channel() + return prefix .. 'scheduled' +end + +local function now_ms() + local time = redis.call('TIME') + return tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000) +end + +-- Formats an integer for storage. Lua's tostring switches to exponent +-- notation above 1e14, which the Rust side would not parse. +local function int(n) + return string.format('%d', n) +end + +-- Members of the ready set share a score per priority, so within a priority +-- they sort by member: zero-padded run_at, then id. The offset keeps run_at +-- non-negative so its digits sort like numbers; 2^52 ms is about 142,000 +-- years either side of 1970, and anything beyond is clamped. +local RUN_AT_OFFSET = 2 ^ 52 +local ID_START = 18 -- 16 digits and a colon come before the id. + +local function ready_member(id, run_at) + local shifted = math.min(math.max(tonumber(run_at) + RUN_AT_OFFSET, 0), 2 * RUN_AT_OFFSET) + return string.format('%016d', shifted) .. ':' .. id +end + +local function ready_member_id(member) + return string.sub(member, ID_START) +end + +local function load_message(id) + local fields = redis.call('HGETALL', message_key(id)) + if #fields == 0 then + return nil + end + local message = {} + for i = 1, #fields, 2 do + message[fields[i]] = fields[i + 1] + end + return message +end + +-- What scripts return for a message: its hash as a flat field/value list. +local function message_reply(id) + return redis.call('HGETALL', message_key(id)) +end + +local function status_counts(queue) + local counts = {} + for i, status in ipairs(STATUSES) do + counts[i] = redis.call('ZCARD', status_index(queue, status)) + end + return counts +end + +local function set_status(message, status) + redis.call('ZREM', status_index(message.queue, message.status), message.id) + redis.call('ZADD', status_index(message.queue, status), 0, message.id) + redis.call('HSET', message_key(message.id), 'status', status) + message.status = status +end + +-- Every scheduled message enters through the delayed set. Leasing promotes +-- the due ones to the ready set, so only one place computes ready members. +local function enqueue(message, run_at) + redis.call('ZADD', queue_index(message.queue, 'delayed'), run_at, message.id) +end + +local function dequeue(message) + redis.call('ZREM', queue_index(message.queue, 'delayed'), message.id) + redis.call('ZREM', queue_index(message.queue, 'ready'), ready_member(message.id, message.run_at)) +end + +local function release_lease(message) + redis.call('ZREM', queue_index(message.queue, 'running'), message.id) + redis.call('HDEL', message_key(message.id), 'lease_token', 'lease_expires_at') +end + +local function finish(message, status, now) + set_status(message, status) + redis.call('HSET', message_key(message.id), 'finished_at', int(now), 'updated_at', int(now)) + redis.call('ZADD', queue_index(message.queue, 'finished'), now, message.id) +end + +-- Writes queue settings taken from ARGV, starting at position `first`: +-- visibility_timeout_ms, max_attempts, backoff_base_ms, backoff_cap_ms, +-- retention_ms, paused (0 or 1), push (JSON, or empty for none). +local function save_settings(queue, first) + local key = queue_key(queue) + redis.call('HSET', key, + 'name', queue, + 'visibility_timeout_ms', ARGV[first], + 'max_attempts', ARGV[first + 1], + 'backoff_base_ms', ARGV[first + 2], + 'backoff_cap_ms', ARGV[first + 3], + 'retention_ms', ARGV[first + 4], + 'paused', ARGV[first + 5]) + if ARGV[first + 6] == '' then + redis.call('HDEL', key, 'push') + else + redis.call('HSET', key, 'push', ARGV[first + 6]) + end +end + diff --git a/crates/dally-core/src/storage/redis/lua/nack.lua b/crates/dally-core/src/storage/redis/lua/nack.lua new file mode 100644 index 0000000..d1d0871 --- /dev/null +++ b/crates/dally-core/src/storage/redis/lua/nack.lua @@ -0,0 +1,29 @@ +-- Records a failed attempt: the message is retried after a delay, or is dead +-- if it has no attempts left. +-- ARGV: prefix, message id, lease token, retry delay in ms, and optionally +-- the error text. +-- Returns the message, or false if it is not running under this lease. + +local message = load_message(ARGV[2]) +if not message or message.status ~= 'running' or message.lease_token ~= ARGV[3] then + return false +end + +local key = message_key(message.id) +local now = now_ms() +release_lease(message) +if ARGV[5] then + redis.call('HSET', key, 'last_error', ARGV[5]) +else + redis.call('HDEL', key, 'last_error') +end + +if tonumber(message.attempts) >= tonumber(message.max_attempts) then + finish(message, 'dead', now) +else + local run_at = now + tonumber(ARGV[4]) + set_status(message, 'scheduled') + redis.call('HSET', key, 'run_at', int(run_at), 'updated_at', int(now)) + enqueue(message, run_at) +end +return message_reply(message.id) diff --git a/crates/dally-core/src/storage/redis/lua/prune.lua b/crates/dally-core/src/storage/redis/lua/prune.lua new file mode 100644 index 0000000..acfd70f --- /dev/null +++ b/crates/dally-core/src/storage/redis/lua/prune.lua @@ -0,0 +1,26 @@ +-- Deletes finished messages older than their queue's retention. +-- ARGV: prefix. +-- Returns how many messages were deleted. + +local now = now_ms() +local deleted = 0 + +for _, queue in ipairs(redis.call('ZRANGE', queues_key(), 0, -1)) do + local retention = tonumber(redis.call('HGET', queue_key(queue), 'retention_ms')) + local finished = queue_index(queue, 'finished') + local cutoff = '(' .. int(now - retention) + + for _, id in ipairs(redis.call('ZRANGE', finished, '-inf', cutoff, 'BYSCORE')) do + local message = load_message(id) + if message then + if message.idempotency_key then + redis.call('HDEL', queue_index(queue, 'keys'), message.idempotency_key) + end + redis.call('ZREM', status_index(queue, message.status), id) + redis.call('DEL', message_key(id)) + end + redis.call('ZREM', finished, id) + deleted = deleted + 1 + end +end +return deleted diff --git a/crates/dally-core/src/storage/redis/lua/put_queue.lua b/crates/dally-core/src/storage/redis/lua/put_queue.lua new file mode 100644 index 0000000..fd2bd84 --- /dev/null +++ b/crates/dally-core/src/storage/redis/lua/put_queue.lua @@ -0,0 +1,18 @@ +-- Creates a queue or replaces its settings, and returns its hash. +-- ARGV: prefix, queue, then the settings as save_settings reads them. + +local queue = ARGV[2] +local key = queue_key(queue) +local now = int(now_ms()) + +save_settings(queue, 3) +redis.call('HSETNX', key, 'created_at', now) +redis.call('HSET', key, 'updated_at', now) +redis.call('ZADD', queues_key(), 0, queue) + +-- Resuming a queue makes its messages deliverable again. +if ARGV[8] == '0' then + redis.call('PUBLISH', channel(), queue) +end + +return redis.call('HGETALL', key) diff --git a/crates/dally-core/src/storage/redis/lua/queues.lua b/crates/dally-core/src/storage/redis/lua/queues.lua new file mode 100644 index 0000000..171b9c5 --- /dev/null +++ b/crates/dally-core/src/storage/redis/lua/queues.lua @@ -0,0 +1,19 @@ +-- Returns {queue hash, status counts} for one queue, or for every queue in +-- name order. +-- ARGV: prefix, and optionally a queue name. + +local names +if ARGV[2] then + names = { ARGV[2] } +else + names = redis.call('ZRANGE', queues_key(), 0, -1) +end + +local summaries = {} +for _, queue in ipairs(names) do + local fields = redis.call('HGETALL', queue_key(queue)) + if #fields > 0 then + summaries[#summaries + 1] = { fields, status_counts(queue) } + end +end +return summaries diff --git a/crates/dally-core/src/storage/redis/lua/reschedule.lua b/crates/dally-core/src/storage/redis/lua/reschedule.lua new file mode 100644 index 0000000..8435ead --- /dev/null +++ b/crates/dally-core/src/storage/redis/lua/reschedule.lua @@ -0,0 +1,21 @@ +-- Changes when a scheduled message runs. +-- ARGV: prefix, message id, run_at in ms ('' to use the delay), delay in ms. +-- Returns the message, or false if it is not scheduled. + +local message = load_message(ARGV[2]) +if not message or message.status ~= 'scheduled' then + return false +end + +local now = now_ms() +local run_at = now + tonumber(ARGV[4]) +if ARGV[3] ~= '' then + run_at = tonumber(ARGV[3]) +end + +-- Dequeue before changing run_at: the ready set's member is built from it. +dequeue(message) +redis.call('HSET', message_key(message.id), 'run_at', int(run_at), 'updated_at', int(now)) +enqueue(message, run_at) +redis.call('PUBLISH', channel(), message.queue) +return message_reply(message.id) diff --git a/crates/dally-core/src/storage/redis/lua/retry_dead.lua b/crates/dally-core/src/storage/redis/lua/retry_dead.lua new file mode 100644 index 0000000..894af41 --- /dev/null +++ b/crates/dally-core/src/storage/redis/lua/retry_dead.lua @@ -0,0 +1,34 @@ +-- Moves dead messages back to scheduled with a fresh set of attempts, due +-- now. +-- ARGV: prefix, queue, then the ids to retry; with no ids, every dead +-- message in the queue. +-- Returns how many messages were moved. + +local queue = ARGV[2] +local ids = {} +if #ARGV > 2 then + for i = 3, #ARGV do + ids[#ids + 1] = ARGV[i] + end +else + ids = redis.call('ZRANGE', status_index(queue, 'dead'), 0, -1) +end + +local now = now_ms() +local moved = 0 +for _, id in ipairs(ids) do + local message = load_message(id) + if message and message.queue == queue and message.status == 'dead' then + redis.call('ZREM', queue_index(queue, 'finished'), id) + redis.call('HDEL', message_key(id), 'finished_at') + set_status(message, 'scheduled') + redis.call('HSET', message_key(id), 'attempts', '0', 'run_at', int(now), 'updated_at', int(now)) + enqueue(message, now) + moved = moved + 1 + end +end + +if moved > 0 then + redis.call('PUBLISH', channel(), queue) +end +return moved diff --git a/crates/dally-core/src/storage/redis/lua/schedule.lua b/crates/dally-core/src/storage/redis/lua/schedule.lua new file mode 100644 index 0000000..a4a087c --- /dev/null +++ b/crates/dally-core/src/storage/redis/lua/schedule.lua @@ -0,0 +1,56 @@ +-- Schedules a batch of messages in one queue. A message whose idempotency +-- key is already used in the queue is not stored; the existing one is +-- returned instead. +-- ARGV: prefix, queue, then eight values per message: id, payload, priority, +-- max_attempts, visibility_timeout_ms, idempotency_key ('' for none), +-- run_at in ms ('' to use the delay), delay_ms. +-- Returns {created (0 or 1), message} for each message, in order. + +local FIELDS = 8 +local queue = ARGV[2] +local keys = queue_index(queue, 'keys') +local now = now_ms() +local results = {} +local created_any = false + +for i = 3, #ARGV, FIELDS do + local id, payload, priority, max_attempts, visibility, key, at, delay = + unpack(ARGV, i, i + FIELDS - 1) + + local existing = key ~= '' and redis.call('HGET', keys, key) + if existing then + results[#results + 1] = { 0, message_reply(existing) } + else + local run_at = now + tonumber(delay) + if at ~= '' then + run_at = tonumber(at) + end + + redis.call('HSET', message_key(id), + 'id', id, + 'queue', queue, + 'payload', payload, + 'status', 'scheduled', + 'priority', priority, + 'attempts', '0', + 'max_attempts', max_attempts, + 'visibility_timeout_ms', visibility, + 'run_at', int(run_at), + 'created_at', int(now), + 'updated_at', int(now)) + if key ~= '' then + redis.call('HSET', message_key(id), 'idempotency_key', key) + redis.call('HSET', keys, key, id) + end + redis.call('ZADD', status_index(queue, 'scheduled'), 0, id) + enqueue({ id = id, queue = queue }, run_at) + + created_any = true + results[#results + 1] = { 1, message_reply(id) } + end +end + +if created_any then + redis.call('PUBLISH', channel(), queue) +end +return results diff --git a/crates/dally-core/src/storage/redis/mod.rs b/crates/dally-core/src/storage/redis/mod.rs new file mode 100644 index 0000000..f4d5641 --- /dev/null +++ b/crates/dally-core/src/storage/redis/mod.rs @@ -0,0 +1,602 @@ +//! The Redis backend. +//! +//! # Data model +//! +//! Every key starts with a prefix (`dally:` by default). For each queue: +//! +//! | Key | Type | Holds | +//! |-----------------------------|------------|-----------------------------------------| +//! | `queues` | sorted set | every queue name, score 0 (name order) | +//! | `queue:{q}` | hash | the queue's settings | +//! | `queue:{q}:delayed` | sorted set | scheduled ids, by `run_at` | +//! | `queue:{q}:ready` | sorted set | due ids, in delivery order | +//! | `queue:{q}:running` | sorted set | leased ids, by lease expiry | +//! | `queue:{q}:status:{status}` | sorted set | ids per status, score 0 (id order) | +//! | `queue:{q}:finished` | sorted set | finished ids, by `finished_at` | +//! | `queue:{q}:keys` | hash | idempotency key to message id | +//! | `message:{id}` | hash | the message | +//! +//! Being due depends on `run_at`, but delivery order depends on priority +//! first, so one sorted set cannot do both. Scheduled messages wait in +//! `delayed`; leasing first moves the due ones to `ready`, whose score is the +//! negated priority and whose members start with a zero-padded `run_at`, so +//! that ties sort by time. See `lua/lib.lua`. +//! +//! Ids are UUIDv7, so the per-status sets list messages in creation order by +//! member alone. +//! +//! # Atomicity and time +//! +//! Every operation that touches more than one key is a Lua script, so it runs +//! atomically. Scripts take their time from `TIME`, the Redis server's clock, +//! so several dally servers agree on what is due. Scripts build key names +//! from data they read, which works on a single Redis server or a replicated +//! setup, but not on Redis Cluster. +//! +//! # Durability +//! +//! Redis only keeps what it has persisted. Run it with `appendonly yes` in +//! production; see `docs/backends/redis.md`. + +use std::collections::HashMap; +use std::sync::{Arc, LazyLock}; +use std::time::Duration; + +use async_trait::async_trait; +use chrono::{DateTime, Utc}; +use futures_util::StreamExt; +use redis::aio::ConnectionManager; +use redis::{AsyncCommands, Script}; +use tokio::task::JoinHandle; +use uuid::Uuid; + +// Selects ring as rustls's crypto provider for `rediss://` connections. +use rustls as _; + +use super::{ConnectOptions, Storage}; +use crate::error::{Error, Result}; +use crate::message::{ + LeaseToken, Leased, Message, MessageFilter, MessageId, NewMessage, Page, Retry, RunAt, + Scheduled, Status, +}; +use crate::notify::{Notifier, Subscription}; +use crate::queue::{ + Backoff, PushSettings, Queue, QueueName, QueueSettings, QueueStats, QueueSummary, +}; + +const DEFAULT_PREFIX: &str = "dally:"; + +/// The Lua scripts, each prepended with the shared helpers. +struct Scripts { + ensure_queue: Script, + put_queue: Script, + queues: Script, + schedule: Script, + lease: Script, + ack: Script, + nack: Script, + cancel: Script, + reschedule: Script, + retry_dead: Script, + prune: Script, +} + +static SCRIPTS: LazyLock = LazyLock::new(|| { + let script = |body: &str| Script::new(&format!("{}\n{body}", include_str!("lua/lib.lua"))); + Scripts { + ensure_queue: script(include_str!("lua/ensure_queue.lua")), + put_queue: script(include_str!("lua/put_queue.lua")), + queues: script(include_str!("lua/queues.lua")), + schedule: script(include_str!("lua/schedule.lua")), + lease: script(include_str!("lua/lease.lua")), + ack: script(include_str!("lua/ack.lua")), + nack: script(include_str!("lua/nack.lua")), + cancel: script(include_str!("lua/cancel.lua")), + reschedule: script(include_str!("lua/reschedule.lua")), + retry_dead: script(include_str!("lua/retry_dead.lua")), + prune: script(include_str!("lua/prune.lua")), + } +}); + +/// A hash as scripts return it. +type Fields = HashMap; + +/// Stores queues and messages in Redis. +pub struct RedisStorage { + connection: ConnectionManager, + prefix: String, + notifier: Arc, + listener: JoinHandle<()>, +} + +impl RedisStorage { + /// Connects using a `redis://` or `rediss://` URL. A `prefix` query + /// parameter sets the key prefix (`redis://host/0?prefix=myapp:`); it + /// defaults to `dally:`. + /// + /// Redis has no schema, so `options.migrate` has nothing to do. + pub async fn connect(url: &str, _options: &ConnectOptions) -> Result { + let (url, prefix) = split_prefix(url)?; + let client = redis::Client::open(url)?; + let connection = client.get_connection_manager().await?; + + let notifier = Arc::new(Notifier::new()); + let channel = format!("{prefix}scheduled"); + let listener = tokio::spawn(listen(client, channel, Arc::clone(¬ifier))); + + Ok(Self { + connection, + prefix, + notifier, + listener, + }) + } + + /// Runs a script with the key prefix as its first argument. + fn invoke(&self, script: &'static Script) -> redis::ScriptInvocation<'static> { + let mut invocation = script.prepare_invoke(); + invocation.arg(&self.prefix); + invocation + } + + fn connection(&self) -> ConnectionManager { + // Cheap: the manager is a handle to one shared, multiplexed connection. + self.connection.clone() + } +} + +impl Drop for RedisStorage { + fn drop(&mut self) { + self.listener.abort(); + } +} + +/// Separates dally's `prefix` parameter from the URL the redis crate sees. +fn split_prefix(url: &str) -> Result<(String, String)> { + let mut parsed = + url::Url::parse(url).map_err(|err| Error::invalid(format!("invalid Redis URL: {err}")))?; + + let mut prefix = DEFAULT_PREFIX.to_owned(); + let others: Vec<(String, String)> = parsed + .query_pairs() + .filter_map(|(name, value)| { + if name == "prefix" { + prefix = value.into_owned(); + None + } else { + Some((name.into_owned(), value.into_owned())) + } + }) + .collect(); + + if others.is_empty() { + parsed.set_query(None); + } else { + parsed.query_pairs_mut().clear().extend_pairs(others); + } + Ok((parsed.into(), prefix)) +} + +/// Forwards `PUBLISH {prefix}scheduled ` to local subscribers. If the +/// connection drops, polls fall back to their periodic recheck until it is +/// back, so nothing is lost. +async fn listen(client: redis::Client, channel: String, notifier: Arc) { + loop { + let result: redis::RedisResult<()> = async { + let mut pubsub = client.get_async_pubsub().await?; + pubsub.subscribe(&channel).await?; + let mut messages = pubsub.on_message(); + while let Some(message) = messages.next().await { + if let Ok(queue) = message.get_payload::() + && let Ok(queue) = QueueName::new(queue) + { + notifier.notify(&queue); + } + } + Ok(()) + } + .await; + + match result { + Ok(()) => tracing::warn!("redis subscription closed; reconnecting in 1s"), + Err(err) => tracing::warn!(error = %err, "redis listener failed; retrying in 1s"), + } + tokio::time::sleep(Duration::from_secs(1)).await; + } +} + +#[async_trait] +impl Storage for RedisStorage { + async fn ensure_queue(&self, name: &QueueName, defaults: &QueueSettings) -> Result { + let mut invocation = self.invoke(&SCRIPTS.ensure_queue); + invocation.arg(name.as_str()); + settings_args(&mut invocation, defaults)?; + let fields: Fields = invocation.invoke_async(&mut self.connection()).await?; + parse_queue(&fields) + } + + async fn put_queue(&self, name: &QueueName, settings: &QueueSettings) -> Result { + let mut invocation = self.invoke(&SCRIPTS.put_queue); + invocation.arg(name.as_str()); + settings_args(&mut invocation, settings)?; + let fields: Fields = invocation.invoke_async(&mut self.connection()).await?; + parse_queue(&fields) + } + + async fn get_queue(&self, name: &QueueName) -> Result> { + let mut invocation = self.invoke(&SCRIPTS.queues); + invocation.arg(name.as_str()); + let summaries: Vec<(Fields, Vec)> = + invocation.invoke_async(&mut self.connection()).await?; + summaries.into_iter().next().map(parse_summary).transpose() + } + + async fn list_queues(&self) -> Result> { + let summaries: Vec<(Fields, Vec)> = self + .invoke(&SCRIPTS.queues) + .invoke_async(&mut self.connection()) + .await?; + summaries.into_iter().map(parse_summary).collect() + } + + async fn schedule( + &self, + queue: &QueueName, + messages: Vec, + ) -> Result> { + let mut invocation = self.invoke(&SCRIPTS.schedule); + invocation.arg(queue.as_str()); + for message in &messages { + let (at, delay) = split_run_at(message.run_at); + invocation + .arg(message.id.to_string()) + .arg(serde_json::to_string(&message.payload).map_err(Error::storage)?) + .arg(message.priority) + .arg(message.max_attempts) + .arg(millis(message.visibility_timeout)) + .arg(message.idempotency_key.as_deref().unwrap_or_default()) + .arg(at) + .arg(delay); + } + + let results: Vec<(i64, Fields)> = invocation.invoke_async(&mut self.connection()).await?; + results + .into_iter() + .map(|(created, fields)| { + Ok(Scheduled { + message: parse_message(&fields)?, + created: created == 1, + }) + }) + .collect() + } + + async fn lease(&self, queue: &QueueName, limit: u32) -> Result> { + let mut invocation = self.invoke(&SCRIPTS.lease); + invocation.arg(queue.as_str()); + for _ in 0..limit { + invocation.arg(LeaseToken::generate().as_str()); + } + + let leased: Vec = invocation.invoke_async(&mut self.connection()).await?; + leased.iter().map(parse_leased).collect() + } + + async fn ack(&self, id: MessageId, lease: &LeaseToken) -> Result> { + let mut invocation = self.invoke(&SCRIPTS.ack); + invocation.arg(id.to_string()).arg(lease.as_str()); + let fields: Option = invocation.invoke_async(&mut self.connection()).await?; + fields.as_ref().map(parse_message).transpose() + } + + async fn nack( + &self, + id: MessageId, + lease: &LeaseToken, + retry: Retry, + ) -> Result> { + let mut invocation = self.invoke(&SCRIPTS.nack); + invocation + .arg(id.to_string()) + .arg(lease.as_str()) + .arg(millis(retry.delay)); + if let Some(error) = &retry.error { + invocation.arg(error); + } + let fields: Option = invocation.invoke_async(&mut self.connection()).await?; + fields.as_ref().map(parse_message).transpose() + } + + async fn get_message(&self, id: MessageId) -> Result> { + let fields: Fields = self.connection().hgetall(self.message_key(id)).await?; + if fields.is_empty() { + return Ok(None); + } + parse_message(&fields).map(Some) + } + + async fn list_messages(&self, filter: &MessageFilter) -> Result> { + let ids = self.newest_ids(filter).await?; + + let mut pipe = redis::pipe(); + for id in &ids { + pipe.hgetall(self.message_key(*id)); + } + let rows: Vec = pipe.query_async(&mut self.connection()).await?; + + // A message can be pruned between the two round trips; skip it. + let mut items = rows + .iter() + .filter(|fields| !fields.is_empty()) + .map(parse_message) + .collect::>>()?; + + let next = if ids.len() > filter.limit as usize { + items.truncate(filter.limit as usize); + items.last().map(|message| message.id) + } else { + None + }; + Ok(Page { items, next }) + } + + async fn cancel(&self, id: MessageId) -> Result> { + let mut invocation = self.invoke(&SCRIPTS.cancel); + invocation.arg(id.to_string()); + let fields: Option = invocation.invoke_async(&mut self.connection()).await?; + fields.as_ref().map(parse_message).transpose() + } + + async fn reschedule(&self, id: MessageId, run_at: RunAt) -> Result> { + let (at, delay) = split_run_at(run_at); + let mut invocation = self.invoke(&SCRIPTS.reschedule); + invocation.arg(id.to_string()).arg(at).arg(delay); + let fields: Option = invocation.invoke_async(&mut self.connection()).await?; + fields.as_ref().map(parse_message).transpose() + } + + async fn retry_dead(&self, queue: &QueueName, ids: Option<&[MessageId]>) -> Result { + // An empty list means "these zero messages", not "all of them". + if ids.is_some_and(<[MessageId]>::is_empty) { + return Ok(0); + } + let mut invocation = self.invoke(&SCRIPTS.retry_dead); + invocation.arg(queue.as_str()); + for id in ids.unwrap_or_default() { + invocation.arg(id.to_string()); + } + Ok(invocation.invoke_async(&mut self.connection()).await?) + } + + async fn prune(&self) -> Result { + Ok(self + .invoke(&SCRIPTS.prune) + .invoke_async(&mut self.connection()) + .await?) + } + + fn subscribe(&self, queue: &QueueName) -> Subscription { + self.notifier.subscribe(queue) + } + + async fn now(&self) -> Result> { + let (seconds, micros): (i64, i64) = redis::cmd("TIME") + .query_async(&mut self.connection()) + .await?; + DateTime::from_timestamp_micros(seconds * 1_000_000 + micros) + .ok_or_else(|| Error::invalid("redis TIME is out of range")) + } +} + +impl RedisStorage { + fn message_key(&self, id: MessageId) -> String { + format!("{}message:{id}", self.prefix) + } + + fn status_key(&self, queue: &str, status: Status) -> String { + format!("{}queue:{queue}:status:{status}", self.prefix) + } + + /// The ids of up to `limit + 1` messages matching the filter, newest + /// first. Each (queue, status) pair has its own index, so this reads the + /// newest few from each index the filter covers and merges them. + async fn newest_ids(&self, filter: &MessageFilter) -> Result> { + let queues: Vec = match &filter.queue { + Some(queue) => vec![queue.to_string()], + None => { + self.connection() + .zrange(format!("{}queues", self.prefix), 0, -1) + .await? + } + }; + let statuses: Vec = match filter.status { + Some(status) => vec![status], + None => Status::ALL.to_vec(), + }; + let wanted = filter.limit as usize + 1; + let upper = match filter.before { + Some(before) => format!("({before}"), + None => "+".to_owned(), + }; + + let mut pipe = redis::pipe(); + for queue in &queues { + for status in &statuses { + pipe.cmd("ZRANGE") + .arg(self.status_key(queue, *status)) + .arg(&upper) + .arg("-") + .arg("BYLEX") + .arg("REV") + .arg("LIMIT") + .arg(0) + .arg(wanted); + } + } + let batches: Vec> = pipe.query_async(&mut self.connection()).await?; + + let mut ids = batches + .into_iter() + .flatten() + .map(|id| id.parse::()) + .collect::>>()?; + ids.sort_unstable_by(|a, b| b.cmp(a)); + ids.dedup(); + ids.truncate(wanted); + Ok(ids) + } +} + +/// Appends queue settings in the order `save_settings` in `lib.lua` reads +/// them. +fn settings_args( + invocation: &mut redis::ScriptInvocation<'_>, + settings: &QueueSettings, +) -> Result<()> { + let push = match &settings.push { + Some(push) => serde_json::to_string(push).map_err(Error::storage)?, + None => String::new(), + }; + invocation + .arg(millis(settings.visibility_timeout)) + .arg(settings.max_attempts) + .arg(millis(settings.backoff.base)) + .arg(millis(settings.backoff.cap)) + .arg(millis(settings.retention)) + .arg(u8::from(settings.paused)) + .arg(push); + Ok(()) +} + +/// Splits a [`RunAt`] into the two arguments scripts expect: an absolute time +/// in ms (empty for none), or a delay from the Redis clock. +fn split_run_at(run_at: RunAt) -> (String, i64) { + match run_at { + RunAt::Now => (String::new(), 0), + RunAt::After(delay) => (String::new(), millis(delay)), + RunAt::At(at) => (at.timestamp_millis().to_string(), 0), + } +} + +fn parse_summary((fields, counts): (Fields, Vec)) -> Result { + let count = |i: usize| counts.get(i).copied().unwrap_or_default(); + Ok(QueueSummary { + queue: parse_queue(&fields)?, + // In the order of STATUSES in lib.lua. + stats: QueueStats { + scheduled: count(0), + running: count(1), + succeeded: count(2), + cancelled: count(3), + dead: count(4), + }, + }) +} + +fn parse_queue(fields: &Fields) -> Result { + let push = match fields.get("push") { + Some(json) => Some(serde_json::from_str::(json).map_err(Error::storage)?), + None => None, + }; + Ok(Queue { + name: QueueName::new(field(fields, "name")?)?, + settings: QueueSettings { + visibility_timeout: duration(fields, "visibility_timeout_ms")?, + max_attempts: number(fields, "max_attempts")?, + backoff: Backoff { + base: duration(fields, "backoff_base_ms")?, + cap: duration(fields, "backoff_cap_ms")?, + }, + retention: duration(fields, "retention_ms")?, + paused: field(fields, "paused")? == "1", + push, + }, + created_at: timestamp(fields, "created_at")?, + updated_at: timestamp(fields, "updated_at")?, + }) +} + +fn parse_message(fields: &Fields) -> Result { + let id = Uuid::parse_str(field(fields, "id")?).map_err(Error::storage)?; + Ok(Message { + id: MessageId::from_uuid(id), + queue: QueueName::new(field(fields, "queue")?)?, + payload: serde_json::from_str(field(fields, "payload")?).map_err(Error::storage)?, + status: field(fields, "status")?.parse()?, + priority: number(fields, "priority")?, + attempts: number(fields, "attempts")?, + max_attempts: number(fields, "max_attempts")?, + visibility_timeout: duration(fields, "visibility_timeout_ms")?, + idempotency_key: fields.get("idempotency_key").cloned(), + run_at: timestamp(fields, "run_at")?, + lease_expires_at: optional_timestamp(fields, "lease_expires_at")?, + last_error: fields.get("last_error").cloned(), + created_at: timestamp(fields, "created_at")?, + updated_at: timestamp(fields, "updated_at")?, + finished_at: optional_timestamp(fields, "finished_at")?, + }) +} + +fn parse_leased(fields: &Fields) -> Result { + let lease = LeaseToken::from(field(fields, "lease_token")?.to_owned()); + Ok(Leased { + message: parse_message(fields)?, + lease, + }) +} + +fn field<'a>(fields: &'a Fields, name: &str) -> Result<&'a str> { + fields + .get(name) + .map(String::as_str) + .ok_or_else(|| Error::invalid(format!("stored record is missing {name}"))) +} + +fn number(fields: &Fields, name: &str) -> Result { + field(fields, name)? + .parse() + .map_err(|_| Error::invalid(format!("stored {name} is not a valid number"))) +} + +fn duration(fields: &Fields, name: &str) -> Result { + number(fields, name).map(Duration::from_millis) +} + +fn timestamp(fields: &Fields, name: &str) -> Result> { + let millis: i64 = number(fields, name)?; + DateTime::from_timestamp_millis(millis) + .ok_or_else(|| Error::invalid(format!("stored {name} is out of range"))) +} + +fn optional_timestamp(fields: &Fields, name: &str) -> Result>> { + if fields.contains_key(name) { + timestamp(fields, name).map(Some) + } else { + Ok(None) + } +} + +fn millis(duration: Duration) -> i64 { + i64::try_from(duration.as_millis()).unwrap_or(i64::MAX) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn prefix_is_taken_out_of_the_url() { + let (url, prefix) = split_prefix("redis://localhost:6379/2?prefix=myapp:").expect("valid"); + assert_eq!(url, "redis://localhost:6379/2"); + assert_eq!(prefix, "myapp:"); + + let (url, prefix) = + split_prefix("rediss://user:pw@host/0?protocol=resp3&prefix=x:").expect("valid"); + assert_eq!(url, "rediss://user:pw@host/0?protocol=resp3"); + assert_eq!(prefix, "x:"); + + let (url, prefix) = split_prefix("redis://localhost").expect("valid"); + assert_eq!(url, "redis://localhost"); + assert_eq!(prefix, DEFAULT_PREFIX); + } +} diff --git a/crates/dally-core/src/storage/sqlite.rs b/crates/dally-core/src/storage/sqlite.rs new file mode 100644 index 0000000..d08af19 --- /dev/null +++ b/crates/dally-core/src/storage/sqlite.rs @@ -0,0 +1,838 @@ +//! The SQLite backend, for local development and small deployments. +//! +//! # One server process per database +//! +//! Only one process may use a database file at a time, for two reasons: +//! long-poll notifications travel through an in-process channel, so a second +//! process would never wake the first one's waiting polls, and timestamps come +//! from the process clock (see below), which two processes need not agree on. +//! +//! [`SqliteStorage`] enforces this with an exclusive lock on a file next to +//! the database, named after it with `.lock` appended (`dally.sqlite.lock` for +//! `dally.sqlite`). Connecting while another process holds the lock fails with +//! [`Error::InvalidInput`]. The operating system releases the lock when the +//! storage is dropped or the process exits, even after a crash, so a stale +//! lock file never blocks a restart. The file itself is left in place. +//! In-memory databases (`sqlite::memory:`) are private to their process and +//! take no lock. +//! +//! # Concurrency +//! +//! The database runs in WAL mode, so reads go through a small pool of +//! read-only connections and never wait for writes. All writes go through one +//! connection, so concurrent writers queue up inside the process rather than +//! retrying against SQLite's file lock. Transactions that read before they +//! write, like leasing, start with `BEGIN IMMEDIATE`: they take the write lock +//! before looking at anything, so two pollers can never pick the same due +//! message. +//! +//! # Time +//! +//! Timestamps come from the process clock. Other backends use the storage +//! clock so that several servers agree on what is due; with a single process +//! there is only one clock to begin with, and SQLite's own date functions read +//! that same system clock anyway. Timestamps are stored as integer +//! milliseconds since the Unix epoch, which sort and compare correctly as +//! plain numbers, unlike SQLite's text dates. Sub-millisecond precision is +//! dropped. + +use std::collections::BTreeMap; +use std::fs::{File, OpenOptions, TryLockError}; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use async_trait::async_trait; +use chrono::{DateTime, Utc}; +use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePool, SqlitePoolOptions}; +use sqlx::types::Json; +use sqlx::{FromRow, Sqlite, Transaction}; +use uuid::fmt::Hyphenated; + +use super::{ConnectOptions, Storage}; +use crate::error::{Error, Result}; +use crate::message::{ + LeaseToken, Leased, Message, MessageFilter, MessageId, NewMessage, Page, Retry, RunAt, + Scheduled, Status, +}; +use crate::notify::{Notifier, Subscription}; +use crate::queue::{ + Backoff, PushSettings, Queue, QueueName, QueueSettings, QueueStats, QueueSummary, +}; + +static MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate!("./migrations/sqlite"); + +/// How long a connection waits for a lock held by someone else, such as the +/// `sqlite3` shell or a backup, before giving up. +const BUSY_TIMEOUT: Duration = Duration::from_secs(5); + +/// Read connections. Reads are short, so a few are plenty. +const READERS: u32 = 4; + +/// Starts a transaction that holds the write lock from its first statement. +const BEGIN_IMMEDIATE: &str = "BEGIN IMMEDIATE"; + +/// Stores queues and messages in a SQLite database. +pub struct SqliteStorage { + writer: SqlitePool, + /// For a file database, read-only connections next to the writer. For an + /// in-memory database, the writer pool itself. + reader: SqlitePool, + notifier: Notifier, + /// Held for as long as the storage lives. Dropping the file releases the + /// lock. + _lock: Option, +} + +impl SqliteStorage { + /// Connects using a `sqlite:` URL: `sqlite://relative/path.sqlite`, + /// `sqlite:///absolute/path.sqlite` or `sqlite::memory:`. A database file + /// that does not exist yet is created. + /// + /// Fails with [`Error::InvalidInput`] if another process is using the + /// database file. + pub async fn connect(url: &str, options: &ConnectOptions) -> Result { + let connect_options: SqliteConnectOptions = url.parse()?; + if is_in_memory(url) { + Self::open_in_memory(connect_options, options).await + } else { + Self::open_file(connect_options, options).await + } + } + + /// Opens the database file at `path`, creating it if it does not exist. + /// + /// Fails with [`Error::InvalidInput`] if another process is using it. + pub async fn open(path: impl AsRef, options: &ConnectOptions) -> Result { + Self::open_file(SqliteConnectOptions::new().filename(path), options).await + } + + async fn open_file( + connect_options: SqliteConnectOptions, + options: &ConnectOptions, + ) -> Result { + let connect_options = connect_options + .foreign_keys(true) + .busy_timeout(BUSY_TIMEOUT); + // Lock before touching the database, so a second server never gets + // as far as running migrations. + let lock = lock_database(connect_options.get_filename())?; + + let writer = single_connection_pool( + connect_options + .clone() + .create_if_missing(true) + .journal_mode(SqliteJournalMode::Wal), + ) + .await?; + if options.migrate { + MIGRATOR.run(&writer).await.map_err(Error::storage)?; + } + + // Readers connect after the writer, which has created the file and + // switched it to WAL mode. + let reader = SqlitePoolOptions::new() + .max_connections(READERS) + .connect_with(connect_options.read_only(true)) + .await?; + + Ok(Self { + writer, + reader, + notifier: Notifier::new(), + _lock: Some(lock), + }) + } + + async fn open_in_memory( + connect_options: SqliteConnectOptions, + options: &ConnectOptions, + ) -> Result { + // One connection serves reads and writes. More connections would + // need SQLite's shared cache, whose lock conflicts are not retried by + // the busy timeout. + let pool = single_connection_pool(connect_options.foreign_keys(true)).await?; + if options.migrate { + MIGRATOR.run(&pool).await.map_err(Error::storage)?; + } + + Ok(Self { + writer: pool.clone(), + reader: pool, + notifier: Notifier::new(), + _lock: None, + }) + } +} + +/// A pool that opens one connection and keeps it forever. An in-memory +/// database disappears with its last connection, and for a file the one +/// writer is opened once and reused. +async fn single_connection_pool(connect_options: SqliteConnectOptions) -> Result { + let pool = SqlitePoolOptions::new() + .max_connections(1) + .min_connections(1) + .idle_timeout(None) + .max_lifetime(None) + .connect_with(connect_options) + .await?; + Ok(pool) +} + +/// Whether a `sqlite:` URL names an in-memory database, following the same +/// rules as [`SqliteConnectOptions`]'s URL parser. +fn is_in_memory(url: &str) -> bool { + let rest = url + .trim_start_matches("sqlite://") + .trim_start_matches("sqlite:"); + let (database, params) = rest.split_once('?').unwrap_or((rest, "")); + database == ":memory:" || params.split('&').any(|param| param == "mode=memory") +} + +/// Takes the exclusive lock that keeps a second server process away from the +/// database at `database`. +fn lock_database(database: &Path) -> Result { + let path = lock_path(database); + let file = OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(&path) + .map_err(|err| { + Error::Storage(format!("cannot open lock file {}: {err}", path.display()).into()) + })?; + + match file.try_lock() { + Ok(()) => Ok(file), + Err(TryLockError::WouldBlock) => Err(Error::invalid(format!( + "SQLite database {} is already in use by another dally server \ + (lock file {} is held); SQLite supports one server process per database, \ + use PostgreSQL to run several", + database.display(), + path.display() + ))), + Err(TryLockError::Error(err)) => Err(Error::Storage( + format!("cannot lock {}: {err}", path.display()).into(), + )), + } +} + +fn lock_path(database: &Path) -> PathBuf { + let mut path = database.as_os_str().to_owned(); + path.push(".lock"); + PathBuf::from(path) +} + +#[async_trait] +impl Storage for SqliteStorage { + async fn ensure_queue(&self, name: &QueueName, defaults: &QueueSettings) -> Result { + // Most calls find the queue, so look before trying to insert. + if let Some(queue) = self.find_queue(name).await? { + return Ok(queue); + } + + let row: Option = sqlx::query_as( + "INSERT INTO dally_queues + (name, visibility_timeout_ms, max_attempts, backoff_base_ms, backoff_cap_ms, + retention_ms, paused, push, created_at, updated_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9) + ON CONFLICT (name) DO NOTHING + RETURNING *", + ) + .bind(name.as_str()) + .bind(millis(defaults.visibility_timeout)) + .bind(i64::from(defaults.max_attempts)) + .bind(millis(defaults.backoff.base)) + .bind(millis(defaults.backoff.cap)) + .bind(millis(defaults.retention)) + .bind(defaults.paused) + .bind(defaults.push.clone().map(Json)) + .bind(now_millis()) + .fetch_optional(&self.writer) + .await?; + + match row { + Some(row) => row.into_queue(), + // Another task created it between our select and insert. + None => self + .find_queue(name) + .await? + .ok_or_else(|| Error::QueueNotFound(name.clone())), + } + } + + async fn put_queue(&self, name: &QueueName, settings: &QueueSettings) -> Result { + let row: QueueRow = sqlx::query_as( + "INSERT INTO dally_queues + (name, visibility_timeout_ms, max_attempts, backoff_base_ms, backoff_cap_ms, + retention_ms, paused, push, created_at, updated_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9) + ON CONFLICT (name) DO UPDATE SET + visibility_timeout_ms = excluded.visibility_timeout_ms, + max_attempts = excluded.max_attempts, + backoff_base_ms = excluded.backoff_base_ms, + backoff_cap_ms = excluded.backoff_cap_ms, + retention_ms = excluded.retention_ms, + paused = excluded.paused, + push = excluded.push, + updated_at = excluded.updated_at + RETURNING *", + ) + .bind(name.as_str()) + .bind(millis(settings.visibility_timeout)) + .bind(i64::from(settings.max_attempts)) + .bind(millis(settings.backoff.base)) + .bind(millis(settings.backoff.cap)) + .bind(millis(settings.retention)) + .bind(settings.paused) + .bind(settings.push.clone().map(Json)) + .bind(now_millis()) + .fetch_one(&self.writer) + .await?; + + // Resuming a queue makes its messages deliverable again. + if !settings.paused { + self.notifier.notify(name); + } + row.into_queue() + } + + async fn get_queue(&self, name: &QueueName) -> Result> { + let Some(queue) = self.find_queue(name).await? else { + return Ok(None); + }; + + let counts: Vec<(String, i64)> = sqlx::query_as( + "SELECT status, count(*) FROM dally_messages WHERE queue = ?1 GROUP BY status", + ) + .bind(name.as_str()) + .fetch_all(&self.reader) + .await?; + + let mut stats = QueueStats::default(); + for (status, count) in counts { + add_count(&mut stats, &status, count)?; + } + Ok(Some(QueueSummary { queue, stats })) + } + + async fn list_queues(&self) -> Result> { + let rows: Vec = sqlx::query_as("SELECT * FROM dally_queues ORDER BY name") + .fetch_all(&self.reader) + .await?; + let counts: Vec<(String, String, i64)> = sqlx::query_as( + "SELECT queue, status, count(*) FROM dally_messages GROUP BY queue, status", + ) + .fetch_all(&self.reader) + .await?; + + let mut summaries = rows + .into_iter() + .map(|row| { + Ok(QueueSummary { + queue: row.into_queue()?, + stats: QueueStats::default(), + }) + }) + .collect::>>()?; + + for (queue, status, count) in counts { + if let Some(summary) = summaries + .iter_mut() + .find(|s| s.queue.name.as_str() == queue) + { + add_count(&mut summary.stats, &status, count)?; + } + } + Ok(summaries) + } + + async fn schedule( + &self, + queue: &QueueName, + messages: Vec, + ) -> Result> { + let mut tx = self.writer.begin_with(BEGIN_IMMEDIATE).await?; + let now = now_millis(); + let mut results = Vec::with_capacity(messages.len()); + + for message in messages { + let inserted: Option = sqlx::query_as( + "INSERT INTO dally_messages + (id, queue, payload, status, priority, max_attempts, visibility_timeout_ms, + idempotency_key, run_at, created_at, updated_at) + VALUES (?1, ?2, ?3, 'scheduled', ?4, ?5, ?6, ?7, ?8, ?9, ?9) + ON CONFLICT (queue, idempotency_key) WHERE idempotency_key IS NOT NULL + DO NOTHING + RETURNING *", + ) + .bind(message.id.as_uuid().hyphenated()) + .bind(queue.as_str()) + .bind(Json(&message.payload)) + .bind(message.priority) + .bind(i64::from(message.max_attempts)) + .bind(millis(message.visibility_timeout)) + .bind(message.idempotency_key.as_deref()) + .bind(run_at_millis(message.run_at, now)) + .bind(now) + .fetch_optional(&mut *tx) + .await?; + + let result = match inserted { + Some(row) => Scheduled { + message: row.into_message()?, + created: true, + }, + None => { + let existing: MessageRow = sqlx::query_as( + "SELECT * FROM dally_messages WHERE queue = ?1 AND idempotency_key = ?2", + ) + .bind(queue.as_str()) + .bind(message.idempotency_key.as_deref()) + .fetch_one(&mut *tx) + .await?; + Scheduled { + message: existing.into_message()?, + created: false, + } + } + }; + results.push(result); + } + tx.commit().await?; + + if results.iter().any(|result| result.created) { + self.notifier.notify(queue); + } + Ok(results) + } + + async fn lease(&self, queue: &QueueName, limit: u32) -> Result> { + let mut tx = self.writer.begin_with(BEGIN_IMMEDIATE).await?; + let now = now_millis(); + bury_expired(&mut tx, queue, now).await?; + + let due: Vec<(Hyphenated,)> = sqlx::query_as( + "SELECT id FROM dally_messages + WHERE queue = ?1 + AND ((status = 'scheduled' AND run_at <= ?2) + OR (status = 'running' AND lease_expires_at <= ?2)) + ORDER BY priority DESC, run_at, id + LIMIT ?3", + ) + .bind(queue.as_str()) + .bind(now) + .bind(i64::from(limit)) + .fetch_all(&mut *tx) + .await?; + + // One update per message, because each gets its own token. The write + // lock is held throughout, so nothing can take these rows meanwhile. + let mut leased = Vec::with_capacity(due.len()); + for (id,) in due { + let row: MessageRow = sqlx::query_as( + "UPDATE dally_messages SET + status = 'running', + attempts = attempts + 1, + lease_token = ?2, + lease_expires_at = ?3 + visibility_timeout_ms, + last_error = CASE WHEN status = 'running' THEN 'lease expired' + ELSE last_error END, + updated_at = ?3 + WHERE id = ?1 + RETURNING *", + ) + .bind(id) + .bind(LeaseToken::generate().as_str()) + .bind(now) + .fetch_one(&mut *tx) + .await?; + leased.push(row.into_leased()?); + } + tx.commit().await?; + + Ok(leased) + } + + async fn ack(&self, id: MessageId, lease: &LeaseToken) -> Result> { + let row: Option = sqlx::query_as( + "UPDATE dally_messages SET + status = 'succeeded', + lease_token = NULL, + lease_expires_at = NULL, + finished_at = ?3, + updated_at = ?3 + WHERE id = ?1 AND status = 'running' AND lease_token = ?2 + RETURNING *", + ) + .bind(id.as_uuid().hyphenated()) + .bind(lease.as_str()) + .bind(now_millis()) + .fetch_optional(&self.writer) + .await?; + + row.map(MessageRow::into_message).transpose() + } + + async fn nack( + &self, + id: MessageId, + lease: &LeaseToken, + retry: Retry, + ) -> Result> { + let now = now_millis(); + let row: Option = sqlx::query_as( + "UPDATE dally_messages SET + status = CASE WHEN attempts >= max_attempts THEN 'dead' ELSE 'scheduled' END, + run_at = CASE WHEN attempts >= max_attempts THEN run_at ELSE ?3 END, + finished_at = CASE WHEN attempts >= max_attempts THEN ?5 END, + last_error = ?4, + lease_token = NULL, + lease_expires_at = NULL, + updated_at = ?5 + WHERE id = ?1 AND status = 'running' AND lease_token = ?2 + RETURNING *", + ) + .bind(id.as_uuid().hyphenated()) + .bind(lease.as_str()) + .bind(now.saturating_add(millis(retry.delay))) + .bind(retry.error.as_deref()) + .bind(now) + .fetch_optional(&self.writer) + .await?; + + row.map(MessageRow::into_message).transpose() + } + + async fn get_message(&self, id: MessageId) -> Result> { + let row: Option = sqlx::query_as("SELECT * FROM dally_messages WHERE id = ?1") + .bind(id.as_uuid().hyphenated()) + .fetch_optional(&self.reader) + .await?; + + row.map(MessageRow::into_message).transpose() + } + + async fn list_messages(&self, filter: &MessageFilter) -> Result> { + // Fetch one extra row to learn whether there is another page. + let rows: Vec = sqlx::query_as( + "SELECT * FROM dally_messages + WHERE (?1 IS NULL OR queue = ?1) + AND (?2 IS NULL OR status = ?2) + AND (?3 IS NULL OR id < ?3) + ORDER BY id DESC + LIMIT ?4", + ) + .bind(filter.queue.as_ref().map(QueueName::as_str)) + .bind(filter.status.map(|status| status.as_str())) + .bind(filter.before.map(|id| id.as_uuid().hyphenated())) + .bind(i64::from(filter.limit) + 1) + .fetch_all(&self.reader) + .await?; + + let mut items = rows + .into_iter() + .map(MessageRow::into_message) + .collect::>>()?; + + let next = if items.len() > filter.limit as usize { + items.truncate(filter.limit as usize); + items.last().map(|message| message.id) + } else { + None + }; + Ok(Page { items, next }) + } + + async fn cancel(&self, id: MessageId) -> Result> { + let row: Option = sqlx::query_as( + "UPDATE dally_messages SET + status = 'cancelled', + finished_at = ?2, + updated_at = ?2 + WHERE id = ?1 AND status = 'scheduled' + RETURNING *", + ) + .bind(id.as_uuid().hyphenated()) + .bind(now_millis()) + .fetch_optional(&self.writer) + .await?; + + row.map(MessageRow::into_message).transpose() + } + + async fn reschedule(&self, id: MessageId, run_at: RunAt) -> Result> { + let now = now_millis(); + let row: Option = sqlx::query_as( + "UPDATE dally_messages SET + run_at = ?2, + updated_at = ?3 + WHERE id = ?1 AND status = 'scheduled' + RETURNING *", + ) + .bind(id.as_uuid().hyphenated()) + .bind(run_at_millis(run_at, now)) + .bind(now) + .fetch_optional(&self.writer) + .await?; + + let message = row.map(MessageRow::into_message).transpose()?; + if let Some(message) = &message { + self.notifier.notify(&message.queue); + } + Ok(message) + } + + async fn retry_dead(&self, queue: &QueueName, ids: Option<&[MessageId]>) -> Result { + // SQLite has no array parameters, so the ids travel as a JSON array. + let result = sqlx::query( + "UPDATE dally_messages SET + status = 'scheduled', + attempts = 0, + run_at = ?3, + finished_at = NULL, + updated_at = ?3 + WHERE queue = ?1 + AND status = 'dead' + AND (?2 IS NULL OR id IN (SELECT value FROM json_each(?2)))", + ) + .bind(queue.as_str()) + .bind(ids.map(Json)) + .bind(now_millis()) + .execute(&self.writer) + .await?; + + if result.rows_affected() > 0 { + self.notifier.notify(queue); + } + Ok(result.rows_affected()) + } + + async fn prune(&self) -> Result { + let result = sqlx::query( + "DELETE FROM dally_messages + WHERE finished_at IS NOT NULL + AND finished_at < ?1 - (SELECT retention_ms FROM dally_queues + WHERE name = dally_messages.queue)", + ) + .bind(now_millis()) + .execute(&self.writer) + .await?; + + Ok(result.rows_affected()) + } + + async fn oldest_due(&self) -> Result>> { + let rows: Vec<(String, i64)> = sqlx::query_as( + "SELECT queue, ?1 - min(run_at) + FROM dally_messages + WHERE status = 'scheduled' AND run_at <= ?1 + GROUP BY queue", + ) + .bind(now_millis()) + .fetch_all(&self.reader) + .await?; + + let oldest = rows + .into_iter() + .map(|(queue, waited)| Ok((QueueName::new(queue)?, from_millis(waited)))) + .collect::>()?; + Ok(Some(oldest)) + } + + fn subscribe(&self, queue: &QueueName) -> Subscription { + self.notifier.subscribe(queue) + } + + async fn now(&self) -> Result> { + Ok(Utc::now()) + } +} + +impl SqliteStorage { + async fn find_queue(&self, name: &QueueName) -> Result> { + let row: Option = sqlx::query_as("SELECT * FROM dally_queues WHERE name = ?1") + .bind(name.as_str()) + .fetch_optional(&self.reader) + .await?; + + row.map(QueueRow::into_queue).transpose() + } +} + +/// Moves running messages whose lease expired on their last attempt to +/// `dead`. Runs before leasing, so they are never handed out again. +async fn bury_expired(tx: &mut Transaction<'_, Sqlite>, queue: &QueueName, now: i64) -> Result<()> { + sqlx::query( + "UPDATE dally_messages SET + status = 'dead', + last_error = 'lease expired', + lease_token = NULL, + lease_expires_at = NULL, + finished_at = ?2, + updated_at = ?2 + WHERE queue = ?1 + AND status = 'running' + AND lease_expires_at <= ?2 + AND attempts >= max_attempts", + ) + .bind(queue.as_str()) + .bind(now) + .execute(&mut **tx) + .await?; + Ok(()) +} + +fn add_count(stats: &mut QueueStats, status: &str, count: i64) -> Result<()> { + let count = u64::try_from(count).unwrap_or_default(); + match status.parse::()? { + Status::Scheduled => stats.scheduled = count, + Status::Running => stats.running = count, + Status::Succeeded => stats.succeeded = count, + Status::Cancelled => stats.cancelled = count, + Status::Dead => stats.dead = count, + } + Ok(()) +} + +fn now_millis() -> i64 { + Utc::now().timestamp_millis() +} + +fn run_at_millis(run_at: RunAt, now: i64) -> i64 { + match run_at { + RunAt::Now => now, + RunAt::After(delay) => now.saturating_add(millis(delay)), + RunAt::At(at) => at.timestamp_millis(), + } +} + +fn from_timestamp(millis: i64) -> Result> { + DateTime::from_timestamp_millis(millis) + .ok_or_else(|| Error::invalid(format!("stored timestamp {millis} is out of range"))) +} + +fn millis(duration: Duration) -> i64 { + i64::try_from(duration.as_millis()).unwrap_or(i64::MAX) +} + +fn from_millis(millis: i64) -> Duration { + Duration::from_millis(u64::try_from(millis).unwrap_or_default()) +} + +fn from_count(n: i64) -> u32 { + u32::try_from(n).unwrap_or_default() +} + +#[derive(FromRow)] +struct QueueRow { + name: String, + visibility_timeout_ms: i64, + max_attempts: i64, + backoff_base_ms: i64, + backoff_cap_ms: i64, + retention_ms: i64, + paused: bool, + push: Option>, + created_at: i64, + updated_at: i64, +} + +impl QueueRow { + fn into_queue(self) -> Result { + Ok(Queue { + name: QueueName::new(self.name)?, + settings: QueueSettings { + visibility_timeout: from_millis(self.visibility_timeout_ms), + max_attempts: from_count(self.max_attempts), + backoff: Backoff { + base: from_millis(self.backoff_base_ms), + cap: from_millis(self.backoff_cap_ms), + }, + retention: from_millis(self.retention_ms), + paused: self.paused, + push: self.push.map(|Json(push)| push), + }, + created_at: from_timestamp(self.created_at)?, + updated_at: from_timestamp(self.updated_at)?, + }) + } +} + +#[derive(FromRow)] +struct MessageRow { + id: Hyphenated, + queue: String, + payload: Json, + status: String, + priority: i32, + attempts: i64, + max_attempts: i64, + visibility_timeout_ms: i64, + idempotency_key: Option, + run_at: i64, + lease_token: Option, + lease_expires_at: Option, + last_error: Option, + created_at: i64, + updated_at: i64, + finished_at: Option, +} + +impl MessageRow { + fn into_message(self) -> Result { + Ok(Message { + id: MessageId::from_uuid(self.id.into_uuid()), + queue: QueueName::new(self.queue)?, + payload: self.payload.0, + status: self.status.parse()?, + priority: self.priority, + attempts: from_count(self.attempts), + max_attempts: from_count(self.max_attempts), + visibility_timeout: from_millis(self.visibility_timeout_ms), + idempotency_key: self.idempotency_key, + run_at: from_timestamp(self.run_at)?, + lease_expires_at: self.lease_expires_at.map(from_timestamp).transpose()?, + last_error: self.last_error, + created_at: from_timestamp(self.created_at)?, + updated_at: from_timestamp(self.updated_at)?, + finished_at: self.finished_at.map(from_timestamp).transpose()?, + }) + } + + fn into_leased(mut self) -> Result { + let lease = self + .lease_token + .take() + .map(LeaseToken::from) + .ok_or_else(|| Error::invalid("leased message has no lease token"))?; + Ok(Leased { + message: self.into_message()?, + lease, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn recognises_in_memory_urls() { + assert!(is_in_memory("sqlite::memory:")); + assert!(is_in_memory("sqlite://:memory:")); + assert!(is_in_memory("sqlite://shared?mode=memory&cache=shared")); + assert!(!is_in_memory("sqlite://dally.sqlite")); + assert!(!is_in_memory( + "sqlite:///var/lib/dally/dally.sqlite?mode=rwc" + )); + } + + #[test] + fn lock_file_sits_next_to_the_database() { + assert_eq!( + lock_path(Path::new("/var/lib/dally/dally.sqlite")), + Path::new("/var/lib/dally/dally.sqlite.lock") + ); + assert_eq!(lock_path(Path::new("dally")), Path::new("dally.lock")); + } +} diff --git a/crates/dally-core/tests/conformance/mod.rs b/crates/dally-core/tests/conformance/mod.rs new file mode 100644 index 0000000..3a3eb90 --- /dev/null +++ b/crates/dally-core/tests/conformance/mod.rs @@ -0,0 +1,861 @@ +//! Behaviour every storage backend must have. +//! +//! Each test gets a fresh, empty storage and drives it through [`Service`], +//! so it checks both the backend and the rules on top of it. A backend's test +//! file only provides a setup function and calls [`conformance_tests!`]: +//! +//! ```ignore +//! mod conformance; +//! +//! async fn setup() -> Option> { ... } +//! +//! conformance_tests!(setup); +//! ``` +//! +//! Setup returns `None` when the backend is not available (for example, no +//! database URL in the environment), and the tests are skipped with a note. + +#![allow(dead_code)] + +use std::collections::HashSet; +use std::sync::Arc; +use std::time::Duration; + +use chrono::Utc; +use dally_core::{ + Error, Leased, MessageFilter, NackRequest, PollRequest, PushSettings, QueueName, QueueSettings, + RunAt, ScheduleRequest, Service, Status, Storage, +}; +use serde_json::json; + +/// Generates one `#[tokio::test]` per conformance check, each with its own +/// storage from `$setup`. +#[macro_export] +macro_rules! conformance_tests { + ($setup:path) => { + $crate::conformance_tests!(@each $setup; + schedule_then_get, + idempotency_key_returns_existing_message, + idempotency_key_is_scoped_to_queue, + duplicate_keys_within_one_batch, + delayed_messages_are_not_due, + lease_orders_by_priority_then_run_at, + lease_respects_limit, + concurrent_polls_never_share_a_message, + ack_needs_the_current_lease, + nack_retries_until_dead, + nack_uses_backoff_by_default, + expired_lease_is_handed_out_again, + expired_lease_on_last_attempt_is_dead, + cancel_only_scheduled_messages, + reschedule_changes_run_at, + retry_dead_gives_fresh_attempts, + paused_queue_delivers_nothing, + list_messages_pages_newest_first, + queue_stats_count_each_status, + put_queue_round_trips_settings, + long_poll_wakes_on_schedule, + long_poll_times_out_empty, + prune_deletes_only_old_finished_messages, + storage_clock_is_sane, + oldest_due_measures_waiting_time, + ); + }; + (@each $setup:path; $($name:ident),* $(,)?) => { + $( + #[tokio::test] + async fn $name() { + let Some(storage) = $setup().await else { + eprintln!("skipping {}: backend not configured", stringify!($name)); + return; + }; + conformance::$name(storage).await; + } + )* + }; +} + +fn service(storage: Arc) -> Service { + Service::new(storage, QueueSettings::default()) +} + +fn queue(name: &str) -> QueueName { + QueueName::new(name).expect("valid queue name") +} + +fn message(payload: serde_json::Value) -> ScheduleRequest { + ScheduleRequest::new(payload) +} + +fn keyed(payload: serde_json::Value, key: &str) -> ScheduleRequest { + ScheduleRequest { + idempotency_key: Some(key.to_owned()), + ..ScheduleRequest::new(payload) + } +} + +async fn schedule_one( + service: &Service, + queue: &QueueName, + request: ScheduleRequest, +) -> dally_core::Message { + let mut scheduled = service + .schedule(queue, vec![request]) + .await + .expect("schedule"); + scheduled.remove(0).message +} + +async fn poll(service: &Service, queue: &QueueName, limit: u32) -> Vec { + let request = PollRequest { + limit, + wait: Duration::ZERO, + }; + service.poll(queue, request).await.expect("poll") +} + +async fn poll_one(service: &Service, queue: &QueueName) -> Leased { + let mut leased = poll(service, queue, 1).await; + assert_eq!(leased.len(), 1, "expected one due message"); + leased.remove(0) +} + +fn nack_now(leased: &Leased, error: &str) -> NackRequest { + NackRequest { + lease: leased.lease.clone(), + error: Some(error.to_owned()), + retry_in: Some(Duration::ZERO), + } +} + +/// Settings with the shortest visibility timeout the service allows, for tests +/// that wait for a lease to expire. +fn short_leases(max_attempts: u32) -> QueueSettings { + QueueSettings { + visibility_timeout: Duration::from_secs(1), + max_attempts, + ..QueueSettings::default() + } +} + +const LEASE_EXPIRY_WAIT: Duration = Duration::from_millis(1100); + +pub async fn schedule_then_get(storage: Arc) { + let service = service(storage); + let emails = queue("emails"); + + let scheduled = service + .schedule(&emails, vec![message(json!({"to": "ana"}))]) + .await + .expect("schedule"); + assert_eq!(scheduled.len(), 1); + assert!(scheduled[0].created); + + let stored = service + .get_message(scheduled[0].message.id) + .await + .expect("get"); + assert_eq!(stored, scheduled[0].message); + assert_eq!(stored.queue, emails); + assert_eq!(stored.payload, json!({"to": "ana"})); + assert_eq!(stored.status, Status::Scheduled); + assert_eq!(stored.attempts, 0); + assert_eq!(stored.max_attempts, QueueSettings::default().max_attempts); + assert_eq!( + stored.visibility_timeout, + QueueSettings::default().visibility_timeout + ); + + let summary = service + .get_queue(&emails) + .await + .expect("queue was created implicitly"); + assert_eq!(summary.queue.settings, QueueSettings::default()); +} + +pub async fn idempotency_key_returns_existing_message(storage: Arc) { + let service = service(storage); + let emails = queue("emails"); + + let first = service + .schedule(&emails, vec![keyed(json!(1), "welcome-42")]) + .await + .expect("first schedule"); + let second = service + .schedule(&emails, vec![keyed(json!(2), "welcome-42")]) + .await + .expect("second schedule"); + + assert!(first[0].created); + assert!(!second[0].created); + assert_eq!(second[0].message.id, first[0].message.id); + assert_eq!( + second[0].message.payload, + json!(1), + "the original payload is kept" + ); +} + +pub async fn idempotency_key_is_scoped_to_queue(storage: Arc) { + let service = service(storage); + + let a = service + .schedule(&queue("a"), vec![keyed(json!(1), "same-key")]) + .await + .expect("schedule in a"); + let b = service + .schedule(&queue("b"), vec![keyed(json!(1), "same-key")]) + .await + .expect("schedule in b"); + + assert!(a[0].created); + assert!(b[0].created); + assert_ne!(a[0].message.id, b[0].message.id); +} + +pub async fn duplicate_keys_within_one_batch(storage: Arc) { + let service = service(storage); + let emails = queue("emails"); + + let results = service + .schedule( + &emails, + vec![ + keyed(json!(1), "k"), + message(json!(2)), + keyed(json!(3), "k"), + ], + ) + .await + .expect("schedule"); + + assert_eq!(results.len(), 3); + assert!(results[0].created); + assert!(results[1].created); + assert!(!results[2].created); + assert_eq!(results[2].message.id, results[0].message.id); + assert_eq!( + results[1].message.payload, + json!(2), + "results keep input order" + ); +} + +pub async fn delayed_messages_are_not_due(storage: Arc) { + let service = service(storage); + let emails = queue("emails"); + + let later = ScheduleRequest { + delay: Some(Duration::from_secs(3600)), + ..message(json!("later")) + }; + let future = ScheduleRequest { + run_at: Some(Utc::now() + chrono::Duration::hours(1)), + ..message(json!("future")) + }; + service + .schedule(&emails, vec![later, future]) + .await + .expect("schedule"); + let now = schedule_one(&service, &emails, message(json!("now"))).await; + + let leased = poll(&service, &emails, 10).await; + assert_eq!(leased.len(), 1); + assert_eq!(leased[0].message.id, now.id); +} + +pub async fn lease_orders_by_priority_then_run_at(storage: Arc) { + let service = service(storage); + let emails = queue("emails"); + let at = |minutes_ago: i64| Some(Utc::now() - chrono::Duration::minutes(minutes_ago)); + + let requests = vec![ + ScheduleRequest { + run_at: at(1), + ..message(json!("low, newer")) + }, + ScheduleRequest { + run_at: at(2), + ..message(json!("low, older")) + }, + ScheduleRequest { + run_at: at(1), + priority: 10, + ..message(json!("high")) + }, + ]; + service.schedule(&emails, requests).await.expect("schedule"); + + let order: Vec<_> = poll(&service, &emails, 10) + .await + .into_iter() + .map(|leased| leased.message.payload) + .collect(); + assert_eq!( + order, + vec![json!("high"), json!("low, older"), json!("low, newer")] + ); +} + +pub async fn lease_respects_limit(storage: Arc) { + let service = service(storage); + let emails = queue("emails"); + let requests = (0..5).map(|i| message(json!(i))).collect(); + service.schedule(&emails, requests).await.expect("schedule"); + + assert_eq!(poll(&service, &emails, 2).await.len(), 2); + assert_eq!(poll(&service, &emails, 10).await.len(), 3); + assert_eq!(poll(&service, &emails, 10).await.len(), 0); +} + +pub async fn concurrent_polls_never_share_a_message(storage: Arc) { + let service = service(storage); + let emails = queue("emails"); + let requests = (0..50).map(|i| message(json!(i))).collect(); + service.schedule(&emails, requests).await.expect("schedule"); + + let pollers = (0..10).map(|_| { + let service = service.clone(); + let emails = emails.clone(); + tokio::spawn(async move { poll(&service, &emails, 7).await }) + }); + + let mut seen = HashSet::new(); + for poller in pollers { + for leased in poller.await.expect("poller task") { + assert!(seen.insert(leased.message.id), "message leased twice"); + } + } + assert_eq!(seen.len(), 50); +} + +pub async fn ack_needs_the_current_lease(storage: Arc) { + let service = service(storage); + let emails = queue("emails"); + schedule_one(&service, &emails, message(json!(1))).await; + let leased = poll_one(&service, &emails).await; + + let wrong = dally_core::LeaseToken::generate(); + let err = service + .ack(leased.message.id, &wrong) + .await + .expect_err("wrong lease"); + assert!(matches!(err, Error::LeaseMismatch(_)), "got {err:?}"); + + let acked = service + .ack(leased.message.id, &leased.lease) + .await + .expect("ack"); + assert_eq!(acked.status, Status::Succeeded); + assert!(acked.finished_at.is_some()); + assert!(acked.lease_expires_at.is_none()); + + let err = service + .ack(leased.message.id, &leased.lease) + .await + .expect_err("acked twice"); + assert!(matches!(err, Error::LeaseMismatch(_)), "got {err:?}"); + + let missing = dally_core::MessageId::generate(); + let err = service + .ack(missing, &leased.lease) + .await + .expect_err("unknown message"); + assert!(matches!(err, Error::MessageNotFound(_)), "got {err:?}"); +} + +pub async fn nack_retries_until_dead(storage: Arc) { + let service = service(storage); + let emails = queue("emails"); + let request = ScheduleRequest { + max_attempts: Some(2), + ..message(json!(1)) + }; + schedule_one(&service, &emails, request).await; + + let first = poll_one(&service, &emails).await; + assert_eq!(first.message.attempts, 1); + let retried = service + .nack(first.message.id, nack_now(&first, "smtp timeout")) + .await + .expect("nack"); + assert_eq!(retried.status, Status::Scheduled); + assert_eq!(retried.last_error.as_deref(), Some("smtp timeout")); + assert!(retried.finished_at.is_none()); + + let second = poll_one(&service, &emails).await; + assert_eq!(second.message.attempts, 2); + assert_ne!(second.lease, first.lease, "each lease gets a fresh token"); + let dead = service + .nack(second.message.id, nack_now(&second, "smtp down")) + .await + .expect("nack"); + assert_eq!(dead.status, Status::Dead); + assert_eq!(dead.last_error.as_deref(), Some("smtp down")); + assert!(dead.finished_at.is_some()); + + assert!(poll(&service, &emails, 10).await.is_empty()); +} + +pub async fn nack_uses_backoff_by_default(storage: Arc) { + let service = service(storage); + let emails = queue("emails"); + schedule_one(&service, &emails, message(json!(1))).await; + let leased = poll_one(&service, &emails).await; + + let request = NackRequest { + lease: leased.lease.clone(), + error: None, + retry_in: None, + }; + let retried = service + .nack(leased.message.id, request) + .await + .expect("nack"); + + // The default backoff is 5s for the first retry, give or take 20%. + let delay = retried.run_at - retried.updated_at; + assert!(delay >= chrono::Duration::seconds(3), "delay was {delay}"); + assert!(delay <= chrono::Duration::seconds(7), "delay was {delay}"); + assert!(poll(&service, &emails, 1).await.is_empty()); +} + +pub async fn expired_lease_is_handed_out_again(storage: Arc) { + let service = service(storage); + let emails = queue("emails"); + service + .put_queue(&emails, short_leases(3)) + .await + .expect("put queue"); + schedule_one(&service, &emails, message(json!(1))).await; + + let first = poll_one(&service, &emails).await; + assert!(poll(&service, &emails, 1).await.is_empty(), "still leased"); + + tokio::time::sleep(LEASE_EXPIRY_WAIT).await; + let second = poll_one(&service, &emails).await; + assert_eq!(second.message.id, first.message.id); + assert_eq!(second.message.attempts, 2); + assert_eq!(second.message.last_error.as_deref(), Some("lease expired")); + + let err = service + .ack(first.message.id, &first.lease) + .await + .expect_err("stale lease"); + assert!(matches!(err, Error::LeaseMismatch(_)), "got {err:?}"); + service + .ack(second.message.id, &second.lease) + .await + .expect("current lease"); +} + +pub async fn expired_lease_on_last_attempt_is_dead(storage: Arc) { + let service = service(storage); + let emails = queue("emails"); + service + .put_queue(&emails, short_leases(1)) + .await + .expect("put queue"); + let scheduled = schedule_one(&service, &emails, message(json!(1))).await; + + poll_one(&service, &emails).await; + tokio::time::sleep(LEASE_EXPIRY_WAIT).await; + assert!(poll(&service, &emails, 1).await.is_empty()); + + let dead = service.get_message(scheduled.id).await.expect("get"); + assert_eq!(dead.status, Status::Dead); + assert_eq!(dead.last_error.as_deref(), Some("lease expired")); +} + +pub async fn cancel_only_scheduled_messages(storage: Arc) { + let service = service(storage); + let emails = queue("emails"); + let waiting = schedule_one( + &service, + &emails, + ScheduleRequest { + delay: Some(Duration::from_secs(3600)), + ..message(json!("waiting")) + }, + ) + .await; + schedule_one(&service, &emails, message(json!("running"))).await; + let running = poll_one(&service, &emails).await; + + let cancelled = service.cancel(waiting.id).await.expect("cancel"); + assert_eq!(cancelled.status, Status::Cancelled); + assert!(cancelled.finished_at.is_some()); + + let err = service + .cancel(running.message.id) + .await + .expect_err("running"); + assert!( + matches!( + err, + Error::InvalidStatus { + status: Status::Running, + .. + } + ), + "got {err:?}" + ); +} + +pub async fn reschedule_changes_run_at(storage: Arc) { + let service = service(storage); + let emails = queue("emails"); + let later = schedule_one( + &service, + &emails, + ScheduleRequest { + delay: Some(Duration::from_secs(3600)), + ..message(json!(1)) + }, + ) + .await; + assert!(poll(&service, &emails, 1).await.is_empty()); + + service + .reschedule(later.id, RunAt::Now) + .await + .expect("reschedule"); + let leased = poll_one(&service, &emails).await; + assert_eq!(leased.message.id, later.id); + + let err = service + .reschedule(later.id, RunAt::After(Duration::from_secs(60))) + .await + .expect_err("running"); + assert!(matches!(err, Error::InvalidStatus { .. }), "got {err:?}"); +} + +pub async fn retry_dead_gives_fresh_attempts(storage: Arc) { + let service = service(storage); + let emails = queue("emails"); + let requests = (0..3) + .map(|i| ScheduleRequest { + max_attempts: Some(1), + ..message(json!(i)) + }) + .collect(); + service.schedule(&emails, requests).await.expect("schedule"); + for leased in poll(&service, &emails, 3).await { + service + .nack(leased.message.id, nack_now(&leased, "boom")) + .await + .expect("nack"); + } + assert_eq!( + service.get_queue(&emails).await.expect("queue").stats.dead, + 3 + ); + + let dead = service + .list_messages(MessageFilter { + queue: Some(emails.clone()), + status: Some(Status::Dead), + ..MessageFilter::default() + }) + .await + .expect("list"); + let one = [dead.items[0].id]; + assert_eq!( + service + .retry_dead(&emails, Some(&one)) + .await + .expect("retry one"), + 1 + ); + assert_eq!( + service.retry_dead(&emails, None).await.expect("retry rest"), + 2 + ); + + let leased = poll(&service, &emails, 10).await; + assert_eq!(leased.len(), 3); + assert!(leased.iter().all(|l| l.message.attempts == 1)); +} + +pub async fn paused_queue_delivers_nothing(storage: Arc) { + let service = service(storage); + let emails = queue("emails"); + schedule_one(&service, &emails, message(json!(1))).await; + + service.set_paused(&emails, true).await.expect("pause"); + schedule_one(&service, &emails, message(json!(2))).await; + assert!(poll(&service, &emails, 10).await.is_empty()); + + service.set_paused(&emails, false).await.expect("resume"); + assert_eq!(poll(&service, &emails, 10).await.len(), 2); +} + +pub async fn list_messages_pages_newest_first(storage: Arc) { + let service = service(storage); + let emails = queue("emails"); + for i in 0..5 { + schedule_one(&service, &emails, message(json!(i))).await; + } + schedule_one(&service, &queue("other"), message(json!("other"))).await; + + let mut filter = MessageFilter { + queue: Some(emails.clone()), + limit: 2, + ..MessageFilter::default() + }; + let mut payloads = Vec::new(); + loop { + let page = service.list_messages(filter.clone()).await.expect("list"); + assert!(page.items.len() <= 2); + payloads.extend(page.items.into_iter().map(|m| m.payload)); + match page.next { + Some(next) => filter.before = Some(next), + None => break, + } + } + assert_eq!( + payloads, + vec![json!(4), json!(3), json!(2), json!(1), json!(0)] + ); + + let all = service + .list_messages(MessageFilter::default()) + .await + .expect("list all"); + assert_eq!(all.items.len(), 6); +} + +pub async fn queue_stats_count_each_status(storage: Arc) { + let service = service(storage); + let emails = queue("emails"); + let requests = (0..4) + .map(|i| ScheduleRequest { + max_attempts: Some(1), + ..message(json!(i)) + }) + .collect(); + let scheduled = service.schedule(&emails, requests).await.expect("schedule"); + service + .cancel(scheduled[3].message.id) + .await + .expect("cancel"); + + let leased = poll(&service, &emails, 3).await; + service + .ack(leased[0].message.id, &leased[0].lease) + .await + .expect("ack"); + service + .nack(leased[1].message.id, nack_now(&leased[1], "boom")) + .await + .expect("nack"); + schedule_one(&service, &emails, message(json!("new"))).await; + + let stats = service.get_queue(&emails).await.expect("queue").stats; + assert_eq!(stats.scheduled, 1); + assert_eq!(stats.running, 1); + assert_eq!(stats.succeeded, 1); + assert_eq!(stats.dead, 1); + assert_eq!(stats.cancelled, 1); + + schedule_one(&service, &queue("another"), message(json!(1))).await; + let queues = service.list_queues().await.expect("list queues"); + let names: Vec<_> = queues.iter().map(|q| q.queue.name.as_str()).collect(); + assert_eq!(names, vec!["another", "emails"]); + assert_eq!(queues[1].stats, stats); +} + +pub async fn put_queue_round_trips_settings(storage: Arc) { + let service = service(storage); + let webhooks = queue("webhooks"); + let settings = QueueSettings { + visibility_timeout: Duration::from_secs(90), + max_attempts: 12, + backoff: dally_core::Backoff { + base: Duration::from_millis(1500), + cap: Duration::from_secs(600), + }, + retention: Duration::from_secs(3600), + paused: true, + push: Some(PushSettings { + url: "https://example.com/jobs".to_owned(), + secret: Some("s3cret".to_owned()), + timeout: Duration::from_secs(5), + concurrency: 3, + }), + }; + + let created = service + .put_queue(&webhooks, settings.clone()) + .await + .expect("put"); + assert_eq!(created.settings, settings); + let fetched = service.get_queue(&webhooks).await.expect("get"); + assert_eq!(fetched.queue.settings, settings); + + let updated = QueueSettings { + max_attempts: 1, + push: None, + ..settings + }; + service + .put_queue(&webhooks, updated.clone()) + .await + .expect("update"); + assert_eq!( + service + .get_queue(&webhooks) + .await + .expect("get") + .queue + .settings, + updated + ); + + let invalid = QueueSettings { + max_attempts: 0, + ..QueueSettings::default() + }; + assert!(service.put_queue(&webhooks, invalid).await.is_err()); +} + +pub async fn long_poll_wakes_on_schedule(storage: Arc) { + let service = service(storage); + let emails = queue("emails"); + // Create the queue first, so the poller and the producer race on nothing + // but the message. + assert!(poll(&service, &emails, 1).await.is_empty()); + + let poller = { + let service = service.clone(); + let emails = emails.clone(); + tokio::spawn(async move { + let started = tokio::time::Instant::now(); + let request = PollRequest { + limit: 1, + wait: Duration::from_secs(10), + }; + let leased = service.poll(&emails, request).await.expect("poll"); + (leased, started.elapsed()) + }) + }; + + tokio::time::sleep(Duration::from_millis(200)).await; + schedule_one(&service, &emails, message(json!("wake up"))).await; + + let (leased, elapsed) = poller.await.expect("poller task"); + assert_eq!(leased.len(), 1); + // Without a notification the poll would only find it on its 1s recheck. + assert!(elapsed < Duration::from_millis(900), "took {elapsed:?}"); +} + +pub async fn long_poll_times_out_empty(storage: Arc) { + let service = service(storage); + let started = tokio::time::Instant::now(); + let request = PollRequest { + limit: 1, + wait: Duration::from_millis(300), + }; + + let leased = service.poll(&queue("empty"), request).await.expect("poll"); + + assert!(leased.is_empty()); + assert!(started.elapsed() >= Duration::from_millis(300)); +} + +pub async fn prune_deletes_only_old_finished_messages(storage: Arc) { + let service = service(storage); + let short = queue("short"); + let long = queue("long"); + let no_retention = QueueSettings { + retention: Duration::ZERO, + ..QueueSettings::default() + }; + service + .put_queue(&short, no_retention) + .await + .expect("put short"); + + for queue in [&short, &long] { + schedule_one(&service, queue, message(json!("done"))).await; + let leased = poll_one(&service, queue).await; + service + .ack(leased.message.id, &leased.lease) + .await + .expect("ack"); + schedule_one(&service, queue, message(json!("pending"))).await; + } + // Retention is measured from finished_at, which has to be strictly in + // the past. + tokio::time::sleep(Duration::from_millis(20)).await; + + assert_eq!(service.prune().await.expect("prune"), 1); + assert_eq!( + service + .get_queue(&short) + .await + .expect("short") + .stats + .succeeded, + 0 + ); + assert_eq!( + service + .get_queue(&short) + .await + .expect("short") + .stats + .scheduled, + 1 + ); + assert_eq!( + service + .get_queue(&long) + .await + .expect("long") + .stats + .succeeded, + 1 + ); +} + +pub async fn storage_clock_is_sane(storage: Arc) { + let now = storage.now().await.expect("now"); + let skew = (now - Utc::now()).abs(); + assert!( + skew < chrono::Duration::seconds(5), + "storage clock is {skew} off" + ); +} + +/// `oldest_due` is optional: `None` means the backend does not support it. +pub async fn oldest_due_measures_waiting_time(storage: Arc) { + let service = service(Arc::clone(&storage)); + let emails = queue("emails"); + let later = queue("later"); + let a_minute_ago = Utc::now() - chrono::Duration::seconds(60); + let overdue = ScheduleRequest { + run_at: Some(a_minute_ago), + ..message(json!(1)) + }; + let delayed = ScheduleRequest { + delay: Some(Duration::from_secs(3600)), + ..message(json!(3)) + }; + schedule_one(&service, &emails, overdue).await; + schedule_one(&service, &emails, message(json!(2))).await; + schedule_one(&service, &later, delayed).await; + + let Some(oldest) = storage.oldest_due().await.expect("oldest due") else { + return; + }; + let waited = oldest.get(&emails).copied().unwrap_or_default(); + assert!( + waited >= Duration::from_secs(55) && waited < Duration::from_secs(70), + "oldest due message in emails waited {waited:?}, expected about 60s" + ); + assert!( + !oldest.contains_key(&later), + "nothing in `later` is due yet" + ); +} diff --git a/crates/dally-core/tests/postgres.rs b/crates/dally-core/tests/postgres.rs new file mode 100644 index 0000000..c0da181 --- /dev/null +++ b/crates/dally-core/tests/postgres.rs @@ -0,0 +1,45 @@ +//! Runs the conformance suite against PostgreSQL. +//! +//! Set `DALLY_TEST_POSTGRES_URL` to a database the tests may create schemas +//! in, for example: +//! +//! ```sh +//! docker run -d --name dally-test-postgres -p 55432:5432 \ +//! -e POSTGRES_PASSWORD=dally postgres:17 +//! export DALLY_TEST_POSTGRES_URL=postgres://postgres:dally@localhost:55432/postgres +//! ``` +//! +//! Each test runs in its own schema, so tests run in parallel without seeing +//! each other's queues. + +#![cfg(feature = "postgres")] + +mod conformance; + +use std::sync::Arc; + +use dally_core::storage::postgres::PostgresStorage; +use dally_core::{ConnectOptions, Storage}; +use sqlx::Connection; +use sqlx::postgres::{PgConnectOptions, PgConnection}; + +async fn setup() -> Option> { + let url = std::env::var("DALLY_TEST_POSTGRES_URL").ok()?; + let options: PgConnectOptions = url.parse().expect("valid DALLY_TEST_POSTGRES_URL"); + + let schema = format!("dally_test_{}", uuid::Uuid::new_v4().simple()); + let mut admin = PgConnection::connect_with(&options).await.expect("connect"); + sqlx::raw_sql(sqlx::AssertSqlSafe(format!("CREATE SCHEMA {schema}"))) + .execute(&mut admin) + .await + .expect("create schema"); + admin.close().await.expect("close"); + + let options = options.options([("search_path", schema.as_str())]); + let storage = PostgresStorage::connect_with(options, &ConnectOptions::default()) + .await + .expect("connect storage"); + Some(Arc::new(storage)) +} + +conformance_tests!(setup); diff --git a/crates/dally-core/tests/redis.rs b/crates/dally-core/tests/redis.rs new file mode 100644 index 0000000..eca1b84 --- /dev/null +++ b/crates/dally-core/tests/redis.rs @@ -0,0 +1,34 @@ +//! Runs the conformance suite against Redis. +//! +//! Set `DALLY_TEST_REDIS_URL`, for example: +//! +//! ```sh +//! docker compose up -d redis +//! export DALLY_TEST_REDIS_URL=redis://localhost:56379 +//! ``` +//! +//! Each test uses its own key prefix, so tests run in parallel without seeing +//! each other's queues. + +#![cfg(feature = "redis")] + +mod conformance; + +use std::sync::Arc; + +use dally_core::storage::redis::RedisStorage; +use dally_core::{ConnectOptions, Storage}; + +async fn setup() -> Option> { + let url = std::env::var("DALLY_TEST_REDIS_URL").ok()?; + let separator = if url.contains('?') { '&' } else { '?' }; + let prefix = format!("dally-test-{}:", uuid::Uuid::new_v4().simple()); + let url = format!("{url}{separator}prefix={prefix}"); + + let storage = RedisStorage::connect(&url, &ConnectOptions::default()) + .await + .expect("connect storage"); + Some(Arc::new(storage)) +} + +conformance_tests!(setup); diff --git a/crates/dally-core/tests/sqlite.rs b/crates/dally-core/tests/sqlite.rs new file mode 100644 index 0000000..db4f480 --- /dev/null +++ b/crates/dally-core/tests/sqlite.rs @@ -0,0 +1,119 @@ +//! Runs the conformance suite against SQLite, plus the checks that only make +//! sense for a file-based backend. +//! +//! Every test gets a fresh database file in its own directory under Cargo's +//! per-target scratch directory (`target/tmp`). The directories are kept +//! rather than deleted, because the storage outlives the setup function that +//! creates them; `cargo clean` removes them. + +#![cfg(feature = "sqlite")] + +mod conformance; + +use std::path::PathBuf; +use std::sync::Arc; + +use dally_core::storage::sqlite::SqliteStorage; +use dally_core::{ConnectOptions, Error, QueueSettings, ScheduleRequest, Service, Storage}; +use serde_json::json; + +fn database_path() -> PathBuf { + let dir = tempfile::Builder::new() + .prefix("dally-sqlite-") + .tempdir_in(env!("CARGO_TARGET_TMPDIR")) + .expect("create temp dir") + .keep(); + dir.join("dally.sqlite") +} + +async fn setup() -> Option> { + let storage = SqliteStorage::open(database_path(), &ConnectOptions::default()) + .await + .expect("open storage"); + Some(Arc::new(storage)) +} + +conformance_tests!(setup); + +#[tokio::test] +async fn second_storage_on_the_same_file_is_refused() { + let path = database_path(); + let first = SqliteStorage::open(&path, &ConnectOptions::default()) + .await + .expect("first open"); + + let err = SqliteStorage::open(&path, &ConnectOptions::default()) + .await + .err() + .expect("second open should fail"); + assert!(matches!(err, Error::InvalidInput(_)), "got {err:?}"); + assert!( + err.to_string().contains("another dally server"), + "got {err}" + ); + + drop(first); + SqliteStorage::open(&path, &ConnectOptions::default()) + .await + .expect("open after the first one is gone"); +} + +#[tokio::test] +async fn messages_survive_reopening() { + let path = database_path(); + let service = + |storage: SqliteStorage| Service::new(Arc::new(storage), QueueSettings::default()); + let emails = dally_core::QueueName::new("emails").expect("valid name"); + + let first = service( + SqliteStorage::open(&path, &ConnectOptions::default()) + .await + .expect("open"), + ); + let scheduled = first + .schedule(&emails, vec![ScheduleRequest::new(json!({"to": "ana"}))]) + .await + .expect("schedule"); + drop(first); + + let second = service( + SqliteStorage::open(&path, &ConnectOptions::default()) + .await + .expect("reopen"), + ); + let stored = second + .get_message(scheduled[0].message.id) + .await + .expect("get"); + assert_eq!(stored, scheduled[0].message); +} + +#[tokio::test] +async fn connect_accepts_file_and_memory_urls() { + let path = database_path(); + let url = format!("sqlite://{}", path.display()); + assert!(path.is_absolute(), "the URL above is sqlite:///..."); + + for url in [url.as_str(), "sqlite::memory:"] { + let storage = dally_core::connect(url, &ConnectOptions::default()) + .await + .unwrap_or_else(|err| panic!("connect to {url}: {err}")); + let service = Service::new(storage, QueueSettings::default()); + let emails = dally_core::QueueName::new("emails").expect("valid name"); + service + .schedule(&emails, vec![ScheduleRequest::new(json!(1))]) + .await + .expect("schedule"); + assert_eq!( + service + .get_queue(&emails) + .await + .expect("queue") + .stats + .scheduled, + 1, + "{url}" + ); + } + assert!(path.exists(), "the database file was created"); +} diff --git a/crates/dally-server/Cargo.toml b/crates/dally-server/Cargo.toml new file mode 100644 index 0000000..ff05031 --- /dev/null +++ b/crates/dally-server/Cargo.toml @@ -0,0 +1,49 @@ +[package] +name = "dally-server" +description = "HTTP server and background tasks for the dally job queue" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true + +[features] +default = [] +postgres = ["dally-core/postgres"] +redis = ["dally-core/redis"] +sqlite = ["dally-core/sqlite"] + +[dependencies] +axum.workspace = true +chrono.workspace = true +chrono-tz.workspace = true +croner.workspace = true +dally-core = { workspace = true, features = ["openapi"] } +figment.workspace = true +hex.workspace = true +hmac.workspace = true +humantime-serde.workspace = true +prometheus-client.workspace = true +utoipa.workspace = true +uuid.workspace = true +reqwest = { workspace = true, features = ["rustls"] } +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +subtle.workspace = true +thiserror.workspace = true +tokio = { workspace = true, features = ["full"] } +tokio-util.workspace = true +tower-http.workspace = true +tracing.workspace = true + +[dev-dependencies] +sqlx = { workspace = true, features = ["postgres"] } +figment = { workspace = true, features = ["test"] } +dally-core = { workspace = true, features = ["postgres", "sqlite"] } +tempfile.workspace = true +reqwest.workspace = true + +[lints] +workspace = true diff --git a/crates/dally-server/src/api/error.rs b/crates/dally-server/src/api/error.rs new file mode 100644 index 0000000..99de7eb --- /dev/null +++ b/crates/dally-server/src/api/error.rs @@ -0,0 +1,69 @@ +use axum::Json; +use axum::extract::rejection::QueryRejection; +use axum::http::StatusCode; +use axum::response::{IntoResponse, Response}; +use serde_json::json; + +/// An error as the API returns it: +/// `{"error": {"code": "lease_mismatch", "message": "..."}}`. +/// +/// `code` is stable and meant for programs; `message` is for people and may +/// change. +#[derive(Debug)] +pub struct ApiError { + status: StatusCode, + code: &'static str, + message: String, +} + +impl ApiError { + pub fn new(status: StatusCode, code: &'static str, message: impl Into) -> Self { + Self { + status, + code, + message: message.into(), + } + } + + pub fn invalid(message: impl Into) -> Self { + Self::new(StatusCode::BAD_REQUEST, "invalid_input", message) + } +} + +impl From for ApiError { + fn from(err: dally_core::Error) -> Self { + use dally_core::Error; + + let (status, code) = match &err { + Error::InvalidInput(_) => (StatusCode::BAD_REQUEST, "invalid_input"), + Error::QueueNotFound(_) => (StatusCode::NOT_FOUND, "queue_not_found"), + Error::MessageNotFound(_) => (StatusCode::NOT_FOUND, "message_not_found"), + Error::LeaseMismatch(_) => (StatusCode::CONFLICT, "lease_mismatch"), + Error::InvalidStatus { .. } => (StatusCode::CONFLICT, "invalid_status"), + Error::Storage(_) => { + // Storage errors can contain connection details, so the client + // gets a generic message and the details go to the log. + tracing::error!(error = %err, "storage error"); + return Self::new( + StatusCode::SERVICE_UNAVAILABLE, + "storage_unavailable", + "storage is unavailable, try again later", + ); + } + }; + Self::new(status, code, err.to_string()) + } +} + +impl From for ApiError { + fn from(rejection: QueryRejection) -> Self { + Self::invalid(rejection.body_text()) + } +} + +impl IntoResponse for ApiError { + fn into_response(self) -> Response { + let body = json!({ "error": { "code": self.code, "message": self.message } }); + (self.status, Json(body)).into_response() + } +} diff --git a/crates/dally-server/src/api/messages.rs b/crates/dally-server/src/api/messages.rs new file mode 100644 index 0000000..35504a0 --- /dev/null +++ b/crates/dally-server/src/api/messages.rs @@ -0,0 +1,303 @@ +use std::time::Duration; + +use axum::body::Bytes; +use axum::extract::{Path, State}; +use axum::http::StatusCode; +use axum::response::{IntoResponse, Response}; +use chrono::{DateTime, Utc}; +use dally_core::{ + LeaseToken, Leased, Message, MessageFilter, MessageId, NackRequest, Page, PollRequest, RunAt, + ScheduleRequest, Scheduled, Service, Status, +}; +use serde::{Deserialize, Serialize}; +use utoipa::{IntoParams, ToSchema}; + +use super::openapi::{ErrorBody, ScheduleBody, ScheduleResponse}; +use super::{ApiError, ApiResult, Json, Query, message_id, optional_json, queue_name}; + +/// `POST /v1/queues/{queue}/messages` takes one message or an array of them. +/// +/// One message: `201 Created` with the message, or `200 OK` with the existing +/// message if its idempotency key was already used. +/// +/// An array: `200 OK` with `{"messages": [{"created": bool, "message": ...}]}` +/// in the same order. +#[utoipa::path( + post, path = "/v1/queues/{queue}/messages", tag = "messages", + params(("queue" = String, Path, description = "Queue name")), + request_body = ScheduleBody, + responses( + (status = 201, description = "Scheduled", body = Message), + (status = 200, description = "The existing message, if its idempotency key was already used; or the results of a batch", body = ScheduleResponse), + (status = 400, description = "Invalid input", body = ErrorBody), (status = 401, description = "Missing or unknown API key", body = ErrorBody), (status = 503, description = "Storage is unavailable", body = ErrorBody) + ) +)] +pub async fn schedule( + State(service): State, + Path(queue): Path, + Json(body): Json, +) -> ApiResult { + let queue = queue_name(queue)?; + + // Parsing by hand rather than with an untagged enum keeps serde's error + // messages useful ("unknown field `dely`") instead of "did not match any + // variant". + let is_batch = body.is_array(); + let requests: Vec = if is_batch { + serde_json::from_value(body) + } else { + serde_json::from_value(body).map(|request| vec![request]) + } + .map_err(|err| ApiError::invalid(err.to_string()))?; + + let mut results = service.schedule(&queue, requests).await?; + + if is_batch { + return Ok(Json(Batch { messages: results }).into_response()); + } + let Scheduled { message, created } = results + .pop() + .ok_or_else(|| ApiError::invalid("nothing was scheduled"))?; + let status = if created { + StatusCode::CREATED + } else { + StatusCode::OK + }; + Ok((status, Json(message)).into_response()) +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct Batch { + messages: Vec, +} + +#[derive(Debug, Default, Deserialize, ToSchema)] +#[serde(default, deny_unknown_fields)] +pub struct PollBody { + /// Lease at most this many messages, 1 to 100. Defaults to 1. + limit: Option, + /// If nothing is due, wait up to this long (at most 30s) for a message. + #[serde(with = "humantime_serde")] + #[schema(value_type = Option, example = "20s")] + wait: Option, +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct Polled { + messages: Vec, +} + +/// `POST /v1/queues/{queue}/poll` with an optional body +/// `{"limit": 10, "wait": "20s"}`. +#[utoipa::path( + post, path = "/v1/queues/{queue}/poll", tag = "messages", + params(("queue" = String, Path, description = "Queue name")), + request_body(content = Option, description = "Optional; defaults to one message and no waiting"), + responses( + (status = 200, description = "Leased messages, possibly none", body = Polled), + (status = 400, description = "Invalid input", body = ErrorBody), (status = 401, description = "Missing or unknown API key", body = ErrorBody), (status = 503, description = "Storage is unavailable", body = ErrorBody) + ) +)] +pub async fn poll( + State(service): State, + Path(queue): Path, + body: Bytes, +) -> ApiResult> { + let queue = queue_name(queue)?; + let body: PollBody = optional_json(&body)?; + let request = PollRequest { + limit: body.limit.unwrap_or(1), + wait: body.wait.unwrap_or_default(), + }; + + let messages = service.poll(&queue, request).await?; + Ok(Json(Polled { messages })) +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct AckBody { + /// The lease token from the poll. + lease: LeaseToken, +} + +/// `POST /v1/messages/{id}/ack` with `{"lease": "..."}`. +#[utoipa::path( + post, path = "/v1/messages/{id}/ack", tag = "messages", + params(("id" = uuid::Uuid, Path, description = "Message id")), + request_body = AckBody, + responses( + (status = 200, description = "Succeeded", body = Message), + (status = 400, description = "Invalid input", body = ErrorBody), (status = 401, description = "Missing or unknown API key", body = ErrorBody), (status = 404, description = "Not found", body = ErrorBody), (status = 409, description = "The lease or status does not allow this", body = ErrorBody), (status = 503, description = "Storage is unavailable", body = ErrorBody) + ) +)] +pub async fn ack( + State(service): State, + Path(id): Path, + Json(body): Json, +) -> ApiResult> { + let message = service.ack(message_id(&id)?, &body.lease).await?; + Ok(Json(message)) +} + +/// `POST /v1/messages/{id}/nack` with `{"lease": "...", "error": "...", +/// "retry_in": "30s"}`. Only `lease` is required. +#[utoipa::path( + post, path = "/v1/messages/{id}/nack", tag = "messages", + params(("id" = uuid::Uuid, Path, description = "Message id")), + request_body = NackRequest, + responses( + (status = 200, description = "Scheduled for a retry, or dead", body = Message), + (status = 400, description = "Invalid input", body = ErrorBody), (status = 401, description = "Missing or unknown API key", body = ErrorBody), (status = 404, description = "Not found", body = ErrorBody), (status = 409, description = "The lease or status does not allow this", body = ErrorBody), (status = 503, description = "Storage is unavailable", body = ErrorBody) + ) +)] +pub async fn nack( + State(service): State, + Path(id): Path, + Json(body): Json, +) -> ApiResult> { + let message = service.nack(message_id(&id)?, body).await?; + Ok(Json(message)) +} + +/// `GET /v1/messages/{id}`. +#[utoipa::path( + get, path = "/v1/messages/{id}", tag = "messages", + params(("id" = uuid::Uuid, Path, description = "Message id")), + responses( + (status = 200, description = "The message", body = Message), + (status = 400, description = "Invalid input", body = ErrorBody), (status = 401, description = "Missing or unknown API key", body = ErrorBody), (status = 404, description = "Not found", body = ErrorBody), (status = 503, description = "Storage is unavailable", body = ErrorBody) + ) +)] +pub async fn get( + State(service): State, + Path(id): Path, +) -> ApiResult> { + Ok(Json(service.get_message(message_id(&id)?).await?)) +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct RescheduleBody { + /// Run after this delay. Cannot be combined with `run_at`. + #[serde(default, with = "humantime_serde")] + #[schema(value_type = Option, example = "1h")] + delay: Option, + /// Run at this time. With neither field, the message runs now. + #[serde(default)] + run_at: Option>, +} + +/// `PATCH /v1/messages/{id}` with `{"delay": "1h"}` or `{"run_at": "..."}`. +/// An empty object runs it now. +#[utoipa::path( + patch, path = "/v1/messages/{id}", tag = "messages", + params(("id" = uuid::Uuid, Path, description = "Message id")), + request_body = RescheduleBody, + responses( + (status = 200, description = "Rescheduled", body = Message), + (status = 400, description = "Invalid input", body = ErrorBody), (status = 401, description = "Missing or unknown API key", body = ErrorBody), (status = 404, description = "Not found", body = ErrorBody), (status = 409, description = "The lease or status does not allow this", body = ErrorBody), (status = 503, description = "Storage is unavailable", body = ErrorBody) + ) +)] +pub async fn reschedule( + State(service): State, + Path(id): Path, + Json(body): Json, +) -> ApiResult> { + let run_at = match (body.delay, body.run_at) { + (Some(_), Some(_)) => { + return Err(ApiError::invalid("use either delay or run_at, not both")); + } + (Some(delay), None) => RunAt::After(delay), + (None, Some(at)) => RunAt::At(at), + (None, None) => RunAt::Now, + }; + Ok(Json(service.reschedule(message_id(&id)?, run_at).await?)) +} + +/// `DELETE /v1/messages/{id}` cancels a scheduled message. +#[utoipa::path( + delete, path = "/v1/messages/{id}", tag = "messages", + params(("id" = uuid::Uuid, Path, description = "Message id")), + responses( + (status = 200, description = "Cancelled", body = Message), + (status = 400, description = "Invalid input", body = ErrorBody), (status = 401, description = "Missing or unknown API key", body = ErrorBody), (status = 404, description = "Not found", body = ErrorBody), (status = 409, description = "The lease or status does not allow this", body = ErrorBody), (status = 503, description = "Storage is unavailable", body = ErrorBody) + ) +)] +pub async fn cancel( + State(service): State, + Path(id): Path, +) -> ApiResult> { + Ok(Json(service.cancel(message_id(&id)?).await?)) +} + +#[derive(Debug, Default, Deserialize, IntoParams)] +#[serde(default, deny_unknown_fields)] +#[into_params(parameter_in = Query)] +pub struct ListParams { + /// Only messages in this queue. + queue: Option, + /// Only messages in this status. + status: Option, + /// Only messages older than this one: pass the previous page's `next`. + #[param(value_type = Option)] + before: Option, + /// At most this many messages, up to 500. Defaults to 50. + limit: Option, +} + +/// The query parameters of the per-queue listing, which takes the queue +/// from the path. Only used to describe the endpoint. +#[derive(IntoParams)] +#[into_params(parameter_in = Query)] +#[allow(dead_code)] +pub struct QueueListParams { + /// Only messages in this status. + status: Option, + /// Only messages older than this one: pass the previous page's `next`. + #[param(value_type = Option)] + before: Option, + /// At most this many messages, up to 500. Defaults to 50. + limit: Option, +} + +/// `GET /v1/messages?queue=&status=&before=&limit=`, newest first. Pass the +/// response's `next` as `before` to get the following page. +#[utoipa::path( + get, path = "/v1/messages", tag = "messages", + params(ListParams), + responses( + (status = 200, description = "One page, newest first", body = Page), + (status = 400, description = "Invalid input", body = ErrorBody), (status = 401, description = "Missing or unknown API key", body = ErrorBody), (status = 503, description = "Storage is unavailable", body = ErrorBody) + ) +)] +pub async fn list( + State(service): State, + Query(params): Query, +) -> ApiResult>> { + let filter = MessageFilter { + queue: params.queue.map(queue_name).transpose()?, + status: params.status, + before: params.before, + limit: params.limit.unwrap_or_default(), + }; + Ok(Json(service.list_messages(filter).await?)) +} + +/// `GET /v1/queues/{queue}/messages?status=&before=&limit=`. +#[utoipa::path( + get, path = "/v1/queues/{queue}/messages", tag = "messages", + params(("queue" = String, Path, description = "Queue name"), QueueListParams), + responses( + (status = 200, description = "One page, newest first", body = Page), + (status = 400, description = "Invalid input", body = ErrorBody), (status = 401, description = "Missing or unknown API key", body = ErrorBody), (status = 503, description = "Storage is unavailable", body = ErrorBody) + ) +)] +pub async fn list_in_queue( + State(service): State, + Path(queue): Path, + Query(mut params): Query, +) -> ApiResult>> { + params.queue = Some(queue); + list(State(service), Query(params)).await +} diff --git a/crates/dally-server/src/api/mod.rs b/crates/dally-server/src/api/mod.rs new file mode 100644 index 0000000..0a11646 --- /dev/null +++ b/crates/dally-server/src/api/mod.rs @@ -0,0 +1,157 @@ +//! The HTTP API. Handlers stay thin: parse, call [`Service`], serialize. +//! Everything they do is documented in `docs/design.md`. + +mod error; +mod messages; +mod openapi; +mod queues; + +use std::sync::Arc; + +use axum::Router; +use axum::body::Bytes; +use axum::extract::{FromRequest, FromRequestParts, State}; +use axum::http::StatusCode; +use axum::middleware::from_fn_with_state; +use axum::routing::{get, post}; +use dally_core::{MessageId, QueueName, Service}; +use tower_http::trace::TraceLayer; + +pub use error::ApiError; + +use crate::auth::{Auth, authenticate}; +use crate::metrics::{self, Metrics, MetricsState}; + +/// A JSON body whose errors come back in the API's error format, not as +/// axum's plain-text rejections. +/// +/// Unlike `axum::Json`, it does not insist on `Content-Type: +/// application/json`, so `curl -d '{...}'` works without extra flags. The +/// body is JSON on every endpoint, so the header adds nothing. +struct Json(T); + +impl FromRequest for Json +where + S: Send + Sync, + T: serde::de::DeserializeOwned, +{ + type Rejection = ApiError; + + async fn from_request(request: axum::extract::Request, state: &S) -> ApiResult { + let body = Bytes::from_request(request, state) + .await + .map_err(|rejection| ApiError::invalid(rejection.body_text()))?; + serde_json::from_slice(&body) + .map(Json) + .map_err(|err| ApiError::invalid(format!("invalid JSON body: {err}"))) + } +} + +impl axum::response::IntoResponse for Json { + fn into_response(self) -> axum::response::Response { + axum::Json(self.0).into_response() + } +} + +/// Query parameters with errors in the API's error format. +#[derive(FromRequestParts)] +#[from_request(via(axum::extract::Query), rejection(ApiError))] +struct Query(T); + +type ApiResult = Result; + +/// Builds the router for the whole API. [`crate::Server::router`] is the +/// public way in. +pub fn router( + service: Service, + auth: Arc, + metrics: Arc, + protect_metrics: bool, +) -> Router { + // Admin-only endpoints say so with an `Admin` argument in their handler. + let v1 = Router::new() + .route("/queues", get(queues::list)) + .route("/queues/{queue}", get(queues::get).put(queues::put)) + .route("/queues/{queue}/pause", post(queues::pause)) + .route("/queues/{queue}/resume", post(queues::resume)) + .route( + "/queues/{queue}/messages", + post(messages::schedule).get(messages::list_in_queue), + ) + .route("/queues/{queue}/poll", post(messages::poll)) + .route("/queues/{queue}/dead/retry", post(queues::retry_dead)) + .route("/messages", get(messages::list)) + .route( + "/messages/{id}", + get(messages::get) + .patch(messages::reschedule) + .delete(messages::cancel), + ) + .route("/messages/{id}/ack", post(messages::ack)) + .route("/messages/{id}/nack", post(messages::nack)) + .route_layer(from_fn_with_state(Arc::clone(&auth), authenticate)); + + let mut metrics_route = Router::new() + .route("/metrics", get(metrics::handler)) + .with_state(MetricsState { + metrics: Arc::clone(&metrics), + service: service.clone(), + }); + if protect_metrics { + metrics_route = metrics_route.route_layer(from_fn_with_state(auth, authenticate)); + } + + Router::new() + .nest("/v1", v1) + .route("/v1/openapi.json", get(openapi::spec)) + .route("/healthz", get(healthz)) + .route("/readyz", get(readyz)) + .with_state(service) + .merge(metrics_route) + .layer(from_fn_with_state(metrics, metrics::track_requests)) + .layer(TraceLayer::new_for_http()) +} + +/// The process is up. +#[utoipa::path( + get, path = "/healthz", tag = "health", security(()), + responses((status = 200, description = "Up", body = String)) +)] +async fn healthz() -> &'static str { + "ok" +} + +/// The process is up and can reach storage. +#[utoipa::path( + get, path = "/readyz", tag = "health", security(()), + responses( + (status = 200, description = "Ready", body = String), + (status = 503, description = "Storage is unavailable", body = String) + ) +)] +async fn readyz(State(service): State) -> (StatusCode, &'static str) { + match service.storage().now().await { + Ok(_) => (StatusCode::OK, "ok"), + Err(err) => { + tracing::warn!(error = %err, "readiness check failed"); + (StatusCode::SERVICE_UNAVAILABLE, "storage unavailable") + } + } +} + +/// Parses a body that may be left out entirely, as in `POST .../poll` with +/// no options. +fn optional_json(body: &Bytes) -> ApiResult { + if body.iter().all(u8::is_ascii_whitespace) { + return Ok(T::default()); + } + serde_json::from_slice(body).map_err(|err| ApiError::invalid(err.to_string())) +} + +fn queue_name(name: String) -> ApiResult { + Ok(QueueName::new(name)?) +} + +fn message_id(id: &str) -> ApiResult { + Ok(id.parse()?) +} diff --git a/crates/dally-server/src/api/openapi.rs b/crates/dally-server/src/api/openapi.rs new file mode 100644 index 0000000..e090ad7 --- /dev/null +++ b/crates/dally-server/src/api/openapi.rs @@ -0,0 +1,126 @@ +//! The OpenAPI description of the HTTP API, generated from the handlers' +//! annotations and served at `GET /v1/openapi.json`. + +use axum::Json; +use dally_core::{Message, ScheduleRequest}; +use serde::Serialize; +use utoipa::openapi::security::{Http, HttpAuthScheme, SecurityScheme}; +use utoipa::{Modify, OpenApi, ToSchema}; + +use super::{messages, queues}; + +#[derive(OpenApi)] +#[openapi( + info( + title = "dally", + description = "A job queue server. See docs/design.md and docs/semantics.md for how \ + delivery works.", + license(name = "MIT OR Apache-2.0", identifier = "MIT OR Apache-2.0"), + ), + paths( + messages::schedule, + messages::poll, + messages::ack, + messages::nack, + messages::get, + messages::reschedule, + messages::cancel, + messages::list, + messages::list_in_queue, + queues::list, + queues::get, + queues::put, + queues::pause, + queues::resume, + queues::retry_dead, + super::healthz, + super::readyz, + ), + modifiers(&BearerAuth), + security(("bearer" = [])), + tags( + (name = "messages", description = "Scheduling, leasing and inspecting messages"), + (name = "queues", description = "Queue settings and dead messages"), + (name = "health", description = "Probes for load balancers and orchestrators"), + ), +)] +pub struct ApiDoc; + +/// Declares the bearer scheme that `security(("bearer" = []))` refers to. +struct BearerAuth; + +impl Modify for BearerAuth { + fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) { + let components = openapi.components.get_or_insert_with(Default::default); + components.add_security_scheme( + "bearer", + SecurityScheme::Http(Http::new(HttpAuthScheme::Bearer)), + ); + } +} + +/// `GET /v1/openapi.json`. +pub async fn spec() -> Json { + Json(ApiDoc::openapi()) +} + +/// The error body every endpoint uses. +#[derive(Debug, Serialize, ToSchema)] +pub struct ErrorBody { + error: ErrorDetail, +} + +#[derive(Debug, Serialize, ToSchema)] +struct ErrorDetail { + /// Stable, for programs: `invalid_input`, `queue_not_found`, + /// `message_not_found`, `lease_mismatch`, `invalid_status`, + /// `unauthorized`, `forbidden` or `storage_unavailable`. + code: String, + /// For people. May change between versions. + message: String, +} + +/// One message, or an array of up to 100. +#[derive(Serialize, ToSchema)] +#[serde(untagged)] +#[allow(dead_code)] // Only describes the body; the handler parses it by hand. +pub enum ScheduleBody { + /// A single message. + One(ScheduleRequest), + /// A batch. + Many(Vec), +} + +/// The message for a single schedule, or the results in order for a batch. +#[derive(Serialize, ToSchema)] +#[serde(untagged)] +#[allow(dead_code)] // Only describes the response. +pub enum ScheduleResponse { + /// The stored message. + One(Message), + /// One result per scheduled message. + Many(messages::Batch), +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Run with `UPDATE_OPENAPI=1 cargo test -p dally-server openapi` after + /// changing the API, and commit `docs/openapi.json`. + #[test] + fn committed_spec_is_up_to_date() { + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../docs/openapi.json"); + let spec = ApiDoc::openapi().to_pretty_json().expect("spec serializes") + "\n"; + + if std::env::var_os("UPDATE_OPENAPI").is_some() { + std::fs::write(path, &spec).expect("write docs/openapi.json"); + return; + } + let committed = std::fs::read_to_string(path).unwrap_or_default(); + assert!( + committed == spec, + "docs/openapi.json is out of date; run UPDATE_OPENAPI=1 cargo test -p dally-server openapi" + ); + } +} diff --git a/crates/dally-server/src/api/queues.rs b/crates/dally-server/src/api/queues.rs new file mode 100644 index 0000000..64414a3 --- /dev/null +++ b/crates/dally-server/src/api/queues.rs @@ -0,0 +1,137 @@ +use axum::body::Bytes; +use axum::extract::{Path, State}; +use dally_core::{MessageId, Queue, QueueSettings, QueueSummary, Service}; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; + +use crate::auth::Admin; + +use super::openapi::ErrorBody; +use super::{ApiResult, Json, optional_json, queue_name}; + +#[derive(Debug, Serialize, ToSchema)] +pub struct QueueList { + queues: Vec, +} + +/// `GET /v1/queues`: every queue with its message counts. +#[utoipa::path( + get, path = "/v1/queues", tag = "queues", + responses( + (status = 200, description = "Every queue with its message counts", body = QueueList), + (status = 401, description = "Missing or unknown API key", body = ErrorBody), (status = 503, description = "Storage is unavailable", body = ErrorBody) + ) +)] +pub async fn list(State(service): State) -> ApiResult> { + let queues = service.list_queues().await?; + Ok(Json(QueueList { queues })) +} + +/// `GET /v1/queues/{queue}`: settings and message counts. +#[utoipa::path( + get, path = "/v1/queues/{queue}", tag = "queues", + params(("queue" = String, Path, description = "Queue name")), + responses( + (status = 200, description = "Settings and message counts", body = QueueSummary), + (status = 400, description = "Invalid input", body = ErrorBody), (status = 401, description = "Missing or unknown API key", body = ErrorBody), (status = 404, description = "Not found", body = ErrorBody), (status = 503, description = "Storage is unavailable", body = ErrorBody) + ) +)] +pub async fn get( + State(service): State, + Path(queue): Path, +) -> ApiResult> { + Ok(Json(service.get_queue(&queue_name(queue)?).await?)) +} + +/// `PUT /v1/queues/{queue}`: creates the queue or replaces its settings. +/// Fields left out get their defaults, not their current values. +#[utoipa::path( + put, path = "/v1/queues/{queue}", tag = "queues", + params(("queue" = String, Path, description = "Queue name")), + request_body = QueueSettings, + responses( + (status = 200, description = "Created or updated", body = Queue), + (status = 400, description = "Invalid input", body = ErrorBody), (status = 401, description = "Missing or unknown API key", body = ErrorBody), (status = 403, description = "Needs an admin key", body = ErrorBody), (status = 503, description = "Storage is unavailable", body = ErrorBody) + ) +)] +pub async fn put( + _admin: Admin, + State(service): State, + Path(queue): Path, + Json(settings): Json, +) -> ApiResult> { + Ok(Json( + service.put_queue(&queue_name(queue)?, settings).await?, + )) +} + +/// `POST /v1/queues/{queue}/pause`. +#[utoipa::path( + post, path = "/v1/queues/{queue}/pause", tag = "queues", + params(("queue" = String, Path, description = "Queue name")), + responses( + (status = 200, description = "Paused", body = Queue), + (status = 400, description = "Invalid input", body = ErrorBody), (status = 401, description = "Missing or unknown API key", body = ErrorBody), (status = 403, description = "Needs an admin key", body = ErrorBody), (status = 404, description = "Not found", body = ErrorBody), (status = 503, description = "Storage is unavailable", body = ErrorBody) + ) +)] +pub async fn pause( + _admin: Admin, + State(service): State, + Path(queue): Path, +) -> ApiResult> { + Ok(Json(service.set_paused(&queue_name(queue)?, true).await?)) +} + +/// `POST /v1/queues/{queue}/resume`. +#[utoipa::path( + post, path = "/v1/queues/{queue}/resume", tag = "queues", + params(("queue" = String, Path, description = "Queue name")), + responses( + (status = 200, description = "Resumed", body = Queue), + (status = 400, description = "Invalid input", body = ErrorBody), (status = 401, description = "Missing or unknown API key", body = ErrorBody), (status = 403, description = "Needs an admin key", body = ErrorBody), (status = 404, description = "Not found", body = ErrorBody), (status = 503, description = "Storage is unavailable", body = ErrorBody) + ) +)] +pub async fn resume( + _admin: Admin, + State(service): State, + Path(queue): Path, +) -> ApiResult> { + Ok(Json(service.set_paused(&queue_name(queue)?, false).await?)) +} + +#[derive(Debug, Default, Deserialize, ToSchema)] +#[serde(default, deny_unknown_fields)] +pub struct RetryBody { + /// Only these messages. Without it, every dead message in the queue. + #[schema(value_type = Option>)] + ids: Option>, +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct Retried { + retried: u64, +} + +/// `POST /v1/queues/{queue}/dead/retry` with an optional `{"ids": [...]}`. +/// Without ids, retries every dead message in the queue. +#[utoipa::path( + post, path = "/v1/queues/{queue}/dead/retry", tag = "queues", + params(("queue" = String, Path, description = "Queue name")), + request_body(content = Option, description = "Optional; without ids, every dead message is retried"), + responses( + (status = 200, description = "How many messages were retried", body = Retried), + (status = 400, description = "Invalid input", body = ErrorBody), (status = 401, description = "Missing or unknown API key", body = ErrorBody), (status = 403, description = "Needs an admin key", body = ErrorBody), (status = 404, description = "Not found", body = ErrorBody), (status = 503, description = "Storage is unavailable", body = ErrorBody) + ) +)] +pub async fn retry_dead( + _admin: Admin, + State(service): State, + Path(queue): Path, + body: Bytes, +) -> ApiResult> { + let body: RetryBody = optional_json(&body)?; + let retried = service + .retry_dead(&queue_name(queue)?, body.ids.as_deref()) + .await?; + Ok(Json(Retried { retried })) +} diff --git a/crates/dally-server/src/auth.rs b/crates/dally-server/src/auth.rs new file mode 100644 index 0000000..2a4e90b --- /dev/null +++ b/crates/dally-server/src/auth.rs @@ -0,0 +1,277 @@ +//! API keys. +//! +//! With no keys configured, auth is off and every request may do anything. +//! With keys, every `/v1` request needs `Authorization: Bearer `. A +//! `client` key may schedule, poll, ack and read; an `admin` key may also +//! change queues. Handlers that need admin take an [`Admin`] argument, so the +//! requirement is visible in their signatures. + +use std::fmt; +use std::sync::Arc; + +use axum::extract::{FromRequestParts, Request, State}; +use axum::http::request::Parts; +use axum::http::{HeaderValue, StatusCode, header}; +use axum::middleware::Next; +use axum::response::{IntoResponse, Response}; +use serde::Deserialize; +use subtle::ConstantTimeEq; +use tracing::Instrument; + +use crate::Error; +use crate::api::ApiError; + +/// What a key may do. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Role { + /// Schedule, poll, ack, nack, reschedule, cancel, and read anything. + Client, + /// Everything, including queue settings, pausing and retrying dead + /// messages. + Admin, +} + +/// One API key in the configuration. +#[derive(Clone, PartialEq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct KeyConfig { + /// Shown in logs instead of the key, such as `billing-worker`. + pub name: String, + /// What the key may do. + pub role: Role, + /// The key itself. Prefer `key_env`, so secrets stay out of the file. + #[serde(default)] + pub key: Option, + /// The environment variable that holds the key. + #[serde(default)] + pub key_env: Option, +} + +// Written by hand so that the key never ends up in logs. +impl fmt::Debug for KeyConfig { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("KeyConfig") + .field("name", &self.name) + .field("role", &self.role) + .field("key", &self.key.as_ref().map(|_| "")) + .field("key_env", &self.key_env) + .finish() + } +} + +/// The `[auth]` section of the configuration. +#[derive(Debug, Clone, Default, PartialEq, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct AuthConfig { + /// The accepted keys. Empty means auth is off. + pub keys: Vec, + /// Require a key, of any role, for `/metrics` too. + pub protect_metrics: bool, +} + +/// Who made a request, as found by [`authenticate`]. +#[derive(Debug, Clone)] +pub struct Caller { + /// The key's name, or `anonymous` when auth is off. + pub name: String, + /// What the caller may do. + pub role: Role, +} + +/// The configured keys, ready to check requests against. +pub struct Auth { + keys: Vec, +} + +struct Key { + name: String, + role: Role, + secret: Vec, +} + +impl Auth { + /// Reads the keys, including those taken from the environment. + pub fn from_config(config: &AuthConfig) -> Result { + let keys = config + .keys + .iter() + .map(|key| { + let secret = match (&key.key, &key.key_env) { + (Some(secret), None) => secret.clone(), + (None, Some(var)) => std::env::var(var).map_err(|_| { + Error::Config(format!( + "auth key {:?}: environment variable {var} is not set", + key.name + )) + })?, + _ => { + return Err(Error::Config(format!( + "auth key {:?}: set exactly one of `key` and `key_env`", + key.name + ))); + } + }; + if secret.len() < 16 { + return Err(Error::Config(format!( + "auth key {:?} is too short; use at least 16 characters", + key.name + ))); + } + Ok(Key { + name: key.name.clone(), + role: key.role, + secret: secret.into_bytes(), + }) + }) + .collect::>()?; + Ok(Self { keys }) + } + + /// Whether any keys are configured. + pub fn is_enabled(&self) -> bool { + !self.keys.is_empty() + } + + /// Finds the key matching `token`. Every key is compared, in constant + /// time, so the time taken does not reveal which keys exist. + fn identify(&self, token: &[u8]) -> Option<&Key> { + let mut found = None; + for key in &self.keys { + if bool::from(key.secret.ct_eq(token)) { + found = Some(key); + } + } + found + } +} + +/// Middleware: checks the bearer token and records the [`Caller`] for +/// handlers and [`Admin`]. With auth off, every caller is an admin. +pub async fn authenticate( + State(auth): State>, + mut request: Request, + next: Next, +) -> Response { + let caller = if auth.is_enabled() { + let token = bearer_token(request.headers().get(header::AUTHORIZATION)); + match token.and_then(|token| auth.identify(token)) { + Some(key) => Caller { + name: key.name.clone(), + role: key.role, + }, + None => return unauthorized(), + } + } else { + Caller { + name: "anonymous".to_owned(), + role: Role::Admin, + } + }; + + let span = tracing::info_span!("caller", key = caller.name); + request.extensions_mut().insert(caller); + next.run(request).instrument(span).await +} + +fn bearer_token(header: Option<&HeaderValue>) -> Option<&[u8]> { + let value = header?.as_bytes(); + let token = value.strip_prefix(b"Bearer ")?; + (!token.is_empty()).then_some(token) +} + +fn unauthorized() -> Response { + let error = ApiError::new( + StatusCode::UNAUTHORIZED, + "unauthorized", + "a valid API key is required: send `Authorization: Bearer `", + ); + ([(header::WWW_AUTHENTICATE, "Bearer")], error).into_response() +} + +/// Proof that the caller has the admin role. Take it as a handler argument to +/// make an endpoint admin-only. +pub struct Admin; + +impl FromRequestParts for Admin { + type Rejection = ApiError; + + async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result { + // No caller means the request skipped `authenticate`; refuse rather + // than guess. + match parts.extensions.get::() { + Some(Caller { + role: Role::Admin, .. + }) => Ok(Admin), + _ => Err(ApiError::new( + StatusCode::FORBIDDEN, + "forbidden", + "this endpoint needs an admin key", + )), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn key(name: &str, role: Role, secret: &str) -> KeyConfig { + KeyConfig { + name: name.to_owned(), + role, + key: Some(secret.to_owned()), + key_env: None, + } + } + + #[test] + fn identifies_keys() { + let config = AuthConfig { + keys: vec![ + key("worker", Role::Client, "client-key-0123456789"), + key("ops", Role::Admin, "admin-key-0123456789"), + ], + protect_metrics: false, + }; + let auth = Auth::from_config(&config).expect("valid config"); + + let found = auth + .identify(b"admin-key-0123456789") + .map(|key| (key.name.as_str(), key.role)); + assert_eq!(found, Some(("ops", Role::Admin))); + assert!(auth.identify(b"admin-key-012345678").is_none()); + assert!(auth.identify(b"").is_none()); + } + + #[test] + fn rejects_bad_key_configs() { + let both = KeyConfig { + key_env: Some("X".to_owned()), + ..key("both", Role::Client, "client-key-0123456789") + }; + let short = key("short", Role::Client, "tiny"); + for bad in [both, short] { + let config = AuthConfig { + keys: vec![bad], + protect_metrics: false, + }; + assert!(Auth::from_config(&config).is_err()); + } + } + + #[test] + fn parses_bearer_tokens() { + let header = |value: &'static str| HeaderValue::from_static(value); + assert_eq!(bearer_token(Some(&header("Bearer abc"))), Some(&b"abc"[..])); + assert_eq!(bearer_token(Some(&header("Basic abc"))), None); + assert_eq!(bearer_token(Some(&header("Bearer "))), None); + assert_eq!(bearer_token(None), None); + } + + #[test] + fn debug_output_hides_keys() { + let config = key("ops", Role::Admin, "admin-key-0123456789"); + assert!(!format!("{config:?}").contains("admin-key")); + } +} diff --git a/crates/dally-server/src/config.rs b/crates/dally-server/src/config.rs new file mode 100644 index 0000000..bb6a4b8 --- /dev/null +++ b/crates/dally-server/src/config.rs @@ -0,0 +1,332 @@ +//! Server configuration, from a TOML file and `DALLY_*` environment variables. + +// figment::Error is large, but it is returned once at startup, so boxing it +// would only add noise. +#![allow(clippy::result_large_err)] + +use std::collections::BTreeMap; +use std::net::SocketAddr; +use std::path::Path; +use std::time::Duration; + +use dally_core::QueueSettings; + +use crate::auth::AuthConfig; +use figment::Figment; +use figment::providers::{Env, Format, Toml}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer}; + +/// Everything `dally server` can be configured with. Every field has a +/// default, so an empty file (or no file) is a valid configuration. +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct Config { + /// The address the HTTP server listens on. + pub listen: SocketAddr, + + /// Where queues and messages are stored. + pub storage: StorageConfig, + + /// Settings for queues that are created implicitly, by scheduling into or + /// polling from a queue that does not exist yet. + pub defaults: QueueSettings, + + /// Queues to create or update on startup. Settings here win over changes + /// made through the API, every time the server starts. + pub queues: BTreeMap, + + /// The background task that deletes old finished messages. + pub janitor: JanitorConfig, + + /// The background task that delivers messages from push queues. + pub push: PushConfig, + + /// API keys. With none, auth is off. + pub auth: AuthConfig, +} + +impl Default for Config { + fn default() -> Self { + Self { + listen: SocketAddr::from(([127, 0, 0, 1], 7070)), + storage: StorageConfig::default(), + defaults: QueueSettings::default(), + queues: BTreeMap::new(), + janitor: JanitorConfig::default(), + push: PushConfig::default(), + auth: AuthConfig::default(), + } + } +} + +/// Where queues and messages are stored. +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct StorageConfig { + /// `postgres://...`, `sqlite://...` or `redis://...`. + pub url: String, + + /// Run pending schema migrations on startup. Turn this off if you run + /// migrations as a separate deploy step. + pub migrate: bool, +} + +impl Default for StorageConfig { + fn default() -> Self { + Self { + url: "sqlite://dally.sqlite".to_owned(), + migrate: true, + } + } +} + +/// How often finished messages past their retention are deleted. +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct JanitorConfig { + /// Time between runs. + #[serde(with = "humantime_serde")] + pub interval: Duration, +} + +impl Default for JanitorConfig { + fn default() -> Self { + Self { + interval: Duration::from_secs(60), + } + } +} + +/// How the push dispatcher finds push queues and talks to their endpoints. +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct PushConfig { + /// How often to look for queues that gained, changed or lost their push + /// settings, or were paused or resumed. + #[serde(with = "humantime_serde")] + pub refresh_interval: Duration, + + /// How long each long poll for new messages waits. Shutting down waits + /// for a poll in progress, so this also bounds how long that takes. + #[serde(with = "humantime_serde")] + pub poll_wait: Duration, + + /// The `User-Agent` header sent to push endpoints. + pub user_agent: String, +} + +impl Default for PushConfig { + fn default() -> Self { + Self { + refresh_interval: Duration::from_secs(5), + poll_wait: Duration::from_secs(5), + user_agent: concat!("dally/", env!("CARGO_PKG_VERSION")).to_owned(), + } + } +} + +/// A queue in the configuration file: its settings, plus the recurring jobs +/// that schedule into it. +/// +/// The settings sit directly in the queue's table, next to `cron`: +/// +/// ```toml +/// [queues.reports] +/// max_attempts = 3 +/// +/// [[queues.reports.cron]] +/// name = "nightly" +/// schedule = "0 3 * * *" +/// ``` +#[derive(Debug, Clone, Default, PartialEq)] +pub struct QueueConfig { + /// The queue's settings, stored in the database on startup. + pub settings: QueueSettings, + + /// Recurring jobs. These live only in the configuration, never in the + /// database, so every server should be given the same list. + pub cron: Vec, +} + +// `#[serde(flatten)]` cannot be combined with the `deny_unknown_fields` that +// `QueueSettings` needs for the HTTP API, so split the table by hand: take +// out `cron`, and let `QueueSettings` reject whatever else it does not know. +impl<'de> Deserialize<'de> for QueueConfig { + fn deserialize>(deserializer: D) -> Result { + let mut table = figment::value::Dict::deserialize(deserializer)?; + let cron = match table.remove("cron") { + Some(cron) => cron.deserialize().map_err(D::Error::custom)?, + None => Vec::new(), + }; + let settings = figment::value::Value::from(table) + .deserialize() + .map_err(D::Error::custom)?; + Ok(Self { settings, cron }) + } +} + +/// A recurring job: a payload scheduled into its queue on a cron schedule. +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CronJob { + /// Identifies the job within its queue. It is part of each message's + /// idempotency key, so renaming a job makes it a new one. + pub name: String, + + /// A cron expression with five fields (minute to day of week), or six + /// with a leading seconds field. + pub schedule: String, + + /// The IANA time zone the schedule is read in, such as + /// `Europe/Bucharest`. Defaults to UTC. + #[serde(default)] + pub timezone: Option, + + /// What each scheduled message carries. + #[serde(default)] + pub payload: serde_json::Value, +} + +impl Config { + /// The top-level keys, which environment variables are matched against. + const SECTIONS: &[&str] = &[ + "listen", "storage", "defaults", "queues", "janitor", "push", "auth", + ]; + + /// Loads the configuration: defaults, then the file at `path` (if given), + /// then environment variables. + /// + /// An environment variable names a setting by its path, with the first + /// `_` after the prefix standing for a dot: `DALLY_LISTEN` sets `listen`, + /// `DALLY_STORAGE_URL` sets `storage.url`, `DALLY_DEFAULTS_MAX_ATTEMPTS` + /// sets `defaults.max_attempts`. + pub fn load(path: Option<&Path>) -> Result { + let mut figment = Figment::new(); + if let Some(path) = path { + figment = figment.merge(Toml::file_exact(path)); + } + // Other DALLY_* variables (DALLY_CONFIG, DALLY_LOG_FORMAT, ...) belong + // to the command line, not to this file's settings. + let settings = Env::prefixed("DALLY_") + .filter(|key| { + let top_level = key.as_str().split('_').next().unwrap_or_default(); + Self::SECTIONS + .iter() + .any(|section| section.eq_ignore_ascii_case(top_level)) + }) + .map(|key| key.as_str().replacen('_', ".", 1).into()); + + figment.merge(settings).extract() + } +} + +#[cfg(test)] +mod tests { + use figment::Jail; + + use super::*; + + #[test] + fn empty_config_uses_defaults() { + Jail::expect_with(|_| { + assert_eq!(Config::load(None)?, Config::default()); + Ok(()) + }); + } + + #[test] + fn file_then_environment() { + Jail::expect_with(|jail| { + jail.create_file( + "dally.toml", + r#" + listen = "0.0.0.0:8080" + + [storage] + url = "postgres://localhost/dally" + + [defaults] + max_attempts = 3 + + [queues.emails] + visibility_timeout = "2m" + + [queues.emails.push] + url = "https://example.com/jobs" + "#, + )?; + jail.set_env("DALLY_STORAGE_URL", "postgres://db/dally"); + jail.set_env("DALLY_DEFAULTS_MAX_ATTEMPTS", "7"); + jail.set_env("DALLY_LOG_FORMAT", "json"); + + let config = Config::load(Some(Path::new("dally.toml")))?; + assert_eq!(config.listen, SocketAddr::from(([0, 0, 0, 0], 8080))); + assert_eq!(config.storage.url, "postgres://db/dally"); + assert_eq!(config.defaults.max_attempts, 7); + + let emails = &config.queues["emails"].settings; + assert_eq!(emails.visibility_timeout, Duration::from_secs(120)); + assert_eq!(emails.push.as_ref().map(|p| p.concurrency), Some(8)); + Ok(()) + }); + } + + #[test] + fn unknown_keys_are_rejected() { + Jail::expect_with(|jail| { + jail.create_file("dally.toml", "lisen = \"0.0.0.0:8080\"")?; + assert!(Config::load(Some(Path::new("dally.toml"))).is_err()); + Ok(()) + }); + } + + #[test] + fn queues_hold_settings_and_cron_jobs() { + Jail::expect_with(|jail| { + jail.create_file( + "dally.toml", + r#" + [queues.reports] + max_attempts = 3 + + [[queues.reports.cron]] + name = "nightly" + schedule = "0 3 * * *" + timezone = "Europe/Bucharest" + payload = { kind = "nightly-report" } + "#, + )?; + let config = Config::load(Some(Path::new("dally.toml")))?; + let reports = &config.queues["reports"]; + assert_eq!(reports.settings.max_attempts, 3); + assert_eq!( + reports.cron, + [CronJob { + name: "nightly".to_owned(), + schedule: "0 3 * * *".to_owned(), + timezone: Some("Europe/Bucharest".to_owned()), + payload: serde_json::json!({"kind": "nightly-report"}), + }] + ); + Ok(()) + }); + } + + #[test] + fn unknown_queue_and_cron_keys_are_rejected() { + let typo_in_settings = "[queues.reports]\nmax_atempts = 3"; + let typo_in_cron = r#" + [[queues.reports.cron]] + name = "nightly" + shedule = "0 3 * * *" + "#; + for file in [typo_in_settings, typo_in_cron] { + Jail::expect_with(|jail| { + jail.create_file("dally.toml", file)?; + assert!(Config::load(Some(Path::new("dally.toml"))).is_err()); + Ok(()) + }); + } + } +} diff --git a/crates/dally-server/src/cron.rs b/crates/dally-server/src/cron.rs new file mode 100644 index 0000000..b3d423e --- /dev/null +++ b/crates/dally-server/src/cron.rs @@ -0,0 +1,309 @@ +//! Recurring jobs: payloads scheduled into a queue on a cron schedule. +//! +//! Every server runs the ticker, and there is no leader. Each occurrence is +//! scheduled with the idempotency key `cron:{name}:{time}`, so when several +//! servers fire the same occurrence, only the first creates a message. +//! +//! Time comes from the storage clock, so servers agree on when an occurrence +//! is due. The ticker asks storage for the time before each wait and sleeps +//! for the difference, so a skewed local clock only shifts when a server wakes +//! up, never which occurrence it schedules. +//! +//! # Missed runs +//! +//! After downtime, the ticker schedules the most recent missed occurrence and +//! then continues normally; older missed runs are skipped. It only does this +//! if that occurrence is within the queue's retention, because only then can +//! it tell, through the idempotency key, whether the run already happened. + +use std::time::Duration; + +use chrono::{DateTime, Utc}; +use chrono_tz::Tz; +use croner::Cron; +use croner::parser::{CronParser, Seconds}; +use dally_core::{QueueName, ScheduleRequest, Service}; +use tokio_util::sync::CancellationToken; + +use crate::Error; +use crate::config::{Config, CronJob}; + +/// The longest allowed job name, so the idempotency key stays well under its +/// 200-byte limit. +const MAX_NAME_LEN: usize = 100; + +/// How long to wait before trying again after storage fails. +const RETRY_DELAY: Duration = Duration::from_secs(5); + +/// A validated recurring job. +#[derive(Debug, Clone)] +pub struct CronEntry { + queue: QueueName, + name: String, + schedule: Cron, + timezone: Tz, + payload: serde_json::Value, +} + +impl CronEntry { + /// Checks a job from the configuration. Errors name the queue and job. + pub fn new(queue: QueueName, job: &CronJob) -> Result { + let context = format!("queues.{queue}.cron {:?}", job.name); + if job.name.is_empty() || job.name.len() > MAX_NAME_LEN { + return Err(Error::Config(format!( + "{context}: name must be 1 to {MAX_NAME_LEN} bytes" + ))); + } + + let schedule = CronParser::builder() + .seconds(Seconds::Optional) + .build() + .parse(&job.schedule) + .map_err(|err| Error::Config(format!("{context}: invalid schedule: {err}")))?; + + let timezone = match &job.timezone { + Some(name) => name + .parse::() + .map_err(|err| Error::Config(format!("{context}: invalid timezone: {err}")))?, + None => Tz::UTC, + }; + + Ok(Self { + queue, + name: job.name.clone(), + schedule, + timezone, + payload: job.payload.clone(), + }) + } + + /// The first occurrence strictly after `after`. + fn next_after(&self, after: DateTime) -> Option> { + let local = after.with_timezone(&self.timezone); + self.schedule + .find_next_occurrence(&local, false) + .ok() + .map(|next| next.with_timezone(&Utc)) + } + + /// The latest occurrence at or before `at`. + fn latest_at_or_before(&self, at: DateTime) -> Option> { + let local = at.with_timezone(&self.timezone); + self.schedule + .find_previous_occurrence(&local, true) + .ok() + .map(|previous| previous.with_timezone(&Utc)) + } + + /// The idempotency key for one occurrence. The time is in UTC, so the + /// key does not depend on the server's or the job's time zone. + fn idempotency_key(&self, occurrence: DateTime) -> String { + let time = occurrence.to_rfc3339_opts(chrono::SecondsFormat::Secs, true); + format!("cron:{}:{time}", self.name) + } +} + +/// Validates every cron job in the configuration. +pub fn entries(config: &Config) -> Result, Error> { + let mut entries = Vec::new(); + for (queue, queue_config) in &config.queues { + let queue = QueueName::new(queue.as_str()) + .map_err(|err| Error::Config(format!("queues.{queue}: {err}")))?; + for job in &queue_config.cron { + entries.push(CronEntry::new(queue.clone(), job)?); + } + } + Ok(entries) +} + +/// Runs every entry until `stop` is cancelled. +pub async fn run(service: Service, entries: Vec, stop: CancellationToken) { + let tickers: Vec<_> = entries + .into_iter() + .map(|entry| tokio::spawn(run_entry(service.clone(), entry, stop.clone()))) + .collect(); + for ticker in tickers { + let _ = ticker.await; + } +} + +async fn run_entry(service: Service, entry: CronEntry, stop: CancellationToken) { + let mut last = match catch_up(&service, &entry).await { + Ok(last) => last, + Err(err) => { + tracing::warn!(queue = %entry.queue, job = entry.name, error = %err, "cron catch-up failed"); + None + } + }; + + loop { + let result = tokio::select! { + _ = stop.cancelled() => return, + result = tick(&service, &entry, last) => result, + }; + match result { + Ok(Some(fired)) => last = Some(fired), + Ok(None) => { + tracing::warn!(queue = %entry.queue, job = entry.name, "cron schedule has no future occurrences"); + return; + } + Err(err) => { + tracing::warn!(queue = %entry.queue, job = entry.name, error = %err, "cron tick failed"); + tokio::select! { + _ = stop.cancelled() => return, + _ = tokio::time::sleep(RETRY_DELAY) => {} + } + } + } + } +} + +/// Schedules the most recent occurrence if it may have been missed, and +/// returns it. +async fn catch_up( + service: &Service, + entry: &CronEntry, +) -> dally_core::Result>> { + let now = service.storage().now().await?; + let Some(latest) = entry.latest_at_or_before(now) else { + return Ok(None); + }; + + let retention = service + .get_queue(&entry.queue) + .await? + .queue + .settings + .retention; + let age = (now - latest).to_std().unwrap_or_default(); + if age < retention { + fire(service, entry, latest).await?; + } + Ok(Some(latest)) +} + +/// Waits for the next occurrence after `last` (or after now) and schedules it. +/// Returns the occurrence, or `None` if the schedule has no more. +async fn tick( + service: &Service, + entry: &CronEntry, + last: Option>, +) -> dally_core::Result>> { + let now = service.storage().now().await?; + // Counting from the last occurrence rather than from now means a server + // that wakes up a little early does not skip an occurrence. + let after = last.map_or(now, |last| last.min(now)); + let Some(next) = entry.next_after(after) else { + return Ok(None); + }; + + if let Ok(wait) = (next - now).to_std() { + tokio::time::sleep(wait).await; + } + fire(service, entry, next).await?; + Ok(Some(next)) +} + +async fn fire( + service: &Service, + entry: &CronEntry, + occurrence: DateTime, +) -> dally_core::Result<()> { + let request = ScheduleRequest { + run_at: Some(occurrence), + idempotency_key: Some(entry.idempotency_key(occurrence)), + ..ScheduleRequest::new(entry.payload.clone()) + }; + let scheduled = service.schedule(&entry.queue, vec![request]).await?; + if scheduled.first().is_some_and(|result| result.created) { + tracing::info!(queue = %entry.queue, job = entry.name, %occurrence, "scheduled cron job"); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use chrono::TimeZone; + + use super::*; + + fn entry(schedule: &str, timezone: Option<&str>) -> CronEntry { + let job = CronJob { + name: "nightly".to_owned(), + schedule: schedule.to_owned(), + timezone: timezone.map(str::to_owned), + payload: serde_json::json!({}), + }; + CronEntry::new(QueueName::new("reports").expect("valid"), &job).expect("valid job") + } + + fn utc(y: i32, mo: u32, d: u32, h: u32, mi: u32, s: u32) -> DateTime { + Utc.with_ymd_and_hms(y, mo, d, h, mi, s) + .single() + .expect("valid time") + } + + #[test] + fn next_occurrence_in_a_time_zone() { + // 03:00 in Bucharest is 01:00 UTC in winter (UTC+2) and 00:00 UTC in + // summer (UTC+3). + let nightly = entry("0 3 * * *", Some("Europe/Bucharest")); + assert_eq!( + nightly.next_after(utc(2026, 1, 10, 12, 0, 0)), + Some(utc(2026, 1, 11, 1, 0, 0)) + ); + assert_eq!( + nightly.next_after(utc(2026, 7, 10, 12, 0, 0)), + Some(utc(2026, 7, 11, 0, 0, 0)) + ); + } + + #[test] + fn next_is_strictly_after() { + let hourly = entry("0 * * * *", None); + let on_the_hour = utc(2026, 3, 1, 10, 0, 0); + assert_eq!( + hourly.next_after(on_the_hour), + Some(utc(2026, 3, 1, 11, 0, 0)) + ); + assert_eq!(hourly.latest_at_or_before(on_the_hour), Some(on_the_hour)); + } + + #[test] + fn seconds_field_is_optional() { + let every_ten_seconds = entry("*/10 * * * * *", None); + assert_eq!( + every_ten_seconds.next_after(utc(2026, 3, 1, 10, 0, 3)), + Some(utc(2026, 3, 1, 10, 0, 10)) + ); + } + + #[test] + fn idempotency_key_is_utc() { + let nightly = entry("0 3 * * *", Some("Europe/Bucharest")); + assert_eq!( + nightly.idempotency_key(utc(2026, 1, 11, 1, 0, 0)), + "cron:nightly:2026-01-11T01:00:00Z" + ); + } + + #[test] + fn invalid_jobs_name_the_queue_and_job() { + let queue = QueueName::new("reports").expect("valid"); + let job = |schedule: &str, timezone: Option<&str>| CronJob { + name: "nightly".to_owned(), + schedule: schedule.to_owned(), + timezone: timezone.map(str::to_owned), + payload: serde_json::Value::Null, + }; + + let err = CronEntry::new(queue.clone(), &job("not a schedule", None)).expect_err("bad"); + assert!( + err.to_string().contains(r#"queues.reports.cron "nightly""#), + "{err}" + ); + + let err = CronEntry::new(queue, &job("0 3 * * *", Some("Mars/Olympus"))).expect_err("bad"); + assert!(err.to_string().contains("timezone"), "{err}"); + } +} diff --git a/crates/dally-server/src/janitor.rs b/crates/dally-server/src/janitor.rs new file mode 100644 index 0000000..9439141 --- /dev/null +++ b/crates/dally-server/src/janitor.rs @@ -0,0 +1,26 @@ +//! Deletes finished messages once they are past their queue's retention. +//! +//! Every server runs a janitor. Pruning is a single idempotent delete, so +//! several janitors at once only cost a few redundant queries. + +use std::time::Duration; + +use dally_core::Service; +use tokio_util::sync::CancellationToken; + +pub async fn run(service: Service, interval: Duration, stop: CancellationToken) { + let mut ticker = tokio::time::interval(interval); + ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + + loop { + tokio::select! { + _ = stop.cancelled() => return, + _ = ticker.tick() => {} + } + match service.prune().await { + Ok(0) => {} + Ok(pruned) => tracing::info!(pruned, "pruned finished messages"), + Err(err) => tracing::warn!(error = %err, "pruning failed"), + } + } +} diff --git a/crates/dally-server/src/lib.rs b/crates/dally-server/src/lib.rs new file mode 100644 index 0000000..8620c64 --- /dev/null +++ b/crates/dally-server/src/lib.rs @@ -0,0 +1,205 @@ +//! The dally server: the HTTP API plus the background tasks that keep queues +//! healthy. +//! +//! Most users run it through the `dally` binary, which calls [`run`]. To +//! embed the server in your own process instead, build a [`Server`], mount +//! [`Server::router`] in your axum app, and call +//! [`Server::start_background_tasks`]: +//! +//! ```no_run +//! # async fn example(storage: std::sync::Arc) -> Result<(), dally_server::Error> { +//! use dally_server::{CancellationToken, Config, Server}; +//! +//! let config = Config::default(); +//! let service = dally_core::Service::new(storage, config.defaults.clone()); +//! let server = Server::new(service, config)?; +//! server.apply_queues().await?; +//! +//! let stop = CancellationToken::new(); +//! let background = server.start_background_tasks(stop.clone())?; +//! let app = axum::Router::new().nest("/dally", server.router()); +//! # Ok(()) +//! # } +//! ``` + +mod api; +pub mod auth; +pub mod config; +mod cron; +mod janitor; +mod metrics; +mod push; +pub mod signature; + +use std::future::Future; +use std::sync::Arc; + +use axum::Router; +use dally_core::{ConnectOptions, QueueName, Service}; +use tokio::task::JoinHandle; + +pub use config::Config; +pub use tokio_util::sync::CancellationToken; + +use crate::auth::Auth; +use crate::metrics::Metrics; + +/// Why the server could not start or stopped with an error. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// The configuration is invalid. + #[error("invalid configuration: {0}")] + Config(String), + + /// Storage could not be reached or migrated. + #[error(transparent)] + Storage(#[from] dally_core::Error), + + /// The listener could not be bound, or serving failed. + #[error("http server: {0}")] + Io(#[from] std::io::Error), +} + +/// A configured server: the service, API keys and metrics, wired so that the +/// HTTP API and the background tasks report to the same metrics. +pub struct Server { + service: Service, + config: Config, + auth: Arc, + metrics: Arc, +} + +impl Server { + /// Checks the configuration and wires everything together. Nothing runs + /// until you serve the router or start the background tasks. + pub fn new(service: Service, config: Config) -> Result { + // Check the cron jobs and the push client now, so mistakes surface + // before anything is served. + cron::entries(&config)?; + push::client(&config.push)?; + + let auth = Arc::new(Auth::from_config(&config.auth)?); + let metrics = Metrics::new(); + let service = service.with_observer(Arc::clone(&metrics) as _); + Ok(Self { + service, + config, + auth, + metrics, + }) + } + + /// The service, reporting to this server's metrics. + pub fn service(&self) -> &Service { + &self.service + } + + /// The HTTP API: `/v1/...`, `/healthz`, `/readyz` and `/metrics`. + pub fn router(&self) -> Router { + api::router( + self.service.clone(), + Arc::clone(&self.auth), + Arc::clone(&self.metrics), + self.config.auth.protect_metrics, + ) + } + + /// Creates or updates the queues listed in the configuration. + pub async fn apply_queues(&self) -> Result<(), Error> { + for (name, queue) in &self.config.queues { + let name = QueueName::new(name.as_str()) + .map_err(|err| Error::Config(format!("queues.{name}: {err}")))?; + self.service + .put_queue(&name, queue.settings.clone()) + .await + .map_err(|err| match err { + dally_core::Error::InvalidInput(message) => { + Error::Config(format!("queues.{name}: {message}")) + } + other => Error::Storage(other), + })?; + } + Ok(()) + } + + /// Starts the janitor, the push dispatcher and the cron ticker. They run + /// until `stop` is cancelled; the returned handle finishes once they have + /// all wound down, including in-flight push requests. + pub fn start_background_tasks(&self, stop: CancellationToken) -> Result, Error> { + let config = &self.config; + let cron_entries = cron::entries(config)?; + let client = push::client(&config.push)?; + let service = self.service.clone(); + + let janitor = tokio::spawn(janitor::run( + service.clone(), + config.janitor.interval, + stop.clone(), + )); + let push = tokio::spawn(push::run( + service.clone(), + config.push.clone(), + client, + stop.clone(), + )); + let cron = tokio::spawn(cron::run(service, cron_entries, stop)); + + Ok(tokio::spawn(async move { + let _ = tokio::join!(janitor, push, cron); + })) + } +} + +/// Connects to storage, applies the configured queues, and serves the API +/// until `shutdown` resolves. In-flight requests get to finish; long polls +/// end at their wait deadline. +pub async fn run( + config: Config, + shutdown: impl Future + Send + 'static, +) -> Result<(), Error> { + run_with(config, Router::new(), shutdown).await +} + +/// Like [`run`], with `extra` routes served next to the API, such as the web +/// UI under `/ui`. +pub async fn run_with( + config: Config, + extra: Router, + shutdown: impl Future + Send + 'static, +) -> Result<(), Error> { + let options = ConnectOptions { + migrate: config.storage.migrate, + }; + let listen = config.listen; + let storage = dally_core::connect(&config.storage.url, &options).await?; + let service = Service::new(storage, config.defaults.clone()); + let server = Server::new(service, config)?; + server.apply_queues().await?; + + if !server.auth.is_enabled() && !listen.ip().is_loopback() { + tracing::warn!( + %listen, + "auth is off and dally is reachable from the network; \ + anyone who can reach it can read and change every queue" + ); + } + + let listener = tokio::net::TcpListener::bind(listen).await?; + tracing::info!(address = %listener.local_addr()?, "dally is listening"); + + let stop = CancellationToken::new(); + let background = server.start_background_tasks(stop.clone())?; + + let serve_stop = stop.clone(); + axum::serve(listener, server.router().merge(extra)) + .with_graceful_shutdown(async move { + shutdown.await; + serve_stop.cancel(); + }) + .await?; + + stop.cancel(); + let _ = background.await; + tracing::info!("dally stopped"); + Ok(()) +} diff --git a/crates/dally-server/src/metrics.rs b/crates/dally-server/src/metrics.rs new file mode 100644 index 0000000..3dd6280 --- /dev/null +++ b/crates/dally-server/src/metrics.rs @@ -0,0 +1,300 @@ +//! Prometheus metrics, served at `GET /metrics`. +//! +//! Message counters come from [`Observer`] callbacks on the [`Service`], so +//! they include messages moved by push delivery and cron, not only by HTTP +//! requests. Queue depths and the age of the oldest due message come from +//! storage, refreshed at most every few seconds when `/metrics` is scraped. +//! +//! Counters are per server process. Gauges read shared storage, so every +//! server reports the same values for them; aggregate with `max`, not `sum`. + +use std::sync::atomic::AtomicU64; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use axum::extract::{MatchedPath, Request, State}; +use axum::http::{StatusCode, header}; +use axum::middleware::Next; +use axum::response::{IntoResponse, Response}; +use dally_core::{Message, Observer, QueueName, Service, Status}; +use prometheus_client::encoding::EncodeLabelSet; +use prometheus_client::metrics::counter::Counter; +use prometheus_client::metrics::family::Family; +use prometheus_client::metrics::gauge::Gauge; +use prometheus_client::metrics::histogram::{Histogram, exponential_buckets}; +use prometheus_client::registry::Registry; + +/// How long gauge values read from storage are reused between scrapes. +const GAUGE_CACHE: Duration = Duration::from_secs(5); + +#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)] +struct QueueLabels { + queue: String, +} + +#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)] +struct QueueStatusLabels { + queue: String, + status: String, +} + +#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)] +struct RequestLabels { + method: String, + route: String, + status: u16, +} + +#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)] +struct RouteLabels { + method: String, + route: String, +} + +type DurationHistogram = Family Histogram>; + +/// Every metric the server exports. +pub struct Metrics { + registry: Registry, + scheduled: Family, + leased: Family, + acked: Family, + nacked: Family, + dead: Family, + requests: Family, + request_duration: DurationHistogram, + queue_messages: Family, + oldest_due: Family>, + gauges_refreshed: Mutex>, +} + +impl Metrics { + /// Creates and registers every metric. + pub fn new() -> Arc { + fn request_histogram() -> Histogram { + // 5 ms up to about 40 s: long polls end up in the top buckets. + Histogram::new(exponential_buckets(0.005, 2.0, 14)) + } + + let scheduled = Family::default(); + let leased = Family::default(); + let acked = Family::default(); + let nacked = Family::default(); + let dead = Family::default(); + let requests = Family::default(); + let request_duration: DurationHistogram = Family::new_with_constructor(request_histogram); + let queue_messages = Family::default(); + let oldest_due = Family::default(); + + let mut registry = Registry::with_prefix("dally"); + registry.register( + "messages_scheduled", + "Messages scheduled, not counting repeated idempotency keys", + scheduled.clone(), + ); + registry.register( + "messages_leased", + "Messages handed to workers", + leased.clone(), + ); + registry.register( + "messages_acked", + "Messages finished successfully", + acked.clone(), + ); + registry.register( + "messages_nacked", + "Failed attempts reported by workers", + nacked.clone(), + ); + registry.register( + "messages_dead", + "Messages that ran out of attempts on a nack; expired leases show in dally_queue_messages", + dead.clone(), + ); + registry.register( + "http_requests", + "HTTP requests by route and status", + requests.clone(), + ); + registry.register( + "http_request_duration_seconds", + "HTTP request duration by route", + request_duration.clone(), + ); + registry.register( + "queue_messages", + "Messages per queue and status, read from storage", + queue_messages.clone(), + ); + registry.register( + "queue_oldest_due_seconds", + "How long the oldest due message in each queue has been waiting", + oldest_due.clone(), + ); + + Arc::new(Self { + registry, + scheduled, + leased, + acked, + nacked, + dead, + requests, + request_duration, + queue_messages, + oldest_due, + gauges_refreshed: Mutex::new(None), + }) + } + + /// Renders every metric in the Prometheus text format, refreshing the + /// storage gauges first if they are stale. + async fn render(&self, service: &Service) -> Result { + if self.gauges_are_stale() { + match self.refresh_gauges(service).await { + Ok(()) => self.mark_refreshed(), + Err(err) => tracing::warn!(error = %err, "cannot read queue gauges"), + } + } + let mut text = String::new(); + prometheus_client::encoding::text::encode(&mut text, &self.registry)?; + Ok(text) + } + + fn gauges_are_stale(&self) -> bool { + let refreshed = self + .gauges_refreshed + .lock() + .unwrap_or_else(|p| p.into_inner()); + refreshed.is_none_or(|at| at.elapsed() >= GAUGE_CACHE) + } + + fn mark_refreshed(&self) { + *self + .gauges_refreshed + .lock() + .unwrap_or_else(|p| p.into_inner()) = Some(Instant::now()); + } + + async fn refresh_gauges(&self, service: &Service) -> dally_core::Result<()> { + let queues = service.list_queues().await?; + let oldest = service.storage().oldest_due().await?; + + for summary in &queues { + let queue = summary.queue.name.to_string(); + let stats = summary.stats; + let counts = [ + (Status::Scheduled, stats.scheduled), + (Status::Running, stats.running), + (Status::Succeeded, stats.succeeded), + (Status::Cancelled, stats.cancelled), + (Status::Dead, stats.dead), + ]; + for (status, count) in counts { + let labels = QueueStatusLabels { + queue: queue.clone(), + status: status.to_string(), + }; + self.queue_messages + .get_or_create(&labels) + .set(i64::try_from(count).unwrap_or(i64::MAX)); + } + + // Backends that cannot measure this report nothing, rather than + // a misleading zero. + if let Some(oldest) = &oldest { + let waited = oldest.get(&summary.queue.name).copied().unwrap_or_default(); + self.oldest_due + .get_or_create(&QueueLabels { queue }) + .set(waited.as_secs_f64()); + } + } + Ok(()) + } + + fn count(family: &Family, queue: &QueueName, n: usize) { + let labels = QueueLabels { + queue: queue.to_string(), + }; + family.get_or_create(&labels).inc_by(n as u64); + } +} + +impl Observer for Metrics { + fn scheduled(&self, queue: &QueueName, created: usize) { + Self::count(&self.scheduled, queue, created); + } + + fn leased(&self, queue: &QueueName, count: usize) { + Self::count(&self.leased, queue, count); + } + + fn acked(&self, message: &Message) { + Self::count(&self.acked, &message.queue, 1); + } + + fn nacked(&self, message: &Message) { + Self::count(&self.nacked, &message.queue, 1); + if message.status == Status::Dead { + Self::count(&self.dead, &message.queue, 1); + } + } +} + +/// The state the `/metrics` handler and the request middleware need. +#[derive(Clone)] +pub struct MetricsState { + pub metrics: Arc, + pub service: Service, +} + +/// `GET /metrics`. +pub async fn handler(State(state): State) -> Response { + match state.metrics.render(&state.service).await { + Ok(text) => ( + [( + header::CONTENT_TYPE, + "application/openmetrics-text; version=1.0.0; charset=utf-8", + )], + text, + ) + .into_response(), + Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), + } +} + +/// Counts requests and their duration by route template, never by raw path, +/// so the number of label values stays bounded. +pub async fn track_requests( + State(metrics): State>, + request: Request, + next: Next, +) -> Response { + let route = request + .extensions() + .get::() + .map_or_else(|| "unmatched".to_owned(), |path| path.as_str().to_owned()); + let method = request.method().to_string(); + let started = Instant::now(); + + let response = next.run(request).await; + + let route_labels = RouteLabels { + method: method.clone(), + route: route.clone(), + }; + metrics + .request_duration + .get_or_create(&route_labels) + .observe(started.elapsed().as_secs_f64()); + metrics + .requests + .get_or_create(&RequestLabels { + method, + route, + status: response.status().as_u16(), + }) + .inc(); + response +} diff --git a/crates/dally-server/src/push.rs b/crates/dally-server/src/push.rs new file mode 100644 index 0000000..5848031 --- /dev/null +++ b/crates/dally-server/src/push.rs @@ -0,0 +1,338 @@ +//! Push delivery: POSTing messages to each push queue's endpoint. +//! +//! A supervisor looks at the queue list every `push.refresh_interval` and +//! keeps one delivery task per queue that has push settings and is not paused. +//! When a queue's push settings change, its task is restarted with the new +//! ones; when they are removed or the queue is paused, its task stops. +//! +//! A delivery task leases messages with a long poll, at most as many as it +//! has free slots (`push.concurrency` per queue, per server), and sends each +//! one in its own task. A 2xx response acks the message. Anything else, a +//! timeout or a connection error nacks it, so the queue's backoff applies. + +use std::collections::HashMap; +use std::sync::Arc; +use std::time::Duration; + +use axum::http::{HeaderMap, StatusCode, header}; +use dally_core::service::limits; +use dally_core::{Leased, NackRequest, PollRequest, PushSettings, QueueName, Service}; +use tokio::sync::{OwnedSemaphorePermit, Semaphore}; +use tokio::task::{JoinHandle, JoinSet}; +use tokio_util::sync::CancellationToken; + +use crate::config::PushConfig; +use crate::{Error, signature}; + +/// How much of an endpoint's error response is kept as the message's error. +const MAX_ERROR_BODY: usize = 1024; + +/// How long a delivery task waits after storage fails before polling again. +const RETRY_DELAY: Duration = Duration::from_secs(1); + +/// Builds the HTTP client shared by every delivery task. +pub fn client(config: &PushConfig) -> Result { + reqwest::Client::builder() + .user_agent(&config.user_agent) + .build() + .map_err(|err| Error::Config(format!("push: cannot build HTTP client: {err}"))) +} + +/// Runs the supervisor until `stop` is cancelled, then waits for every +/// delivery task to finish its in-flight requests. +pub async fn run( + service: Service, + config: PushConfig, + client: reqwest::Client, + stop: CancellationToken, +) { + let mut deliveries: HashMap = HashMap::new(); + let mut ticker = tokio::time::interval(config.refresh_interval); + ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + + loop { + tokio::select! { + _ = stop.cancelled() => break, + _ = ticker.tick() => {} + } + match push_queues(&service).await { + Ok(wanted) => reconcile(&mut deliveries, wanted, &service, &config, &client), + Err(err) => tracing::warn!(error = %err, "cannot list push queues"), + } + } + + for delivery in deliveries.into_values() { + delivery.stop().await; + } +} + +/// The queues that should be delivering right now, with their settings. +async fn push_queues(service: &Service) -> dally_core::Result> { + Ok(service + .list_queues() + .await? + .into_iter() + .filter(|summary| !summary.queue.settings.paused) + .filter_map(|summary| { + let push = summary.queue.settings.push?; + Some((summary.queue.name, push)) + }) + .collect()) +} + +/// Starts, restarts and stops delivery tasks so they match `wanted`. +fn reconcile( + deliveries: &mut HashMap, + wanted: HashMap, + service: &Service, + config: &PushConfig, + client: &reqwest::Client, +) { + deliveries.retain(|queue, delivery| { + let keep = wanted.get(queue) == Some(&delivery.settings); + if !keep { + tracing::info!(%queue, "stopping push delivery"); + // In-flight requests finish in the background; the old task and + // a new one may briefly overlap, which at-least-once allows. + delivery.cancel.cancel(); + } + keep + }); + + for (queue, settings) in wanted { + if deliveries.contains_key(&queue) { + continue; + } + tracing::info!(%queue, url = settings.url, "starting push delivery"); + let delivery = Delivery::start(service, queue.clone(), settings, config, client); + deliveries.insert(queue, delivery); + } +} + +/// A running delivery task for one queue. +struct Delivery { + settings: PushSettings, + cancel: CancellationToken, + task: JoinHandle<()>, +} + +impl Delivery { + fn start( + service: &Service, + queue: QueueName, + settings: PushSettings, + config: &PushConfig, + client: &reqwest::Client, + ) -> Self { + let cancel = CancellationToken::new(); + let task = tokio::spawn(deliver_queue( + service.clone(), + queue, + settings.clone(), + client.clone(), + config.poll_wait, + cancel.clone(), + )); + Self { + settings, + cancel, + task, + } + } + + async fn stop(self) { + self.cancel.cancel(); + let _ = self.task.await; + } +} + +async fn deliver_queue( + service: Service, + queue: QueueName, + settings: PushSettings, + client: reqwest::Client, + poll_wait: Duration, + cancel: CancellationToken, +) { + let slots = Arc::new(Semaphore::new(settings.concurrency as usize)); + let settings = Arc::new(settings); + let mut in_flight = JoinSet::new(); + + loop { + // Wait for at least one free slot, then take every other free one, so + // a single poll fills the queue's whole concurrency. + let first = tokio::select! { + _ = cancel.cancelled() => break, + permit = Arc::clone(&slots).acquire_owned() => match permit { + Ok(permit) => permit, + Err(_) => break, + }, + }; + let mut permits = vec![first]; + while permits.len() < limits::MAX_POLL as usize { + match Arc::clone(&slots).try_acquire_owned() { + Ok(permit) => permits.push(permit), + Err(_) => break, + } + } + + // Not cancellable: a poll that is dropped halfway may already hold + // leases. `poll_wait` bounds how long shutdown waits for it. + let request = PollRequest { + limit: permits.len() as u32, + wait: poll_wait, + }; + match service.poll(&queue, request).await { + Ok(messages) => { + for (message, permit) in messages.into_iter().zip(permits) { + let (service, client, settings) = + (service.clone(), client.clone(), Arc::clone(&settings)); + in_flight.spawn(async move { + deliver(&service, &client, &settings, message, permit).await; + }); + } + } + Err(err) => { + tracing::warn!(%queue, error = %err, "push poll failed"); + tokio::select! { + _ = cancel.cancelled() => break, + _ = tokio::time::sleep(RETRY_DELAY) => {} + } + } + } + while in_flight.try_join_next().is_some() {} + } + + while in_flight.join_next().await.is_some() {} +} + +/// Sends one message and acks or nacks it depending on the response. The +/// permit is held until the outcome is recorded. +async fn deliver( + service: &Service, + client: &reqwest::Client, + settings: &PushSettings, + leased: Leased, + _permit: OwnedSemaphorePermit, +) { + let Leased { message, lease } = leased; + let outcome = send(client, settings, &message).await; + + let result = match outcome { + Outcome::Delivered => service.ack(message.id, &lease).await.map(|_| ()), + Outcome::Failed { error, retry_in } => { + tracing::info!(queue = %message.queue, id = %message.id, error, "push delivery failed"); + let nack = NackRequest { + lease, + error: Some(error), + retry_in, + }; + service.nack(message.id, nack).await.map(|_| ()) + } + }; + + if let Err(err) = result { + // Most likely the lease expired while the request was running, and + // the message was handed out again. That attempt decides its fate. + tracing::warn!(queue = %message.queue, id = %message.id, error = %err, "cannot record push outcome"); + } +} + +enum Outcome { + Delivered, + Failed { + error: String, + retry_in: Option, + }, +} + +async fn send( + client: &reqwest::Client, + settings: &PushSettings, + message: &dally_core::Message, +) -> Outcome { + let body = match serde_json::to_vec(&message.payload) { + Ok(body) => body, + Err(err) => { + return Outcome::Failed { + error: format!("cannot encode payload: {err}"), + retry_in: None, + }; + } + }; + + let mut request = client + .post(&settings.url) + .timeout(settings.timeout) + .header(header::CONTENT_TYPE, "application/json") + .header("Dally-Message-Id", message.id.to_string()) + .header("Dally-Queue", message.queue.as_str()) + .header("Dally-Attempt", message.attempts.to_string()); + if let Some(secret) = &settings.secret { + let timestamp = chrono::Utc::now().timestamp(); + let signature = signature::sign(secret.as_bytes(), timestamp, &body); + request = request.header(signature::HEADER, signature); + } + + let response = match request.body(body).send().await { + Ok(response) => response, + Err(err) => { + return Outcome::Failed { + error: format!("request failed: {err}"), + retry_in: None, + }; + } + }; + + let status = response.status(); + if status.is_success() { + return Outcome::Delivered; + } + + let retry_in = match status { + StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE => { + retry_after(response.headers()) + } + _ => None, + }; + let body = response.bytes().await.unwrap_or_default(); + let excerpt = String::from_utf8_lossy(&body[..body.len().min(MAX_ERROR_BODY)]); + Outcome::Failed { + error: format!("HTTP {}: {}", status.as_u16(), excerpt.trim()), + retry_in, + } +} + +/// Reads a `Retry-After` header given in seconds. The HTTP-date form is rare +/// for APIs and is ignored, so the queue's backoff applies instead. +fn retry_after(headers: &HeaderMap) -> Option { + let value = headers.get(header::RETRY_AFTER)?.to_str().ok()?; + value.trim().parse().ok().map(Duration::from_secs) +} + +#[cfg(test)] +mod tests { + use axum::http::HeaderValue; + + use super::*; + + fn headers(retry_after: &str) -> HeaderMap { + let mut headers = HeaderMap::new(); + let value = HeaderValue::from_str(retry_after).expect("valid header"); + headers.insert(header::RETRY_AFTER, value); + headers + } + + #[test] + fn retry_after_in_seconds() { + assert_eq!(retry_after(&headers("120")), Some(Duration::from_secs(120))); + assert_eq!(retry_after(&headers(" 5 ")), Some(Duration::from_secs(5))); + } + + #[test] + fn retry_after_dates_and_junk_are_ignored() { + assert_eq!(retry_after(&headers("Wed, 21 Oct 2026 07:28:00 GMT")), None); + assert_eq!(retry_after(&headers("-1")), None); + assert_eq!(retry_after(&HeaderMap::new()), None); + } +} diff --git a/crates/dally-server/src/signature.rs b/crates/dally-server/src/signature.rs new file mode 100644 index 0000000..2c88aac --- /dev/null +++ b/crates/dally-server/src/signature.rs @@ -0,0 +1,211 @@ +//! Signing push requests, and checking those signatures on the receiving end. +//! +//! When a push queue has a secret, every request carries a header +//! +//! ```text +//! Dally-Signature: t=1763550000,v1=5f0e... +//! ``` +//! +//! where `t` is the time of signing in Unix seconds and `v1` is the hex +//! HMAC-SHA256 of `"."` keyed with the secret. Including the +//! timestamp in the signed text lets receivers reject old requests that were +//! captured and replayed. +//! +//! ``` +//! use std::time::Duration; +//! +//! use dally_server::signature; +//! +//! let body = br#"{"to":"ana@example.com"}"#; +//! let header = signature::sign(b"secret", 1_763_550_000, body); +//! assert!(signature::verify(b"secret", &header, body, 1_763_550_010, Duration::from_secs(300)).is_ok()); +//! ``` + +use std::time::Duration; + +use hmac::{KeyInit, Mac}; + +type HmacSha256 = hmac::Hmac; + +/// The name of the header that carries the signature. +pub const HEADER: &str = "Dally-Signature"; + +/// Signs `body` as sent at `timestamp` (Unix seconds) and returns the value of +/// the [`HEADER`] header. +pub fn sign(secret: &[u8], timestamp: i64, body: &[u8]) -> String { + let digest = mac(secret, timestamp, body).finalize().into_bytes(); + format!("t={timestamp},v1={}", hex::encode(digest)) +} + +/// Why a signature was rejected. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub enum SignatureError { + /// The header is not of the form `t=,v1=`. + #[error("malformed signature header")] + Malformed, + + /// The timestamp is further from now than the allowed tolerance. + #[error("signature timestamp is outside the allowed tolerance")] + Expired, + + /// No signature in the header matches the body and secret. + #[error("signature does not match")] + Mismatch, +} + +/// Checks a [`HEADER`] value against the raw request body. +/// +/// `now` is the receiver's current time in Unix seconds. Requests signed more +/// than `tolerance` before or after it are rejected, which limits how long a +/// captured request can be replayed; five minutes is a good default. The +/// comparison runs in constant time. +/// +/// The header may hold several `v1` entries; any one matching is enough. dally +/// sends one, but this leaves room to sign with two secrets while rotating. +pub fn verify( + secret: &[u8], + header: &str, + body: &[u8], + now: i64, + tolerance: Duration, +) -> Result<(), SignatureError> { + let parsed = Header::parse(header)?; + + let tolerance = i64::try_from(tolerance.as_secs()).unwrap_or(i64::MAX); + if now.abs_diff(parsed.timestamp) > tolerance.unsigned_abs() { + return Err(SignatureError::Expired); + } + + let matches = parsed.signatures.iter().any(|signature| { + hex::decode(signature).is_ok_and(|expected| { + mac(secret, parsed.timestamp, body) + .verify_slice(&expected) + .is_ok() + }) + }); + if matches { + Ok(()) + } else { + Err(SignatureError::Mismatch) + } +} + +/// A parsed `t=...,v1=...` header. Unknown keys are ignored so that a future +/// `v2` scheme can be added next to `v1` without breaking receivers. +struct Header<'a> { + timestamp: i64, + signatures: Vec<&'a str>, +} + +impl<'a> Header<'a> { + fn parse(header: &'a str) -> Result { + let mut timestamp = None; + let mut signatures = Vec::new(); + for item in header.split(',') { + let (key, value) = item + .trim() + .split_once('=') + .ok_or(SignatureError::Malformed)?; + match key { + "t" => { + let parsed = value.parse().map_err(|_| SignatureError::Malformed)?; + timestamp = Some(parsed); + } + "v1" => signatures.push(value), + _ => {} + } + } + match timestamp { + Some(timestamp) if !signatures.is_empty() => Ok(Self { + timestamp, + signatures, + }), + _ => Err(SignatureError::Malformed), + } + } +} + +fn mac(secret: &[u8], timestamp: i64, body: &[u8]) -> HmacSha256 { + let Ok(mut mac) = HmacSha256::new_from_slice(secret) else { + unreachable!("HMAC accepts keys of any length"); + }; + mac.update(timestamp.to_string().as_bytes()); + mac.update(b"."); + mac.update(body); + mac +} + +#[cfg(test)] +mod tests { + use super::*; + + const TOLERANCE: Duration = Duration::from_secs(300); + + #[test] + fn known_vector() { + // Computed independently with: + // printf '%s' '1700000000.{"hello":"world"}' \ + // | openssl dgst -sha256 -hmac 'whsec_test' + let header = sign(b"whsec_test", 1_700_000_000, br#"{"hello":"world"}"#); + assert_eq!( + header, + "t=1700000000,v1=f592bbf3951cfc94e560eecfb5d9dd4da6b0fff2e626235f8ab4b54860925d0b" + ); + } + + #[test] + fn round_trip() { + let header = sign(b"secret", 1_000, b"{}"); + assert_eq!(verify(b"secret", &header, b"{}", 1_000, TOLERANCE), Ok(())); + } + + #[test] + fn rejects_tampering() { + let header = sign(b"secret", 1_000, b"{}"); + assert_eq!( + verify(b"secret", &header, b"{ }", 1_000, TOLERANCE), + Err(SignatureError::Mismatch) + ); + assert_eq!( + verify(b"other", &header, b"{}", 1_000, TOLERANCE), + Err(SignatureError::Mismatch) + ); + let moved = header.replace("t=1000", "t=1001"); + assert_eq!( + verify(b"secret", &moved, b"{}", 1_000, TOLERANCE), + Err(SignatureError::Mismatch) + ); + } + + #[test] + fn rejects_old_and_future_timestamps() { + let header = sign(b"secret", 1_000, b"{}"); + assert_eq!(verify(b"secret", &header, b"{}", 1_300, TOLERANCE), Ok(())); + assert_eq!( + verify(b"secret", &header, b"{}", 1_301, TOLERANCE), + Err(SignatureError::Expired) + ); + assert_eq!( + verify(b"secret", &header, b"{}", 699, TOLERANCE), + Err(SignatureError::Expired) + ); + } + + #[test] + fn accepts_any_matching_v1() { + let header = sign(b"new", 1_000, b"{}"); + let rotated = header.replace("v1=", "v1=00ff,v1="); + assert_eq!(verify(b"new", &rotated, b"{}", 1_000, TOLERANCE), Ok(())); + } + + #[test] + fn rejects_malformed_headers() { + for header in ["", "t=1000", "v1=abcd", "t=soon,v1=abcd", "garbage"] { + assert_eq!( + verify(b"secret", header, b"{}", 1_000, TOLERANCE), + Err(SignatureError::Malformed), + "{header:?}" + ); + } + } +} diff --git a/crates/dally-server/tests/auth_metrics.rs b/crates/dally-server/tests/auth_metrics.rs new file mode 100644 index 0000000..69f6ffc --- /dev/null +++ b/crates/dally-server/tests/auth_metrics.rs @@ -0,0 +1,224 @@ +//! API keys and Prometheus metrics, against SQLite. + +use std::sync::Arc; + +use dally_core::storage::sqlite::SqliteStorage; +use dally_core::{ConnectOptions, QueueSettings, Service}; +use dally_server::auth::{AuthConfig, KeyConfig, Role}; +use dally_server::{Config, Server}; +use reqwest::StatusCode; +use serde_json::json; + +const CLIENT_KEY: &str = "client-key-0123456789"; +const ADMIN_KEY: &str = "admin-key-0123456789"; + +/// Serves a server built from `config` on a random port and returns its URL. +async fn serve(config: Config) -> String { + let dir = tempfile::Builder::new() + .prefix("dally-auth-") + .tempdir_in(env!("CARGO_TARGET_TMPDIR")) + .expect("temp dir") + .keep(); + let storage = SqliteStorage::open(dir.join("dally.sqlite"), &ConnectOptions::default()) + .await + .expect("open storage"); + let service = Service::new(Arc::new(storage), QueueSettings::default()); + let router = Server::new(service, config).expect("server").router(); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind"); + let address = listener.local_addr().expect("address"); + tokio::spawn(async move { axum::serve(listener, router).await.expect("serve") }); + format!("http://{address}") +} + +fn with_keys(protect_metrics: bool) -> Config { + let key = |name: &str, role, secret: &str| KeyConfig { + name: name.to_owned(), + role, + key: Some(secret.to_owned()), + key_env: None, + }; + Config { + auth: AuthConfig { + keys: vec![ + key("worker", Role::Client, CLIENT_KEY), + key("ops", Role::Admin, ADMIN_KEY), + ], + protect_metrics, + }, + ..Config::default() + } +} + +async fn status(request: reqwest::RequestBuilder) -> StatusCode { + request.send().await.expect("request").status() +} + +#[tokio::test] +async fn without_keys_everything_is_open() { + let base = serve(Config::default()).await; + let http = reqwest::Client::new(); + + let put = http + .put(format!("{base}/v1/queues/emails")) + .json(&json!({})); + assert_eq!(status(put).await, StatusCode::OK); + assert_eq!( + status(http.get(format!("{base}/metrics"))).await, + StatusCode::OK + ); +} + +#[tokio::test] +async fn keys_and_roles() { + let base = serve(with_keys(false)).await; + let http = reqwest::Client::new(); + let poll = || http.post(format!("{base}/v1/queues/emails/poll")); + let put = || { + http.put(format!("{base}/v1/queues/emails")) + .json(&json!({})) + }; + + let response = poll().send().await.expect("request"); + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + assert_eq!( + response + .headers() + .get("www-authenticate") + .and_then(|v| v.to_str().ok()), + Some("Bearer") + ); + let body: serde_json::Value = response.json().await.expect("json"); + assert_eq!(body["error"]["code"], "unauthorized"); + + assert_eq!( + status(poll().bearer_auth("not-a-key")).await, + StatusCode::UNAUTHORIZED + ); + assert_eq!(status(poll().bearer_auth(CLIENT_KEY)).await, StatusCode::OK); + assert_eq!( + status(put().bearer_auth(CLIENT_KEY)).await, + StatusCode::FORBIDDEN + ); + assert_eq!(status(put().bearer_auth(ADMIN_KEY)).await, StatusCode::OK); + assert_eq!(status(poll().bearer_auth(ADMIN_KEY)).await, StatusCode::OK); + + // Health checks and metrics stay open for probes and scrapers. + assert_eq!( + status(http.get(format!("{base}/healthz"))).await, + StatusCode::OK + ); + assert_eq!( + status(http.get(format!("{base}/metrics"))).await, + StatusCode::OK + ); +} + +#[tokio::test] +async fn metrics_can_require_a_key() { + let base = serve(with_keys(true)).await; + let http = reqwest::Client::new(); + let metrics = || http.get(format!("{base}/metrics")); + + assert_eq!(status(metrics()).await, StatusCode::UNAUTHORIZED); + assert_eq!( + status(metrics().bearer_auth(CLIENT_KEY)).await, + StatusCode::OK + ); +} + +#[tokio::test] +async fn metrics_count_messages_and_requests() { + let base = serve(Config::default()).await; + let http = reqwest::Client::new(); + + for i in 0..3 { + let request = http + .post(format!("{base}/v1/queues/emails/messages")) + .json(&json!({"payload": i, "max_attempts": 1})); + assert_eq!(status(request).await, StatusCode::CREATED); + } + let polled: serde_json::Value = http + .post(format!("{base}/v1/queues/emails/poll")) + .json(&json!({"limit": 2})) + .send() + .await + .expect("poll") + .json() + .await + .expect("json"); + let [first, second] = [&polled["messages"][0], &polled["messages"][1]]; + let ack = http + .post(format!( + "{base}/v1/messages/{}/ack", + first["id"].as_str().expect("id") + )) + .json(&json!({"lease": first["lease"]})); + assert_eq!(status(ack).await, StatusCode::OK); + let nack = http + .post(format!( + "{base}/v1/messages/{}/nack", + second["id"].as_str().expect("id") + )) + .json(&json!({"lease": second["lease"], "error": "boom"})); + assert_eq!(status(nack).await, StatusCode::OK); + + let text = http + .get(format!("{base}/metrics")) + .send() + .await + .expect("metrics") + .text() + .await + .expect("text"); + let has = |line: &str| text.lines().any(|l| l == line); + + assert!( + has(r#"dally_messages_scheduled_total{queue="emails"} 3"#), + "{text}" + ); + assert!( + has(r#"dally_messages_leased_total{queue="emails"} 2"#), + "{text}" + ); + assert!( + has(r#"dally_messages_acked_total{queue="emails"} 1"#), + "{text}" + ); + assert!( + has(r#"dally_messages_nacked_total{queue="emails"} 1"#), + "{text}" + ); + assert!( + has(r#"dally_messages_dead_total{queue="emails"} 1"#), + "{text}" + ); + assert!( + has(r#"dally_queue_messages{queue="emails",status="scheduled"} 1"#), + "{text}" + ); + assert!( + has(r#"dally_queue_messages{queue="emails",status="succeeded"} 1"#), + "{text}" + ); + assert!( + has(r#"dally_queue_messages{queue="emails",status="dead"} 1"#), + "{text}" + ); + assert!( + text.contains(r#"dally_queue_oldest_due_seconds{queue="emails"}"#), + "{text}" + ); + + // Routes are labelled by template, never by the raw path. + assert!( + text.contains(r#"route="/v1/messages/{id}/ack""#), + "expected a templated route label: {text}" + ); + assert!( + !text.contains("/v1/messages/0"), + "raw ids leaked into labels: {text}" + ); +} diff --git a/crates/dally-server/tests/background.rs b/crates/dally-server/tests/background.rs new file mode 100644 index 0000000..31a1229 --- /dev/null +++ b/crates/dally-server/tests/background.rs @@ -0,0 +1,329 @@ +//! Tests for push delivery and cron, against SQLite so they need no external +//! services. + +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Duration; + +use axum::Router; +use axum::body::Bytes; +use axum::extract::State; +use axum::http::{HeaderMap, StatusCode}; +use axum::routing::post; +use dally_core::storage::sqlite::SqliteStorage; +use dally_core::{ + Backoff, ConnectOptions, MessageFilter, PushSettings, QueueName, QueueSettings, + ScheduleRequest, Service, Status, +}; +use dally_server::config::{CronJob, PushConfig, QueueConfig}; +use dally_server::{CancellationToken, Config, Server, signature}; +use serde_json::json; +use tokio::sync::mpsc; + +const SECRET: &str = "test-secret"; + +async fn service() -> Service { + let dir = tempfile::Builder::new() + .prefix("dally-server-") + .tempdir_in(env!("CARGO_TARGET_TMPDIR")) + .expect("temp dir") + .keep(); + let storage = SqliteStorage::open(dir.join("dally.sqlite"), &ConnectOptions::default()) + .await + .expect("open storage"); + Service::new(Arc::new(storage), QueueSettings::default()) +} + +/// A config whose background tasks react within a fraction of a second. +fn fast_config() -> Config { + Config { + push: PushConfig { + refresh_interval: Duration::from_millis(100), + poll_wait: Duration::from_millis(200), + ..PushConfig::default() + }, + ..Config::default() + } +} + +fn push_queue(url: String, concurrency: u32, max_attempts: u32) -> QueueSettings { + QueueSettings { + max_attempts, + backoff: Backoff { + base: Duration::from_millis(50), + cap: Duration::from_millis(50), + }, + push: Some(PushSettings { + url, + secret: Some(SECRET.to_owned()), + timeout: Duration::from_secs(5), + concurrency, + }), + ..QueueSettings::default() + } +} + +/// Serves `app` on a random port and returns its URL. +async fn serve(app: Router) -> String { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind"); + let address = listener.local_addr().expect("address"); + tokio::spawn(async move { axum::serve(listener, app).await.expect("serve") }); + format!("http://{address}/jobs") +} + +/// Waits until `check` holds, or fails after five seconds. +async fn eventually(what: &str, mut check: F) +where + F: FnMut() -> Fut, + Fut: Future, +{ + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + while !check().await { + assert!( + tokio::time::Instant::now() < deadline, + "timed out waiting for {what}" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } +} + +async fn status_of(service: &Service, id: dally_core::MessageId) -> Status { + service.get_message(id).await.expect("get message").status +} + +#[tokio::test] +async fn success_acks_with_payload_headers_and_signature() { + let (sender, mut received) = mpsc::unbounded_channel::<(HeaderMap, Bytes)>(); + let app = Router::new() + .route( + "/jobs", + post( + |State(sender): State>, + headers: HeaderMap, + body: Bytes| async move { + let _ = sender.send((headers, body)); + StatusCode::NO_CONTENT + }, + ), + ) + .with_state(sender); + let url = serve(app).await; + + let service = service().await; + let emails = QueueName::new("emails").expect("valid"); + service + .put_queue(&emails, push_queue(url, 4, 5)) + .await + .expect("put queue"); + let scheduled = service + .schedule( + &emails, + vec![ScheduleRequest::new(json!({"to": "ana@example.com"}))], + ) + .await + .expect("schedule"); + let id = scheduled[0].message.id; + + let stop = CancellationToken::new(); + let tasks = Server::new(service.clone(), fast_config()) + .expect("server") + .start_background_tasks(stop.clone()) + .expect("start"); + + let (headers, body) = tokio::time::timeout(Duration::from_secs(5), received.recv()) + .await + .expect("delivery in time") + .expect("a request"); + assert_eq!( + serde_json::from_slice::(&body).ok(), + Some(json!({"to": "ana@example.com"})) + ); + let header = |name: &str| { + headers + .get(name) + .and_then(|v| v.to_str().ok()) + .unwrap_or_default() + .to_owned() + }; + assert_eq!(header("content-type"), "application/json"); + assert_eq!(header("dally-message-id"), id.to_string()); + assert_eq!(header("dally-queue"), "emails"); + assert_eq!(header("dally-attempt"), "1"); + let now = chrono::Utc::now().timestamp(); + signature::verify( + SECRET.as_bytes(), + &header(signature::HEADER), + &body, + now, + Duration::from_secs(60), + ) + .expect("valid signature"); + + eventually("the ack", || async { + status_of(&service, id).await == Status::Succeeded + }) + .await; + stop.cancel(); + tasks.await.expect("background tasks"); +} + +#[tokio::test] +async fn failures_are_retried_until_dead() { + let calls = Arc::new(AtomicUsize::new(0)); + let app = Router::new() + .route( + "/jobs", + post(|State(calls): State>| async move { + calls.fetch_add(1, Ordering::SeqCst); + (StatusCode::INTERNAL_SERVER_ERROR, "database is down") + }), + ) + .with_state(Arc::clone(&calls)); + let url = serve(app).await; + + let service = service().await; + let emails = QueueName::new("emails").expect("valid"); + service + .put_queue(&emails, push_queue(url, 1, 3)) + .await + .expect("put queue"); + let scheduled = service + .schedule(&emails, vec![ScheduleRequest::new(json!(1))]) + .await + .expect("schedule"); + let id = scheduled[0].message.id; + + let stop = CancellationToken::new(); + let tasks = Server::new(service.clone(), fast_config()) + .expect("server") + .start_background_tasks(stop.clone()) + .expect("start"); + + eventually("the message to die", || async { + status_of(&service, id).await == Status::Dead + }) + .await; + let message = service.get_message(id).await.expect("get"); + assert_eq!(message.attempts, 3); + assert_eq!( + message.last_error.as_deref(), + Some("HTTP 500: database is down") + ); + assert_eq!(calls.load(Ordering::SeqCst), 3); + + stop.cancel(); + tasks.await.expect("background tasks"); +} + +#[tokio::test] +async fn concurrency_is_respected() { + #[derive(Default)] + struct Load { + current: AtomicUsize, + peak: AtomicUsize, + } + let load = Arc::new(Load::default()); + let app = Router::new() + .route( + "/jobs", + post(|State(load): State>| async move { + let now = load.current.fetch_add(1, Ordering::SeqCst) + 1; + load.peak.fetch_max(now, Ordering::SeqCst); + tokio::time::sleep(Duration::from_millis(200)).await; + load.current.fetch_sub(1, Ordering::SeqCst); + StatusCode::OK + }), + ) + .with_state(Arc::clone(&load)); + let url = serve(app).await; + + let service = service().await; + let emails = QueueName::new("emails").expect("valid"); + service + .put_queue(&emails, push_queue(url, 2, 5)) + .await + .expect("put queue"); + let requests = (0..6).map(|i| ScheduleRequest::new(json!(i))).collect(); + service.schedule(&emails, requests).await.expect("schedule"); + + let stop = CancellationToken::new(); + let tasks = Server::new(service.clone(), fast_config()) + .expect("server") + .start_background_tasks(stop.clone()) + .expect("start"); + + eventually("every message to be acked", || async { + service + .get_queue(&emails) + .await + .expect("queue") + .stats + .succeeded + == 6 + }) + .await; + assert_eq!(load.peak.load(Ordering::SeqCst), 2); + + stop.cancel(); + tasks.await.expect("background tasks"); +} + +#[tokio::test] +async fn two_cron_tickers_schedule_each_occurrence_once() { + let service = service().await; + let mut config = fast_config(); + config.queues.insert( + "reports".to_owned(), + QueueConfig { + settings: QueueSettings::default(), + cron: vec![CronJob { + name: "every-second".to_owned(), + schedule: "* * * * * *".to_owned(), + timezone: None, + payload: json!({"kind": "tick"}), + }], + }, + ); + let server = Server::new(service.clone(), config).expect("server"); + server.apply_queues().await.expect("apply queues"); + + let stop = CancellationToken::new(); + let first = server + .start_background_tasks(stop.clone()) + .expect("start first"); + let second = server + .start_background_tasks(stop.clone()) + .expect("start second"); + tokio::time::sleep(Duration::from_millis(2500)).await; + stop.cancel(); + first.await.expect("first"); + second.await.expect("second"); + + let messages = service + .list_messages(MessageFilter { + queue: QueueName::new("reports").ok(), + ..MessageFilter::default() + }) + .await + .expect("list") + .items; + let mut keys: Vec<_> = messages + .iter() + .filter_map(|m| m.idempotency_key.clone()) + .collect(); + assert!( + keys.len() >= 2, + "expected at least two occurrences, got {keys:?}" + ); + assert_eq!(keys.len(), messages.len(), "every cron message has a key"); + keys.sort(); + keys.dedup(); + assert_eq!( + keys.len(), + messages.len(), + "no occurrence was scheduled twice" + ); + assert!(keys.iter().all(|key| key.starts_with("cron:every-second:"))); +} diff --git a/crates/dally-server/tests/http.rs b/crates/dally-server/tests/http.rs new file mode 100644 index 0000000..0654718 --- /dev/null +++ b/crates/dally-server/tests/http.rs @@ -0,0 +1,216 @@ +//! End-to-end tests of the HTTP API against PostgreSQL. They need +//! `DALLY_TEST_POSTGRES_URL`; see `dally-core/tests/postgres.rs`. + +use std::sync::Arc; + +use dally_core::storage::postgres::PostgresStorage; +use dally_core::{ConnectOptions, QueueSettings, Service}; +use reqwest::StatusCode; +use serde_json::{Value, json}; +use sqlx::Connection; +use sqlx::postgres::{PgConnectOptions, PgConnection}; + +/// Serves the API on a random port, backed by a fresh schema. Returns the +/// base URL, or `None` when no test database is configured. +async fn serve() -> Option { + let url = std::env::var("DALLY_TEST_POSTGRES_URL").ok()?; + let options: PgConnectOptions = url.parse().expect("valid DALLY_TEST_POSTGRES_URL"); + + let schema = format!("dally_test_{}", uuid::Uuid::new_v4().simple()); + let mut admin = PgConnection::connect_with(&options).await.expect("connect"); + sqlx::raw_sql(sqlx::AssertSqlSafe(format!("CREATE SCHEMA {schema}"))) + .execute(&mut admin) + .await + .expect("create schema"); + + let options = options.options([("search_path", schema.as_str())]); + let storage = PostgresStorage::connect_with(options, &ConnectOptions::default()) + .await + .expect("connect storage"); + let service = Service::new(Arc::new(storage), QueueSettings::default()); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind"); + let address = listener.local_addr().expect("local addr"); + tokio::spawn(async move { + axum::serve( + listener, + dally_server::Server::new(service, dally_server::Config::default()) + .expect("server") + .router(), + ) + .await + .expect("serve"); + }); + Some(format!("http://{address}")) +} + +macro_rules! serve_or_skip { + () => { + match serve().await { + Some(base) => (base, reqwest::Client::new()), + None => { + eprintln!("skipping: DALLY_TEST_POSTGRES_URL is not set"); + return; + } + } + }; +} + +async fn send(request: reqwest::RequestBuilder) -> (StatusCode, Value) { + let response = request.send().await.expect("request"); + let status = response.status(); + let body = response.json().await.unwrap_or(Value::Null); + (status, body) +} + +#[tokio::test] +async fn schedule_poll_ack() { + let (base, client) = serve_or_skip!(); + + let (status, message) = send( + client + .post(format!("{base}/v1/queues/emails/messages")) + .json(&json!({"payload": {"to": "ana@example.com"}, "idempotency_key": "welcome-42"})), + ) + .await; + assert_eq!(status, StatusCode::CREATED); + assert_eq!(message["status"], "scheduled"); + assert_eq!(message["visibility_timeout"], "30s"); + + let (status, again) = send( + client + .post(format!("{base}/v1/queues/emails/messages")) + .json(&json!({"payload": {}, "idempotency_key": "welcome-42"})), + ) + .await; + assert_eq!( + status, + StatusCode::OK, + "a repeated key returns the existing message" + ); + assert_eq!(again["id"], message["id"]); + + let (status, polled) = send( + client + .post(format!("{base}/v1/queues/emails/poll")) + .json(&json!({"limit": 5, "wait": "1s"})), + ) + .await; + assert_eq!(status, StatusCode::OK); + let leased = &polled["messages"][0]; + assert_eq!(leased["id"], message["id"]); + assert_eq!(leased["payload"]["to"], "ana@example.com"); + + let id = leased["id"].as_str().expect("id"); + let (status, acked) = send( + client + .post(format!("{base}/v1/messages/{id}/ack")) + .json(&json!({"lease": leased["lease"]})), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(acked["status"], "succeeded"); + + let (status, queue) = send(client.get(format!("{base}/v1/queues/emails"))).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(queue["stats"]["succeeded"], 1); +} + +#[tokio::test] +async fn batch_schedule_and_empty_poll_body() { + let (base, client) = serve_or_skip!(); + + let (status, body) = send( + client + .post(format!("{base}/v1/queues/reports/messages")) + .json(&json!([{"payload": 1}, {"payload": 2, "delay": "1h"}])), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["messages"].as_array().map(Vec::len), Some(2)); + assert_eq!(body["messages"][0]["created"], true); + + let (status, polled) = send(client.post(format!("{base}/v1/queues/reports/poll"))).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(polled["messages"].as_array().map(Vec::len), Some(1)); +} + +#[tokio::test] +async fn errors_have_codes() { + let (base, client) = serve_or_skip!(); + + let (status, body) = send( + client + .post(format!("{base}/v1/queues/bad%20name/messages")) + .json(&json!({"payload": 1})), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(body["error"]["code"], "invalid_input"); + + let (status, body) = send( + client + .post(format!("{base}/v1/queues/emails/messages")) + .json(&json!({"payload": 1, "dely": "1m"})), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + let message = body["error"]["message"].as_str().unwrap_or_default(); + assert!( + message.contains("dely"), + "message should name the bad field: {message}" + ); + + let missing = uuid::Uuid::now_v7(); + let (status, body) = send(client.get(format!("{base}/v1/messages/{missing}"))).await; + assert_eq!(status, StatusCode::NOT_FOUND); + assert_eq!(body["error"]["code"], "message_not_found"); + + let (status, body) = send(client.get(format!("{base}/v1/queues/nope"))).await; + assert_eq!(status, StatusCode::NOT_FOUND); + assert_eq!(body["error"]["code"], "queue_not_found"); + + let (_, scheduled) = send( + client + .post(format!("{base}/v1/queues/emails/messages")) + .json(&json!({"payload": 1})), + ) + .await; + let id = scheduled["id"].as_str().expect("id"); + let (status, body) = send( + client + .post(format!("{base}/v1/messages/{id}/ack")) + .json(&json!({"lease": "not-the-lease"})), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!(body["error"]["code"], "lease_mismatch"); +} + +#[tokio::test] +async fn health_endpoints() { + let (base, client) = serve_or_skip!(); + for path in ["healthz", "readyz"] { + let response = client + .get(format!("{base}/{path}")) + .send() + .await + .expect("request"); + assert_eq!(response.status(), StatusCode::OK, "{path}"); + } +} + +#[tokio::test] +async fn json_bodies_need_no_content_type() { + let (base, client) = serve_or_skip!(); + + let response = client + .post(format!("{base}/v1/queues/emails/messages")) + .body(r#"{"payload": {"to": "ana"}}"#) + .send() + .await + .expect("request"); + assert_eq!(response.status(), StatusCode::CREATED); +} diff --git a/crates/dally-server/tests/openapi.rs b/crates/dally-server/tests/openapi.rs new file mode 100644 index 0000000..6644e3f --- /dev/null +++ b/crates/dally-server/tests/openapi.rs @@ -0,0 +1,65 @@ +//! The published OpenAPI spec matches the routes the server actually serves. + +use std::sync::Arc; + +use dally_core::storage::sqlite::SqliteStorage; +use dally_core::{ConnectOptions, QueueSettings, Service}; +use dally_server::{Config, Server}; +use reqwest::{Method, StatusCode}; + +#[tokio::test] +async fn every_documented_route_is_served() { + let storage = SqliteStorage::connect("sqlite::memory:", &ConnectOptions::default()) + .await + .expect("open storage"); + let service = Service::new(Arc::new(storage), QueueSettings::default()); + let router = Server::new(service, Config::default()) + .expect("server") + .router(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind"); + let base = format!("http://{}", listener.local_addr().expect("address")); + tokio::spawn(async move { axum::serve(listener, router).await.expect("serve") }); + + let http = reqwest::Client::new(); + let spec: serde_json::Value = http + .get(format!("{base}/v1/openapi.json")) + .send() + .await + .expect("spec") + .json() + .await + .expect("spec is JSON"); + let paths = spec["paths"].as_object().expect("paths"); + assert!( + paths.len() >= 13, + "expected the whole API, got {} paths", + paths.len() + ); + + for (path, operations) in paths { + let url = format!("{base}{path}") + .replace("{queue}", "emails") + .replace("{id}", "00000000-0000-7000-8000-000000000000"); + for method in operations.as_object().expect("operations").keys() { + let method: Method = method.to_uppercase().parse().expect("HTTP method"); + let response = http + .request(method.clone(), &url) + .send() + .await + .expect("request"); + let status = response.status(); + let body = response.text().await.unwrap_or_default(); + + // A route that exists answers with its own JSON error at worst; + // a missing one gets axum's empty 404 or a 405. + let unrouted = status == StatusCode::METHOD_NOT_ALLOWED + || (status == StatusCode::NOT_FOUND && !body.contains("\"error\"")); + assert!( + !unrouted, + "{method} {path} is documented but not served ({status})" + ); + } + } +} diff --git a/crates/dally-ui/Cargo.toml b/crates/dally-ui/Cargo.toml new file mode 100644 index 0000000..db36712 --- /dev/null +++ b/crates/dally-ui/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "dally-ui" +description = "Web UI for the dally job queue, talking to the server over its HTTP API" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true + +[dependencies] +askama.workspace = true +axum.workspace = true +chrono.workspace = true +dally-client.workspace = true +serde.workspace = true +serde_json.workspace = true +tracing.workspace = true + +[dev-dependencies] +dally-core = { workspace = true, features = ["sqlite"] } +dally-server.workspace = true +reqwest = { workspace = true, features = ["form"] } +tokio = { workspace = true, features = ["full"] } + +[lints] +workspace = true diff --git a/crates/dally-ui/assets/htmx.min.js b/crates/dally-ui/assets/htmx.min.js new file mode 100644 index 0000000..59937d7 --- /dev/null +++ b/crates/dally-ui/assets/htmx.min.js @@ -0,0 +1 @@ +var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=cn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true},parseInterval:null,_:null,version:"2.0.4"};Q.onLoad=j;Q.process=kt;Q.on=ye;Q.off=be;Q.trigger=he;Q.ajax=Rn;Q.find=u;Q.findAll=x;Q.closest=g;Q.remove=z;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=$e;Q.defineExtension=Fn;Q.removeExtension=Bn;Q.logAll=V;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:le,canAccessLocalStorage:B,findThisElement:Se,filterValues:hn,swap:$e,hasAttribute:s,getAttributeValue:te,getClosestAttributeValue:re,getClosestMatch:o,getExpressionVars:En,getHeaders:fn,getInputValues:cn,getInternalData:ie,getSwapSpecification:gn,getTriggerSpecs:st,getTarget:Ee,makeFragment:P,mergeObjects:ce,makeSettleInfo:xn,oobSwap:He,querySelectorExt:ae,settleImmediately:Kt,shouldCancel:ht,triggerEvent:he,triggerErrorEvent:fe,withExtensions:Ft};const r=["get","post","put","delete","patch"];const H=r.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function c(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function ne(){return document}function m(e,t){return e.getRootNode?e.getRootNode({composed:t}):ne()}function o(e,t){while(e&&!t(e)){e=c(e)}return e||null}function i(e,t,n){const r=te(t,n);const o=te(t,"hx-disinherit");var i=te(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function re(t,n){let r=null;o(t,function(e){return!!(r=i(t,ue(e),n))});if(r!=="unset"){return r}}function h(e,t){const n=e instanceof Element&&(e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector);return!!n&&n.call(e,t)}function T(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function q(e){const t=new DOMParser;return t.parseFromString(e,"text/html")}function L(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function A(e){const t=ne().createElement("script");se(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function N(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(N(e)){const t=A(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){O(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/]*)?>[\s\S]*?<\/head>/i,"");const n=T(t);let r;if(n==="html"){r=new DocumentFragment;const i=q(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=q(t);L(r,i.body);r.title=i.title}else{const i=q('");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function oe(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return typeof e==="function"}function D(e){return t(e,"Object")}function ie(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function M(t){const n=[];if(t){for(let e=0;e=0}function le(e){return e.getRootNode({composed:true})===document}function F(e){return e.trim().split(/\s+/)}function ce(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function S(e){try{return JSON.parse(e)}catch(e){O(e);return null}}function B(){const e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function U(t){try{const e=new URL(t);if(e){t=e.pathname+e.search}if(!/^\/$/.test(t)){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function e(e){return vn(ne().body,function(){return eval(e)})}function j(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function V(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function _(){Q.logger=null}function u(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return u(ne(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(ne(),e)}}function E(){return window}function z(e,t){e=y(e);if(t){E().setTimeout(function(){z(e);e=null},t)}else{c(e).removeChild(e)}}function ue(e){return e instanceof Element?e:null}function $(e){return e instanceof HTMLElement?e:null}function J(e){return typeof e==="string"?e:null}function f(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function K(e,t,n){e=ue(y(e));if(!e){return}if(n){E().setTimeout(function(){K(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function G(e,t,n){let r=ue(y(e));if(!r){return}if(n){E().setTimeout(function(){G(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=y(e);e.classList.toggle(t)}function Z(e,t){e=y(e);se(e.parentElement.children,function(e){G(e,t)});K(ue(e),t)}function g(e,t){e=ue(y(e));if(e&&e.closest){return e.closest(t)}else{do{if(e==null||h(e,t)){return e}}while(e=e&&ue(c(e)));return null}}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function ge(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function p(t,r,n){if(r.indexOf("global ")===0){return p(t,r.slice(7),true)}t=y(t);const o=[];{let t=0;let n=0;for(let e=0;e"){t--}}if(n0){const r=ge(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ue(t),ge(r.substr(8)))}else if(r.indexOf("find ")===0){e=u(f(t),ge(r.substr(5)))}else if(r==="next"||r==="nextElementSibling"){e=ue(t).nextElementSibling}else if(r.indexOf("next ")===0){e=pe(t,ge(r.substr(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ue(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,ge(r.substr(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=m(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=f(m(t,!!n));i.push(...M(c.querySelectorAll(e)))}return i}var pe=function(t,e,n){const r=f(m(t,n)).querySelectorAll(e);for(let e=0;e=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ae(e,t){if(typeof e!=="string"){return p(e,t)[0]}else{return p(ne().body,e)[0]}}function y(e,t){if(typeof e==="string"){return u(f(t)||document,e)}else{return e}}function xe(e,t,n,r){if(k(t)){return{target:ne().body,event:J(e),listener:t,options:n}}else{return{target:y(e),event:J(t),listener:n,options:r}}}function ye(t,n,r,o){Vn(function(){const e=xe(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=k(n);return e?n:r}function be(t,n,r){Vn(function(){const e=xe(t,n,r);e.target.removeEventListener(e.event,e.listener)});return k(n)?n:r}const ve=ne().createElement("output");function we(e,t){const n=re(e,t);if(n){if(n==="this"){return[Se(e,t)]}else{const r=p(e,n);if(r.length===0){O('The selector "'+n+'" on '+t+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ue(o(e,function(e){return te(ue(e),t)!=null}))}function Ee(e){const t=re(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ae(e,t)}}else{const n=ie(e);if(n.boosted){return ne().body}else{return e}}}function Ce(t){const n=Q.config.attributesToSettle;for(let e=0;e0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=p(t,n,false);if(r){se(r,function(e){let t;const n=o.cloneNode(true);t=ne().createDocumentFragment();t.appendChild(n);if(!Re(s,e)){t=f(n)}const r={shouldSwap:true,target:e,fragment:t};if(!he(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);_e(s,e,e,t,i);Te()}se(i.elts,function(e){he(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(ne().body,"htmx:oobErrorNoTarget",{content:o})}return e}function Te(){const e=u("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=u("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){se(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=te(e,"id");const n=ne().getElementById(t);if(n!=null){if(e.moveBefore){let e=u("#--htmx-preserve-pantry--");if(e==null){ne().body.insertAdjacentHTML("afterend","
");e=u("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Le(l,e,c){se(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=f(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Ae(e){return function(){G(e,Q.config.addedClass);kt(ue(e));Ne(f(e));he(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=$(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function a(e,t,n,r){Le(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;K(ue(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Ae(o))}}}function Ie(e,t){let n=0;while(n0}function $e(e,t,r,o){if(!o){o={}}e=y(e);const i=o.contextElement?m(o.contextElement,false):ne();const n=document.activeElement;let s={};try{s={elt:n,start:n?n.selectionStart:null,end:n?n.selectionEnd:null}}catch(e){}const l=xn(e);if(r.swapStyle==="textContent"){e.textContent=t}else{let n=P(t);l.title=n.title;if(o.selectOOB){const u=o.selectOOB.split(",");for(let t=0;t0){E().setTimeout(c,r.settleDelay)}else{c()}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=S(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(D(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}he(n,i,e)}}}else{const s=r.split(",");for(let e=0;e0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=vn(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(ne().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function C(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=C(e,Qe).trim();e.shift()}else{t=C(e,v)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{C(o,w);const l=o.length;const c=C(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};C(o,w);u.pollInterval=d(C(o,/[,\[\s]/));C(o,w);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const a={trigger:c};var i=nt(e,o,"event");if(i){a.eventFilter=i}C(o,w);while(o.length>0&&o[0]!==","){const f=o.shift();if(f==="changed"){a.changed=true}else if(f==="once"){a.once=true}else if(f==="consume"){a.consume=true}else if(f==="delay"&&o[0]===":"){o.shift();a.delay=d(C(o,v))}else if(f==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=C(o,v);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}a.from=s}else if(f==="target"&&o[0]===":"){o.shift();a.target=rt(o)}else if(f==="throttle"&&o[0]===":"){o.shift();a.throttle=d(C(o,v))}else if(f==="queue"&&o[0]===":"){o.shift();a.queue=C(o,v)}else if(f==="root"&&o[0]===":"){o.shift();a[f]=rt(o)}else if(f==="threshold"&&o[0]===":"){o.shift();a[f]=C(o,v)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}r.push(a)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=te(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){ie(e).cancelled=true}function ct(e,t,n){const r=ie(e);r.timeout=E().setTimeout(function(){if(le(e)&&r.cancelled!==true){if(!gt(n,e,Mt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function at(e){return g(e,Q.config.disableSelector)}function ft(t,n,e){if(t instanceof HTMLAnchorElement&&ut(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=ne().location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){pt(t,function(e,t){const n=ue(e);if(at(n)){b(n);return}de(r,o,n,t)},n,e,true)})}}function ht(e,t){const n=ue(t);if(!n){return false}if(e.type==="submit"||e.type==="click"){if(n.tagName==="FORM"){return true}if(h(n,'input[type="submit"], button')&&(h(n,"[form]")||g(n,"form")!==null)){return true}if(n instanceof HTMLAnchorElement&&n.href&&(n.getAttribute("href")==="#"||n.getAttribute("href").indexOf("#")!==0)){return true}}return false}function dt(e,t){return ie(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function gt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(ne().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function pt(l,c,e,u,a){const f=ie(l);let t;if(u.from){t=p(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in f)){f.lastValue=new WeakMap}t.forEach(function(e){if(!f.lastValue.has(u)){f.lastValue.set(u,new WeakMap)}f.lastValue.get(u).set(e,e.value)})}se(t,function(i){const s=function(e){if(!le(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(a||ht(e,l)){e.preventDefault()}if(gt(u,l,e)){return}const t=ie(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ue(e.target),u.target)){return}}if(u.once){if(f.triggeredOnce){return}else{f.triggeredOnce=true}}if(u.changed){const n=event.target;const r=n.value;const o=f.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(f.delayed){clearTimeout(f.delayed)}if(f.throttle){return}if(u.throttle>0){if(!f.throttle){he(l,"htmx:trigger");c(l,e);f.throttle=E().setTimeout(function(){f.throttle=null},u.throttle)}}else if(u.delay>0){f.delayed=E().setTimeout(function(){he(l,"htmx:trigger");c(l,e)},u.delay)}else{he(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let xt=null;function yt(){if(!xt){xt=function(){mt=true};window.addEventListener("scroll",xt);window.addEventListener("resize",xt);setInterval(function(){if(mt){mt=false;se(ne().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&X(e)){e.setAttribute("data-hx-revealed","true");const t=ie(e);if(t.initHash){he(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){he(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;he(e,"htmx:trigger");t(e)}};if(r>0){E().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;se(r,function(r){if(s(t,"hx-"+r)){const o=te(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ue(e);if(g(n,Q.config.disableSelector)){b(n);return}de(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){yt();pt(r,n,t,e);bt(ue(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ae(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e0){t.polling=true;ct(ue(r),n,e)}else{pt(r,n,t,e)}}function Et(e){const t=ue(e);if(!t){return false}const n=t.attributes;for(let e=0;e", "+e).join(""));return o}else{return[]}}function Tt(e){const t=g(ue(e.target),"button, input[type='submit']");const n=Lt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Lt(e);if(t){t.lastButtonClicked=null}}function Lt(e){const t=g(ue(e.target),"button, input[type='submit']");if(!t){return}const n=y("#"+ee(t,"form"),t.getRootNode())||g(t,"form");if(!n){return}return ie(n)}function At(e){e.addEventListener("click",Tt);e.addEventListener("focusin",Tt);e.addEventListener("focusout",qt)}function Nt(t,e,n){const r=ie(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){vn(t,function(){if(at(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function It(t){ke(t);for(let e=0;eQ.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(ne().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Vt(t){if(!B()){return null}t=U(t);const n=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){he(ne().body,"htmx:historyCacheMissLoad",i);const e=P(this.response);const t=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;const n=Ut();const r=xn(n);kn(e.title);qe(e);Ve(n,t,r);Te();Kt(r.tasks);Bt=o;he(ne().body,"htmx:historyRestore",{path:o,cacheMiss:true,serverResponse:this.response})}else{fe(ne().body,"htmx:historyCacheMissLoadError",i)}};e.send()}function Wt(e){zt();e=e||location.pathname+location.search;const t=Vt(e);if(t){const n=P(t.content);const r=Ut();const o=xn(r);kn(t.title);qe(n);Ve(r,n,o);Te();Kt(o.tasks);E().setTimeout(function(){window.scrollTo(0,t.scroll)},0);Bt=e;he(ne().body,"htmx:historyRestore",{path:e,item:t})}else{if(Q.config.refreshOnHistoryMiss){window.location.reload(true)}else{Gt(e)}}}function Zt(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function Yt(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function Qt(e,t){se(e.concat(t),function(e){const t=ie(e);t.requestCount=(t.requestCount||1)-1});se(e,function(e){const t=ie(e);if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});se(t,function(e){const t=ie(e);if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function en(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);se(e,e=>r.append(t,e))}}function on(t,n,r,o,i){if(o==null||en(t,o)){return}else{t.push(o)}if(tn(o)){const s=ee(o,"name");let e=o.value;if(o instanceof HTMLSelectElement&&o.multiple){e=M(o.querySelectorAll("option:checked")).map(function(e){return e.value})}if(o instanceof HTMLInputElement&&o.files){e=M(o.files)}nn(s,e,n);if(i){sn(o,r)}}if(o instanceof HTMLFormElement){se(o.elements,function(e){if(t.indexOf(e)>=0){rn(e.name,e.value,n)}else{t.push(e)}if(i){sn(e,r)}});new FormData(o).forEach(function(e,t){if(e instanceof File&&e.name===""){return}nn(t,e,n)})}}function sn(e,t){const n=e;if(n.willValidate){he(n,"htmx:validation:validate");if(!n.checkValidity()){t.push({elt:n,message:n.validationMessage,validity:n.validity});he(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})}}}function ln(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function cn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=ie(e);if(s.lastButtonClicked&&!le(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||te(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){on(n,o,i,g(e,"form"),l)}on(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const a=ee(u,"name");nn(a,u.value,o)}const c=we(e,"hx-include");se(c,function(e){on(n,r,i,ue(e),l);if(!h(e,"form")){se(f(e).querySelectorAll(ot),function(e){on(n,r,i,e,l)})}});ln(r,o);return{errors:i,formData:r,values:An(r)}}function un(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function an(e){e=qn(e);let n="";e.forEach(function(e,t){n=un(n,t,e)});return n}function fn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":te(t,"id"),"HX-Current-URL":ne().location.href};bn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(ie(e).boosted){r["HX-Boosted"]="true"}return r}function hn(n,e){const t=re(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){se(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;se(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function dn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function gn(e,t){const n=t||re(e,"hx-swap");const r={swapStyle:ie(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&ie(e).boosted&&!dn(e)){r.show="top"}if(n){const s=F(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const a=l.slice(5);var o=a.split(":");const f=o.pop();var i=o.length>0?o.join(":"):null;r.show=f;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{O("Unknown modifier in hx-swap: "+l)}}}}return r}function pn(e){return re(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function mn(t,n,r){let o=null;Ft(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(pn(n)){return ln(new FormData,qn(r))}else{return an(r)}}}function xn(e){return{tasks:[],elts:[e]}}function yn(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ue(ae(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ue(ae(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function bn(r,e,o,i){if(i==null){i={}}if(r==null){return i}const s=te(r,e);if(s){let e=s.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=vn(r,function(){return Function("return ("+e+")")()},{})}else{n=S(e)}for(const l in n){if(n.hasOwnProperty(l)){if(i[l]==null){i[l]=n[l]}}}}return bn(ue(c(r)),e,o,i)}function vn(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function wn(e,t){return bn(e,"hx-vars",true,t)}function Sn(e,t){return bn(e,"hx-vals",false,t)}function En(e){return ce(wn(e),Sn(e))}function Cn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function On(t){if(t.responseURL&&typeof URL!=="undefined"){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(ne().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function R(e,t){return t.test(e.getAllResponseHeaders())}function Rn(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return de(t,n,null,null,{targetOverride:y(r)||ve,returnPromise:true})}else{let e=y(r.target);if(r.target&&!e||r.source&&!e&&!y(r.source)){e=ve}return de(t,n,y(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true})}}else{return de(t,n,null,null,{returnPromise:true})}}function Hn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function Tn(e,t,n){let r;let o;if(typeof URL==="function"){o=new URL(t,document.location.href);const i=document.location.origin;r=i===o.origin}else{o=t;r=l(t,document.location.origin)}if(Q.config.selfRequestsOnly){if(!r){return false}}return he(e,"htmx:validateUrl",ce({url:o,sameHost:r},n))}function qn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Ln(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function An(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}else{return e[t]}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Ln(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function de(t,n,r,o,i,D){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=ne().body}const M=i.handler||Dn;const X=i.select||null;if(!le(r)){oe(s);return e}const c=i.targetOverride||ue(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:te(r,"hx-target")});oe(l);return e}let u=ie(r);const a=u.lastButtonClicked;if(a){const L=ee(a,"formaction");if(L!=null){n=L}const A=ee(a,"formmethod");if(A!=null){if(A.toLowerCase()!=="dialog"){t=A}}}const f=re(r,"hx-confirm");if(D===undefined){const K=function(e){return de(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:f};if(he(r,"htmx:confirm",G)===false){oe(s);return e}}let h=r;let d=re(r,"hx-sync");let g=null;let F=false;if(d){const N=d.split(":");const I=N[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ue(ae(r,I))}d=(N[1]||"drop").trim();u=ie(h);if(d==="drop"&&u.xhr&&u.abortable!==true){oe(s);return e}else if(d==="abort"){if(u.xhr){oe(s);return e}else{F=true}}else if(d==="replace"){he(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");g=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){he(h,"htmx:abort")}else{if(g==null){if(o){const P=ie(o);if(P&&P.triggerSpec&&P.triggerSpec.queue){g=P.triggerSpec.queue}}if(g==null){g="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(g==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="all"){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){de(t,n,r,o,i)})}oe(s);return e}}const p=new XMLHttpRequest;u.xhr=p;u.abortable=F;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const B=re(r,"hx-prompt");if(B){var x=prompt(B);if(x===null||!he(r,"htmx:prompt",{prompt:x,target:c})){oe(s);m();return e}}if(f&&!D){if(!confirm(f)){oe(s);m();return e}}let y=fn(r,c,x);if(t!=="get"&&!pn(r)){y["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){y=ce(y,i.headers)}const U=cn(r,t);let b=U.errors;const j=U.formData;if(i.values){ln(j,qn(i.values))}const V=qn(En(r));const v=ln(j,V);let w=hn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=ne().location.href}const S=bn(r,"hx-request");const _=ie(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:_,useUrlParams:E,formData:w,parameters:An(w),unfilteredFormData:v,unfilteredParameters:An(v),headers:y,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!he(r,"htmx:configRequest",C)){oe(s);m();return e}n=C.path;t=C.verb;y=C.headers;w=qn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){he(r,"htmx:validation:halted",C);oe(s);m();return e}const z=n.split("#");const $=z[0];const O=z[1];let R=n;if(E){R=$;const Z=!w.keys().next().done;if(Z){if(R.indexOf("?")<0){R+="?"}else{R+="&"}R+=an(w);if(O){R+="#"+O}}}if(!Tn(r,R,C)){fe(r,"htmx:invalidPath",C);oe(l);return e}p.open(t.toUpperCase(),R,true);p.overrideMimeType("text/html");p.withCredentials=C.withCredentials;p.timeout=C.timeout;if(S.noHeaders){}else{for(const k in y){if(y.hasOwnProperty(k)){const Y=y[k];Cn(p,k,Y)}}}const H={xhr:p,target:c,requestConfig:C,etc:i,boosted:_,select:X,pathInfo:{requestPath:n,finalRequestPath:R,responsePath:null,anchor:O}};p.onload=function(){try{const t=Hn(r);H.pathInfo.responsePath=On(p);M(r,H);if(H.keepIndicators!==true){Qt(T,q)}he(r,"htmx:afterRequest",H);he(r,"htmx:afterOnLoad",H);if(!le(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(le(n)){e=n}}if(e){he(e,"htmx:afterRequest",H);he(e,"htmx:afterOnLoad",H)}}oe(s);m()}catch(e){fe(r,"htmx:onLoadError",ce({error:e},H));throw e}};p.onerror=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendError",H);oe(l);m()};p.onabort=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendAbort",H);oe(l);m()};p.ontimeout=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:timeout",H);oe(l);m()};if(!he(r,"htmx:beforeRequest",H)){oe(s);m();return e}var T=Zt(r);var q=Yt(r);se(["loadstart","loadend","progress","abort"],function(t){se([p,p.upload],function(e){e.addEventListener(t,function(e){he(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});he(r,"htmx:beforeSend",H);const J=E?null:mn(p,r,w);p.send(J);return e}function Nn(e,t){const n=t.xhr;let r=null;let o=null;if(R(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(R(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(R(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=re(e,"hx-push-url");const c=re(e,"hx-replace-url");const u=ie(e).boosted;let a=null;let f=null;if(l){a="push";f=l}else if(c){a="replace";f=c}else if(u){a="push";f=s||i}if(f){if(f==="false"){return{}}if(f==="true"){f=s||i}if(t.pathInfo.anchor&&f.indexOf("#")===-1){f=f+"#"+t.pathInfo.anchor}return{type:a,path:f}}else{return{}}}function In(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Pn(e){for(var t=0;t0){E().setTimeout(e,x.swapDelay)}else{e()}}if(f){fe(o,"htmx:responseError",ce({error:"Response Status Error Code "+s.status+" from "+i.pathInfo.requestPath},i))}}const Mn={};function Xn(){return{init:function(e){return null},getSelectors:function(){return null},onEvent:function(e,t){return true},transformResponse:function(e,t,n){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,n,r){return false},encodeParameters:function(e,t,n){return null}}}function Fn(e,t){if(t.init){t.init(n)}Mn[e]=ce(Xn(),t)}function Bn(e){delete Mn[e]}function Un(e,n,r){if(n==undefined){n=[]}if(e==undefined){return n}if(r==undefined){r=[]}const t=te(e,"hx-ext");if(t){se(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){r.push(e.slice(7));return}if(r.indexOf(e)<0){const t=Mn[e];if(t&&n.indexOf(t)<0){n.push(t)}}})}return Un(ue(c(e)),n,r)}var jn=false;ne().addEventListener("DOMContentLoaded",function(){jn=true});function Vn(e){if(jn||ne().readyState==="complete"){e()}else{ne().addEventListener("DOMContentLoaded",e)}}function _n(){if(Q.config.includeIndicatorStyles!==false){const e=Q.config.inlineStyleNonce?` nonce="${Q.config.inlineStyleNonce}"`:"";ne().head.insertAdjacentHTML("beforeend"," ."+Q.config.indicatorClass+"{opacity:0} ."+Q.config.requestClass+" ."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ."+Q.config.requestClass+"."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ")}}function zn(){const e=ne().querySelector('meta[name="htmx-config"]');if(e){return S(e.content)}else{return null}}function $n(){const e=zn();if(e){Q.config=ce(Q.config,e)}}Vn(function(){$n();_n();let e=ne().body;kt(e);const t=ne().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.target;const n=ie(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){Wt();se(t,function(e){he(e,"htmx:restored",{document:ne(),triggerEvent:he})})}else{if(n){n(e)}}};E().setTimeout(function(){he(e,"htmx:load",{});e=null},0)});return Q}(); \ No newline at end of file diff --git a/crates/dally-ui/assets/style.css b/crates/dally-ui/assets/style.css new file mode 100644 index 0000000..d9abc67 --- /dev/null +++ b/crates/dally-ui/assets/style.css @@ -0,0 +1,109 @@ +:root { + --bg: #fafaf9; + --surface: #ffffff; + --text: #1c1917; + --muted: #78716c; + --border: #e7e5e4; + --accent: #2563eb; + --danger: #b91c1c; + --badge: #f5f5f4; + color-scheme: light dark; +} + +@media (prefers-color-scheme: dark) { + :root { + --bg: #1c1917; + --surface: #292524; + --text: #f5f5f4; + --muted: #a8a29e; + --border: #44403c; + --accent: #60a5fa; + --danger: #f87171; + --badge: #44403c; + } +} + +* { box-sizing: border-box; } + +body { + margin: 0; + background: var(--bg); + color: var(--text); + font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; +} + +header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 12px 24px; + border-bottom: 1px solid var(--border); + background: var(--surface); +} + +main { max-width: 1100px; margin: 0 auto; padding: 24px; } + +a { color: var(--accent); text-decoration: none; } +a:hover { text-decoration: underline; } +.brand { font-weight: 700; font-size: 18px; color: var(--text); } + +h1 { font-size: 24px; margin: 0 0 16px; } +h2 { font-size: 17px; margin: 28px 0 8px; } + +table { + width: 100%; + border-collapse: collapse; + background: var(--surface); + border: 1px solid var(--border); +} +th, td { padding: 8px 12px; text-align: left; border-bottom: 1px solid var(--border); } +th { font-size: 13px; color: var(--muted); font-weight: 600; } +.number { text-align: right; font-variant-numeric: tabular-nums; } + +.fields { display: grid; grid-template-columns: max-content 1fr; gap: 4px 24px; margin: 0 0 24px; } +.fields dt { color: var(--muted); } +.fields dd { margin: 0; } + +.tabs { display: flex; gap: 4px; margin: 0 0 12px; flex-wrap: wrap; } +.tabs a { padding: 6px 12px; border-radius: 6px; color: var(--muted); } +.tabs a.active { background: var(--surface); color: var(--text); border: 1px solid var(--border); } +.count { color: var(--muted); font-size: 13px; } + +.actions { display: flex; gap: 8px; margin: 0 0 20px; } +form { margin: 0; } +button { + font: inherit; + padding: 6px 14px; + border-radius: 6px; + border: 1px solid var(--border); + background: var(--surface); + color: var(--text); + cursor: pointer; +} +button:hover { border-color: var(--accent); } +button.danger { color: var(--danger); } +button.quiet { border: none; background: none; color: var(--muted); } + +.login { display: flex; flex-direction: column; gap: 8px; max-width: 360px; } +.login input { font: inherit; padding: 8px; border-radius: 6px; border: 1px solid var(--border); background: var(--surface); color: var(--text); } + +.badge, .status { display: inline-block; padding: 1px 8px; border-radius: 999px; background: var(--badge); font-size: 13px; font-weight: 500; } +.status.dead, .dead, .error, .error-text { color: var(--danger); } +.error-text { max-width: 360px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.crumbs { margin: 0 0 4px; color: var(--muted); } +.empty { color: var(--muted); } +.mono { font-family: ui-monospace, "SF Mono", Menlo, monospace; font-size: 13px; } + +pre { + background: var(--surface); + border: 1px solid var(--border); + padding: 12px; + overflow-x: auto; + font: 13px/1.5 ui-monospace, "SF Mono", Menlo, monospace; +} + +@media (max-width: 640px) { + main { padding: 16px; } + table { font-size: 14px; } + th, td { padding: 6px 8px; } +} diff --git a/crates/dally-ui/src/lib.rs b/crates/dally-ui/src/lib.rs new file mode 100644 index 0000000..64d88f1 --- /dev/null +++ b/crates/dally-ui/src/lib.rs @@ -0,0 +1,228 @@ +//! A web UI for [dally](https://github.com/platonv/dally). +//! +//! The UI is a client of the server like any other: every page is built from +//! calls to the public HTTP API through `dally-client`, and it never touches +//! storage. It can run inside the server process (`dally server --ui`) or on +//! its own (`dally ui --server URL`). +//! +//! The UI holds no key of its own. When the server has auth on, you log in +//! with your API key, which is kept in an `HttpOnly`, `SameSite=Strict` +//! cookie and sent with each API call, so the UI can do exactly what your key +//! can and nothing more. +//! +//! Pages are rendered on the server with askama. htmx refreshes the live +//! parts, but every page and button also works without JavaScript. + +mod pages; +mod view; + +use std::time::Duration; + +use axum::Router; +use axum::extract::FromRequestParts; +use axum::http::request::Parts; +use axum::http::{HeaderValue, header}; +use axum::response::IntoResponse; +use axum::routing::{get, post}; +use dally_client::Client; + +/// Where the UI finds the server and where it is mounted. +#[derive(Debug, Clone)] +pub struct UiConfig { + /// The server's base URL, such as `http://127.0.0.1:7070`. + pub server: String, + /// The path the UI is mounted under, such as `/ui`, or empty when it is + /// served at the root. Links and cookies are scoped to it. + pub base_path: String, +} + +/// Builds the UI's routes. Mount them at `config.base_path` with +/// [`Router::nest`]; [`mount`] does that, including the trailing-slash +/// redirect. +pub fn router(config: UiConfig) -> Router { + let ui = Ui::new(config); + Router::new() + .route("/", get(pages::queues)) + .route("/partials/queues", get(pages::queues_table)) + .route("/queues/{queue}", get(pages::queue)) + .route("/queues/{queue}/pause", post(pages::pause)) + .route("/queues/{queue}/resume", post(pages::resume)) + .route("/queues/{queue}/retry-dead", post(pages::retry_dead)) + .route("/messages/{id}", get(pages::message)) + .route("/messages/{id}/cancel", post(pages::cancel)) + .route("/messages/{id}/run-now", post(pages::run_now)) + .route("/login", get(pages::login_form).post(pages::login)) + .route("/logout", post(pages::logout)) + .route("/assets/htmx.min.js", get(htmx)) + .route("/assets/style.css", get(stylesheet)) + .with_state(ui) +} + +/// The UI nested at `config.base_path`, ready to merge into another router. +/// `{base}/` redirects to `{base}`, which a nested router alone would 404. +pub fn mount(config: UiConfig) -> Router { + let base = config.base_path.trim_end_matches('/').to_owned(); + if base.is_empty() { + return router(config); + } + let home = base.clone(); + Router::new() + .route( + &format!("{base}/"), + get(move || async move { axum::response::Redirect::permanent(&home) }), + ) + .nest(&base, router(config)) +} + +/// What every handler shares. +#[derive(Clone)] +struct Ui { + server: String, + base: String, + http: dally_client::reqwest::Client, +} + +impl Ui { + fn new(config: UiConfig) -> Self { + let base = config.base_path.trim_end_matches('/').to_owned(); + Self { + server: config.server, + base, + // One connection pool for every visitor; each request only adds + // its own key. + http: dally_client::reqwest::Client::new(), + } + } + + /// A client that calls the API with the visitor's key. + fn client(&self, key: &ApiKey) -> Result { + let mut builder = Client::builder(&self.server) + .http_client(self.http.clone()) + .timeout(Duration::from_secs(10)); + if let Some(key) = &key.0 { + builder = builder.api_key(key); + } + builder.build() + } + + /// A path inside the UI, such as `/queues/emails` under `/ui`. The UI's + /// home is the mount point itself (`/ui`), since a nested router does + /// not answer `/ui/`. + fn link(&self, path: &str) -> String { + match (self.base.as_str(), path) { + ("", path) => path.to_owned(), + (base, "/") => base.to_owned(), + (base, path) => format!("{base}{path}"), + } + } + + fn base(&self) -> Base<'_> { + Base(&self.base) + } + + fn cookie_path(&self) -> &str { + if self.base.is_empty() { + "/" + } else { + &self.base + } + } +} + +/// The mount point, as templates use it: `{{ base }}/queues/...` for links +/// and `{{ base.home() }}` for the UI's front page. +#[derive(Clone, Copy)] +struct Base<'a>(&'a str); + +impl Base<'_> { + fn home(&self) -> &str { + if self.0.is_empty() { "/" } else { self.0 } + } +} + +impl std::fmt::Display for Base<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.0) + } +} + +const KEY_COOKIE: &str = "dally_key"; + +/// The visitor's API key, from the login cookie. +struct ApiKey(Option); + +impl FromRequestParts for ApiKey { + type Rejection = std::convert::Infallible; + + async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result { + let key = parts + .headers + .get_all(header::COOKIE) + .iter() + .filter_map(|value| value.to_str().ok()) + .flat_map(|cookies| cookies.split(';')) + .find_map(|cookie| cookie.trim().strip_prefix(KEY_COOKIE)?.strip_prefix('=')) + .and_then(from_hex); + Ok(ApiKey(key)) + } +} + +/// The key is hex-encoded in the cookie, so any characters survive. +fn to_hex(text: &str) -> String { + text.bytes().map(|byte| format!("{byte:02x}")).collect() +} + +fn from_hex(hex: &str) -> Option { + if !hex.len().is_multiple_of(2) { + return None; + } + let bytes = (0..hex.len()) + .step_by(2) + .map(|i| u8::from_str_radix(hex.get(i..i + 2)?, 16).ok()) + .collect::>>()?; + String::from_utf8(bytes).ok() +} + +fn key_cookie(ui: &Ui, key: Option<&str>) -> HeaderValue { + let (value, max_age) = match key { + Some(key) => (to_hex(key), ""), + None => (String::new(), "; Max-Age=0"), + }; + let cookie = format!( + "{KEY_COOKIE}={value}; Path={}; HttpOnly; SameSite=Strict{max_age}", + ui.cookie_path() + ); + HeaderValue::from_str(&cookie).unwrap_or_else(|_| HeaderValue::from_static("")) +} + +async fn htmx() -> impl IntoResponse { + asset("text/javascript", include_str!("../assets/htmx.min.js")) +} + +async fn stylesheet() -> impl IntoResponse { + asset("text/css", include_str!("../assets/style.css")) +} + +fn asset(content_type: &'static str, body: &'static str) -> impl IntoResponse { + ( + [ + (header::CONTENT_TYPE, content_type), + (header::CACHE_CONTROL, "public, max-age=3600"), + ], + body, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keys_round_trip_through_hex() { + for key in ["admin-key-0123456789", "with spaces; and=signs", "ключ"] { + assert_eq!(from_hex(&to_hex(key)).as_deref(), Some(key)); + } + assert_eq!(from_hex("abc"), None); + assert_eq!(from_hex("zz"), None); + } +} diff --git a/crates/dally-ui/src/pages.rs b/crates/dally-ui/src/pages.rs new file mode 100644 index 0000000..528351b --- /dev/null +++ b/crates/dally-ui/src/pages.rs @@ -0,0 +1,464 @@ +//! The pages and the form actions behind their buttons. + +use askama::Template; +use axum::Form; +use axum::extract::{Path, Query, State}; +use axum::http::{StatusCode, header}; +use axum::response::{Html, IntoResponse, Redirect, Response}; +use chrono::Utc; +use dally_client::{MessageFilter, MessageId, QueueName, RunAt, Status}; +use serde::Deserialize; + +use crate::view::{self, MessageRow, QueueRow}; +use crate::{ApiKey, Base, Ui, key_cookie}; + +/// How many messages a queue page lists at once. +const PAGE_SIZE: u32 = 50; + +/// Why a page could not be shown. +enum Failure { + Api(dally_client::Error), + Render(askama::Error), + BadInput(String), +} + +impl From for Failure { + fn from(err: dally_client::Error) -> Self { + Failure::Api(err) + } +} + +impl From for Failure { + fn from(err: askama::Error) -> Self { + Failure::Render(err) + } +} + +type PageResult = Result; + +impl Ui { + /// Runs a page handler and turns its failure into a page: the login form + /// for a missing or rejected key, an error page for everything else. + async fn respond(&self, key: &ApiKey, page: impl Future) -> Response { + let failure = match page.await { + Ok(response) => return response, + Err(failure) => failure, + }; + + let (status, title, detail) = match failure { + Failure::Api(err) if err.status() == Some(StatusCode::UNAUTHORIZED) => { + return Redirect::to(&self.link("/login")).into_response(); + } + Failure::Api(err) if err.status() == Some(StatusCode::FORBIDDEN) => ( + StatusCode::FORBIDDEN, + "Not allowed", + "Your API key cannot do this. Log in with an admin key.".to_owned(), + ), + Failure::Api(err) if err.is_not_found() => { + (StatusCode::NOT_FOUND, "Not found", err.to_string()) + } + Failure::Api(err) if err.status().is_none() => ( + StatusCode::BAD_GATEWAY, + "Cannot reach the server", + format!("The UI could not reach dally at {}: {err}", self.server), + ), + Failure::Api(err) => ( + StatusCode::BAD_GATEWAY, + "Something went wrong", + err.to_string(), + ), + Failure::BadInput(detail) => (StatusCode::BAD_REQUEST, "Bad request", detail), + Failure::Render(err) => { + tracing::error!(error = %err, "cannot render page"); + ( + StatusCode::INTERNAL_SERVER_ERROR, + "Something went wrong", + "The page could not be rendered.".to_owned(), + ) + } + }; + + let page = ErrorPage { + base: self.base(), + signed_in: key.0.is_some(), + title, + detail, + }; + match page.render() { + Ok(html) => (status, Html(html)).into_response(), + Err(_) => (status, format!("dally: {title}")).into_response(), + } + } +} + +fn render(page: impl Template) -> PageResult { + Ok(Html(page.render()?).into_response()) +} + +fn queue_name(name: &str) -> Result { + QueueName::new(name).map_err(|err| Failure::BadInput(err.to_string())) +} + +#[derive(Template)] +#[template(path = "error.html")] +struct ErrorPage<'a> { + base: Base<'a>, + signed_in: bool, + title: &'a str, + detail: String, +} + +#[derive(Template)] +#[template(path = "queues.html")] +struct QueuesPage<'a> { + base: Base<'a>, + signed_in: bool, + rows: Vec, +} + +#[derive(Template)] +#[template(path = "queues_table.html")] +struct QueuesTable<'a> { + base: Base<'a>, + rows: Vec, +} + +/// `GET /`: every queue with its counts. +pub async fn queues(State(ui): State, key: ApiKey) -> Response { + ui.respond(&key, async { + let queues = ui.client(&key)?.list_queues().await?; + render(QueuesPage { + base: ui.base(), + signed_in: key.0.is_some(), + rows: queues.iter().map(QueueRow::from).collect(), + }) + }) + .await +} + +/// `GET /partials/queues`: the queue table alone, for htmx to refresh. +pub async fn queues_table(State(ui): State, key: ApiKey) -> Response { + ui.respond(&key, async { + let queues = ui.client(&key)?.list_queues().await?; + render(QueuesTable { + base: ui.base(), + rows: queues.iter().map(QueueRow::from).collect(), + }) + }) + .await +} + +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +pub struct QueueParams { + status: Option, + before: Option, +} + +/// A status filter tab on the queue page. +struct Tab { + label: &'static str, + count: u64, + active: bool, +} + +#[derive(Template)] +#[template(path = "queue.html")] +struct QueuePage<'a> { + base: Base<'a>, + signed_in: bool, + name: String, + paused: bool, + settings: Vec<(&'static str, String)>, + tabs: Vec, + status: &'static str, + dead: u64, + rows: Vec, + next: Option, +} + +/// `GET /queues/{queue}?status=&before=`: settings, counts and messages. +pub async fn queue( + State(ui): State, + key: ApiKey, + Path(name): Path, + Query(params): Query, +) -> Response { + ui.respond(&key, async { + let queue = queue_name(&name)?; + let client = ui.client(&key)?; + let summary = client.get_queue(queue.as_str()).await?; + let status = params.status.unwrap_or(Status::Scheduled); + let page = client + .list_messages(&MessageFilter { + queue: Some(queue.clone()), + status: Some(status), + before: params.before, + limit: PAGE_SIZE, + }) + .await?; + + let settings = &summary.queue.settings; + let stats = summary.stats; + let duration = |d| format_duration(d); + let now = Utc::now(); + render(QueuePage { + base: ui.base(), + signed_in: key.0.is_some(), + name: queue.to_string(), + paused: settings.paused, + settings: vec![ + ("Visibility timeout", duration(settings.visibility_timeout)), + ("Max attempts", settings.max_attempts.to_string()), + ( + "Backoff", + format!( + "{} doubling up to {}", + duration(settings.backoff.base), + duration(settings.backoff.cap) + ), + ), + ("Retention", duration(settings.retention)), + ( + "Push", + settings + .push + .as_ref() + .map_or_else(|| "off, workers poll".to_owned(), |push| push.url.clone()), + ), + ], + tabs: view::STATUSES + .iter() + .map(|&tab| Tab { + label: tab.as_str(), + count: match tab { + Status::Scheduled => stats.scheduled, + Status::Running => stats.running, + Status::Succeeded => stats.succeeded, + Status::Cancelled => stats.cancelled, + Status::Dead => stats.dead, + }, + active: tab == status, + }) + .collect(), + status: status.as_str(), + dead: stats.dead, + rows: page + .items + .iter() + .map(|message| MessageRow::new(message, now)) + .collect(), + next: page.next.map(|id| id.to_string()), + }) + }) + .await +} + +/// Durations as the server's config files write them: `30s`, `5m`, `7days`. +fn format_duration(duration: std::time::Duration) -> String { + let seconds = duration.as_secs(); + match seconds { + 0 => format!("{}ms", duration.as_millis()), + s if s % 86_400 == 0 => format!("{}d", s / 86_400), + s if s % 3_600 == 0 => format!("{}h", s / 3_600), + s if s % 60 == 0 => format!("{}m", s / 60), + s => format!("{s}s"), + } +} + +/// `POST /queues/{queue}/pause`. +pub async fn pause(State(ui): State, key: ApiKey, Path(name): Path) -> Response { + ui.respond(&key, async { + ui.client(&key)?.pause(queue_name(&name)?.as_str()).await?; + Ok(Redirect::to(&ui.link(&format!("/queues/{name}"))).into_response()) + }) + .await +} + +/// `POST /queues/{queue}/resume`. +pub async fn resume(State(ui): State, key: ApiKey, Path(name): Path) -> Response { + ui.respond(&key, async { + ui.client(&key)?.resume(queue_name(&name)?.as_str()).await?; + Ok(Redirect::to(&ui.link(&format!("/queues/{name}"))).into_response()) + }) + .await +} + +/// `POST /queues/{queue}/retry-dead`: retries every dead message. +pub async fn retry_dead(State(ui): State, key: ApiKey, Path(name): Path) -> Response { + ui.respond(&key, async { + ui.client(&key)? + .retry_dead(queue_name(&name)?.as_str(), None) + .await?; + Ok(Redirect::to(&ui.link(&format!("/queues/{name}?status=scheduled"))).into_response()) + }) + .await +} + +#[derive(Template)] +#[template(path = "message.html")] +struct MessagePage<'a> { + base: Base<'a>, + signed_in: bool, + id: String, + queue: String, + status: &'static str, + scheduled: bool, + fields: Vec<(&'static str, String)>, + last_error: Option, + payload: String, +} + +/// `GET /messages/{id}`. +pub async fn message(State(ui): State, key: ApiKey, Path(id): Path) -> Response { + ui.respond(&key, async { + let id: MessageId = id + .parse() + .map_err(|_| Failure::BadInput(format!("{id:?} is not a message id")))?; + let message = ui.client(&key)?.get_message(id).await?; + let now = Utc::now(); + let optional = |value: Option| value.unwrap_or_else(|| "-".to_owned()); + + render(MessagePage { + base: ui.base(), + signed_in: key.0.is_some(), + id: message.id.to_string(), + queue: message.queue.to_string(), + status: message.status.as_str(), + scheduled: message.status == Status::Scheduled, + fields: vec![ + ( + "Attempts", + format!("{} of {}", message.attempts, message.max_attempts), + ), + ("Priority", message.priority.to_string()), + ( + "Run at", + format!( + "{} ({})", + view::timestamp(message.run_at), + view::relative(message.run_at, now) + ), + ), + ("Idempotency key", optional(message.idempotency_key.clone())), + ("Created", view::timestamp(message.created_at)), + ( + "Finished", + optional(message.finished_at.map(view::timestamp)), + ), + ( + "Lease expires", + optional(message.lease_expires_at.map(view::timestamp)), + ), + ], + last_error: message.last_error.clone(), + payload: serde_json::to_string_pretty(&message.payload).unwrap_or_default(), + }) + }) + .await +} + +/// `POST /messages/{id}/cancel`. +pub async fn cancel(State(ui): State, key: ApiKey, Path(id): Path) -> Response { + ui.respond(&key, async { + let id: MessageId = id + .parse() + .map_err(|_| Failure::BadInput(format!("{id:?} is not a message id")))?; + ui.client(&key)?.cancel(id).await?; + Ok(Redirect::to(&ui.link(&format!("/messages/{id}"))).into_response()) + }) + .await +} + +/// `POST /messages/{id}/run-now`: reschedules a waiting message to now. +pub async fn run_now(State(ui): State, key: ApiKey, Path(id): Path) -> Response { + ui.respond(&key, async { + let id: MessageId = id + .parse() + .map_err(|_| Failure::BadInput(format!("{id:?} is not a message id")))?; + ui.client(&key)?.reschedule(id, RunAt::Now).await?; + Ok(Redirect::to(&ui.link(&format!("/messages/{id}"))).into_response()) + }) + .await +} + +#[derive(Template)] +#[template(path = "login.html")] +struct LoginPage<'a> { + base: Base<'a>, + signed_in: bool, + error: Option<&'a str>, +} + +/// `GET /login`. +pub async fn login_form(State(ui): State, key: ApiKey) -> Response { + ui.respond(&key, async { + render(LoginPage { + base: ui.base(), + signed_in: false, + error: None, + }) + }) + .await +} + +#[derive(Debug, Deserialize)] +pub struct LoginForm { + key: String, +} + +/// `POST /login`: checks the key against the server, then keeps it in a +/// cookie. +pub async fn login(State(ui): State, Form(form): Form) -> Response { + let key = ApiKey(Some(form.key.trim().to_owned())); + let checked = match ui.client(&key) { + Ok(client) => client.list_queues().await.map(|_| ()), + Err(err) => Err(err), + }; + + match checked { + Ok(()) => ( + [(header::SET_COOKIE, key_cookie(&ui, key.0.as_deref()))], + Redirect::to(&ui.link("/")), + ) + .into_response(), + Err(err) if err.status() == Some(StatusCode::UNAUTHORIZED) => { + let page = LoginPage { + base: ui.base(), + signed_in: false, + error: Some("The server did not accept that key."), + }; + ui.respond(&ApiKey(None), async { render(page) }).await + } + Err(err) => { + ui.respond(&ApiKey(None), async { Err(Failure::Api(err)) }) + .await + } + } +} + +/// `POST /logout`. +pub async fn logout(State(ui): State) -> Response { + ( + [(header::SET_COOKIE, key_cookie(&ui, None))], + Redirect::to(&ui.link("/login")), + ) + .into_response() +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use super::*; + + #[test] + fn durations_use_the_largest_whole_unit() { + assert_eq!(format_duration(Duration::from_secs(30)), "30s"); + assert_eq!(format_duration(Duration::from_secs(300)), "5m"); + assert_eq!(format_duration(Duration::from_secs(3_600)), "1h"); + assert_eq!(format_duration(Duration::from_secs(7 * 86_400)), "7d"); + assert_eq!(format_duration(Duration::from_secs(90)), "90s"); + assert_eq!(format_duration(Duration::from_millis(250)), "250ms"); + } +} diff --git a/crates/dally-ui/src/view.rs b/crates/dally-ui/src/view.rs new file mode 100644 index 0000000..11b4963 --- /dev/null +++ b/crates/dally-ui/src/view.rs @@ -0,0 +1,91 @@ +//! Turning API types into what the templates show. + +use chrono::{DateTime, Utc}; +use dally_client::{Message, QueueSummary, Status}; + +/// One row of the queue table. +pub struct QueueRow { + pub name: String, + pub scheduled: u64, + pub running: u64, + pub succeeded: u64, + pub dead: u64, + pub paused: bool, +} + +impl From<&QueueSummary> for QueueRow { + fn from(summary: &QueueSummary) -> Self { + Self { + name: summary.queue.name.to_string(), + scheduled: summary.stats.scheduled, + running: summary.stats.running, + succeeded: summary.stats.succeeded, + dead: summary.stats.dead, + paused: summary.queue.settings.paused, + } + } +} + +/// One row of a message table. +pub struct MessageRow { + pub id: String, + pub attempts: String, + pub run_at: String, + pub when: String, + pub last_error: String, +} + +impl MessageRow { + pub fn new(message: &Message, now: DateTime) -> Self { + Self { + id: message.id.to_string(), + attempts: format!("{}/{}", message.attempts, message.max_attempts), + run_at: timestamp(message.run_at), + when: relative(message.run_at, now), + last_error: message.last_error.clone().unwrap_or_default(), + } + } +} + +/// A timestamp to the second, in UTC. +pub fn timestamp(at: DateTime) -> String { + at.format("%Y-%m-%d %H:%M:%S UTC").to_string() +} + +/// "in 5m" or "3h ago", rounded to the largest unit. +pub fn relative(at: DateTime, now: DateTime) -> String { + let seconds = (at - now).num_seconds(); + let magnitude = seconds.unsigned_abs(); + let amount = match magnitude { + 0..=59 => format!("{magnitude}s"), + 60..=3_599 => format!("{}m", magnitude / 60), + 3_600..=86_399 => format!("{}h", magnitude / 3_600), + _ => format!("{}d", magnitude / 86_400), + }; + if magnitude < 1 { + "now".to_owned() + } else if seconds > 0 { + format!("in {amount}") + } else { + format!("{amount} ago") + } +} + +/// The status filter tabs on a queue page, in lifecycle order. +pub const STATUSES: [Status; 5] = Status::ALL; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn relative_times() { + let now = Utc::now(); + let at = |seconds: i64| now + chrono::Duration::seconds(seconds); + assert_eq!(relative(at(0), now), "now"); + assert_eq!(relative(at(30), now), "in 30s"); + assert_eq!(relative(at(-90), now), "1m ago"); + assert_eq!(relative(at(7_200), now), "in 2h"); + assert_eq!(relative(at(-3 * 86_400), now), "3d ago"); + } +} diff --git a/crates/dally-ui/templates/base.html b/crates/dally-ui/templates/base.html new file mode 100644 index 0000000..68d9f29 --- /dev/null +++ b/crates/dally-ui/templates/base.html @@ -0,0 +1,21 @@ + + + + + + {% block title %}dally{% endblock %} + + + + +
+ dally + {% if signed_in %} +
+ {% endif %} +
+
+ {% block content %}{% endblock %} +
+ + diff --git a/crates/dally-ui/templates/error.html b/crates/dally-ui/templates/error.html new file mode 100644 index 0000000..1963bf9 --- /dev/null +++ b/crates/dally-ui/templates/error.html @@ -0,0 +1,7 @@ +{% extends "base.html" %} +{% block title %}{{ title }} · dally{% endblock %} +{% block content %} +

{{ title }}

+

{{ detail }}

+

Back to queues

+{% endblock %} diff --git a/crates/dally-ui/templates/login.html b/crates/dally-ui/templates/login.html new file mode 100644 index 0000000..d04b6a3 --- /dev/null +++ b/crates/dally-ui/templates/login.html @@ -0,0 +1,12 @@ +{% extends "base.html" %} +{% block title %}Log in · dally{% endblock %} +{% block content %} +

Log in

+

This server needs an API key. A client key can look around; changing queues needs an admin key.

+{% if let Some(error) = error %}

{{ error }}

{% endif %} + +{% endblock %} diff --git a/crates/dally-ui/templates/message.html b/crates/dally-ui/templates/message.html new file mode 100644 index 0000000..3db0071 --- /dev/null +++ b/crates/dally-ui/templates/message.html @@ -0,0 +1,28 @@ +{% extends "base.html" %} +{% block title %}Message {{ id }} · dally{% endblock %} +{% block content %} +

Queues / {{ queue }} /

+

{{ id }}

+

{{ status }}

+ +{% if scheduled %} +
+
+
+
+{% endif %} + +
+ {% for (label, value) in fields %} +
{{ label }}
{{ value }}
+ {% endfor %} +
+ +{% if let Some(error) = last_error %} +

Last error

+
{{ error }}
+{% endif %} + +

Payload

+
{{ payload }}
+{% endblock %} diff --git a/crates/dally-ui/templates/queue.html b/crates/dally-ui/templates/queue.html new file mode 100644 index 0000000..ce8808b --- /dev/null +++ b/crates/dally-ui/templates/queue.html @@ -0,0 +1,52 @@ +{% extends "base.html" %} +{% block title %}{{ name }} · dally{% endblock %} +{% block content %} +

Queues /

+

{{ name }} {% if paused %}paused{% endif %}

+ +
+ {% if paused %} +
+ {% else %} +
+ {% endif %} + {% if dead > 0 %} +
+ {% endif %} +
+ +
+ {% for (label, value) in settings %} +
{{ label }}
{{ value }}
+ {% endfor %} +
+ + + +{% if rows.is_empty() %} +

No {{ status }} messages.

+{% else %} + + + + + + {% for row in rows %} + + + + + + + {% endfor %} + +
MessageAttemptsRun atLast error
{{ row.id }}{{ row.attempts }}{{ row.when }}{{ row.last_error }}
+{% if let Some(next) = next %} +

Older messages

+{% endif %} +{% endif %} +{% endblock %} diff --git a/crates/dally-ui/templates/queues.html b/crates/dally-ui/templates/queues.html new file mode 100644 index 0000000..922a978 --- /dev/null +++ b/crates/dally-ui/templates/queues.html @@ -0,0 +1,6 @@ +{% extends "base.html" %} +{% block title %}Queues · dally{% endblock %} +{% block content %} +

Queues

+{% include "queues_table.html" %} +{% endblock %} diff --git a/crates/dally-ui/templates/queues_table.html b/crates/dally-ui/templates/queues_table.html new file mode 100644 index 0000000..d337ba9 --- /dev/null +++ b/crates/dally-ui/templates/queues_table.html @@ -0,0 +1,23 @@ +
+{% if rows.is_empty() %} +

No queues yet. Schedule a message and its queue appears here.

+{% else %} + + + + + + {% for row in rows %} + + + + + + + + + {% endfor %} + +
QueueScheduledRunningSucceededDead
{{ row.name }}{{ row.scheduled }}{{ row.running }}{{ row.succeeded }}{% if row.dead > 0 %}{{ row.dead }}{% else %}0{% endif %}{% if row.paused %}paused{% endif %}
+{% endif %} +
diff --git a/crates/dally-ui/tests/ui.rs b/crates/dally-ui/tests/ui.rs new file mode 100644 index 0000000..3688518 --- /dev/null +++ b/crates/dally-ui/tests/ui.rs @@ -0,0 +1,223 @@ +//! The UI against a real server on SQLite, mounted at `/ui` like +//! `dally server --ui` does. + +use std::sync::Arc; + +use dally_core::storage::sqlite::SqliteStorage; +use dally_core::{ConnectOptions, QueueSettings, Service}; +use dally_server::auth::{AuthConfig, KeyConfig, Role}; +use dally_server::{Config, Server}; +use dally_ui::UiConfig; +use reqwest::StatusCode; +use reqwest::redirect::Policy; +use serde_json::json; + +const CLIENT_KEY: &str = "client-key-0123456789"; +const ADMIN_KEY: &str = "admin-key-0123456789"; + +/// Serves the API and the UI on one random port, and returns its URL. +async fn serve(config: Config) -> String { + let storage = SqliteStorage::connect("sqlite::memory:", &ConnectOptions::default()) + .await + .expect("open storage"); + let service = Service::new(Arc::new(storage), QueueSettings::default()); + let api = Server::new(service, config).expect("server").router(); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind"); + let base = format!("http://{}", listener.local_addr().expect("address")); + let ui = dally_ui::mount(UiConfig { + server: base.clone(), + base_path: "/ui".to_owned(), + }); + tokio::spawn(async move { axum::serve(listener, api.merge(ui)).await.expect("serve") }); + base +} + +fn browser() -> reqwest::Client { + reqwest::Client::builder() + .redirect(Policy::none()) + .build() + .expect("client") +} + +async fn page(http: &reqwest::Client, url: String) -> (StatusCode, String) { + let response = http.get(url).send().await.expect("request"); + (response.status(), response.text().await.expect("body")) +} + +async fn json(request: reqwest::RequestBuilder) -> serde_json::Value { + request + .send() + .await + .expect("request") + .json() + .await + .expect("json") +} + +fn with_keys() -> Config { + let key = |name: &str, role, secret: &str| KeyConfig { + name: name.to_owned(), + role, + key: Some(secret.to_owned()), + key_env: None, + }; + Config { + auth: AuthConfig { + keys: vec![ + key("worker", Role::Client, CLIENT_KEY), + key("ops", Role::Admin, ADMIN_KEY), + ], + protect_metrics: false, + }, + ..Config::default() + } +} + +#[tokio::test] +async fn pages_show_queues_and_messages() { + let base = serve(Config::default()).await; + let http = browser(); + + let scheduled = json( + http.post(format!("{base}/v1/queues/emails/messages")) + .json(&json!({"payload": {"to": "ana"}, "max_attempts": 1})), + ) + .await; + let id = scheduled["id"].as_str().expect("id").to_owned(); + let polled = json(http.post(format!("{base}/v1/queues/emails/poll"))).await; + json( + http.post(format!("{base}/v1/messages/{id}/nack")) + .json(&json!({"lease": polled["messages"][0]["lease"], "error": "smtp timeout"})), + ) + .await; + + let (status, html) = page(&http, format!("{base}/ui")).await; + assert_eq!(status, StatusCode::OK); + assert!( + html.contains(r#"emails"#), + "{html}" + ); + + let slash = http + .get(format!("{base}/ui/")) + .send() + .await + .expect("request"); + assert_eq!(slash.status(), StatusCode::PERMANENT_REDIRECT); + + let (status, html) = page(&http, format!("{base}/ui/queues/emails?status=dead")).await; + assert_eq!(status, StatusCode::OK); + assert!(html.contains("smtp timeout"), "{html}"); + assert!(html.contains("Retry 1 dead"), "{html}"); + + let (status, html) = page(&http, format!("{base}/ui/messages/{id}")).await; + assert_eq!(status, StatusCode::OK); + assert!( + html.contains(r#"dead"#), + "{html}" + ); + + let retried = http + .post(format!("{base}/ui/queues/emails/retry-dead")) + .send() + .await + .expect("retry"); + assert_eq!(retried.status(), StatusCode::SEE_OTHER); + let queue = json(http.get(format!("{base}/v1/queues/emails"))).await; + assert_eq!(queue["stats"]["scheduled"], 1); + + let missing = format!("{base}/ui/messages/00000000-0000-7000-8000-000000000000"); + let (status, html) = page(&http, missing).await; + assert_eq!(status, StatusCode::NOT_FOUND); + assert!(html.contains("

Not found

"), "{html}"); +} + +#[tokio::test] +async fn login_uses_the_visitors_own_key() { + let base = serve(with_keys()).await; + let http = browser(); + + let anonymous = http + .get(format!("{base}/ui")) + .send() + .await + .expect("request"); + assert_eq!(anonymous.status(), StatusCode::SEE_OTHER); + assert_eq!(anonymous.headers()["location"], "/ui/login"); + + let rejected = http + .post(format!("{base}/ui/login")) + .form(&[("key", "not-a-key")]) + .send() + .await + .expect("login"); + let body = rejected.text().await.expect("body"); + assert!(body.contains("did not accept that key"), "{body}"); + + let login = async |key: &str| { + let response = http + .post(format!("{base}/ui/login")) + .form(&[("key", key)]) + .send() + .await + .expect("login"); + assert_eq!(response.status(), StatusCode::SEE_OTHER); + let cookie = response.headers()["set-cookie"] + .to_str() + .expect("cookie") + .to_owned(); + assert!(cookie.contains("HttpOnly"), "{cookie}"); + assert!(cookie.contains("SameSite=Strict"), "{cookie}"); + assert!(cookie.contains("Path=/ui"), "{cookie}"); + cookie.split(';').next().expect("name=value").to_owned() + }; + let client_cookie = login(CLIENT_KEY).await; + let admin_cookie = login(ADMIN_KEY).await; + + json( + http.put(format!("{base}/v1/queues/emails")) + .bearer_auth(ADMIN_KEY) + .json(&json!({})), + ) + .await; + + let dashboard = http + .get(format!("{base}/ui")) + .header("cookie", &client_cookie) + .send() + .await + .expect("dashboard"); + assert_eq!(dashboard.status(), StatusCode::OK); + + let pause = async |cookie: &str| { + http.post(format!("{base}/ui/queues/emails/pause")) + .header("cookie", cookie) + .send() + .await + .expect("pause") + .status() + }; + assert_eq!(pause(&client_cookie).await, StatusCode::FORBIDDEN); + assert_eq!(pause(&admin_cookie).await, StatusCode::SEE_OTHER); +} + +#[tokio::test] +async fn assets_are_served() { + let base = serve(Config::default()).await; + let http = browser(); + for (path, content_type) in [ + ("htmx.min.js", "text/javascript"), + ("style.css", "text/css"), + ] { + let response = http + .get(format!("{base}/ui/assets/{path}")) + .send() + .await + .expect("asset"); + assert_eq!(response.status(), StatusCode::OK, "{path}"); + assert_eq!(response.headers()["content-type"], content_type, "{path}"); + } +} diff --git a/crates/dally/Cargo.toml b/crates/dally/Cargo.toml new file mode 100644 index 0000000..741d8d6 --- /dev/null +++ b/crates/dally/Cargo.toml @@ -0,0 +1,47 @@ +[package] +name = "dally" +description = "A job queue server: schedule work over HTTP, run it later" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true +readme = "../../README.md" + +[features] +default = ["postgres", "sqlite", "redis", "ui"] +postgres = ["dally-server/postgres"] +redis = ["dally-server/redis"] +sqlite = ["dally-server/sqlite"] +# The web UI, served by `dally server --ui` or `dally ui`. +ui = ["dep:dally-ui", "dep:axum"] +# Export traces over OTLP when OTEL_EXPORTER_OTLP_ENDPOINT is set. +otel = [ + "dep:opentelemetry", + "dep:opentelemetry_sdk", + "dep:opentelemetry-otlp", + "dep:tracing-opentelemetry", +] + +[dependencies] +anyhow.workspace = true +axum = { workspace = true, optional = true } +chrono.workspace = true +clap.workspace = true +dally-client.workspace = true +dally-server.workspace = true +dally-ui = { workspace = true, optional = true } +humantime.workspace = true +opentelemetry = { workspace = true, optional = true } +opentelemetry-otlp = { workspace = true, optional = true } +opentelemetry_sdk = { workspace = true, optional = true } +serde.workspace = true +serde_json.workspace = true +tokio = { workspace = true, features = ["full"] } +tracing.workspace = true +tracing-opentelemetry = { workspace = true, optional = true } +tracing-subscriber.workspace = true + +[lints] +workspace = true diff --git a/crates/dally/src/cli.rs b/crates/dally/src/cli.rs new file mode 100644 index 0000000..ada73ed --- /dev/null +++ b/crates/dally/src/cli.rs @@ -0,0 +1,361 @@ +//! The client subcommands. They talk to a running server through +//! `dally-client`, never to storage directly. + +use std::time::Duration; + +use anyhow::{Context, Result}; +use chrono::{DateTime, Utc}; +use clap::{Args, Subcommand}; +use dally_client::{Client, Message, MessageFilter, MessageId, QueueSummary, Status}; +use serde::Serialize; + +/// Where the server is and how to authenticate. +#[derive(Debug, Args)] +pub struct Connection { + /// The server's base URL. + #[arg( + long, + global = true, + env = "DALLY_SERVER", + default_value = "http://127.0.0.1:7070" + )] + server: String, + + /// API key, sent as a bearer token. + #[arg(long, global = true, env = "DALLY_API_KEY", hide_env_values = true)] + api_key: Option, + + /// Print JSON instead of tables. + #[arg(long, global = true)] + json: bool, +} + +#[derive(Debug, Subcommand)] +pub enum QueuesCommand { + /// List queues with their message counts. + Ls, + /// Show a queue's settings and message counts. + Show { name: String }, + /// Stop delivering messages from a queue. New messages are still accepted. + Pause { name: String }, + /// Start delivering messages from a paused queue again. + Resume { name: String }, +} + +#[derive(Debug, Args)] +pub struct ScheduleArgs { + /// The queue to schedule into. It is created if it does not exist. + queue: String, + + /// The payload, as JSON. + #[arg(long)] + payload: String, + + /// Run after this delay, such as `10m` or `1h30m`. + #[arg(long, value_parser = humantime::parse_duration, conflicts_with = "run_at")] + delay: Option, + + /// Run at this time (RFC 3339, such as `2026-12-01T09:00:00Z`). + #[arg(long)] + run_at: Option>, + + /// Scheduling twice with the same key creates one message. + #[arg(long)] + key: Option, + + /// Higher priorities are delivered first. + #[arg(long, default_value_t = 0, allow_negative_numbers = true)] + priority: i32, +} + +#[derive(Debug, Subcommand)] +pub enum MessagesCommand { + /// List messages, newest first. + Ls { + /// Only messages in this queue. + #[arg(long)] + queue: Option, + /// Only messages in this status: scheduled, running, succeeded, + /// cancelled or dead. + #[arg(long, value_parser = parse_status)] + status: Option, + /// At most this many messages. + #[arg(long, default_value_t = 50)] + limit: u32, + }, +} + +#[derive(Debug, Subcommand)] +pub enum DeadCommand { + /// Give dead messages a fresh set of attempts. Without ids, retries every + /// dead message in the queue. + Retry { queue: String, ids: Vec }, +} + +fn parse_status(value: &str) -> Result { + value.parse::().map_err(|err| err.to_string()) +} + +impl Connection { + /// The server's base URL. + #[cfg(feature = "ui")] + pub fn server(&self) -> &str { + &self.server + } + + fn client(&self) -> Result { + let mut builder = Client::builder(&self.server); + if let Some(key) = &self.api_key { + builder = builder.api_key(key); + } + builder.build().context("invalid --server URL") + } + + /// Prints `value` as JSON, or as text produced by `human`. + fn print(&self, value: &T, human: impl FnOnce(&T) -> String) -> Result<()> { + if self.json { + println!("{}", serde_json::to_string_pretty(value)?); + } else { + print!("{}", human(value)); + } + Ok(()) + } +} + +pub async fn queues(connection: &Connection, command: QueuesCommand) -> Result<()> { + let client = connection.client()?; + match command { + QueuesCommand::Ls => { + let queues = client.list_queues().await?; + connection.print(&queues, |queues| queue_table(queues)) + } + QueuesCommand::Show { name } => { + let summary = client.get_queue(&name).await?; + connection.print(&summary, queue_details) + } + QueuesCommand::Pause { name } => { + let queue = client.pause(&name).await?; + connection.print(&queue, |queue| format!("paused {}\n", queue.name)) + } + QueuesCommand::Resume { name } => { + let queue = client.resume(&name).await?; + connection.print(&queue, |queue| format!("resumed {}\n", queue.name)) + } + } +} + +pub async fn schedule(connection: &Connection, args: ScheduleArgs) -> Result<()> { + let payload: serde_json::Value = + serde_json::from_str(&args.payload).context("--payload is not valid JSON")?; + + let client = connection.client()?; + let mut request = client + .schedule(&args.queue, &payload) + .priority(args.priority); + if let Some(delay) = args.delay { + request = request.delay(delay); + } + if let Some(at) = args.run_at { + request = request.run_at(at); + } + if let Some(key) = args.key { + request = request.idempotency_key(key); + } + + let scheduled = request.send().await?; + connection.print(&scheduled, |scheduled| { + let verb = if scheduled.created { + "scheduled" + } else { + "already scheduled" + }; + let message = &scheduled.message; + format!( + "{verb} {} in {}, due {}\n", + message.id, message.queue, message.run_at + ) + }) +} + +pub async fn inspect(connection: &Connection, id: MessageId) -> Result<()> { + let message = connection.client()?.get_message(id).await?; + connection.print(&message, message_details) +} + +pub async fn messages(connection: &Connection, command: MessagesCommand) -> Result<()> { + let MessagesCommand::Ls { + queue, + status, + limit, + } = command; + let filter = MessageFilter { + queue: queue.map(dally_client::QueueName::new).transpose()?, + status, + before: None, + limit, + }; + let page = connection.client()?.list_messages(&filter).await?; + connection.print(&page.items, |messages| message_table(messages)) +} + +pub async fn dead(connection: &Connection, command: DeadCommand) -> Result<()> { + let DeadCommand::Retry { queue, ids } = command; + let ids = (!ids.is_empty()).then_some(ids.as_slice()); + let retried = connection.client()?.retry_dead(&queue, ids).await?; + connection.print(&serde_json::json!({ "retried": retried }), |_| { + format!("retried {retried} dead messages in {queue}\n") + }) +} + +fn queue_table(queues: &[QueueSummary]) -> String { + let rows = queues.iter().map(|summary| { + let stats = summary.stats; + vec![ + summary.queue.name.to_string(), + stats.scheduled.to_string(), + stats.running.to_string(), + stats.succeeded.to_string(), + stats.dead.to_string(), + if summary.queue.settings.paused { + "paused" + } else { + "" + } + .to_owned(), + ] + }); + table( + &["QUEUE", "SCHEDULED", "RUNNING", "SUCCEEDED", "DEAD", ""], + rows, + ) +} + +fn queue_details(summary: &QueueSummary) -> String { + let settings = &summary.queue.settings; + let stats = summary.stats; + let duration = |d: Duration| humantime::format_duration(d).to_string(); + let push = settings + .push + .as_ref() + .map_or("none".to_owned(), |push| push.url.clone()); + + fields(&[ + ("queue", summary.queue.name.to_string()), + ("paused", settings.paused.to_string()), + ("visibility timeout", duration(settings.visibility_timeout)), + ("max attempts", settings.max_attempts.to_string()), + ( + "backoff", + format!( + "{} up to {}", + duration(settings.backoff.base), + duration(settings.backoff.cap) + ), + ), + ("retention", duration(settings.retention)), + ("push", push), + ("scheduled", stats.scheduled.to_string()), + ("running", stats.running.to_string()), + ("succeeded", stats.succeeded.to_string()), + ("cancelled", stats.cancelled.to_string()), + ("dead", stats.dead.to_string()), + ]) +} + +fn message_table(messages: &[Message]) -> String { + let rows = messages.iter().map(|message| { + vec![ + message.id.to_string(), + message.queue.to_string(), + message.status.to_string(), + format!("{}/{}", message.attempts, message.max_attempts), + message.run_at.format("%Y-%m-%d %H:%M:%S").to_string(), + ] + }); + table(&["ID", "QUEUE", "STATUS", "ATTEMPTS", "RUN AT (UTC)"], rows) +} + +fn message_details(message: &Message) -> String { + let optional = |value: Option| value.unwrap_or_else(|| "-".to_owned()); + let mut text = fields(&[ + ("id", message.id.to_string()), + ("queue", message.queue.to_string()), + ("status", message.status.to_string()), + ( + "attempts", + format!("{} of {}", message.attempts, message.max_attempts), + ), + ("priority", message.priority.to_string()), + ("run at", message.run_at.to_rfc3339()), + ("idempotency key", optional(message.idempotency_key.clone())), + ("last error", optional(message.last_error.clone())), + ("created at", message.created_at.to_rfc3339()), + ( + "finished at", + optional(message.finished_at.map(|at| at.to_rfc3339())), + ), + ]); + let payload = serde_json::to_string_pretty(&message.payload).unwrap_or_default(); + text.push_str(&format!("payload:\n{payload}\n")); + text +} + +/// Lines of `name: value`, with the values lined up. +fn fields(fields: &[(&str, String)]) -> String { + let width = fields.iter().map(|(name, _)| name.len()).max().unwrap_or(0) + 1; + fields + .iter() + .map(|(name, value)| format!("{:width$} {value}\n", format!("{name}:"))) + .collect() +} + +/// A plain text table with left-aligned columns separated by two spaces. +fn table(headers: &[&str], rows: impl Iterator>) -> String { + let rows: Vec> = rows.collect(); + let mut widths: Vec = headers.iter().map(|header| header.len()).collect(); + for row in &rows { + for (width, cell) in widths.iter_mut().zip(row) { + *width = (*width).max(cell.len()); + } + } + + let line = |cells: Vec<&str>| { + let padded: Vec = cells + .iter() + .zip(&widths) + .map(|(cell, width)| format!("{cell:width$}")) + .collect(); + format!("{}\n", padded.join(" ").trim_end()) + }; + + let mut text = line(headers.to_vec()); + for row in &rows { + text.push_str(&line(row.iter().map(String::as_str).collect())); + } + text +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tables_align_columns() { + let rows = vec![ + vec!["emails".to_owned(), "3".to_owned()], + vec!["reports-nightly".to_owned(), "12".to_owned()], + ]; + assert_eq!( + table(&["QUEUE", "SCHEDULED"], rows.into_iter()), + "QUEUE SCHEDULED\n\ + emails 3\n\ + reports-nightly 12\n" + ); + } + + #[test] + fn fields_align_values() { + let text = fields(&[("id", "1".to_owned()), ("last error", "boom".to_owned())]); + assert_eq!(text, "id: 1\nlast error: boom\n"); + } +} diff --git a/crates/dally/src/main.rs b/crates/dally/src/main.rs new file mode 100644 index 0000000..b1f949e --- /dev/null +++ b/crates/dally/src/main.rs @@ -0,0 +1,222 @@ +//! The `dally` command line: runs the server, and talks to a running one. + +mod cli; +#[cfg(feature = "otel")] +mod telemetry; + +use std::path::PathBuf; + +use anyhow::Context; +use clap::{Parser, Subcommand, ValueEnum}; +use dally_server::Config; +use tracing_subscriber::EnvFilter; +use tracing_subscriber::layer::{Layer, SubscriberExt}; +use tracing_subscriber::util::SubscriberInitExt; + +#[derive(Debug, Parser)] +#[command(version, about)] +struct Cli { + /// Log format. + #[arg( + long, + global = true, + env = "DALLY_LOG_FORMAT", + default_value = "pretty" + )] + log_format: LogFormat, + + #[command(flatten)] + connection: cli::Connection, + + #[command(subcommand)] + command: Command, +} + +#[derive(Debug, Subcommand)] +enum Command { + /// Run the server. + Server { + /// Configuration file (TOML). `DALLY_*` environment variables override it. + #[arg(short, long, env = "DALLY_CONFIG")] + config: Option, + + /// Also serve the web UI, under `/ui`. + #[cfg(feature = "ui")] + #[arg(long, env = "DALLY_UI")] + ui: bool, + }, + + /// Serve the web UI on its own, for a server running elsewhere. Use + /// `--server` to say where. + #[cfg(feature = "ui")] + Ui { + /// The address to serve the UI on. + #[arg(long, default_value = "127.0.0.1:7071")] + listen: std::net::SocketAddr, + }, + + /// Inspect and manage queues. + #[command(subcommand)] + Queues(cli::QueuesCommand), + + /// Schedule a message. + Schedule(cli::ScheduleArgs), + + /// Show one message, including its payload and last error. + Inspect { + /// The message id. + id: dally_client::MessageId, + }, + + /// List messages. + #[command(subcommand)] + Messages(cli::MessagesCommand), + + /// Work with dead messages. + #[command(subcommand)] + Dead(cli::DeadCommand), +} + +#[derive(Debug, Clone, Copy, ValueEnum)] +enum LogFormat { + Pretty, + Json, +} + +fn main() -> anyhow::Result<()> { + let cli = Cli::parse(); + // Set up logging before the runtime starts and keep the guard until it + // has stopped: trace export uses a blocking HTTP client, which must not + // be created or flushed from inside async code. + let _logging = init_logging(cli.log_format); + + tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .context("starting the async runtime")? + .block_on(run(cli)) +} + +async fn run(cli: Cli) -> anyhow::Result<()> { + match cli.command { + #[cfg(feature = "ui")] + Command::Server { config, ui } => { + let config = Config::load(config.as_deref()).context("loading configuration")?; + let extra = if ui { + ui_in_server(&config) + } else { + axum::Router::new() + }; + dally_server::run_with(config, extra, shutdown_signal()).await?; + } + #[cfg(not(feature = "ui"))] + Command::Server { config } => { + let config = Config::load(config.as_deref()).context("loading configuration")?; + dally_server::run(config, shutdown_signal()).await?; + } + #[cfg(feature = "ui")] + Command::Ui { listen } => serve_ui(&cli.connection, listen).await?, + Command::Queues(command) => cli::queues(&cli.connection, command).await?, + Command::Schedule(args) => cli::schedule(&cli.connection, args).await?, + Command::Inspect { id } => cli::inspect(&cli.connection, id).await?, + Command::Messages(command) => cli::messages(&cli.connection, command).await?, + Command::Dead(command) => cli::dead(&cli.connection, command).await?, + } + Ok(()) +} + +/// The UI mounted at `/ui` inside the server. It still talks to the server +/// over HTTP, through the server's own listen address. +#[cfg(feature = "ui")] +fn ui_in_server(config: &Config) -> axum::Router { + let mut address = config.listen; + if address.ip().is_unspecified() { + address.set_ip(std::net::Ipv4Addr::LOCALHOST.into()); + } + tracing::info!("serving the web UI at /ui"); + dally_ui::mount(dally_ui::UiConfig { + server: format!("http://{address}"), + base_path: "/ui".to_owned(), + }) +} + +/// `dally ui`: the UI on its own listener, for the server at `--server`. +#[cfg(feature = "ui")] +async fn serve_ui( + connection: &cli::Connection, + listen: std::net::SocketAddr, +) -> anyhow::Result<()> { + let ui = dally_ui::router(dally_ui::UiConfig { + server: connection.server().to_owned(), + base_path: String::new(), + }); + let listener = tokio::net::TcpListener::bind(listen) + .await + .with_context(|| format!("listening on {listen}"))?; + tracing::info!(address = %listen, server = connection.server(), "serving the web UI"); + axum::serve(listener, ui) + .with_graceful_shutdown(shutdown_signal()) + .await?; + Ok(()) +} + +/// What has to stay alive while the program logs. +struct LoggingGuard { + #[cfg(feature = "otel")] + _telemetry: telemetry::Guard, +} + +/// Logs at `info` unless `RUST_LOG` says otherwise. Logs go to stderr so that +/// `--json` output on stdout stays parseable. +fn init_logging(format: LogFormat) -> LoggingGuard { + let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); + let output = tracing_subscriber::fmt::layer().with_writer(std::io::stderr); + let output = match format { + LogFormat::Pretty => output.boxed(), + LogFormat::Json => output.json().boxed(), + }; + let subscriber = tracing_subscriber::registry().with(filter).with(output); + + #[cfg(feature = "otel")] + { + let (export, guard) = telemetry::layer(); + subscriber.with(export).init(); + LoggingGuard { _telemetry: guard } + } + #[cfg(not(feature = "otel"))] + { + subscriber.init(); + LoggingGuard {} + } +} + +/// Resolves on Ctrl-C or, on Unix, SIGTERM (what Docker and Kubernetes send). +async fn shutdown_signal() { + let ctrl_c = async { + if let Err(err) = tokio::signal::ctrl_c().await { + tracing::error!(error = %err, "cannot listen for Ctrl-C"); + std::future::pending::<()>().await; + } + }; + + #[cfg(unix)] + let terminate = async { + match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) { + Ok(mut signal) => { + signal.recv().await; + } + Err(err) => { + tracing::error!(error = %err, "cannot listen for SIGTERM"); + std::future::pending::<()>().await; + } + } + }; + #[cfg(not(unix))] + let terminate = std::future::pending::<()>(); + + tokio::select! { + _ = ctrl_c => {} + _ = terminate => {} + } + tracing::info!("shutting down"); +} diff --git a/crates/dally/src/telemetry.rs b/crates/dally/src/telemetry.rs new file mode 100644 index 0000000..683f8bd --- /dev/null +++ b/crates/dally/src/telemetry.rs @@ -0,0 +1,68 @@ +//! Trace export over OTLP, built with the `otel` feature. +//! +//! Export only starts when `OTEL_EXPORTER_OTLP_ENDPOINT` (or the traces-only +//! `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`) is set. Everything else is +//! configured with the standard `OTEL_*` variables, such as +//! `OTEL_SERVICE_NAME` and `OTEL_RESOURCE_ATTRIBUTES`. The protocol is OTLP +//! over HTTP with protobuf, which every collector accepts on port 4318. + +use opentelemetry::trace::TracerProvider as _; +use opentelemetry_otlp::SpanExporter; +use opentelemetry_sdk::Resource; +use opentelemetry_sdk::trace::SdkTracerProvider; +use tracing::Subscriber; +use tracing_subscriber::Layer; +use tracing_subscriber::registry::LookupSpan; + +/// Flushes and stops the exporter when dropped. Drop it outside the async +/// runtime: the exporter uses a blocking HTTP client. +pub struct Guard(Option); + +impl Drop for Guard { + fn drop(&mut self) { + if let Some(provider) = self.0.take() + && let Err(err) = provider.shutdown() + { + eprintln!("dally: flushing OpenTelemetry traces failed: {err}"); + } + } +} + +/// The tracing layer that exports spans, if export is configured. +pub fn layer() -> (Option>, Guard) +where + S: Subscriber + for<'span> LookupSpan<'span>, +{ + let configured = [ + "OTEL_EXPORTER_OTLP_ENDPOINT", + "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", + ] + .iter() + .any(|var| std::env::var_os(var).is_some()); + if !configured { + return (None, Guard(None)); + } + + let exporter = match SpanExporter::builder().with_http().build() { + Ok(exporter) => exporter, + Err(err) => { + // Logging is not set up yet, and a broken exporter should not + // stop the queue from running. + eprintln!("dally: OpenTelemetry export is disabled: {err}"); + return (None, Guard(None)); + } + }; + + let mut resource = Resource::builder(); + if std::env::var_os("OTEL_SERVICE_NAME").is_none() { + resource = resource.with_service_name("dally"); + } + let provider = SdkTracerProvider::builder() + .with_batch_exporter(exporter) + .with_resource(resource.build()) + .build(); + let tracer = provider.tracer("dally"); + + let layer = tracing_opentelemetry::layer().with_tracer(tracer); + (Some(layer), Guard(Some(provider))) +} diff --git a/docs/backends/redis.md b/docs/backends/redis.md new file mode 100644 index 0000000..e444ede --- /dev/null +++ b/docs/backends/redis.md @@ -0,0 +1,79 @@ +# Redis + +```toml +[storage] +url = "redis://localhost:6379/0" +# url = "rediss://user:password@redis.internal:6380/0?prefix=myapp:dally:" +``` + +Redis is a good fit if you already run it and want dally to be fast without +adding a database. Any number of dally servers can share one Redis. + +## Durability: turn on AOF + +By default Redis keeps data in memory and only saves snapshots every few +minutes. If it crashes, everything since the last snapshot is gone: scheduled +messages, retries in progress, acks. For a job queue that means lost jobs. + +Run Redis with the append-only file and an fsync every second: + +``` +appendonly yes +appendfsync everysec +``` + +With that, a crash loses at most about one second of writes. `appendfsync +always` loses nothing but is much slower. Managed Redis services usually call +this "persistence" or "AOF"; check that it is on. + +## Key prefix + +Every key dally writes starts with `dally:`. Set another prefix with the +`prefix` URL parameter, for example to run two dally setups on one Redis: + +``` +redis://localhost:6379/0?prefix=staging:dally: +``` + +The parameter is removed from the URL before connecting, so it never reaches +Redis. + +## How it is stored + +Each message is a hash. Each queue has a few sorted sets: messages waiting +for their time, messages due now in delivery order, running messages by lease +expiry, finished messages by completion time, and one index per status. +Every operation that touches more than one key is a Lua script, so it is +atomic. Scripts use Redis's own clock (`TIME`), so several dally servers agree +on what is due. The module docs in `crates/dally-core/src/storage/redis/mod.rs` +describe the keys in detail. + +Scripts build key names from the data they read, so dally supports a single +Redis server (with replicas, or Sentinel for failover) but not Redis Cluster. + +## Memory + +Everything lives in memory. As a rough guide, a message takes a few hundred +bytes plus its payload. Finished messages are kept for the queue's retention +period (7 days by default) and then deleted, so memory use is about: + +``` +(messages per day × retention in days + messages waiting) × (300 B + payload) +``` + +Lower `retention` on busy queues if that adds up. Set `maxmemory-policy +noeviction`, the default, so Redis refuses writes when full rather than +silently evicting messages. + +## Long polling + +Scheduling a message publishes on the `scheduled` channel, and every +dally server subscribes to it, so waiting workers are woken right away. If +the subscription drops, polls still find due messages within a second. + +## Metrics + +The Redis backend does not report `dally_queue_oldest_due_seconds`. Due +messages in the ready set are ordered by priority, not by `run_at`, so finding +the oldest one would mean scanning the whole set on every scrape. Every other +metric works as with the other backends. diff --git a/docs/backends/sqlite.md b/docs/backends/sqlite.md new file mode 100644 index 0000000..056f9dd --- /dev/null +++ b/docs/backends/sqlite.md @@ -0,0 +1,65 @@ +# SQLite + +SQLite is the default backend: `dally server` with no configuration stores +everything in `./dally.sqlite`. It needs no database server, which makes it +the right choice for local development, tests, and small deployments that run +on a single machine. + +```toml +[storage] +url = "sqlite://dally.sqlite" # relative to the working directory +# url = "sqlite:///var/lib/dally/dally.sqlite" # absolute path +# url = "sqlite::memory:" # gone when the process exits +``` + +The file is created if it does not exist, and migrations run on startup. + +## One server process + +Only one `dally server` can use a database file at a time. dally takes an +exclusive lock on `dally.sqlite.lock` next to the database, and a second +server on the same file refuses to start: + +``` +SQLite database dally.sqlite is already in use by another dally server +``` + +The lock is released when the process exits, even if it crashes, so a stale +lock file never blocks a restart. + +The reason is that long polls are woken through an in-process channel, and +timestamps come from the process clock. A second process would not wake the +first one's waiting workers, and the two clocks need not agree. If you need +more than one server, use PostgreSQL. + +You can still have any number of *workers*: they talk to the server over +HTTP, not to the file. + +## Guarantees + +- Writes are durable once the request returns. The database runs in WAL mode, + which keeps reads from waiting on writes. +- Leasing takes SQLite's write lock before it looks for due messages, so two + concurrent polls never get the same message. +- All writes go through one connection, so throughput is bounded by a single + writer. That is thousands of small operations per second on an SSD, which is + plenty for most single-machine setups. + +## Backups + +Copy the database while the server runs with the `sqlite3` shell, which takes +a consistent snapshot: + +```sh +sqlite3 dally.sqlite ".backup dally-backup.sqlite" +``` + +Copying the file with `cp` while the server is running can produce a corrupt +copy, because the `-wal` file holds recent writes. + +## When to move to PostgreSQL + +- You want more than one dally server, for availability or throughput. +- The database lives on a network file system. SQLite's locking is unreliable + there. +- You already run PostgreSQL and would rather back up one database than two. diff --git a/docs/design.md b/docs/design.md new file mode 100644 index 0000000..c9ceb5e --- /dev/null +++ b/docs/design.md @@ -0,0 +1,402 @@ +# dally design + +dally is a job queue server. Applications in any language schedule work over +HTTP, and dally hands it back to workers when it is due, either by letting +workers poll for it or by pushing it to a webhook. + +This document describes what dally does and the decisions behind it. It is the +reference for contributors. User-facing docs live in the README and the other +files in `docs/`. + +## Goals + +- **Language-agnostic.** Anything that can make an HTTP request can use dally. + Adding background jobs to an existing web app should take one endpoint and a + few lines of code. +- **Boring storage.** Run it on the database you already have: PostgreSQL, + SQLite or Redis. +- **Honest guarantees.** At-least-once delivery, clearly documented, with no + hidden ways to lose a message. +- **Easy to run.** One binary. With no configuration it starts on a local + SQLite file. +- **Stateless servers.** Any number of `dally server` processes can share one + database. All coordination happens in storage. + +Non-goals: exactly-once delivery, pub/sub fan-out, and ordered streams (use +Kafka or NATS for those). + +## Concepts + +**Queue.** A named stream of messages with its own settings. A queue is +created on first use with default settings, and can be configured later. + +| Setting | Default | Meaning | +|----------------------|----------|-----------------------------------------------------------| +| `visibility_timeout` | 30s | How long a lease lasts before the message is handed out again | +| `max_attempts` | 5 | Attempts before the message is marked `dead` | +| `backoff` | exp, 5s base, 1h cap | Delay before a retry after a failed attempt | +| `retention` | 7d | How long finished messages are kept | +| `paused` | false | A paused queue accepts messages but delivers none | +| `push` | none | Optional webhook endpoint (see [Push delivery](#push-delivery)) | + +**Message.** A JSON payload scheduled to run at a point in time. A message has +a server-generated `id`, an optional `idempotency_key`, a `priority` (higher +runs first, default 0) and optional per-message overrides for +`visibility_timeout` and `max_attempts`. + +**Lease.** A worker that takes a message gets a lease: a random token that +expires after the visibility timeout. Only the holder of a valid lease can ack +or nack the message. This guards against the classic bug where a slow worker +acks a message that was already handed to someone else. + +### Message lifecycle + +``` + schedule + │ + ▼ + ┌──────────► scheduled ──── cancel ────► cancelled + │ │ + │ nack / lease │ run_at reached, polled + │ expired ▼ + │ (attempts running ───── ack ───────► succeeded + │ left) │ + └────────────────┤ + │ nack / lease expired, no attempts left + ▼ + dead ──── retry (manual) ──► scheduled +``` + +`succeeded`, `cancelled` and `dead` messages are deleted after the queue's +retention period. A message counts as `failed` in stats when it reached `dead`. + +## Delivery semantics + +dally delivers **at least once**. A message can be delivered more than once +when: + +- a worker crashes or exceeds the visibility timeout before acking, +- a worker finishes the work but its ack never reaches the server. + +Handlers must therefore be safe to run twice. The docs say this up front, and +show the usual pattern of storing a "done" marker under the message id. + +When a message is due, it is delivered by priority, highest first, then by +`run_at`. dally does not promise strict ordering beyond that. + +### Retries + +A nack ends the current attempt. If the message has attempts left, it goes +back to `scheduled` with `run_at = now + backoff(attempt)`. + +A lease that expires also ends the attempt, but without backoff: the message +can be leased again right away, as in SQS. The worker probably crashed, so +waiting longer only adds latency. If it was the last attempt, the message moves +to `dead` with the error `lease expired`. The backoff is +`min(base * 2^(attempt - 1), cap)` with ±20% jitter. A nack may also give its +own `retry_in` delay. The error text from a nack is stored on the message so +the UI can show why it failed. + +### Idempotency + +`idempotency_key` is unique per queue for as long as a message with that key +exists, which is until it is pruned after the retention period. Scheduling with +a key that already exists does not create a new message. It returns the +existing message with `200 OK` instead of `201 Created`. Rescheduling and +cancelling are separate operations, never a side effect of reusing a key. + +### Time + +All timestamps come from the storage clock (`now()` in Postgres, `TIME` in +Redis), never from the server process. That way several servers with slightly +different clocks still agree. SQLite only ever runs with a single server +process, so it uses that process's clock. + +## Architecture + +``` + ┌────────────┐ ┌───────────┐ ┌──────────────┐ + │ your app │ │ dally CLI │ │ dally-ui │ (optional, feature "ui") + └─────┬──────┘ └─────┬─────┘ └──────┬───────┘ + │ HTTP │ dally-client │ dally-client + ▼ ▼ ▼ + ┌───────────────────────────────────────────────┐ + │ dally-server HTTP (axum) · gRPC later │ + │ push dispatcher · cron · janitor│ + ├───────────────────────────────────────────────┤ + │ dally-core Service: the rules │ + │ Storage trait │ + ├──────────────┬──────────────┬─────────────────┤ + │ postgres │ sqlite │ redis │ (cargo features) + └──────────────┴──────────────┴─────────────────┘ +``` + +### Crates + +| Crate | What it holds | +|----------------|---------------------------------------------------------------------| +| `dally-core` | Domain types, the `Service` (validation, lifecycle rules), the `Storage` trait and the backends behind cargo features | +| `dally-server` | HTTP API, push dispatcher, cron ticker, janitor, config, metrics | +| `dally-client` | Rust HTTP client and a `Worker` that runs a handler with bounded concurrency | +| `dally-ui` | Web UI: askama templates + htmx. Talks to the server only through `dally-client` | +| `dally` | The binary: `dally server`, `dally ui`, and the client subcommands | + +Two rules keep this honest: + +1. **Transports are thin.** HTTP handlers parse the request, call `Service` + and serialize the result. All behaviour lives in `dally-core`, so a gRPC + transport is a new thin layer later, not a rewrite. +2. **The UI and CLI are clients.** They use the public API and nothing else. + If the UI needs something, the API grows it, and every user gets it too. + +### Storage trait + +The trait is small and works in terms of the operations dally needs, not +generic CRUD. Each backend implements every method atomically. The shared +conformance test suite (`dally-core/tests/conformance`) runs the same tests +against every backend. + +In brief (see `crates/dally-core/src/storage/mod.rs` for the documented +version): + +```rust +#[async_trait] +pub trait Storage: Send + Sync + 'static { + async fn ensure_queue(&self, name: &QueueName, defaults: &QueueSettings) -> Result; + async fn put_queue(&self, name: &QueueName, settings: &QueueSettings) -> Result; + async fn get_queue(&self, name: &QueueName) -> Result>; + async fn list_queues(&self) -> Result>; + + async fn schedule(&self, queue: &QueueName, messages: Vec) + -> Result>; + async fn lease(&self, queue: &QueueName, limit: u32) -> Result>; + async fn ack(&self, id: MessageId, lease: &LeaseToken) -> Result>; + async fn nack(&self, id: MessageId, lease: &LeaseToken, retry: Retry) + -> Result>; + + async fn get_message(&self, id: MessageId) -> Result>; + async fn list_messages(&self, filter: &MessageFilter) -> Result>; + async fn cancel(&self, id: MessageId) -> Result>; + async fn reschedule(&self, id: MessageId, run_at: RunAt) -> Result>; + async fn retry_dead(&self, queue: &QueueName, ids: Option<&[MessageId]>) -> Result; + async fn prune(&self) -> Result; + + /// Optional; used for the oldest-due metric. + async fn oldest_due(&self) -> Result>> { Ok(None) } + + fn subscribe(&self, queue: &QueueName) -> Subscription; + async fn now(&self) -> Result>; +} +``` + +`None` from ack, nack, cancel and reschedule means "nothing matched"; the +`Service` then looks the message up to say whether it is missing, held under +another lease, or in the wrong status. Backoff, defaults and validation live in +the `Service`, so backends only store and fetch. + +### Backends + +**PostgreSQL** (13 or later) is the reference backend. `lease` is one statement using +`FOR UPDATE SKIP LOCKED`, so concurrent pollers never block each other or take +the same row. `LISTEN/NOTIFY` wakes long-polling requests as soon as a message +is scheduled. A partial index on `(queue, priority DESC, run_at)` over +`status = 'scheduled'` keeps polling fast. + +**SQLite** runs in WAL mode with one writer. It supports a single server +process only, and the server refuses to start a second process against the +same file. Notifications go through an in-process channel. It is meant for +local development and small deployments. + +**Redis** keeps each message in a hash, due messages in a sorted set per queue +scored by `run_at` and priority, and leases in a second sorted set scored by +expiry. Every operation that touches more than one key is a Lua script, so it +is atomic. Durability depends on Redis persistence: with default settings, +recent messages can be lost on a crash. The docs require `appendonly yes` for +production use. + +## Delivery + +### Pull + +`POST /v1/queues/{queue}/poll` with `{"limit": 10, "wait_seconds": 20}` +returns up to `limit` leased messages. If none are due, the request waits up to +`wait_seconds` for one to arrive (long polling), so idle workers send very few +requests. The `dally-client` `Worker` is built on this. + +### Push delivery + +A queue may have one push endpoint: + +```toml +[queues.emails.push] +url = "https://app.example.com/jobs/emails" +secret = "${EMAILS_WEBHOOK_SECRET}" +timeout = "30s" +concurrency = 8 +``` + +The push dispatcher in each server leases messages from push queues and POSTs +them to the endpoint. A `2xx` response acks the message. Anything else, +including a timeout, nacks it with the response status and the first 1 KiB of +the body as the error text. Each request carries: + +- `Dally-Message-Id`, `Dally-Queue`, `Dally-Attempt` +- `Dally-Signature: t=,v1=.")>` + +The docs include a short "verify the signature" snippet for common languages. +Push is one endpoint per queue by design. Fan-out to many subscribers is +pub/sub, which dally does not do. + +## Cron + +Recurring jobs are defined per queue: + +```toml +[[queues.reports.cron]] +name = "nightly" +schedule = "0 3 * * *" +timezone = "Europe/Bucharest" +payload = { kind = "nightly-report" } +``` + +Every server runs a ticker that works out the next run time for each entry and +schedules it with `idempotency_key = "cron:{name}:{run_at}"`. When several +servers do this at once, idempotency means only one message is created. No +leader election is needed. + +## HTTP API + +All endpoints are under `/v1` and use JSON. Errors have the shape +`{"error": {"code": "lease_expired", "message": "..."}}`. The OpenAPI spec is +generated from the code with `utoipa` and served at `/v1/openapi.json`. + +| Method & path | Purpose | +|----------------------------------------|---------------------------------------------| +| `POST /v1/queues/{queue}/messages` | Schedule one message or a batch | +| `POST /v1/queues/{queue}/poll` | Lease due messages, optionally long polling | +| `POST /v1/messages/{id}/ack` | Finish a message (`{"lease": "..."}`) | +| `POST /v1/messages/{id}/nack` | Fail an attempt (`lease`, `error`, `retry_in`) | +| `GET /v1/messages/{id}` | Inspect a message | +| `PATCH /v1/messages/{id}` | Reschedule | +| `DELETE /v1/messages/{id}` | Cancel | +| `GET /v1/queues` | List queues with counts per status | +| `GET /v1/queues/{queue}` | Queue settings and stats | +| `PUT /v1/queues/{queue}` | Update settings | +| `POST /v1/queues/{queue}/pause`, `/resume` | Pause or resume delivery | +| `GET /v1/queues/{queue}/messages` | List messages, filterable by status | +| `POST /v1/queues/{queue}/dead/retry` | Move dead messages back to `scheduled` | +| `GET /v1/messages` | List messages across queues | +| `GET /v1/openapi.json` | This API as OpenAPI 3.1 | +| `GET /healthz`, `GET /readyz` | Liveness and readiness | +| `GET /metrics` | Prometheus metrics | + +Scheduling example: + +```http +POST /v1/queues/emails/messages +{ + "payload": {"to": "ana@example.com", "template": "welcome"}, + "delay": "10m", + "idempotency_key": "welcome-email-user-42", + "priority": 0 +} +``` + +`delay` (a duration) and `run_at` (RFC 3339) are mutually exclusive. If +neither is given, the message runs now. + +## Auth + +Auth is off by default. When API keys are configured, every request needs +`Authorization: Bearer `. Keys have one of two roles: + +- **client**: schedule, poll, ack, nack, and read messages. +- **admin**: everything, including queue settings, retrying dead messages and + the UI. + +Keys stored in the database with a management UI may come later. + +## Web UI + +`dally-ui` is optional. It is compiled only with the `ui` cargo feature, and +when it is compiled in it can run: + +- inside the server: `dally server --ui` mounts it under `/ui`, +- on its own: `dally ui --server https://dally.internal --api-key ...`. + +It shows queues with counts and throughput, lets you browse and filter +messages, inspect payloads and errors, retry or delete dead messages, pause +queues and edit settings. It is server-rendered with askama and htmx, so the +build needs no JavaScript toolchain. + +## CLI + +``` +dally server [--config dally.toml] [--ui] +dally ui --server URL +dally queues ls | show NAME | pause NAME | resume NAME +dally schedule QUEUE --payload JSON [--delay 10m] [--key K] +dally inspect ID +dally messages ls [--queue Q] [--status S] +dally dead retry QUEUE [ID...] +``` + +The client subcommands go through `dally-client`, never straight to storage. + +## Configuration + +A TOML file plus environment variables. `DALLY_*` variables override the file +(`DALLY_STORAGE_URL`, `DALLY_LISTEN`, ...). Storage is chosen by URL scheme: +`postgres://`, `sqlite://`, `redis://`. Migrations run on startup unless +`storage.migrate = false`. With no configuration, dally listens on +`127.0.0.1:7070` and stores data in `./dally.sqlite`. + +## Background tasks + +Each server runs three loops. All of them are safe to run on many servers at +once: + +- **push dispatcher**: delivers push queues, as described above. +- **cron ticker**: schedules recurring jobs through idempotency keys. +- **janitor**: prunes finished messages past their retention period. Expired + leases need no loop of their own, because they are reclaimed when a message + is leased. + +## Observability + +- Logs come from `tracing`, as JSON or pretty-printed text. +- Spans can be exported with OpenTelemetry (OTLP) behind the `otel` feature. +- Prometheus metrics at `/metrics`: messages scheduled, leased, acked, nacked + and dead per queue; queue depth by status; age of the oldest due message; + push latency and status codes. + +## Quality + +- Edition 2024, with the minimum supported Rust version (MSRV) set in + `Cargo.toml` and tested in CI. +- CI runs `cargo fmt --check`, `cargo clippy -- -D warnings`, unit tests, and + the conformance suite against real Postgres and Redis (service containers) + plus SQLite. +- Library crates use `thiserror` for errors and the binary uses `anyhow`. + There is no `unwrap()` outside tests. +- Every public item has rustdoc. `docs/` holds architecture notes, the + delivery semantics, and one page per backend describing its guarantees. +- Dual licensed under MIT or Apache-2.0. + +## Out of scope for now + +- The gRPC transport. The design leaves room for it. +- Hand-written SDKs for languages other than Rust. The OpenAPI spec lets people + generate clients in the meantime. +- API keys managed in the database. +- Workflows (job dependencies, chains). These may come later. + +## Moving from the prototype + +The prototype keeps its git history. What carries over is the idea from +[the original article][article]: a due-time column that doubles as the lock. +The rename from `kind` to `queue`, the lease token, statuses and per-queue +config replace the rest. There are no users yet, so the database schema is +written fresh rather than migrated. + +[article]: https://alexn.org/blog/2022/10/21/modeling-queue-for-delayed-messages-via-rdbms/ diff --git a/docs/openapi.json b/docs/openapi.json new file mode 100644 index 0000000..d9ff044 --- /dev/null +++ b/docs/openapi.json @@ -0,0 +1,2116 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "dally", + "description": "A job queue server. See docs/design.md and docs/semantics.md for how delivery works.", + "contact": { + "name": "Vlad Platon" + }, + "license": { + "name": "MIT OR Apache-2.0", + "identifier": "MIT OR Apache-2.0" + }, + "version": "0.1.0" + }, + "paths": { + "/healthz": { + "get": { + "tags": [ + "health" + ], + "summary": "The process is up.", + "operationId": "healthz", + "responses": { + "200": { + "description": "Up", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + } + }, + "security": [ + {} + ] + } + }, + "/readyz": { + "get": { + "tags": [ + "health" + ], + "summary": "The process is up and can reach storage.", + "operationId": "readyz", + "responses": { + "200": { + "description": "Ready", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "503": { + "description": "Storage is unavailable", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + } + }, + "security": [ + {} + ] + } + }, + "/v1/messages": { + "get": { + "tags": [ + "messages" + ], + "summary": "`GET /v1/messages?queue=&status=&before=&limit=`, newest first. Pass the\nresponse's `next` as `before` to get the following page.", + "operationId": "list", + "parameters": [ + { + "name": "queue", + "in": "query", + "description": "Only messages in this queue.", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "status", + "in": "query", + "description": "Only messages in this status.", + "required": false, + "schema": { + "$ref": "#/components/schemas/Status" + } + }, + { + "name": "before", + "in": "query", + "description": "Only messages older than this one: pass the previous page's `next`.", + "required": false, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "limit", + "in": "query", + "description": "At most this many messages, up to 500. Defaults to 50.", + "required": false, + "schema": { + "type": "integer", + "format": "int32", + "minimum": 0 + } + } + ], + "responses": { + "200": { + "description": "One page, newest first", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Page_Message" + } + } + } + }, + "400": { + "description": "Invalid input", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "401": { + "description": "Missing or unknown API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "503": { + "description": "Storage is unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + } + } + }, + "/v1/messages/{id}": { + "get": { + "tags": [ + "messages" + ], + "summary": "`GET /v1/messages/{id}`.", + "operationId": "get", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Message id", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The message", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Message" + } + } + } + }, + "400": { + "description": "Invalid input", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "401": { + "description": "Missing or unknown API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "503": { + "description": "Storage is unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + } + }, + "delete": { + "tags": [ + "messages" + ], + "summary": "`DELETE /v1/messages/{id}` cancels a scheduled message.", + "operationId": "cancel", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Message id", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "Cancelled", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Message" + } + } + } + }, + "400": { + "description": "Invalid input", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "401": { + "description": "Missing or unknown API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "409": { + "description": "The lease or status does not allow this", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "503": { + "description": "Storage is unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + } + }, + "patch": { + "tags": [ + "messages" + ], + "summary": "`PATCH /v1/messages/{id}` with `{\"delay\": \"1h\"}` or `{\"run_at\": \"...\"}`.\nAn empty object runs it now.", + "operationId": "reschedule", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Message id", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RescheduleBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Rescheduled", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Message" + } + } + } + }, + "400": { + "description": "Invalid input", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "401": { + "description": "Missing or unknown API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "409": { + "description": "The lease or status does not allow this", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "503": { + "description": "Storage is unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + } + } + }, + "/v1/messages/{id}/ack": { + "post": { + "tags": [ + "messages" + ], + "summary": "`POST /v1/messages/{id}/ack` with `{\"lease\": \"...\"}`.", + "operationId": "ack", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Message id", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AckBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Succeeded", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Message" + } + } + } + }, + "400": { + "description": "Invalid input", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "401": { + "description": "Missing or unknown API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "409": { + "description": "The lease or status does not allow this", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "503": { + "description": "Storage is unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + } + } + }, + "/v1/messages/{id}/nack": { + "post": { + "tags": [ + "messages" + ], + "summary": "`POST /v1/messages/{id}/nack` with `{\"lease\": \"...\", \"error\": \"...\",\n\"retry_in\": \"30s\"}`. Only `lease` is required.", + "operationId": "nack", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Message id", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NackRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Scheduled for a retry, or dead", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Message" + } + } + } + }, + "400": { + "description": "Invalid input", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "401": { + "description": "Missing or unknown API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "409": { + "description": "The lease or status does not allow this", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "503": { + "description": "Storage is unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + } + } + }, + "/v1/queues": { + "get": { + "tags": [ + "queues" + ], + "summary": "`GET /v1/queues`: every queue with its message counts.", + "operationId": "list", + "responses": { + "200": { + "description": "Every queue with its message counts", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/QueueList" + } + } + } + }, + "401": { + "description": "Missing or unknown API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "503": { + "description": "Storage is unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + } + } + }, + "/v1/queues/{queue}": { + "get": { + "tags": [ + "queues" + ], + "summary": "`GET /v1/queues/{queue}`: settings and message counts.", + "operationId": "get", + "parameters": [ + { + "name": "queue", + "in": "path", + "description": "Queue name", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Settings and message counts", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/QueueSummary" + } + } + } + }, + "400": { + "description": "Invalid input", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "401": { + "description": "Missing or unknown API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "503": { + "description": "Storage is unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + } + }, + "put": { + "tags": [ + "queues" + ], + "summary": "`PUT /v1/queues/{queue}`: creates the queue or replaces its settings.\nFields left out get their defaults, not their current values.", + "operationId": "put", + "parameters": [ + { + "name": "queue", + "in": "path", + "description": "Queue name", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/QueueSettings" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Created or updated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Queue" + } + } + } + }, + "400": { + "description": "Invalid input", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "401": { + "description": "Missing or unknown API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "403": { + "description": "Needs an admin key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "503": { + "description": "Storage is unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + } + } + }, + "/v1/queues/{queue}/dead/retry": { + "post": { + "tags": [ + "queues" + ], + "summary": "`POST /v1/queues/{queue}/dead/retry` with an optional `{\"ids\": [...]}`.\nWithout ids, retries every dead message in the queue.", + "operationId": "retry_dead", + "parameters": [ + { + "name": "queue", + "in": "path", + "description": "Queue name", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "description": "Optional; without ids, every dead message is retried", + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/RetryBody" + }, + { + "type": "null" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "How many messages were retried", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Retried" + } + } + } + }, + "400": { + "description": "Invalid input", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "401": { + "description": "Missing or unknown API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "403": { + "description": "Needs an admin key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "503": { + "description": "Storage is unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + } + } + }, + "/v1/queues/{queue}/messages": { + "get": { + "tags": [ + "messages" + ], + "summary": "`GET /v1/queues/{queue}/messages?status=&before=&limit=`.", + "operationId": "list_in_queue", + "parameters": [ + { + "name": "queue", + "in": "path", + "description": "Queue name", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "status", + "in": "query", + "description": "Only messages in this status.", + "required": false, + "schema": { + "$ref": "#/components/schemas/Status" + } + }, + { + "name": "before", + "in": "query", + "description": "Only messages older than this one: pass the previous page's `next`.", + "required": false, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "limit", + "in": "query", + "description": "At most this many messages, up to 500. Defaults to 50.", + "required": false, + "schema": { + "type": "integer", + "format": "int32", + "minimum": 0 + } + } + ], + "responses": { + "200": { + "description": "One page, newest first", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Page_Message" + } + } + } + }, + "400": { + "description": "Invalid input", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "401": { + "description": "Missing or unknown API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "503": { + "description": "Storage is unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + } + }, + "post": { + "tags": [ + "messages" + ], + "summary": "`POST /v1/queues/{queue}/messages` takes one message or an array of them.", + "description": "One message: `201 Created` with the message, or `200 OK` with the existing\nmessage if its idempotency key was already used.\n\nAn array: `200 OK` with `{\"messages\": [{\"created\": bool, \"message\": ...}]}`\nin the same order.", + "operationId": "schedule", + "parameters": [ + { + "name": "queue", + "in": "path", + "description": "Queue name", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScheduleBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "The existing message, if its idempotency key was already used; or the results of a batch", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ScheduleResponse" + } + } + } + }, + "201": { + "description": "Scheduled", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Message" + } + } + } + }, + "400": { + "description": "Invalid input", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "401": { + "description": "Missing or unknown API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "503": { + "description": "Storage is unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + } + } + }, + "/v1/queues/{queue}/pause": { + "post": { + "tags": [ + "queues" + ], + "summary": "`POST /v1/queues/{queue}/pause`.", + "operationId": "pause", + "parameters": [ + { + "name": "queue", + "in": "path", + "description": "Queue name", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Paused", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Queue" + } + } + } + }, + "400": { + "description": "Invalid input", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "401": { + "description": "Missing or unknown API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "403": { + "description": "Needs an admin key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "503": { + "description": "Storage is unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + } + } + }, + "/v1/queues/{queue}/poll": { + "post": { + "tags": [ + "messages" + ], + "summary": "`POST /v1/queues/{queue}/poll` with an optional body\n`{\"limit\": 10, \"wait\": \"20s\"}`.", + "operationId": "poll", + "parameters": [ + { + "name": "queue", + "in": "path", + "description": "Queue name", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "description": "Optional; defaults to one message and no waiting", + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/PollBody" + }, + { + "type": "null" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "Leased messages, possibly none", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Polled" + } + } + } + }, + "400": { + "description": "Invalid input", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "401": { + "description": "Missing or unknown API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "503": { + "description": "Storage is unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + } + } + }, + "/v1/queues/{queue}/resume": { + "post": { + "tags": [ + "queues" + ], + "summary": "`POST /v1/queues/{queue}/resume`.", + "operationId": "resume", + "parameters": [ + { + "name": "queue", + "in": "path", + "description": "Queue name", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Resumed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Queue" + } + } + } + }, + "400": { + "description": "Invalid input", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "401": { + "description": "Missing or unknown API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "403": { + "description": "Needs an admin key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "503": { + "description": "Storage is unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "AckBody": { + "type": "object", + "required": [ + "lease" + ], + "properties": { + "lease": { + "$ref": "#/components/schemas/LeaseToken", + "description": "The lease token from the poll." + } + }, + "additionalProperties": false + }, + "Backoff": { + "type": "object", + "description": "Exponential backoff with jitter: attempt `n` waits about\n`min(base * 2^(n - 1), cap)`, give or take 20%.", + "properties": { + "base": { + "type": "string", + "description": "The delay after the first failed attempt.", + "default": { + "nanos": 0, + "secs": 5 + }, + "example": "5s" + }, + "cap": { + "type": "string", + "description": "The longest delay between attempts.", + "default": { + "nanos": 0, + "secs": 3600 + }, + "example": "1h" + } + }, + "additionalProperties": false + }, + "Batch": { + "type": "object", + "required": [ + "messages" + ], + "properties": { + "messages": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Scheduled" + } + } + } + }, + "ErrorBody": { + "type": "object", + "description": "The error body every endpoint uses.", + "required": [ + "error" + ], + "properties": { + "error": { + "$ref": "#/components/schemas/ErrorDetail" + } + } + }, + "ErrorDetail": { + "type": "object", + "required": [ + "code", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "Stable, for programs: `invalid_input`, `queue_not_found`,\n`message_not_found`, `lease_mismatch`, `invalid_status`,\n`unauthorized`, `forbidden` or `storage_unavailable`." + }, + "message": { + "type": "string", + "description": "For people. May change between versions." + } + } + }, + "LeaseToken": { + "type": "string", + "description": "The token that proves a worker holds a message. It changes every time the\nmessage is leased, so a worker whose lease expired cannot ack a message\nthat was handed to someone else.", + "example": "0f8e2c4b9d1a4e7f8a3b5c6d7e8f9a0b" + }, + "Leased": { + "allOf": [ + { + "$ref": "#/components/schemas/Message", + "description": "The message." + }, + { + "type": "object", + "required": [ + "lease" + ], + "properties": { + "lease": { + "$ref": "#/components/schemas/LeaseToken", + "description": "The proof that this worker holds it." + } + } + } + ], + "description": "A message handed to a worker, with the token it needs to ack or nack it." + }, + "Message": { + "type": "object", + "description": "A message as stored.", + "required": [ + "id", + "queue", + "payload", + "status", + "priority", + "attempts", + "max_attempts", + "visibility_timeout", + "run_at", + "created_at", + "updated_at" + ], + "properties": { + "attempts": { + "type": "integer", + "format": "int32", + "description": "How many times it has been leased.", + "minimum": 0 + }, + "created_at": { + "type": "string", + "format": "date-time", + "description": "When it was scheduled." + }, + "finished_at": { + "type": [ + "string", + "null" + ], + "format": "date-time", + "description": "When it reached a finished status." + }, + "id": { + "$ref": "#/components/schemas/MessageId", + "description": "The message's id." + }, + "idempotency_key": { + "type": [ + "string", + "null" + ], + "description": "The key that prevents duplicates, if one was given." + }, + "last_error": { + "type": [ + "string", + "null" + ], + "description": "The error reported by the last failed attempt." + }, + "lease_expires_at": { + "type": [ + "string", + "null" + ], + "format": "date-time", + "description": "When the current lease expires, while it is running." + }, + "max_attempts": { + "type": "integer", + "format": "int32", + "description": "How many attempts it gets before it is marked dead.", + "minimum": 0 + }, + "payload": { + "description": "What the worker gets." + }, + "priority": { + "type": "integer", + "format": "int32", + "description": "Higher priorities are delivered first." + }, + "queue": { + "$ref": "#/components/schemas/QueueName", + "description": "The queue it belongs to." + }, + "run_at": { + "type": "string", + "format": "date-time", + "description": "When it is next due." + }, + "status": { + "$ref": "#/components/schemas/Status", + "description": "Where it is in its lifecycle." + }, + "updated_at": { + "type": "string", + "format": "date-time", + "description": "When it last changed." + }, + "visibility_timeout": { + "type": "string", + "description": "How long each lease lasts.", + "example": "30s" + } + } + }, + "MessageId": { + "type": "string", + "format": "uuid", + "description": "A message id. Ids are UUIDv7, so sorting them sorts messages by creation\ntime." + }, + "NackRequest": { + "type": "object", + "description": "What a worker reports when an attempt fails.", + "required": [ + "lease" + ], + "properties": { + "error": { + "type": [ + "string", + "null" + ], + "description": "What went wrong. Shown in the UI and kept on the message." + }, + "lease": { + "$ref": "#/components/schemas/LeaseToken", + "description": "The lease that proves the worker holds the message." + }, + "retry_in": { + "type": [ + "string", + "null" + ], + "description": "Retry after this delay instead of the queue's backoff.", + "example": "30s" + } + }, + "additionalProperties": false + }, + "Page_Message": { + "type": "object", + "description": "One page of a listing, newest first.", + "required": [ + "items" + ], + "properties": { + "items": { + "type": "array", + "items": { + "type": "object", + "description": "A message as stored.", + "required": [ + "id", + "queue", + "payload", + "status", + "priority", + "attempts", + "max_attempts", + "visibility_timeout", + "run_at", + "created_at", + "updated_at" + ], + "properties": { + "attempts": { + "type": "integer", + "format": "int32", + "description": "How many times it has been leased.", + "minimum": 0 + }, + "created_at": { + "type": "string", + "format": "date-time", + "description": "When it was scheduled." + }, + "finished_at": { + "type": [ + "string", + "null" + ], + "format": "date-time", + "description": "When it reached a finished status." + }, + "id": { + "$ref": "#/components/schemas/MessageId", + "description": "The message's id." + }, + "idempotency_key": { + "type": [ + "string", + "null" + ], + "description": "The key that prevents duplicates, if one was given." + }, + "last_error": { + "type": [ + "string", + "null" + ], + "description": "The error reported by the last failed attempt." + }, + "lease_expires_at": { + "type": [ + "string", + "null" + ], + "format": "date-time", + "description": "When the current lease expires, while it is running." + }, + "max_attempts": { + "type": "integer", + "format": "int32", + "description": "How many attempts it gets before it is marked dead.", + "minimum": 0 + }, + "payload": { + "description": "What the worker gets." + }, + "priority": { + "type": "integer", + "format": "int32", + "description": "Higher priorities are delivered first." + }, + "queue": { + "$ref": "#/components/schemas/QueueName", + "description": "The queue it belongs to." + }, + "run_at": { + "type": "string", + "format": "date-time", + "description": "When it is next due." + }, + "status": { + "$ref": "#/components/schemas/Status", + "description": "Where it is in its lifecycle." + }, + "updated_at": { + "type": "string", + "format": "date-time", + "description": "When it last changed." + }, + "visibility_timeout": { + "type": "string", + "description": "How long each lease lasts.", + "example": "30s" + } + } + }, + "description": "The items on this page." + }, + "next": { + "oneOf": [ + { + "$ref": "#/components/schemas/MessageId", + "description": "The cursor for the next page, if there is one." + }, + { + "type": "null" + } + ] + } + } + }, + "PollBody": { + "type": "object", + "properties": { + "limit": { + "type": [ + "integer", + "null" + ], + "format": "int32", + "description": "Lease at most this many messages, 1 to 100. Defaults to 1.", + "default": null, + "minimum": 0 + }, + "wait": { + "type": [ + "string", + "null" + ], + "description": "If nothing is due, wait up to this long (at most 30s) for a message.", + "default": null, + "example": "20s" + } + }, + "additionalProperties": false + }, + "Polled": { + "type": "object", + "required": [ + "messages" + ], + "properties": { + "messages": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Leased" + } + } + } + }, + "PushSettings": { + "type": "object", + "description": "Where and how to push messages from a queue.", + "required": [ + "url" + ], + "properties": { + "concurrency": { + "type": "integer", + "format": "int32", + "description": "How many requests to have in flight at once, per server.", + "minimum": 0 + }, + "secret": { + "type": [ + "string", + "null" + ], + "description": "When set, each request is signed with HMAC-SHA256 using this secret." + }, + "timeout": { + "type": "string", + "description": "How long to wait for the endpoint to respond.", + "example": "30s" + }, + "url": { + "type": "string", + "description": "The endpoint that receives each message as a POST request." + } + }, + "additionalProperties": false + }, + "Queue": { + "allOf": [ + { + "$ref": "#/components/schemas/QueueSettings", + "description": "How messages in this queue are delivered." + }, + { + "type": "object", + "required": [ + "name", + "created_at", + "updated_at" + ], + "properties": { + "created_at": { + "type": "string", + "format": "date-time", + "description": "When the queue was created." + }, + "name": { + "$ref": "#/components/schemas/QueueName", + "description": "The queue's name." + }, + "updated_at": { + "type": "string", + "format": "date-time", + "description": "When the settings last changed." + } + } + } + ], + "description": "A queue as stored, with its settings." + }, + "QueueList": { + "type": "object", + "required": [ + "queues" + ], + "properties": { + "queues": { + "type": "array", + "items": { + "$ref": "#/components/schemas/QueueSummary" + } + } + } + }, + "QueueName": { + "type": "string", + "description": "The name of a queue: 1 to 100 ASCII letters, digits, `-`, `_` or `.`.\n\nThe character set is deliberately small so names are safe in URLs, Redis\nkeys and metric labels without escaping.", + "example": "emails", + "pattern": "^[A-Za-z0-9._-]{1,100}$" + }, + "QueueSettings": { + "type": "object", + "description": "The settings of a queue. Every field has a default, so a queue created\nimplicitly by scheduling a message works without configuration.", + "properties": { + "backoff": { + "$ref": "#/components/schemas/Backoff", + "description": "How long to wait before retrying a failed attempt.", + "default": { + "base": "5s", + "cap": "1h" + } + }, + "max_attempts": { + "type": "integer", + "format": "int32", + "description": "How many times a message is attempted before it is marked dead.", + "default": 5, + "minimum": 0 + }, + "paused": { + "type": "boolean", + "description": "A paused queue accepts new messages but delivers none.", + "default": false + }, + "push": { + "oneOf": [ + { + "$ref": "#/components/schemas/PushSettings", + "description": "When set, the server delivers messages by POSTing them to this endpoint\ninstead of waiting for workers to poll." + }, + { + "type": "null" + } + ], + "default": null + }, + "retention": { + "type": "string", + "description": "How long finished messages are kept before they are deleted. This is\nalso how long idempotency keys are remembered.", + "default": { + "nanos": 0, + "secs": 604800 + }, + "example": "7days" + }, + "visibility_timeout": { + "type": "string", + "description": "How long a lease lasts. A message that is not acked or nacked in this\ntime is handed to another worker.", + "default": { + "nanos": 0, + "secs": 30 + }, + "example": "30s" + } + }, + "additionalProperties": false + }, + "QueueStats": { + "type": "object", + "description": "How many messages a queue holds in each status.", + "required": [ + "scheduled", + "running", + "succeeded", + "cancelled", + "dead" + ], + "properties": { + "cancelled": { + "type": "integer", + "format": "int64", + "description": "Cancelled before running.", + "minimum": 0 + }, + "dead": { + "type": "integer", + "format": "int64", + "description": "Out of attempts.", + "minimum": 0 + }, + "running": { + "type": "integer", + "format": "int64", + "description": "Leased by a worker.", + "minimum": 0 + }, + "scheduled": { + "type": "integer", + "format": "int64", + "description": "Waiting to run, now or later.", + "minimum": 0 + }, + "succeeded": { + "type": "integer", + "format": "int64", + "description": "Finished successfully.", + "minimum": 0 + } + } + }, + "QueueSummary": { + "allOf": [ + { + "$ref": "#/components/schemas/Queue", + "description": "The queue." + }, + { + "type": "object", + "required": [ + "stats" + ], + "properties": { + "stats": { + "$ref": "#/components/schemas/QueueStats", + "description": "Its message counts." + } + } + } + ], + "description": "A queue together with its message counts." + }, + "RescheduleBody": { + "type": "object", + "properties": { + "delay": { + "type": [ + "string", + "null" + ], + "description": "Run after this delay. Cannot be combined with `run_at`.", + "example": "1h" + }, + "run_at": { + "type": [ + "string", + "null" + ], + "format": "date-time", + "description": "Run at this time. With neither field, the message runs now." + } + }, + "additionalProperties": false + }, + "Retried": { + "type": "object", + "required": [ + "retried" + ], + "properties": { + "retried": { + "type": "integer", + "format": "int64", + "minimum": 0 + } + } + }, + "RetryBody": { + "type": "object", + "properties": { + "ids": { + "type": [ + "array", + "null" + ], + "items": { + "type": "string", + "format": "uuid" + }, + "description": "Only these messages. Without it, every dead message in the queue.", + "default": null + } + }, + "additionalProperties": false + }, + "ScheduleBody": { + "oneOf": [ + { + "$ref": "#/components/schemas/ScheduleRequest", + "description": "A single message." + }, + { + "type": "array", + "items": { + "$ref": "#/components/schemas/ScheduleRequest" + }, + "description": "A batch." + } + ], + "description": "One message, or an array of up to 100." + }, + "ScheduleRequest": { + "type": "object", + "description": "A request to schedule a message, as clients send it.", + "required": [ + "payload" + ], + "properties": { + "delay": { + "type": [ + "string", + "null" + ], + "description": "Run after this delay. Cannot be combined with `run_at`.", + "example": "10m" + }, + "idempotency_key": { + "type": [ + "string", + "null" + ], + "description": "Scheduling twice with the same key in the same queue creates only one\nmessage." + }, + "max_attempts": { + "type": [ + "integer", + "null" + ], + "format": "int32", + "description": "Overrides the queue's `max_attempts` for this message.", + "minimum": 0 + }, + "payload": { + "description": "What the worker gets." + }, + "priority": { + "type": "integer", + "format": "int32", + "description": "Higher priorities are delivered first. Defaults to 0." + }, + "run_at": { + "type": [ + "string", + "null" + ], + "format": "date-time", + "description": "Run at this time. Cannot be combined with `delay`." + }, + "visibility_timeout": { + "type": [ + "string", + "null" + ], + "description": "Overrides the queue's `visibility_timeout` for this message.", + "example": "2m" + } + }, + "additionalProperties": false + }, + "ScheduleResponse": { + "oneOf": [ + { + "$ref": "#/components/schemas/Message", + "description": "The stored message." + }, + { + "$ref": "#/components/schemas/Batch", + "description": "One result per scheduled message." + } + ], + "description": "The message for a single schedule, or the results in order for a batch." + }, + "Scheduled": { + "type": "object", + "description": "The result of scheduling one message.", + "required": [ + "message", + "created" + ], + "properties": { + "created": { + "type": "boolean", + "description": "False when a message with the same idempotency key already existed." + }, + "message": { + "$ref": "#/components/schemas/Message", + "description": "The stored message: the new one, or the existing one with the same\nidempotency key." + } + } + }, + "Status": { + "type": "string", + "description": "Where a message is in its lifecycle. See `docs/design.md` for the diagram.", + "enum": [ + "scheduled", + "running", + "succeeded", + "cancelled", + "dead" + ] + } + }, + "securitySchemes": { + "bearer": { + "type": "http", + "scheme": "bearer" + } + } + }, + "security": [ + { + "bearer": [] + } + ], + "tags": [ + { + "name": "messages", + "description": "Scheduling, leasing and inspecting messages" + }, + { + "name": "queues", + "description": "Queue settings and dead messages" + }, + { + "name": "health", + "description": "Probes for load balancers and orchestrators" + } + ] +} diff --git a/docs/operations.md b/docs/operations.md new file mode 100644 index 0000000..99c3001 --- /dev/null +++ b/docs/operations.md @@ -0,0 +1,100 @@ +# Running dally in production + +## Storage + +Pick a backend by URL in `storage.url` (or `DALLY_STORAGE_URL`): + +| Backend | Good for | Notes | +|------------|---------------------------------------|----------------------------------------| +| PostgreSQL | Production, several servers | 13 or later. The reference backend. | +| SQLite | Local development, one small server | One server process per file. See [backends/sqlite.md](backends/sqlite.md). | +| Redis | Teams that already run Redis | Needs `appendonly yes`. See [backends/redis.md](backends/redis.md). | + +Migrations run on startup. To run them as a separate deploy step instead, +start one server with migrations on, and the rest with +`storage.migrate = false`. + +## API keys + +Auth is off until you configure a key. With auth off, anyone who can reach +the server can read and change every queue, and dally logs a warning at +startup if it listens on anything other than localhost. + +```toml +[[auth.keys]] +name = "web-app" +role = "client" # schedule, poll, ack, nack, read +key_env = "DALLY_WEB_KEY" # read the key from the environment + +[[auth.keys]] +name = "ops" +role = "admin" # also change queues, pause, retry dead messages +key_env = "DALLY_ADMIN_KEY" +``` + +Clients send `Authorization: Bearer `. Keys must be at least 16 +characters; `openssl rand -hex 32` makes a good one. `key = "..."` works too, +but keeps the secret in the file. Key names show up in logs and traces; keys +never do. + +`/healthz` and `/readyz` are always open, so load balancers can use them. +`/metrics` is open unless `auth.protect_metrics = true`, in which case it needs +a key of any role. + +## Health checks + +- `GET /healthz` returns 200 while the process is up. Use it for liveness. +- `GET /readyz` returns 200 when storage answers, and 503 otherwise. Use it for + readiness, so traffic only goes to servers that can do work. + +## Metrics + +`GET /metrics` serves Prometheus metrics: + +| Metric | Type | Labels | +|-----------------------------------------|-----------|---------------------------| +| `dally_messages_scheduled_total` | counter | `queue` | +| `dally_messages_leased_total` | counter | `queue` | +| `dally_messages_acked_total` | counter | `queue` | +| `dally_messages_nacked_total` | counter | `queue` | +| `dally_messages_dead_total` | counter | `queue` | +| `dally_http_requests_total` | counter | `method`, `route`, `status` | +| `dally_http_request_duration_seconds` | histogram | `method`, `route` | +| `dally_queue_messages` | gauge | `queue`, `status` | +| `dally_queue_oldest_due_seconds` | gauge | `queue` | + +Counters are per server, so `sum` them across servers. The gauges read shared +storage, so every server reports the same values; use `max`. They are cached +for 5 seconds. `dally_messages_dead_total` counts messages that died on a nack; +messages whose last lease expired show up in `dally_queue_messages{status="dead"}`. +The Redis backend does not report `dally_queue_oldest_due_seconds`. + +Two alerts worth having: + +```yaml +- alert: DallyQueueFallingBehind + expr: max by (queue) (dally_queue_oldest_due_seconds) > 300 + for: 10m +- alert: DallyDeadMessages + expr: max by (queue) (dally_queue_messages{status="dead"}) > 0 +``` + +## Tracing + +Build with the `otel` feature (`cargo install dally --features otel`) and set +`OTEL_EXPORTER_OTLP_ENDPOINT`, for example `http://otel-collector:4318`. Spans +go out over OTLP/HTTP with protobuf. The standard `OTEL_*` variables apply; +the service name defaults to `dally`. + +## Logs + +Logs go to stderr. `--log-format json` (or `DALLY_LOG_FORMAT=json`, the default +in the Docker image) writes one JSON object per line. `RUST_LOG` sets the +level, for example `RUST_LOG=dally_server=debug,info`. + +## Shutting down + +On SIGTERM or Ctrl-C, dally stops accepting connections, lets in-flight +requests finish (long polls end at their wait deadline, at most 30 seconds), +waits for push requests in flight, and exits. Give it at least 35 seconds +before a hard kill, for example `terminationGracePeriodSeconds: 40`. diff --git a/docs/push.md b/docs/push.md new file mode 100644 index 0000000..49be06e --- /dev/null +++ b/docs/push.md @@ -0,0 +1,210 @@ +# Push delivery + +With push delivery, dally sends each message to your app as an HTTP request, +so you don't need to run a worker. A background job handler becomes one more +endpoint in the web app you already have. + +## Setting it up + +Give a queue a push endpoint, in the config file: + +```toml +[queues.emails.push] +url = "https://app.example.com/jobs/emails" +secret = "a long random string" # optional, but recommended +timeout = "30s" # how long to wait for a response +concurrency = 8 # requests in flight at once, per server +``` + +or at runtime through the API: + +```sh +curl -X PUT localhost:7070/v1/queues/emails \ + -d '{"push": {"url": "https://app.example.com/jobs/emails", "secret": "..."}}' +``` + +Changes made through the API are picked up within a few seconds. Pausing the +queue stops deliveries until it is resumed. + +## What your endpoint receives + +```http +POST /jobs/emails HTTP/1.1 +Content-Type: application/json +Dally-Message-Id: 0193b0f2-4c1e-7d2a-9f3e-6a1b2c3d4e5f +Dally-Queue: emails +Dally-Attempt: 1 +Dally-Signature: t=1763550000,v1=6f1c... + +{"to": "ana@example.com", "template": "welcome"} +``` + +The body is the message's payload, exactly as it was scheduled. +`Dally-Attempt` counts from 1, so a handler can tell a retry from a first try. + +## What your endpoint should return + +- **Any 2xx** means the work is done, and the message is acked. +- **Anything else**, a timeout or a connection error means it failed. dally + retries with the queue's backoff and marks the message dead after + `max_attempts`. The status and the first 1 KiB of the response body become + the message's `last_error`, so a short explanation in the body shows up in + the API and the UI. +- **429 or 503 with `Retry-After: `** asks dally to retry after that + delay instead of the usual backoff. + +Respond within the queue's `timeout`, and keep it below the queue's +`visibility_timeout`. Otherwise the message can be delivered again while the +first request is still running. For long jobs, accept the request, do the work +elsewhere, and schedule a follow-up message when it is done. + +## Delivered at least once + +Push has the same guarantee as polling: every message arrives at least once, +and sometimes more than once (see [semantics.md](semantics.md)). If your +handler finishes the work but the response never reaches dally, the message is +delivered again. Use `Dally-Message-Id` to recognise duplicates. + +## Verifying the signature + +When the queue has a `secret`, every request carries a `Dally-Signature` +header: + +```text +Dally-Signature: t=,v1=."> +``` + +To verify it: + +1. Read the raw request body before parsing it. Any change, even + re-serializing the JSON, breaks the signature. +2. Compute the HMAC-SHA256 of the timestamp, a dot and the body, keyed with + the secret. +3. Compare it with each `v1` value in constant time. +4. Reject timestamps more than five minutes from your clock. That stops a + captured request from being replayed later. + +### Rust + +`dally-server` exports the same function dally uses to check its own tests: + +```rust +use std::time::Duration; + +use dally_server::signature; + +let now = chrono::Utc::now().timestamp(); +signature::verify(secret, header, &body, now, Duration::from_secs(300))?; +``` + +### Python + +```python +import hashlib +import hmac +import time + + +def verify(secret: bytes, header: str, body: bytes, tolerance: int = 300) -> bool: + timestamp, signatures = None, [] + for part in header.split(","): + key, _, value = part.strip().partition("=") + if key == "t": + timestamp = value + elif key == "v1": + signatures.append(value) + + if timestamp is None or not timestamp.isdigit(): + return False + if abs(time.time() - int(timestamp)) > tolerance: + return False + + expected = hmac.new(secret, timestamp.encode() + b"." + body, hashlib.sha256).hexdigest() + return any(hmac.compare_digest(expected, signature) for signature in signatures) +``` + +### TypeScript (Node) + +```ts +import { createHmac, timingSafeEqual } from "node:crypto"; + +export function verify( + secret: string, + header: string, + body: Buffer, + toleranceSeconds = 300, +): boolean { + let timestamp: string | undefined; + const signatures: string[] = []; + for (const part of header.split(",")) { + const [key, value] = part.trim().split("=", 2); + if (key === "t") timestamp = value; + else if (key === "v1" && value) signatures.push(value); + } + + if (!timestamp || !/^\d+$/.test(timestamp)) return false; + if (Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranceSeconds) return false; + + const expected = createHmac("sha256", secret).update(`${timestamp}.`).update(body).digest(); + return signatures.some((signature) => { + const given = Buffer.from(signature, "hex"); + return given.length === expected.length && timingSafeEqual(given, expected); + }); +} +``` + +With Express, use `express.raw({ type: "application/json" })` on the route so +`req.body` is the raw `Buffer`. + +### Go + +```go +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "strconv" + "strings" + "time" +) + +func Verify(secret []byte, header string, body []byte, tolerance time.Duration) bool { + var timestamp string + var signatures []string + for _, part := range strings.Split(header, ",") { + key, value, _ := strings.Cut(strings.TrimSpace(part), "=") + switch key { + case "t": + timestamp = value + case "v1": + signatures = append(signatures, value) + } + } + + seconds, err := strconv.ParseInt(timestamp, 10, 64) + if err != nil { + return false + } + if age := time.Since(time.Unix(seconds, 0)); age > tolerance || age < -tolerance { + return false + } + + mac := hmac.New(sha256.New, secret) + mac.Write([]byte(timestamp + ".")) + mac.Write(body) + expected := mac.Sum(nil) + for _, signature := range signatures { + if given, err := hex.DecodeString(signature); err == nil && hmac.Equal(given, expected) { + return true + } + } + return false +} +``` + +## Rotating the secret + +The header format allows several `v1` values, and every verifier above accepts +a match on any of them. To rotate without downtime, deploy receivers that +accept both the old and the new secret, then change the queue's `secret`, and +finally remove the old one from the receivers. diff --git a/docs/semantics.md b/docs/semantics.md new file mode 100644 index 0000000..4152de9 --- /dev/null +++ b/docs/semantics.md @@ -0,0 +1,80 @@ +# Delivery semantics + +This page describes what dally promises about delivery, and what it does not. +It applies to every storage backend; the backend pages describe their +durability. + +## At least once + +Every message is delivered at least once, unless it is cancelled first. It may +be delivered more than once. That happens when: + +1. **The worker is slower than the visibility timeout.** The lease expires and + another worker gets the message while the first one is still working on it. + The first worker's ack then fails with `409 lease_mismatch`. +2. **The ack is lost.** The worker finishes, but the ack request fails, or the + worker crashes before sending it. The lease expires and the message is + delivered again. +3. **A push endpoint does the work but responds too slowly, or with a non-2xx + status.** dally counts that as a failure and retries. + +dally cannot tell these cases apart from a worker that failed, so it retries. +The alternative, at most once, loses work whenever a worker crashes. + +## Making handlers safe to run twice + +Pick the cheapest that fits: + +- **Naturally idempotent work.** "Set the user's plan to pro" is safe to repeat; + "add 10 credits" is not. Prefer the first kind where you can. +- **A done marker.** Store the message id when the work is done, in the same + transaction as the work, and skip messages whose id is already stored. +- **Idempotency keys downstream.** Pass the message id as the idempotency key + to the payment provider, email service or API you call. + +## Leases + +A poll hands out each message with a lease token. The token is valid until the +message's visibility timeout runs out (30 seconds by default, configurable per +queue and per message). Only the holder of the current token can ack or nack +the message. Each new lease gets a new token, so a worker whose lease expired +can never ack a message that has since gone to someone else. + +An ack after the lease expired still succeeds if nobody else has leased the +message in the meantime, because the work is done and redoing it helps nobody. + +## Retries and dead messages + +- A **nack** ends the attempt. The message is retried after the queue's backoff + (5 seconds, doubling each time, capped at 1 hour, with ±20% jitter), or after + the `retry_in` the worker asked for. +- An **expired lease** ends the attempt too, but the message can be leased + again right away: the worker most likely crashed, so waiting would only add + latency. +- After `max_attempts` attempts (5 by default), the message becomes **dead**. + Dead messages keep their last error, stay visible in the API and the UI, and + can be retried with `POST /v1/queues/{queue}/dead/retry`. + +## Ordering + +When a poll finds several due messages, the highest `priority` goes first, +then the earliest `run_at`. That is a best effort, not a guarantee: +concurrent workers, retries and expired leases all reorder messages. If you +need strict ordering, a job queue is the wrong tool. + +## Idempotency keys + +Scheduling with an `idempotency_key` that already exists in the queue does not +create a second message. You get the existing one back with `200 OK` instead of +`201 Created`. Keys are remembered for as long as the message is stored: until +it finishes and the queue's retention period (7 days by default) has passed. + +Use them whenever a retried request could schedule the same job twice, which is +almost always: `"welcome-email:user-42"`, `"invoice:2026-11:customer-7"`. + +## Time + +Due times are measured by the storage clock (PostgreSQL's `now()`, Redis's +`TIME`), not by each server's clock, so several servers agree on what is due. +A message is delivered at or after its `run_at`, usually within a second +because that is how often waiting polls check for messages that became due. diff --git a/migrations/20240513171635_create_tables.sql b/migrations/20240513171635_create_tables.sql deleted file mode 100644 index bff250e..0000000 --- a/migrations/20240513171635_create_tables.sql +++ /dev/null @@ -1,20 +0,0 @@ -CREATE TABLE delayed_queue ( - pkey VARCHAR(200) NOT NULL, - pkind VARCHAR(100) NOT NULL, - payload BYTEA NOT NULL, - scheduled_at BIGINT NOT NULL, - scheduled_at_initially BIGINT NOT NULL, - created_at BIGINT NOT NULL, - PRIMARY KEY (pkey, pkind) -); - -CREATE TABLE webhooks ( - id VARCHAR(200) NOT NULL, - url VARCHAR(200) NOT NULL, - fails_count INT NOT NULL, - created_at BIGINT NOT NULL, - updated_at BIGINT NOT NULL, - PRIMARY KEY (id) -); - -CREATE INDEX delayed_queue__kind_scheduled_at_index ON delayed_queue (pkind, scheduled_at); \ No newline at end of file diff --git a/src/delayed_queue.rs b/src/delayed_queue.rs deleted file mode 100644 index d57063e..0000000 --- a/src/delayed_queue.rs +++ /dev/null @@ -1,152 +0,0 @@ -use anyhow::Result; -use sqlx::postgres::PgPool; - -use crate::message::Message; - -#[derive(Clone)] -pub struct DelayedQueuePostgres { - pool: PgPool, -} - -impl DelayedQueuePostgres { - pub async fn new(pool: PgPool) -> Result { - Ok(Self { pool }) - } - - pub async fn get_messages(self: &Self) -> Result> { - let messages = sqlx::query!( - r#" - SELECT pkey, pkind, payload, scheduled_at, scheduled_at_initially, created_at FROM delayed_queue ORDER BY created_at - "# - ) - .map(|row| { - Ok(Message { - key: row.pkey.clone(), - kind: row.pkind.clone(), - payload: row.payload.clone(), - scheduled_at: row.scheduled_at as u64, - scheduled_at_initially: row.scheduled_at_initially as u64, - created_at: row.created_at as u64, - }) - }) - .fetch_all(&self.pool) - .await?; - - messages.into_iter().collect() - } - - pub async fn poll(self: &Self, now: u64, kind: Option<&str>) -> Result> { - Box::pin(async move { - let message_opt = self.get_scheduled(now, kind).await?; - - match message_opt { - Some(message) => { - let lock_result = self.lock(&message.key, kind, message.scheduled_at).await?; - - if lock_result { - Ok(vec![message] - .into_iter() - .chain(self.poll(now, kind).await?.into_iter()) - .collect()) - } else { - Ok(self.poll(now, kind).await?) - } - } - None => Ok(Vec::new()), - } - }) - .await - } - - pub async fn ack(self: &Self, key: &str, kind: &str, created_at: &u64) -> Result { - let res = sqlx::query!( - r#" - DELETE FROM delayed_queue - WHERE - pkey = $1 AND pkind = $2 AND created_at = $3 - "#, - key, - kind, - *created_at as i64, - ) - .execute(&self.pool) - .await?; - - Ok(res.rows_affected()) - } - - pub async fn schedule_message(self: &Self, message: &Message) -> Result<()> { - sqlx::query!( - r#" - INSERT INTO delayed_queue - (pkey, pkind, payload, scheduled_at, scheduled_at_initially, created_at) - VALUES ($1, $2, $3, $4, $5, $6) - "#, - message.key, - message.kind, - message.payload, - message.scheduled_at as i64, - message.scheduled_at_initially as i64, - message.created_at as i64 - ) - .execute(&self.pool) - .await?; - - Ok(()) - } - - async fn get_scheduled(self: &Self, now: u64, kind: Option<&str>) -> Result> { - let result = sqlx::query!( - r#" - SELECT pkey, pkind, payload, scheduled_at, created_at - FROM delayed_queue - WHERE - (CASE - WHEN $2 != '' THEN pkind = $2 AND scheduled_at <= $1 - ELSE scheduled_at <= $1 - END) - ORDER BY scheduled_at - "#, - now as i64, - kind - ) - .map(|row| Message { - key: row.pkey.clone(), - kind: row.pkind.clone(), - payload: row.payload.clone(), - scheduled_at: row.scheduled_at as u64, - scheduled_at_initially: row.scheduled_at as u64, - created_at: row.created_at as u64, - }) - .fetch_optional(&self.pool) - .await?; - - Ok(result) - } - - async fn lock(self: &Self, key: &str, kind: Option<&str>, scheduled_at: u64) -> Result { - let result = sqlx::query!( - r#" - UPDATE delayed_queue - SET - scheduled_at = $4 - WHERE - ( - CASE - WHEN $2 != '' THEN pkey = $1 AND pkind = $2 AND scheduled_at = $3 - ELSE pkey = $1 AND scheduled_at = $3 - END - ) - ; - "#, - key, - kind, - scheduled_at as i64, - (scheduled_at as i64) + 5 // retry interval - ) - .execute(&self.pool) - .await?; - - Ok(result.rows_affected() == 1) - } -} diff --git a/src/http_server.rs b/src/http_server.rs deleted file mode 100644 index c5375b5..0000000 --- a/src/http_server.rs +++ /dev/null @@ -1,162 +0,0 @@ -use actix_web::body::BoxBody; -use actix_web::http::header::ContentType; -use actix_web::middleware::Logger; -use derive_more::{Display, Error}; -use reqwest::StatusCode; -use serde::Deserialize; -use std::sync::{Arc, Mutex}; -use std::time::SystemTime; - -use crate::delayed_queue::DelayedQueuePostgres; -use crate::message::Message; -use crate::webhooks::{Webhook, WebhooksPostgres}; - -use actix_web::{error, web, App, HttpRequest, HttpResponse, HttpServer, Responder}; - -pub struct DelayedQueueHttpServer {} - -#[derive(Deserialize)] -struct AckData { - key: String, - kind: String, - created_at: u64, -} - -#[derive(Deserialize)] -struct CreateWebhook { - url: String, -} - -impl CreateWebhook { - fn to_webhook(&self) -> Webhook { - Webhook::from_url(self.url.clone()) - } -} - -impl DelayedQueueHttpServer { - pub fn new() -> Self { - Self {} - } - - pub async fn start( - &self, - delayed_queue: &DelayedQueuePostgres, - webhooks: &WebhooksPostgres, - ) -> std::io::Result<()> { - let delayed_queue = web::Data::new(Arc::new(Mutex::new(delayed_queue.clone()))); - let hooks: web::Data>> = - web::Data::new(Arc::new(Mutex::new(webhooks.clone()))); - - println!("Starting HTTP server on port 9876"); - HttpServer::new(move || { - App::new() - .wrap(Logger::default()) - .app_data(delayed_queue.clone()) - .app_data(hooks.clone()) - .app_data(hooks.clone()) - .route("/get_messages", web::get().to(Self::get_messages)) - .route("/schedule_message", web::post().to(Self::schedule_message)) - .route("/poll/{kind}", web::get().to(Self::poll)) - .route("/webhooks", web::post().to(Self::register_webhook)) - .route("/echo", web::post().to(Self::echo)) - .route("/ack", web::post().to(Self::ack)) - }) - .bind("0.0.0.0:9876")? - .run() - .await - } - - // TODO: Get rid of the unwrap calls - async fn get_messages(data: web::Data>>) -> impl Responder { - let messages = data.lock().unwrap().get_messages().await.unwrap(); - format!("{:?}", messages) - } - - // TODO: Get rid of the unwrap calls - async fn schedule_message(data: web::Data>>) -> impl Responder { - let message = Message::sample(); - data.lock() - .unwrap() - .schedule_message(&message) - .await - .unwrap(); - format!("{:?}", message) - } - - async fn poll( - kind: web::Path, - data: web::Data>>, - ) -> impl Responder { - let now: u64 = SystemTime::now() - .duration_since(SystemTime::UNIX_EPOCH) - .unwrap() - .as_secs(); - - let res = data.lock().unwrap().poll(now, Some(&kind)).await; - - format!("{:?}", res) - } - - async fn ack( - data: web::Data>>, - ack_data: web::Json, - ) -> impl Responder { - let ack_data = ack_data.into_inner(); - data.lock() - .unwrap() - .ack(&ack_data.key, &ack_data.kind, &ack_data.created_at) - .await - .unwrap(); - format!("Acked") - } - - async fn register_webhook( - data: web::Data>>, - webhook: web::Json, - ) -> Result { - let webhook = webhook.into_inner().to_webhook(); - data.lock() - .unwrap() - .create(&webhook) - .await - .map_err(|_err_| AppError::InternalError); - Ok(webhook) - } - - async fn echo(req: web::Bytes) -> impl Responder { - let body_string = String::from_utf8(req.to_vec()).unwrap(); - println!("-------------- ECHO: {:?}", body_string); - format!("Ok") - } -} - -#[derive(Debug, Display, Error)] - -enum AppError { - #[display(fmt = "An internal error occurred. Please try again later.")] - InternalError, -} - -impl error::ResponseError for AppError { - fn error_response(&self) -> HttpResponse { - HttpResponse::build(self.status_code()).body(self.to_string()) - } - - fn status_code(&self) -> reqwest::StatusCode { - match *self { - AppError::InternalError => StatusCode::INTERNAL_SERVER_ERROR, - } - } -} - -impl Responder for Webhook { - type Body = BoxBody; - - fn respond_to(self, _req: &HttpRequest) -> HttpResponse { - let body = serde_json::to_string(&self).unwrap(); - - HttpResponse::Ok() - .content_type(ContentType::json()) - .body(body) - } -} diff --git a/src/main.rs b/src/main.rs deleted file mode 100644 index 1fa704a..0000000 --- a/src/main.rs +++ /dev/null @@ -1,126 +0,0 @@ -use anyhow::Result; -use clap::{command, Command}; -use delayed_queue::DelayedQueuePostgres; -use http_server::DelayedQueueHttpServer; -use std::{env, sync::Arc}; -use webhooks::WebhooksPostgres; - -use crate::{message::Message, webhooks::Webhook}; - -mod delayed_queue; -mod http_server; -mod message; -mod webhooks; - -#[tokio::main(flavor = "current_thread")] -async fn main() -> Result<()> { - let database_url = "postgres://postgres:password@localhost:5432/delayed-queue"; - - let pg_pool = sqlx::PgPool::connect(&database_url).await?; - - let delayed_queue = Arc::new(DelayedQueuePostgres::new(pg_pool.clone()).await?); - let webhooks = Arc::new(WebhooksPostgres::new(pg_pool.clone()).await?); - - let matches = command!() - .subcommand( - Command::new("queue") - .about("Delayed queue operations") - .subcommand(Command::new("get").about("Get messages")) - .subcommand(Command::new("count").about("Count messages")) - .subcommand(Command::new("schedule").about("Schedule sample message")), - ) - .subcommand( - Command::new("webhooks") - .about("Webhooks operations") - .subcommand(Command::new("get").about("Get webhooks")) - .subcommand(Command::new("create").about("Create a new webhook")), - ) - .subcommand(Command::new("server").about("Start HTTP server")) - .get_matches(); - - match matches.subcommand() { - Some(("queue", queue_matches)) => match queue_matches.subcommand() { - Some(("get", _)) => { - let messages = delayed_queue.get_messages().await?; - println!("{:?}", messages); - } - Some(("schedule", _)) => { - let message = Message::sample(); - delayed_queue.schedule_message(&message).await?; - println!("Message scheduled at: {}", message.scheduled_at); - } - _ => { - println!("Invalid command"); - } - }, - Some(("webhooks", queue_matches)) => match queue_matches.subcommand() { - Some(("get", _)) => { - let webhooks = webhooks.get_all().await?; - println!("{:?}", webhooks); - } - Some(("create", _)) => { - let webhook = Webhook::sample(); - webhooks.create(&webhook).await?; - println!("Webhook created: {:?}", webhook); - } - _ => { - println!("Invalid command"); - } - }, - Some(("server", _)) => { - env::set_var("RUST_LOG", "actix_web=info"); - env_logger::init(); - - let mut interval = tokio::time::interval(std::time::Duration::from_secs(2)); - - let cloned_delayed_queue = Arc::clone(&delayed_queue); - let cloned_webhooks = Arc::clone(&webhooks); - - // TODO: This is from just playing around. Structure this better - tokio::spawn(async move { - loop { - interval.tick().await; - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_secs(); - let messages = cloned_delayed_queue - .poll(now, None) - .await - .expect("Poll failed"); - let hooks = cloned_webhooks - .get_all() - .await - .expect("Get webhooks failed"); - - for message in messages.iter() { - println!("Polled message: {:?}", message); - - println!("{:?}", hooks); - for hook in hooks.iter() { - println!("{:?}", hook); - let res = hook.send(message).await; - println!("Webhook result for {:?}: {:?}", message.key, res) - } - - let res = cloned_delayed_queue - .ack(&message.key, &message.kind, &message.created_at) - .await; - println!("Ack result for {:?}: {:?}", &message.key, res) - } - } - }); - - let server = DelayedQueueHttpServer::new(); - server.start(&delayed_queue, &webhooks).await?; - } - _ => { - println!("Invalid command"); - } - } - - println!("Closing connection"); - pg_pool.close().await; - - Ok(()) -} diff --git a/src/message.rs b/src/message.rs deleted file mode 100644 index 7ce7fd4..0000000 --- a/src/message.rs +++ /dev/null @@ -1,49 +0,0 @@ -use std::time::{SystemTime, UNIX_EPOCH}; - -use serde::Serialize; -use uuid::Uuid; - -#[derive(Serialize, Clone)] -pub struct Message { - pub key: String, - pub kind: String, - pub payload: Vec, - pub scheduled_at: u64, - pub scheduled_at_initially: u64, - pub created_at: u64, -} - -impl Message { - pub fn sample() -> Self { - Self { - key: Uuid::new_v4().to_string(), - kind: "sample_kind".to_string(), - payload: b"sample_payload".to_vec(), - scheduled_at: SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_secs(), - scheduled_at_initially: SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_secs(), - created_at: SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_secs(), - } - } -} - -impl std::fmt::Debug for Message { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Message") - .field("key", &self.key) - .field("kind", &self.kind) - .field("payload", &String::from_utf8_lossy(&self.payload)) - .field("scheduled_at", &self.scheduled_at) - .field("scheduled_at_initially", &self.scheduled_at_initially) - .field("created_at", &self.created_at) - .finish() - } -} diff --git a/src/webhooks.rs b/src/webhooks.rs deleted file mode 100644 index c4040cc..0000000 --- a/src/webhooks.rs +++ /dev/null @@ -1,135 +0,0 @@ -use std::time::{SystemTime, UNIX_EPOCH}; - -use anyhow::Result; -use serde::{Deserialize, Serialize}; -use sqlx::postgres::PgPool; - -#[derive(Debug, Serialize, Deserialize)] -pub struct Webhook { - pub id: String, - pub url: String, - pub fails_count: u64, - pub created_at: u64, - pub updated_at: u64, -} - -impl Webhook { - pub fn new(id: String, url: String, created_at: u64) -> Self { - Self { - id, - url, - fails_count: 0, - created_at, - updated_at: created_at, - } - } - - pub fn from_url(url: String) -> Self { - let ts = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_secs(); - Self { - id: uuid::Uuid::new_v4().to_string(), - url, - fails_count: 0, - created_at: ts, - updated_at: ts, - } - } - - pub fn sample() -> Self { - Self { - id: uuid::Uuid::new_v4().to_string(), - url: "http://localhost:9876".to_string(), - fails_count: 0, - created_at: SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_secs(), - updated_at: SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_secs(), - } - } - - pub async fn send(&self, data: &T) -> Result<()> { - let client = reqwest::Client::new(); - println!("Sending to {}", &self.url); - client - .post(&self.url) - .body(serde_json::to_string(data)?) - .send() - .await?; - Ok(()) - } -} - -#[derive(Clone)] -pub struct WebhooksPostgres { - pool: PgPool, -} - -impl WebhooksPostgres { - pub async fn new(pool: PgPool) -> Result { - Ok(Self { pool }) - } - - pub async fn get_all(self: &Self) -> Result> { - let webhooks = sqlx::query!(r#"SELECT * FROM webhooks"#) - .map(|row| { - Ok(Webhook { - id: row.id.clone(), - url: row.url.clone(), - fails_count: row.fails_count as u64, - created_at: row.created_at as u64, - updated_at: row.updated_at as u64, - }) - }) - .fetch_all(&self.pool) - .await?; - - webhooks.into_iter().collect() - } - - pub async fn create(self: &Self, webhook: &Webhook) -> Result<()> { - println!("Creating webhook: {:?}", webhook); - sqlx::query!( - r#" - INSERT INTO webhooks (id, url, fails_count, created_at, updated_at) VALUES ($1, $2, $3, $4, $5) - "#, - webhook.id, - webhook.url, - webhook.fails_count as i64, - webhook.created_at as i64, - webhook.updated_at as i64 - ) - .execute(&self.pool) - .await?; - - Ok(()) - } - - pub async fn update(self: &Self, webhook: &Webhook) -> Result<()> { - sqlx::query!( - r#" - UPDATE webhooks - SET - url = $2, - fails_count = $3, - updated_at = $4 - WHERE - id = $1 - "#, - webhook.id, - webhook.url, - webhook.fails_count as i64, - webhook.updated_at as i64 - ) - .execute(&self.pool) - .await?; - - Ok(()) - } -}