diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..1f27f55 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,39 @@ +name: CI + +on: + push: + branches: [master] + pull_request: + +jobs: + rust: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + targets: wasm32-unknown-unknown + components: rustfmt, clippy + - uses: Swatinem/rust-cache@v2 + - run: cargo fmt --check + - run: cargo clippy --workspace --all-targets -- -D warnings + - run: cargo test --workspace + - run: cargo install worker-build --version 0.9.0 --locked + - run: worker-build --release + working-directory: crates/worker + + door: + runs-on: ubuntu-latest + defaults: + run: + working-directory: door + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + cache-dependency-path: door/package-lock.json + - run: npm ci + - run: npm run typecheck + - run: npm test diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..e634b5a --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,880 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[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 = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "js-sys", + "num-traits", + "wasm-bindgen", +] + +[[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 = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-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 = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "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 = "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 = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[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 = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "mailroom-logic" +version = "0.1.0" +dependencies = [ + "chrono", + "pollster", + "schemars", + "serde", + "serde_json", +] + +[[package]] +name = "mailroom-worker" +version = "0.1.0" +dependencies = [ + "futures-util", + "mailroom-logic", + "serde", + "serde_json", + "worker", +] + +[[package]] +name = "matchit" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pollster" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[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 = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "dyn-clone", + "ref-cast", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 3.0.10", +] + +[[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-wasm-bindgen" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8302e169f0eddcc139c70f139d19d6467353af16f9fce27e8c30158036a1e16b" +dependencies = [ + "js-sys", + "serde", + "wasm-bindgen", +] + +[[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_derive_internals" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" +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_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 = "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" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[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 = "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 = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "pin-project-lite", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[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 = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[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 = "wasm-streams" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "434504846030952e6c0d1e0abf6cb4be16f56e129a9af54a4452d5a2a40f84b1" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[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 = "worker" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d055db1ea6baa6c329730897f63ff7b6ac93c46a9f053804e497e5960eb98e3" +dependencies = [ + "async-trait", + "bytes", + "chrono", + "futures-channel", + "futures-util", + "http", + "http-body", + "js-sys", + "matchit", + "pin-project", + "serde", + "serde-wasm-bindgen", + "serde_json", + "serde_urlencoded", + "strum", + "tokio", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "worker-macros", + "worker-sys", +] + +[[package]] +name = "worker-macros" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37729e2aa37d2bc2a755e4cc71c6e567b31496c0f2de634c200608aa70bd3ead" +dependencies = [ + "async-trait", + "proc-macro2", + "quote", + "strum", + "syn 3.0.10", + "wasm-bindgen", + "wasm-bindgen-macro-support", + "worker-sys", +] + +[[package]] +name = "worker-sys" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9adbe3d1305578979a7019a140bbfb7448254e73c0e62521717e4ce8c2ab5a64" +dependencies = [ + "cfg-if", + "js-sys", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[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 = "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 = "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 new file mode 100644 index 0000000..6ffa89e --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,8 @@ +[workspace] +resolver = "2" +members = ["crates/logic", "crates/worker"] + +[profile.release] +opt-level = "s" +lto = true +codegen-units = 1 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d080c48 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Cycle Five + +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 new file mode 100644 index 0000000..0a19fa9 --- /dev/null +++ b/README.md @@ -0,0 +1,409 @@ +# mailroom + +Per-agent mailboxes on Cloudflare Workers. A deterministic poller collects Discord and +GitHub activity into one inbox per AI agent. The agent reads it over MCP with a cursor, +instead of spending inference walking channels and repos to find out whether anything +needs it. + +``` + claude.ai / Manus + │ OAuth bearer + ▼ + mailroom (TypeScript door, public) discord-broker[-manus] github-broker + /authorize consent + mailbox picker ┌──▶ Feed (internal, read-only) ◀──┐ + /callback Discord sign-in ───────────┘ ▲ │ + /mcp token check, then forward │ service bindings │ + │ service binding │ │ + ▼ │ │ + mailroom-core (Rust, no public URL) ──────────────┴──────────────────────────┘ + fetch MCP JSON-RPC ─▶ Mailbox DO (by agent name) + scheduled every minute ─▶ each agent's Mailbox DO: tick + Mailbox DO SQLite inbox, cursor, per-target poll state +``` + +The design follows a mailbox pattern first built by Muse, another agent in the same team, +for a single agent on one host. Mailroom is that pattern at Cloudflare size, for several +agents. + +## Why + +Without it, every wake-up costs model tokens: list the channels, read each one, list the +repos, read each one, decide that nothing was for you. Most wake-ups find nothing. With +mailroom the looking is done by code that costs nothing to run, and the agent makes one +`read_mail` call. It reaches for the brokers only to act on what it found. + +## Rules + +1. **The poller never thinks.** It copies new activity into the inbox and applies + mechanical filters. It has no model, no judgement and no Discord token or GitHub key: + those stay in the brokers. +2. **The agent reads in batches and acknowledges only what it handled.** `read_mail` never + moves the cursor. `ack` does, and only to a sequence number the agent chose. +3. **Nothing pushes.** Mailroom never wakes an agent and never acts on Discord or GitHub. + It only reads. Delivery stays decoupled from attention. + +A failed poll changes nothing and is visible in `mailbox_info`. It is never guessed past. + +## Pieces + +| Piece | Language | Public | Holds | +| --- | --- | --- | --- | +| `mailroom` (the door, `door/`) | TypeScript | yes | the OAuth KV; no secrets | +| `mailroom-core` (`crates/worker/`) | Rust | no | the inboxes | +| `Feed` entrypoint in [discord-broker](https://github.com/CycleFive/discord-broker) and [github-broker](https://github.com/CycleFive/github-broker) | TypeScript | no | nothing new | + +`crates/logic/` is the pure-Rust part (records, config, filters, pollers, MCP protocol). +It has no Workers dependency, so its tests run with plain `cargo test`. + +The brokers must be at version 0.2.0 or later: that version adds the internal `Feed` +entrypoint mailroom reads through. `Feed` is read-only and has no public URL. It is +reachable only through a service binding from a Worker in the same Cloudflare account, and +the brokers' allowlists (`DISCORD_ALLOWED_GUILDS`, `DISCORD_ALLOWED_CHANNELS`) apply to it. + +The door is TypeScript only because `@cloudflare/workers-oauth-provider`, the tested OAuth +2.1 authorization server, exists in no other language. It holds no mailbox logic. + +## Records + +Every item in every inbox has this shape: + +```json +{"seq": 12, "ts_ingest": "2026-11-18T10:05:00Z", "src": "discord", "kind": "message", + "id": "dc:123456789012345678", "ts": "2026-11-18T10:04:40.123000+00:00", "actor": "Nyx", + "ref": "#general", "title": "", "body": "...", + "url": "https://discord.com/channels/111111111111111111/222222222222222222/123456789012345678", + "tags": ["routed:mention"]} +``` + +| Field | Meaning | +| --- | --- | +| `seq` | Assigned by the inbox. Strictly increasing, never reused. | +| `ts_ingest` | When the poller stored it. | +| `src` | `discord` or `github`. | +| `kind` | See below. | +| `id` | Unique per inbox. A second append of the same `id` is ignored, so overlapping polls are harmless. | +| `ts`, `actor` | When it happened and who did it. | +| `ref` | `#` for Discord, `/#` for GitHub. | +| `title`, `body` | An excerpt: Discord content up to 2000 characters (attachment and embed summary lines are appended after the cut), GitHub bodies up to 600 with ` [...]`. | +| `url` | What the agent needs to act: a Discord jump link (guild, channel, message IDs) or a GitHub `html_url` (repo and number). | +| `tags` | Built-in and rule-added tags, below. | + +Records are pointers, not evidence. Fetch the thread or the diff through the broker before +acting on one. + +Kinds: Discord has `message`, `reaction` and `gap` (messages may have been skipped; see +below). GitHub has `issue`, `pr`, `issue_comment`, `review_comment`, `review` and `event` +(`assigned`, `labeled`, `review_requested`, `closed`, `merged`, `reopened`). + +Tags the poller adds itself: + +| Tag | Meaning | +| --- | --- | +| `routed:mention` | Discord: the message mentions the agent's bot. GitHub: the text contains `@`. | +| `routed:reply` | Discord: the message replies to one of the bot's messages. | +| `routed:assigned` | GitHub: the agent is an assignee. | +| `routed:review` | GitHub: the PR carries `review_label` or the agent is a requested reviewer. | +| `mine` | GitHub: a comment, review or event on an issue or PR the agent authored. | + +Tags starting `routed:` are addressed to the agent. `mine` is activity on its own work. +Untagged records are context. Rules can add more tags (see Configuration). + +## Tools + +| Tool | Arguments | Returns | +| --- | --- | --- | +| `read_mail` | `limit` 1-200 (default 50); `after` a seq (default: the cursor); `tags` keeps records carrying any of them | `{agent, cursor, last_seq, unread, returned, more, records[]}`, oldest first. Never moves the cursor. | +| `ack` | `seq` | `{cursor, unread}`. Moves the cursor to `seq`. Refused unless `cursor <= seq <= last_seq`. | +| `mailbox_info` | none | `{agent, signed_in_as, version, cursor, last_seq, unread, unread_by_tag, sources[]}`. Each source lists its targets with last success, last error and next due time. | + +The server instructions tell the agent the discipline: read, act through the brokers, +acknowledge only what was handled, and end quietly on an empty mailbox. Every tool call +writes one audit line (tool, agent, signed-in user, ok, ms) to Workers Logs. + +## Configuration + +One JSON var, `MAILROOM`, in `crates/worker/wrangler.jsonc`. That file is git-ignored; +copy `crates/worker/wrangler.example.jsonc`. The var is parsed on every request and every +tick, and unknown fields are rejected. + +**Top level** + +| Field | Default | Rule | +| --- | --- | --- | +| `retain_days` | `30` | Acknowledged records older than this are pruned. `0` keeps everything. Unread records are never pruned. | +| `agents` | required | Map of agent name to `{ "sources": [...] }`. Must not be empty. Names are 1-32 characters of `a-z`, `0-9`, `-`. | + +**Discord source** (`"type": "discord"`) + +| Field | Default | Rule | +| --- | --- | --- | +| `broker` | required | Name of a service binding to a discord-broker `Feed`. Non-empty, only `A-Z`, `0-9`, `_`. | +| `channels` | required | Channel IDs. Not empty, no duplicates, each 5-25 ASCII digits. A thread is watched by listing its ID here. | +| `every_secs` | `120` | Minimum `60` (the cron resolution). | +| `reactions` | `true` | Record reactions added to recent messages. | +| `skip_self` | `true` | Items authored by the agent's own bot produce no record. | +| `keep` | `"all"` | `"all"` or `"tagged"`. | +| `rules` | `[]` | See below. | + +**GitHub source** (`"type": "github"`) + +| Field | Default | Rule | +| --- | --- | --- | +| `broker` | required | Name of a service binding to a github-broker `Feed`. Same rule as above. | +| `repos` | required | `owner/name`. Not empty, no duplicates. | +| `every_secs` | `300` | Minimum `60`. | +| `review_label` | none | A label that means "review this". When set it must not be empty. | +| `skip_self` | `true` | As above. | +| `keep` | `"all"` | `"all"` or `"tagged"`. | +| `rules` | `[]` | See below. | + +**Rules.** Each rule is `{ "when": {...}, "then": ... }`. `then` is `"drop"` or +`{ "tag": "name" }` (the tag must not be empty). `when` holds conditions that must all +match; each is a list that matches if any element does, and an empty or missing list is no +condition. + +| Condition | Matches | +| --- | --- | +| `kind` | the record's kind (`message`, `reaction`, `gap`, `issue`, `pr`, `issue_comment`, `review_comment`, `review`, `event`) | +| `actor` | the actor, case-insensitive | +| `actor_not` | none of these actors | +| `ref` | the exact `ref` | +| `tag` | the record already carries one of these tags | +| `body_contains` | a case-insensitive substring of title plus body | + +There are no regular expressions. + +**Filter order.** For each new upstream item: + +1. `skip_self`: the agent's own items produce no record. They still advance the watermarks. +2. Built-in tags are added. +3. Rules run first to last. A tag rule adds its tag; a drop rule discards the record and + stops there. +4. `keep`: `"all"` keeps every surviving record, `"tagged"` keeps only records with at + least one tag. + +**Invalid config fails closed.** The poller does nothing, and every request to +`mailroom-core` answers HTTP 500 with `mailroom config: `. It is also logged. +An agent removed from the config keeps its stored inbox but becomes unreachable. Nothing +purges it. + +**Example** (all IDs are fake): + +```jsonc +"MAILROOM": { + "retain_days": 30, + "agents": { + "claude": { + "sources": [ + { "type": "discord", "broker": "DISCORD_CLAUDE", "every_secs": 120, + "channels": ["123456789012345678", "123456789012345679"], + "reactions": true, "skip_self": true, "keep": "all", + "rules": [ + { "when": { "kind": ["reaction"], "actor_not": ["Alice"] }, "then": "drop" }, + { "when": { "body_contains": ["deploy"] }, "then": { "tag": "deploy" } } + ] }, + { "type": "github", "broker": "GITHUB", "every_secs": 300, + "repos": ["your-org/your-repo"], "review_label": "review:claude", + "skip_self": true, "keep": "tagged", "rules": [] } + ] + }, + "manus": { + "sources": [ + { "type": "discord", "broker": "DISCORD_MANUS", + "channels": ["123456789012345678"] } + ] + } + } +} +``` + +## What is polled, and what is missed + +Polling is REST only: a cron trigger fires every minute, and each target (a channel or a +repo) is polled when it is next due, about `every_secs` after its last attempt. There is no gateway listener and no +webhook. + +- **First contact emits nothing.** The first poll of a target records its current position + and produces no records. History is never replayed. +- **Discord messages.** Each poll reads the latest 50 messages of the channel. If all 50 + are new it pages back, up to 5 pages. If the last position is still not reached it + appends one `gap` record saying messages may have been skipped, then continues from the + newest. Only ordinary messages and replies become records. +- **Reactions.** Read from the same 50-message window. When a count rises, the new + reactors become one `reaction` record each. A reaction on a message older than the + window is missed, and so are removed reactions. +- **Threads.** Not discovered. A thread is watched only when its ID is listed in + `channels`. +- **Edits and deletions** are ignored, on both Discord and GitHub. +- **GitHub.** Issues, pulls, issue comments, review comments, reviews and issue events. + Reviews are found by their submission time since the last check. The last-check time is stored 60 seconds early so nothing falls + between two polls; the unique `id` absorbs the overlap. Workflow runs are not recorded. +- **Limits.** Each GitHub list is read 50 items per poll. If a list comes back full and + every item on it is new, one `gap` record names the list and repo (items may have been + skipped; look at the repo directly). Reviews are read 100 per page, up to 10 pages per + pull request, with a `gap` record if that is not enough. Discord reactor lists are + capped at 100 per message, and reactions from burst reactors are not recorded. + A `gap` record is never dropped by `rules` or `keep`. +- **Failures.** A failed target changes nothing except its status (time and error text), + and the target is retried when it is next due (after its own `every_secs`), from the + same position. Targets fail independently. If a + broker's identity cannot be read, every target of that source fails for the tick. + +## Setup + +You need: + +- Rust (stable) with the wasm target: `rustup target add wasm32-unknown-unknown` +- `worker-build`: `cargo install worker-build --version 0.9.0 --locked` +- Node 22.12 or newer +- A Cloudflare account +- discord-broker and github-broker, both at 0.2.0 or later, already set up + +The Discord redirect and the mailbox picker below assume the broker bound as `SIGNIN` is +the discord-broker whose application you already sign in with. + +### 1. Deploy the brokers' `Feed` + +Merge and deploy discord-broker (and its `--env manus` copy, if you run one) and +github-broker at 0.2.0 or later. Nothing else changes for them. + +### 2. Deploy `mailroom-core` + +```sh +cd crates/worker +cp wrangler.example.jsonc wrangler.jsonc +``` + +Edit `wrangler.jsonc`: fill in `MAILROOM` (see Configuration), and make sure there is one +`services` entry per broker named in it, each with `"entrypoint": "Feed"`. Then: + +```sh +npx wrangler@4 login +npx wrangler@4 deploy +``` + +This crate has no `package.json`, so `npx wrangler@4` fetches Wrangler on the fly; the +`@4` pins the major version. + +The Worker is named `mailroom-core`. It has no public URL (`workers_dev` and `preview_urls` are +both false, and there are no routes); the door reaches it through a service binding. It also runs a cron +trigger every minute. + +### 3. Deploy the door + +```sh +cd door +npm install +cp wrangler.example.jsonc wrangler.jsonc +npx wrangler kv namespace create OAUTH_KV +``` + +`wrangler.jsonc` is git-ignored: it holds your own IDs and URL, no secrets. Paste the KV id +into it and fill in `vars`: + +| Var | | +| --- | --- | +| `PUBLIC_URL` | The door's public origin, no trailing slash. | +| `ALLOWED_DISCORD_USERS` | Your numeric Discord user ID (Developer Mode, right-click yourself, Copy User ID), not a username. Comma- or space-separated. | +| `ALLOWED_ORIGINS` | Optional. Comma-separated Origins accepted when a request carries an Origin header. | +| `DISABLE_CIMD` | Optional. `"true"` makes clients register through Dynamic Client Registration instead of a Client ID Metadata Document. | + +The `MAILROOM` service binding points at `mailroom-core`. The `SIGNIN` binding points at +`discord-broker` with entrypoint `Feed`. The door holds no secrets: the Discord client +secret stays in the broker. + +```sh +npx wrangler deploy +``` + +It is deployed as `mailroom`, so the MCP URL is +`https://mailroom..workers.dev/mcp`. Put that origin in `PUBLIC_URL` and +deploy again. + +### 4. Add the Discord redirect + +On the Discord application of the broker bound as `SIGNIN`, open OAuth2 and add the +Redirect `https://mailroom..workers.dev/callback`. It must match exactly, with +no trailing slash. Every operator signs in through that application whichever mailbox they +pick, so this one redirect is enough. + +### 5. Connect + +- **claude.ai**: Settings, Connectors, Add custom connector. Give the URL + `https://mailroom..workers.dev/mcp` exactly, and leave Advanced settings + blank. +- **Claude Code**: `claude mcp add --transport http mailroom https://mailroom..workers.dev/mcp` +- **Manus**: add a custom MCP server with the same URL, and complete the sign-in. + +You see the consent page (check it names the client you expect), then Discord's +"authorize" screen asking only for your username. + +### 6. Pick the mailbox + +The consent page lists the configured agents as radio buttons with none selected. Pick the +one this client is. The choice is stored in the grant and cannot be changed without +signing in again. Nothing stops a client being given another agent's mailbox if you pick +it, so the page shows the agent name prominently and `mailbox_info` returns it. Check +`agent` in `mailbox_info` after connecting. + +## If something is wrong + +| You see | Usually | +| --- | --- | +| `mailbox_info` shows a `last_error` on a target | That target's last poll failed; the position has not moved and the target is retried when it is next due (after its own `every_secs`). The text says whether the broker, the allowlist or Discord/GitHub refused. Discord sometimes answers Workers with a 429 because of other traffic on a shared IP; it usually clears. | +| HTTP 500 `mailroom config: ...` on every call, or an error page saying "The mailroom is misconfigured" on the consent page (the door shows it as 502) | The `MAILROOM` var is invalid. The page is generic on purpose; the door logs the reason as `agents_unavailable`, and the call's body names the agent, source and field. Fix it and deploy `mailroom-core`. | +| "Pick a mailbox." | The mailbox you posted is not in the current config. Go back and pick. | +| `The mailbox "" is no longer configured.` | The agent was removed from config between your approval and the Discord sign-in. Start again and pick another. | +| Discord says "Invalid OAuth2 redirect_uri" | The Redirect on the `SIGNIN` broker's application is not exactly `/callback`. | +| The door's sign-in page shows a broker error | The code exchange failed in the broker (usually the client secret or the redirect). Fix it there. | +| "not in ALLOWED_DISCORD_USERS" | The page names the account and ID; put that ID in the door's var and deploy. | +| `ack` is refused | `seq` must be between the cursor and `last_seq`. | +| A channel produces nothing | First contact emits nothing; check `last_ok` in `mailbox_info`, the broker's channel allowlist, and that the bot can read the channel. | + +`npx wrangler@4 tail mailroom-core` (from `crates/worker`) shows one JSON line per poll +(`poll`) and tool call (`tool_call`). `npx wrangler tail` in `door/` shows the door's +sign-in and OAuth events (`oauth_endpoint`, `authorize_error`, `sign_in`, `sign_in_refused`, +`sign_in_cancelled`, `agent_gone`, `agents_unavailable`, `config_error`, and a few +failure events). The brokers log their own `feed` lines; read those with `wrangler tail` +in each broker. + +## A prompt for the agent + +``` +On waking, call read_mail on the mailroom MCP server. If it returns no records, end +quietly. Otherwise go through the records oldest first. A record is a pointer: before +acting, fetch the thread or diff through the Discord or GitHub broker, and act there. +Records tagged routed:* are addressed to you; mine is activity on your own work; untagged +records are context. When you are done, call ack with the highest seq you actually +handled. Leave anything you did not handle unacknowledged. +``` + +## Development + +```sh +cargo test --workspace # the logic crate: config, filters, pollers, MCP +cargo clippy --workspace --all-targets -- -D warnings +crates/worker/smoke/run.sh # wrangler dev with a fake Feed: tick, read_mail, ack, mailbox_info +cd door && npm test && npm run typecheck # sign-in flow, picker, header stripping +``` + +The smoke test needs `worker-build`, `curl` and `jq`. The door's tests run the whole +sign-in against fake `SIGNIN` and `mailroom-core` service bindings; nothing touches a real +Discord or GitHub. + +CI (`.github/workflows/ci.yml`) runs `cargo fmt --check`, clippy, `cargo test`, the wasm +build of `crates/worker`, and the door's typecheck and tests. + +Layout: `crates/logic/src/` (`config.rs`, `record.rs`, `filter.rs`, `discord.rs`, +`github.rs`, `feed.rs`, `time.rs`, and the MCP protocol), `crates/worker/` (the +`Mailbox` Durable Object, SQLite storage, the service-binding `Feed` client, the fetch and +scheduled handlers), `door/src/` (`index.ts` routing and forwarding, `auth.ts` consent and +sign-in, `env.ts`). + +Not covered: a Discord gateway listener, GitHub webhooks, workflow-run records, automatic +thread discovery, editing filters at runtime, and restricting which client may take which +mailbox. + +## License + +MIT, see [LICENSE](LICENSE). diff --git a/crates/logic/Cargo.toml b/crates/logic/Cargo.toml new file mode 100644 index 0000000..146ee17 --- /dev/null +++ b/crates/logic/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "mailroom-logic" +version = "0.1.0" +edition = "2021" +license = "MIT" + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = { version = "1", features = ["raw_value"] } +chrono = { version = "0.4", default-features = false, features = ["alloc"] } +schemars = "1" + +[dev-dependencies] +pollster = "0.4" diff --git a/crates/logic/src/config.rs b/crates/logic/src/config.rs new file mode 100644 index 0000000..a4351d9 --- /dev/null +++ b/crates/logic/src/config.rs @@ -0,0 +1,273 @@ +//! Validated mailroom configuration (the `MAILROOM` var). + +use std::collections::BTreeMap; +use std::collections::BTreeSet; +use std::fmt; + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use crate::record::{Kind, Src}; + +const MIN_EVERY_SECS: u32 = 60; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Config { + #[serde(default = "default_retain_days")] + pub retain_days: u32, + pub agents: BTreeMap, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct AgentConfig { + pub sources: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum SourceConfig { + Discord(DiscordSource), + Github(GithubSource), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct DiscordSource { + pub broker: String, + #[serde(default = "default_discord_every")] + pub every_secs: u32, + pub channels: Vec, + #[serde(default = "default_true")] + pub reactions: bool, + #[serde(default = "default_true")] + pub skip_self: bool, + #[serde(default)] + pub keep: Keep, + #[serde(default)] + pub rules: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct GithubSource { + pub broker: String, + #[serde(default = "default_github_every")] + pub every_secs: u32, + pub repos: Vec, + #[serde(default)] + pub review_label: Option, + #[serde(default = "default_true")] + pub skip_self: bool, + #[serde(default)] + pub keep: Keep, + #[serde(default)] + pub rules: Vec, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Keep { + #[default] + All, + Tagged, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Rule { + pub when: When, + pub then: Then, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(default, deny_unknown_fields)] +pub struct When { + pub kind: Vec, + pub actor: Vec, + pub actor_not: Vec, + #[serde(rename = "ref")] + pub reference: Vec, + pub tag: Vec, + pub body_contains: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Then { + Drop, + Tag(String), +} + +fn default_retain_days() -> u32 { + 30 +} +fn default_discord_every() -> u32 { + 120 +} +fn default_github_every() -> u32 { + 300 +} +fn default_true() -> bool { + true +} + +/// A configuration problem; `Display` prints the message. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ConfigError(pub String); + +impl fmt::Display for ConfigError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for ConfigError {} + +impl Config { + /// Deserializes, then validates. + pub fn parse(json: &str) -> Result { + let config: Config = + serde_json::from_str(json).map_err(|e| ConfigError(format!("invalid config: {e}")))?; + config.validate()?; + Ok(config) + } + + pub fn validate(&self) -> Result<(), ConfigError> { + if self.agents.is_empty() { + return Err(ConfigError("agents: must not be empty".into())); + } + for (name, agent) in &self.agents { + let valid_name = (1..=32).contains(&name.len()) + && name + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-'); + if !valid_name { + return Err(ConfigError(format!( + "agent {name:?}: name must be 1-32 chars of a-z, 0-9, '-'" + ))); + } + for (i, source) in agent.sources.iter().enumerate() { + validate_source(name, i, source)?; + } + } + Ok(()) + } +} + +fn validate_source(agent: &str, index: usize, source: &SourceConfig) -> Result<(), ConfigError> { + let at = format!("agent {agent:?} source {index}"); + let fail = |field: &str, msg: String| Err(ConfigError(format!("{at}: {field}: {msg}"))); + + let broker = source.broker(); + if broker.is_empty() + || !broker + .bytes() + .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_') + { + return fail( + "broker", + format!("{broker:?} must be non-empty and only A-Z, 0-9, '_'"), + ); + } + if source.every_secs() < MIN_EVERY_SECS { + return fail( + "every_secs", + format!("{} is below the minimum of {MIN_EVERY_SECS}", source.every_secs()), + ); + } + + let mut seen = BTreeSet::new(); + match source { + SourceConfig::Discord(d) => { + if d.channels.is_empty() { + return fail("channels", "must not be empty".into()); + } + for c in &d.channels { + if !(5..=25).contains(&c.len()) || !c.bytes().all(|b| b.is_ascii_digit()) { + return fail("channels", format!("{c:?} must be 5-25 ASCII digits")); + } + if !seen.insert(c) { + return fail("channels", format!("duplicate {c:?}")); + } + } + } + SourceConfig::Github(g) => { + if g.repos.is_empty() { + return fail("repos", "must not be empty".into()); + } + for r in &g.repos { + let ok = matches!(r.split_once('/'), Some((o, n)) if !o.is_empty() && !n.is_empty() && !n.contains('/')); + if !ok { + return fail("repos", format!("{r:?} must be owner/name")); + } + if !seen.insert(r) { + return fail("repos", format!("duplicate {r:?}")); + } + } + if g.review_label.as_deref() == Some("") { + return fail("review_label", "must not be empty".into()); + } + } + } + for rule in source.rules() { + if rule.then == Then::Tag(String::new()) { + return fail("rules", "tag must not be empty".into()); + } + } + Ok(()) +} + +impl SourceConfig { + pub fn broker(&self) -> &str { + match self { + SourceConfig::Discord(d) => &d.broker, + SourceConfig::Github(g) => &g.broker, + } + } + + pub fn every_secs(&self) -> u32 { + match self { + SourceConfig::Discord(d) => d.every_secs, + SourceConfig::Github(g) => g.every_secs, + } + } + + pub fn src(&self) -> Src { + match self { + SourceConfig::Discord(_) => Src::Discord, + SourceConfig::Github(_) => Src::Github, + } + } + + pub fn keep(&self) -> Keep { + match self { + SourceConfig::Discord(d) => d.keep, + SourceConfig::Github(g) => g.keep, + } + } + + pub fn rules(&self) -> &[Rule] { + match self { + SourceConfig::Discord(d) => &d.rules, + SourceConfig::Github(g) => &g.rules, + } + } + + /// "discord::" or "github::/", in config order. + pub fn target_keys(&self) -> Vec { + match self { + SourceConfig::Discord(d) => d + .channels + .iter() + .map(|c| format!("discord:{}:{c}", d.broker)) + .collect(), + SourceConfig::Github(g) => g + .repos + .iter() + .map(|r| format!("github:{}:{r}", g.broker)) + .collect(), + } + } +} diff --git a/crates/logic/src/discord.rs b/crates/logic/src/discord.rs new file mode 100644 index 0000000..2ad211b --- /dev/null +++ b/crates/logic/src/discord.rs @@ -0,0 +1,400 @@ +//! Polls one Discord channel: new messages and new reactions since the previous state. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use crate::config::DiscordSource; +use crate::feed::{get_json, FeedClient, Identity, Poll, PollError}; +use crate::record::{truncate, Kind, NewRecord, Src}; + +const PAGE: usize = 50; +const MAX_PAGES: usize = 5; +const PAGE_LIMIT: &str = "50"; +const BODY_MAX: usize = 2000; +/// One reactor fetch returns at most this many users; a list at the cap is not fetched again. +const REACTOR_CAP: usize = 100; +const REACTOR_LIMIT: &str = "100"; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct DiscordState { + pub channel_name: String, + pub guild_id: String, + pub watermark: u64, + /// message id -> emoji key -> reactor user ids + pub reactions: BTreeMap>>, +} + +#[derive(Deserialize)] +struct Channel { + #[serde(default)] + name: String, + #[serde(default)] + guild_id: Option, +} + +#[derive(Deserialize)] +struct Message { + id: String, + #[serde(default, rename = "type")] + kind: u32, + #[serde(default)] + timestamp: String, + #[serde(default)] + content: String, + #[serde(default)] + author: User, + #[serde(default)] + mentions: Vec, + #[serde(default)] + referenced_message: Option, + #[serde(default)] + attachments: Vec, + #[serde(default)] + embeds: Vec, + #[serde(default)] + reactions: Vec, +} + +#[derive(Deserialize, Default)] +struct User { + #[serde(default)] + id: String, + #[serde(default)] + username: String, + #[serde(default)] + global_name: Option, +} + +impl User { + fn display(&self) -> String { + match self.global_name.as_deref() { + Some(g) if !g.is_empty() => g.to_string(), + _ => self.username.clone(), + } + } +} + +#[derive(Deserialize, Default)] +struct UserId { + #[serde(default)] + id: String, +} + +#[derive(Deserialize)] +struct Referenced { + #[serde(default)] + author: UserId, +} + +#[derive(Deserialize)] +struct Attachment {} + +#[derive(Deserialize)] +struct Embed { + #[serde(default)] + title: Option, +} + +#[derive(Deserialize)] +struct ReactionSummary { + #[serde(default)] + count: usize, + #[serde(default)] + count_details: Option, + emoji: Emoji, +} + +#[derive(Deserialize)] +struct CountDetails { + #[serde(default)] + normal: usize, +} + +#[derive(Deserialize)] +struct Emoji { + #[serde(default)] + id: Option, + #[serde(default)] + name: Option, +} + +impl Emoji { + /// The unicode character, or `name:id` for a custom emoji. + fn key(&self) -> String { + let name = self.name.as_deref().unwrap_or(""); + match &self.id { + Some(id) => format!("{name}:{id}"), + None => name.to_string(), + } + } + + /// The unicode character, or `:name:` for a custom emoji. + fn body(&self) -> String { + let name = self.name.as_deref().unwrap_or(""); + match &self.id { + Some(_) => format!(":{name}:"), + None => name.to_string(), + } + } +} + +/// An emoji on a page-1 message, as last seen. +struct Seen { + key: String, + body: String, + count: usize, +} + +fn parse_id(id: &str) -> Result { + id.parse() + .map_err(|_| PollError(format!("unparsable Discord id {id:?}"))) +} + +/// Percent-encodes every byte outside the unreserved set. +fn encode(key: &str) -> String { + let mut out = String::new(); + for b in key.bytes() { + if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') { + out.push(b as char); + } else { + out.push_str(&format!("%{b:02X}")); + } + } + out +} + +async fn fetch_reactors( + feed: &impl FeedClient, + channel_id: &str, + message_id: &str, + key: &str, +) -> Result, PollError> { + let path = format!( + "/channels/{channel_id}/messages/{message_id}/reactions/{}", + encode(key) + ); + Ok(get_json(feed, &path, &[("limit", REACTOR_LIMIT)]).await?) +} + +fn jump_url(guild_id: &str, channel_id: &str, message_id: &str) -> String { + format!("https://discord.com/channels/{guild_id}/{channel_id}/{message_id}") +} + +pub async fn poll_channel( + feed: &impl FeedClient, + me: &Identity, + channel_id: &str, + opts: &DiscordSource, + prev: Option, + now: &str, +) -> Result, PollError> { + let messages_path = format!("/channels/{channel_id}/messages"); + + let Some(prev) = prev else { + let channel: Channel = get_json(feed, &format!("/channels/{channel_id}"), &[]).await?; + let page: Vec = get_json(feed, &messages_path, &[("limit", PAGE_LIMIT)]).await?; + let mut watermark = 0; + for m in &page { + watermark = watermark.max(parse_id(&m.id)?); + } + let mut reactions = BTreeMap::new(); + if opts.reactions { + for m in &page { + for r in &m.reactions { + let key = r.emoji.key(); + let users = fetch_reactors(feed, channel_id, &m.id, &key).await?; + let ids = users.into_iter().map(|u| u.id).collect(); + reactions + .entry(m.id.clone()) + .or_insert_with(BTreeMap::new) + .insert(key, ids); + } + } + } + return Ok(Poll { + records: Vec::new(), + state: DiscordState { + channel_name: channel.name, + guild_id: channel.guild_id.unwrap_or_else(|| "@me".to_string()), + watermark, + reactions, + }, + }); + }; + + // Page 1, then older pages while every message so far has been new. + let first: Vec = get_json(feed, &messages_path, &[("limit", PAGE_LIMIT)]).await?; + let mut ids = Vec::with_capacity(first.len()); + for m in &first { + ids.push(parse_id(&m.id)?); + } + let mut new: Vec<(u64, Message)> = Vec::new(); + let mut seen_max = ids.iter().copied().max().unwrap_or(0); + let mut full_and_new = first.len() == PAGE && ids.iter().all(|&i| i > prev.watermark); + let mut lowest = ids.iter().copied().min(); + let mut pages = 1; + // Page 1's messages (new and old) are the ones whose reactions are tracked. + let page_one_info: Vec<(String, Vec)> = first + .iter() + .map(|m| { + ( + m.id.clone(), + m.reactions + .iter() + .map(|r| Seen { + key: r.emoji.key(), + body: r.emoji.body(), + count: r.count_details.as_ref().map_or(r.count, |d| d.normal), + }) + .collect(), + ) + }) + .collect(); + for (id, m) in ids.iter().copied().zip(first) { + if id > prev.watermark { + new.push((id, m)); + } + } + + let mut gap = false; + while full_and_new { + if pages == MAX_PAGES { + gap = true; + break; + } + let before = lowest.unwrap_or(0).to_string(); + let page: Vec = get_json( + feed, + &messages_path, + &[("limit", PAGE_LIMIT), ("before", &before)], + ) + .await?; + pages += 1; + let mut page_ids = Vec::with_capacity(page.len()); + for m in &page { + page_ids.push(parse_id(&m.id)?); + } + seen_max = seen_max.max(page_ids.iter().copied().max().unwrap_or(0)); + full_and_new = page.len() == PAGE && page_ids.iter().all(|&i| i > prev.watermark); + if let Some(l) = page_ids.iter().copied().min() { + lowest = Some(lowest.map_or(l, |c| c.min(l))); + } + for (id, m) in page_ids.into_iter().zip(page) { + if id > prev.watermark { + new.push((id, m)); + } + } + } + new.sort_by_key(|(id, _)| *id); + + let guild_id = &prev.guild_id; + let reference = format!("#{}", prev.channel_name); + let mut records = Vec::new(); + + if gap { + let newest = new.last().map(|(id, _)| *id).unwrap_or(0); + let oldest = lowest.unwrap_or(0); + records.push(NewRecord { + src: Src::Discord, + kind: Kind::Gap, + id: format!("dc:gap:{channel_id}:{newest}"), + ts: now.to_string(), + actor: String::new(), + reference: reference.clone(), + title: "messages may have been skipped".to_string(), + body: String::new(), + url: jump_url(guild_id, channel_id, &oldest.to_string()), + tags: Vec::new(), + }); + } + + for (id, m) in &new { + if m.kind != 0 && m.kind != 19 { + continue; + } + if opts.skip_self && m.author.id == me.id { + continue; + } + let mut body = truncate(&m.content, BODY_MAX, ""); + if !m.attachments.is_empty() { + body.push_str(&format!("\n[{} attachment(s)]", m.attachments.len())); + } + for title in m.embeds.iter().filter_map(|e| e.title.as_deref()) { + body.push_str(&format!("\n[embed] {title}")); + } + let mut tags = Vec::new(); + if m.mentions.iter().any(|u| u.id == me.id) { + tags.push("routed:mention".to_string()); + } + if m.referenced_message + .as_ref() + .is_some_and(|r| r.author.id == me.id) + { + tags.push("routed:reply".to_string()); + } + records.push(NewRecord { + src: Src::Discord, + kind: Kind::Message, + id: format!("dc:{id}"), + ts: m.timestamp.clone(), + actor: m.author.display(), + reference: reference.clone(), + title: String::new(), + body, + url: jump_url(guild_id, channel_id, &m.id), + tags, + }); + } + + let mut reactions: BTreeMap>> = BTreeMap::new(); + if opts.reactions { + for (message_id, emojis) in &page_one_info { + for Seen { key, body, count } in emojis { + let stored = prev + .reactions + .get(message_id) + .and_then(|m| m.get(key)) + .cloned() + .unwrap_or_default(); + let list = if *count > stored.len() && stored.len() < REACTOR_CAP { + let users = fetch_reactors(feed, channel_id, message_id, key).await?; + for u in &users { + if stored.contains(&u.id) || (opts.skip_self && u.id == me.id) { + continue; + } + records.push(NewRecord { + src: Src::Discord, + kind: Kind::Reaction, + id: format!("dc:react:{message_id}:{key}:{}", u.id), + ts: now.to_string(), + actor: u.display(), + reference: reference.clone(), + title: String::new(), + body: body.clone(), + url: jump_url(guild_id, channel_id, message_id), + tags: Vec::new(), + }); + } + users.into_iter().map(|u| u.id).collect() + } else { + stored + }; + reactions + .entry(message_id.clone()) + .or_default() + .insert(key.clone(), list); + } + } + } + + Ok(Poll { + records, + state: DiscordState { + channel_name: prev.channel_name.clone(), + guild_id: prev.guild_id.clone(), + watermark: prev.watermark.max(seen_max), + reactions, + }, + }) +} diff --git a/crates/logic/src/feed.rs b/crates/logic/src/feed.rs new file mode 100644 index 0000000..9ec3505 --- /dev/null +++ b/crates/logic/src/feed.rs @@ -0,0 +1,75 @@ +//! The upstream-read abstraction shared by the pollers. + +use std::fmt; + +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; + +use crate::record::NewRecord; + +/// Who the bot is on the upstream service. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Identity { + pub id: String, + pub login: String, + pub name: String, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum FeedError { + Status { status: u16, message: String }, + Transport(String), + Decode(String), +} + +impl fmt::Display for FeedError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + FeedError::Status { status, message } => write!(f, "upstream status {status}: {message}"), + FeedError::Transport(m) => write!(f, "transport error: {m}"), + FeedError::Decode(m) => write!(f, "decode error: {m}"), + } + } +} + +impl std::error::Error for FeedError {} + +#[allow(async_fn_in_trait)] +pub trait FeedClient { + /// GET an upstream API path (e.g. "/channels/1/messages"); returns the response body text. + async fn get(&self, path: &str, query: &[(&str, &str)]) -> Result; +} + +/// GETs `path` and deserializes the body; a body that is not valid JSON for `T` is a +/// `FeedError::Decode` naming the path. +pub async fn get_json( + feed: &impl FeedClient, + path: &str, + query: &[(&str, &str)], +) -> Result { + let body = feed.get(path, query).await?; + serde_json::from_str(&body).map_err(|e| FeedError::Decode(format!("{path}: {e}"))) +} + +/// The result of one poll: records to append and the state to persist (only on `Ok`). +pub struct Poll { + pub records: Vec, + pub state: S, +} + +#[derive(Debug)] +pub struct PollError(pub String); + +impl fmt::Display for PollError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for PollError {} + +impl From for PollError { + fn from(e: FeedError) -> Self { + PollError(e.to_string()) + } +} diff --git a/crates/logic/src/filter.rs b/crates/logic/src/filter.rs new file mode 100644 index 0000000..40e31a0 --- /dev/null +++ b/crates/logic/src/filter.rs @@ -0,0 +1,54 @@ +//! Mechanical rule engine: decides which records are kept and which extra tags they get. + +use crate::config::{Keep, Rule, Then, When}; +use crate::record::{Kind, NewRecord}; + +/// Rules first to last, then `keep`. Built-in tags are already on the records. +/// A `gap` record is the only sign that items were skipped, so it bypasses +/// every rule and `keep`, and is always kept untouched. +pub fn apply(records: Vec, rules: &[Rule], keep: Keep) -> Vec { + records + .into_iter() + .filter_map(|record| { + if record.kind == Kind::Gap { + return Some(record); + } + run_rules(record, rules).filter(|record| keep == Keep::All || !record.tags.is_empty()) + }) + .collect() +} + +fn run_rules(mut record: NewRecord, rules: &[Rule]) -> Option { + for rule in rules { + if !matches(&rule.when, &record) { + continue; + } + match &rule.then { + Then::Drop => return None, + Then::Tag(tag) => { + if !record.tags.contains(tag) { + record.tags.push(tag.clone()); + } + } + } + } + Some(record) +} + +/// Empty lists are "no condition"; a non-empty list matches if any element does; +/// all non-empty conditions must match. +pub fn matches(when: &When, record: &NewRecord) -> bool { + let actor = record.actor.to_lowercase(); + let actor_is = |a: &String| a.to_lowercase() == actor; + (when.kind.is_empty() || when.kind.contains(&record.kind)) + && (when.actor.is_empty() || when.actor.iter().any(actor_is)) + && (when.actor_not.is_empty() || !when.actor_not.iter().any(actor_is)) + && (when.reference.is_empty() || when.reference.contains(&record.reference)) + && (when.tag.is_empty() || when.tag.iter().any(|t| record.tags.contains(t))) + && (when.body_contains.is_empty() || { + let haystack = format!("{}\n{}", record.title, record.body).to_lowercase(); + when.body_contains + .iter() + .any(|needle| haystack.contains(&needle.to_lowercase())) + }) +} diff --git a/crates/logic/src/github.rs b/crates/logic/src/github.rs new file mode 100644 index 0000000..650b540 --- /dev/null +++ b/crates/logic/src/github.rs @@ -0,0 +1,548 @@ +//! Polls one GitHub repository: new issues, pull requests, comments, reviews and events. + +use serde::{Deserialize, Serialize}; + +use crate::config::GithubSource; +use crate::feed::{get_json, FeedClient, Identity, Poll, PollError}; +use crate::record::{truncate, Kind, NewRecord, Src}; +use crate::time::{epoch, iso}; + +const PER_PAGE: &str = "50"; +/// A list response with this many items may have more behind it. +const PER_PAGE_N: usize = 50; +const REVIEWS_PER_PAGE: &str = "100"; +const REVIEWS_PER_PAGE_N: usize = 100; +/// Reviews are paged (oldest first) at most this many times per pull request. +const REVIEWS_MAX_PAGES: usize = 10; +const BODY_MAX: usize = 600; +const BODY_SUFFIX: &str = " [...]"; +/// `last_check_at` is stored this many seconds early so nothing falls between polls. +const OVERLAP_SECS: i64 = 60; +const EVENT_KINDS: [&str; 6] = [ + "assigned", + "labeled", + "review_requested", + "closed", + "merged", + "reopened", +]; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct GithubState { + pub last_issue_number: u64, + pub last_pr_number: u64, + pub last_issue_comment_id: u64, + pub last_review_comment_id: u64, + pub last_event_id: u64, + /// ISO time of the last successful poll, stored 60 s early. + pub last_check_at: String, +} + +#[derive(Deserialize, Default)] +struct User { + #[serde(default)] + login: String, +} + +#[derive(Deserialize)] +struct Label { + #[serde(default)] + name: String, +} + +/// An entry of `/issues` or `/pulls`; the fields not present on one are defaulted. +#[derive(Deserialize)] +struct Item { + number: u64, + #[serde(default)] + title: String, + #[serde(default)] + body: Option, + #[serde(default)] + html_url: String, + #[serde(default)] + created_at: String, + #[serde(default)] + updated_at: String, + #[serde(default)] + user: User, + #[serde(default)] + assignees: Vec, + #[serde(default)] + labels: Vec