Constellation, Spacedust, Slingshot, UFOs: atproto crates and services for microcosm

Merge branch 'main' into constellation/filtering

+15
.github/FUNDING.yml
··· 1 + # These are supported funding model platforms 2 + 3 + github: uniphil 4 + patreon: # Replace with a single Patreon username 5 + open_collective: # Replace with a single Open Collective username 6 + ko_fi: # Replace with a single Ko-fi username 7 + tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 + community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 + liberapay: # Replace with a single Liberapay username 10 + issuehunt: # Replace with a single IssueHunt username 11 + lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 12 + polar: # Replace with a single Polar username 13 + buy_me_a_coffee: # Replace with a single Buy Me a Coffee username 14 + thanks_dev: # Replace with a single thanks.dev username 15 + custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
+21
.github/workflows/build.yml
··· 1 + name: Build 2 + 3 + on: 4 + push: 5 + tags: 6 + - "reflector-v*.*.*" 7 + 8 + jobs: 9 + build: 10 + runs-on: ubuntu-latest 11 + permissions: 12 + contents: write 13 + 14 + steps: 15 + - uses: actions/checkout@v4 16 + - name: build reflector 17 + run: cargo build --bin reflector --release && mv target/release/reflector target/release/reflector_amd64 18 + - name: release 19 + uses: softprops/action-gh-release@v2 20 + with: 21 + files: target/release/reflector_amd64
+4 -2
.github/workflows/checks.yml
··· 16 16 - uses: actions/checkout@v4 17 17 - name: Build lib 18 18 run: cargo build --verbose 19 + - name: Check (default features) 20 + run: cargo check 19 21 - name: Run tests 20 - run: cargo test --verbose 22 + run: cargo test --all-features --verbose 21 23 22 24 style: 23 25 runs-on: ubuntu-24.04 ··· 26 28 - name: get nightly toolchain for jetstream fmt 27 29 run: rustup toolchain install nightly --allow-downgrade -c rustfmt 28 30 - name: fmt 29 - run: cargo fmt --package links --package constellation --package ufos -- --check 31 + run: cargo fmt --package links --package constellation --package ufos --package spacedust --package who-am-i --package slingshot --package pocket -- --check 30 32 - name: fmt jetstream (nightly) 31 33 run: cargo +nightly fmt --package jetstream -- --check 32 34 - name: clippy
+2580 -184
Cargo.lock
··· 24 24 checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" 25 25 dependencies = [ 26 26 "cfg-if", 27 + "getrandom 0.2.15", 27 28 "once_cell", 28 29 "version_check", 29 30 "zerocopy 0.7.35", ··· 122 123 checksum = "dde20b3d026af13f561bdd0f15edf01fc734f0dafcedbaf42bba506a9517f223" 123 124 124 125 [[package]] 126 + name = "arc-swap" 127 + version = "1.7.1" 128 + source = "registry+https://github.com/rust-lang/crates.io-index" 129 + checksum = "69f7f8c3906b62b754cd5326047894316021dcfe5a194c8ea52bdd94934a3457" 130 + 131 + [[package]] 125 132 name = "arrayvec" 126 133 version = "0.7.6" 127 134 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 155 162 "proc-macro2", 156 163 "quote", 157 164 "serde", 158 - "syn", 165 + "syn 2.0.103", 159 166 ] 160 167 161 168 [[package]] ··· 174 181 ] 175 182 176 183 [[package]] 184 + name = "asn1-rs" 185 + version = "0.7.1" 186 + source = "registry+https://github.com/rust-lang/crates.io-index" 187 + checksum = "56624a96882bb8c26d61312ae18cb45868e5a9992ea73c58e45c3101e56a1e60" 188 + dependencies = [ 189 + "asn1-rs-derive", 190 + "asn1-rs-impl", 191 + "displaydoc", 192 + "nom", 193 + "num-traits", 194 + "rusticata-macros", 195 + "thiserror 2.0.16", 196 + "time", 197 + ] 198 + 199 + [[package]] 200 + name = "asn1-rs-derive" 201 + version = "0.6.0" 202 + source = "registry+https://github.com/rust-lang/crates.io-index" 203 + checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" 204 + dependencies = [ 205 + "proc-macro2", 206 + "quote", 207 + "syn 2.0.103", 208 + "synstructure", 209 + ] 210 + 211 + [[package]] 212 + name = "asn1-rs-impl" 213 + version = "0.2.0" 214 + source = "registry+https://github.com/rust-lang/crates.io-index" 215 + checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" 216 + dependencies = [ 217 + "proc-macro2", 218 + "quote", 219 + "syn 2.0.103", 220 + ] 221 + 222 + [[package]] 223 + name = "async-channel" 224 + version = "2.5.0" 225 + source = "registry+https://github.com/rust-lang/crates.io-index" 226 + checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" 227 + dependencies = [ 228 + "concurrent-queue", 229 + "event-listener-strategy", 230 + "futures-core", 231 + "pin-project-lite", 232 + ] 233 + 234 + [[package]] 235 + name = "async-compression" 236 + version = "0.4.25" 237 + source = "registry+https://github.com/rust-lang/crates.io-index" 238 + checksum = "40f6024f3f856663b45fd0c9b6f2024034a702f453549449e0d84a305900dad4" 239 + dependencies = [ 240 + "flate2", 241 + "futures-core", 242 + "memchr", 243 + "pin-project-lite", 244 + "tokio", 245 + ] 246 + 247 + [[package]] 177 248 name = "async-lock" 178 249 version = "3.4.0" 179 250 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 203 274 dependencies = [ 204 275 "proc-macro2", 205 276 "quote", 206 - "syn", 277 + "syn 2.0.103", 207 278 ] 208 279 209 280 [[package]] 281 + name = "async-task" 282 + version = "4.7.1" 283 + source = "registry+https://github.com/rust-lang/crates.io-index" 284 + checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" 285 + 286 + [[package]] 210 287 name = "async-trait" 211 288 version = "0.1.88" 212 289 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 214 291 dependencies = [ 215 292 "proc-macro2", 216 293 "quote", 217 - "syn", 294 + "syn 2.0.103", 218 295 ] 219 296 220 297 [[package]] ··· 225 302 226 303 [[package]] 227 304 name = "atrium-api" 228 - version = "0.25.3" 229 - source = "git+https://github.com/uniphil/atrium?branch=fix%2Fnsid-allow-nonleading-name-digits#c4364f318d337bbc3e3e3aaf97c9f971e95f5f7e" 305 + version = "0.25.4" 306 + source = "registry+https://github.com/rust-lang/crates.io-index" 307 + checksum = "46355d3245edc7b3160b2a45fe55d09a6963ebd3eee0252feb6b72fb0eb71463" 308 + dependencies = [ 309 + "atrium-common 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", 310 + "atrium-xrpc 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)", 311 + "chrono", 312 + "http", 313 + "ipld-core", 314 + "langtag", 315 + "regex", 316 + "serde", 317 + "serde_bytes", 318 + "serde_json", 319 + "thiserror 1.0.69", 320 + "tokio", 321 + "trait-variant", 322 + ] 323 + 324 + [[package]] 325 + name = "atrium-api" 326 + version = "0.25.4" 327 + source = "git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace#80a355991ac9b48ba3f559d12aac74f071fc638c" 230 328 dependencies = [ 231 - "atrium-common", 232 - "atrium-xrpc", 329 + "atrium-common 0.1.2 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)", 330 + "atrium-xrpc 0.12.3 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)", 233 331 "chrono", 234 332 "http", 235 333 "ipld-core", ··· 239 337 "serde_bytes", 240 338 "serde_json", 241 339 "thiserror 1.0.69", 340 + "tokio", 242 341 "trait-variant", 243 342 ] 244 343 245 344 [[package]] 246 345 name = "atrium-common" 247 346 version = "0.1.2" 248 - source = "git+https://github.com/uniphil/atrium?branch=fix%2Fnsid-allow-nonleading-name-digits#c4364f318d337bbc3e3e3aaf97c9f971e95f5f7e" 347 + source = "registry+https://github.com/rust-lang/crates.io-index" 348 + checksum = "9ed5610654043faa396a5a15afac0ac646d76aebe45aebd7cef4f8b96b0ab7f4" 349 + dependencies = [ 350 + "dashmap", 351 + "lru", 352 + "moka", 353 + "thiserror 1.0.69", 354 + "tokio", 355 + "trait-variant", 356 + "web-time", 357 + ] 358 + 359 + [[package]] 360 + name = "atrium-common" 361 + version = "0.1.2" 362 + source = "git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace#80a355991ac9b48ba3f559d12aac74f071fc638c" 249 363 dependencies = [ 250 364 "dashmap", 251 365 "lru", ··· 257 371 ] 258 372 259 373 [[package]] 374 + name = "atrium-crypto" 375 + version = "0.1.2" 376 + source = "registry+https://github.com/rust-lang/crates.io-index" 377 + checksum = "73a3da430c71dd9006d61072c20771f264e5c498420a49c32305ceab8bd71955" 378 + dependencies = [ 379 + "ecdsa", 380 + "k256", 381 + "multibase", 382 + "p256", 383 + "thiserror 1.0.69", 384 + ] 385 + 386 + [[package]] 387 + name = "atrium-identity" 388 + version = "0.1.5" 389 + source = "registry+https://github.com/rust-lang/crates.io-index" 390 + checksum = "c9e2d42bb4dbea038f4f5f45e3af2a89d61a9894a75f06aa550b74a60d2be380" 391 + dependencies = [ 392 + "atrium-api 0.25.4 (registry+https://github.com/rust-lang/crates.io-index)", 393 + "atrium-common 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", 394 + "atrium-xrpc 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)", 395 + "serde", 396 + "serde_html_form", 397 + "serde_json", 398 + "thiserror 1.0.69", 399 + "trait-variant", 400 + ] 401 + 402 + [[package]] 403 + name = "atrium-identity" 404 + version = "0.1.5" 405 + source = "git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace#80a355991ac9b48ba3f559d12aac74f071fc638c" 406 + dependencies = [ 407 + "atrium-api 0.25.4 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)", 408 + "atrium-common 0.1.2 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)", 409 + "atrium-xrpc 0.12.3 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)", 410 + "serde", 411 + "serde_html_form", 412 + "serde_json", 413 + "thiserror 1.0.69", 414 + "trait-variant", 415 + ] 416 + 417 + [[package]] 418 + name = "atrium-oauth" 419 + version = "0.1.3" 420 + source = "registry+https://github.com/rust-lang/crates.io-index" 421 + checksum = "ca22dc4eaf77fd9bf050b21192ac58cd654a437d28e000ec114ebd93a51d36f5" 422 + dependencies = [ 423 + "atrium-api 0.25.4 (registry+https://github.com/rust-lang/crates.io-index)", 424 + "atrium-common 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", 425 + "atrium-identity 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", 426 + "atrium-xrpc 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)", 427 + "base64 0.22.1", 428 + "chrono", 429 + "dashmap", 430 + "ecdsa", 431 + "elliptic-curve", 432 + "jose-jwa", 433 + "jose-jwk", 434 + "p256", 435 + "rand 0.8.5", 436 + "reqwest", 437 + "serde", 438 + "serde_html_form", 439 + "serde_json", 440 + "sha2", 441 + "thiserror 1.0.69", 442 + "tokio", 443 + "trait-variant", 444 + ] 445 + 446 + [[package]] 447 + name = "atrium-oauth" 448 + version = "0.1.3" 449 + source = "git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace#80a355991ac9b48ba3f559d12aac74f071fc638c" 450 + dependencies = [ 451 + "atrium-api 0.25.4 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)", 452 + "atrium-common 0.1.2 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)", 453 + "atrium-identity 0.1.5 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)", 454 + "atrium-xrpc 0.12.3 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)", 455 + "base64 0.22.1", 456 + "chrono", 457 + "dashmap", 458 + "ecdsa", 459 + "elliptic-curve", 460 + "jose-jwa", 461 + "jose-jwk", 462 + "p256", 463 + "rand 0.8.5", 464 + "reqwest", 465 + "serde", 466 + "serde_html_form", 467 + "serde_json", 468 + "sha2", 469 + "thiserror 1.0.69", 470 + "tokio", 471 + "trait-variant", 472 + ] 473 + 474 + [[package]] 260 475 name = "atrium-xrpc" 261 476 version = "0.12.3" 262 - source = "git+https://github.com/uniphil/atrium?branch=fix%2Fnsid-allow-nonleading-name-digits#c4364f318d337bbc3e3e3aaf97c9f971e95f5f7e" 477 + source = "registry+https://github.com/rust-lang/crates.io-index" 478 + checksum = "0216ad50ce34e9ff982e171c3659e65dedaa2ed5ac2994524debdc9a9647ffa8" 479 + dependencies = [ 480 + "http", 481 + "serde", 482 + "serde_html_form", 483 + "serde_json", 484 + "thiserror 1.0.69", 485 + "trait-variant", 486 + ] 487 + 488 + [[package]] 489 + name = "atrium-xrpc" 490 + version = "0.12.3" 491 + source = "git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace#80a355991ac9b48ba3f559d12aac74f071fc638c" 263 492 dependencies = [ 264 493 "http", 265 494 "serde", ··· 270 499 ] 271 500 272 501 [[package]] 502 + name = "auto_enums" 503 + version = "0.8.7" 504 + source = "registry+https://github.com/rust-lang/crates.io-index" 505 + checksum = "9c170965892137a3a9aeb000b4524aa3cc022a310e709d848b6e1cdce4ab4781" 506 + dependencies = [ 507 + "derive_utils", 508 + "proc-macro2", 509 + "quote", 510 + "syn 2.0.103", 511 + ] 512 + 513 + [[package]] 273 514 name = "autocfg" 274 515 version = "1.4.0" 275 516 source = "registry+https://github.com/rust-lang/crates.io-index" 276 517 checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" 277 518 278 519 [[package]] 520 + name = "aws-lc-rs" 521 + version = "1.13.1" 522 + source = "registry+https://github.com/rust-lang/crates.io-index" 523 + checksum = "93fcc8f365936c834db5514fc45aee5b1202d677e6b40e48468aaaa8183ca8c7" 524 + dependencies = [ 525 + "aws-lc-sys", 526 + "zeroize", 527 + ] 528 + 529 + [[package]] 530 + name = "aws-lc-sys" 531 + version = "0.29.0" 532 + source = "registry+https://github.com/rust-lang/crates.io-index" 533 + checksum = "61b1d86e7705efe1be1b569bab41d4fa1e14e220b60a160f78de2db687add079" 534 + dependencies = [ 535 + "bindgen 0.69.5", 536 + "cc", 537 + "cmake", 538 + "dunce", 539 + "fs_extra", 540 + ] 541 + 542 + [[package]] 279 543 name = "axum" 280 - version = "0.8.3" 544 + version = "0.8.4" 281 545 source = "registry+https://github.com/rust-lang/crates.io-index" 282 - checksum = "de45108900e1f9b9242f7f2e254aa3e2c029c921c258fe9e6b4217eeebd54288" 546 + checksum = "021e862c184ae977658b36c4500f7feac3221ca5da43e3f25bd04ab6c79a29b5" 283 547 dependencies = [ 284 548 "axum-core", 285 549 "bytes", ··· 338 602 "axum", 339 603 "axum-core", 340 604 "bytes", 605 + "cookie", 341 606 "futures-util", 342 607 "headers", 343 608 "http", ··· 368 633 ] 369 634 370 635 [[package]] 636 + name = "axum-template" 637 + version = "3.0.0" 638 + source = "registry+https://github.com/rust-lang/crates.io-index" 639 + checksum = "3df50f7d669bfc3a8c348f08f536fe37e7acfbeded3cfdffd2ad3d76725fc40c" 640 + dependencies = [ 641 + "axum", 642 + "handlebars", 643 + "serde", 644 + "thiserror 2.0.16", 645 + ] 646 + 647 + [[package]] 371 648 name = "backtrace" 372 649 version = "0.3.74" 373 650 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 379 656 "miniz_oxide", 380 657 "object", 381 658 "rustc-demangle", 382 - "windows-targets", 659 + "windows-targets 0.52.6", 383 660 ] 384 661 385 662 [[package]] ··· 389 666 checksum = "4cbbc9d0964165b47557570cce6c952866c2678457aca742aafc9fb771d30270" 390 667 391 668 [[package]] 669 + name = "base16ct" 670 + version = "0.2.0" 671 + source = "registry+https://github.com/rust-lang/crates.io-index" 672 + checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" 673 + 674 + [[package]] 392 675 name = "base64" 393 676 version = "0.21.7" 394 677 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 399 682 version = "0.22.1" 400 683 source = "registry+https://github.com/rust-lang/crates.io-index" 401 684 checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" 685 + 686 + [[package]] 687 + name = "base64ct" 688 + version = "1.8.0" 689 + source = "registry+https://github.com/rust-lang/crates.io-index" 690 + checksum = "55248b47b0caf0546f7988906588779981c43bb1bc9d0c44087278f80cdb44ba" 402 691 403 692 [[package]] 404 693 name = "basic-toml" ··· 450 739 "itertools 0.12.1", 451 740 "lazy_static", 452 741 "lazycell", 742 + "log", 743 + "prettyplease", 453 744 "proc-macro2", 454 745 "quote", 455 746 "regex", 456 747 "rustc-hash 1.1.0", 457 748 "shlex", 458 - "syn", 749 + "syn 2.0.103", 750 + "which", 459 751 ] 460 752 461 753 [[package]] ··· 473 765 "regex", 474 766 "rustc-hash 1.1.0", 475 767 "shlex", 476 - "syn", 768 + "syn 2.0.103", 477 769 ] 478 770 479 771 [[package]] ··· 491 783 "regex", 492 784 "rustc-hash 2.1.1", 493 785 "shlex", 494 - "syn", 786 + "syn 2.0.103", 787 + ] 788 + 789 + [[package]] 790 + name = "bitcoin-io" 791 + version = "0.1.3" 792 + source = "registry+https://github.com/rust-lang/crates.io-index" 793 + checksum = "0b47c4ab7a93edb0c7198c5535ed9b52b63095f4e9b45279c6736cec4b856baf" 794 + 795 + [[package]] 796 + name = "bitcoin_hashes" 797 + version = "0.14.0" 798 + source = "registry+https://github.com/rust-lang/crates.io-index" 799 + checksum = "bb18c03d0db0247e147a21a6faafd5a7eb851c743db062de72018b6b7e8e4d16" 800 + dependencies = [ 801 + "bitcoin-io", 802 + "hex-conservative", 495 803 ] 496 804 497 805 [[package]] ··· 571 879 572 880 [[package]] 573 881 name = "cardinality-estimator-safe" 574 - version = "4.0.1" 882 + version = "4.0.2" 575 883 source = "registry+https://github.com/rust-lang/crates.io-index" 576 - checksum = "b41ec0cd313b46ba3b508377544b25aa1d56d05ce9e657e77dfb001d5e726e53" 884 + checksum = "dc9887b4092040ea9a416fc3de9769ee7783e3cd5c168c941e6a8de69723b971" 577 885 dependencies = [ 578 886 "digest", 579 887 "enum_dispatch", ··· 628 936 ] 629 937 630 938 [[package]] 939 + name = "ciborium" 940 + version = "0.2.2" 941 + source = "registry+https://github.com/rust-lang/crates.io-index" 942 + checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" 943 + dependencies = [ 944 + "ciborium-io", 945 + "ciborium-ll", 946 + "serde", 947 + ] 948 + 949 + [[package]] 950 + name = "ciborium-io" 951 + version = "0.2.2" 952 + source = "registry+https://github.com/rust-lang/crates.io-index" 953 + checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" 954 + 955 + [[package]] 956 + name = "ciborium-ll" 957 + version = "0.2.2" 958 + source = "registry+https://github.com/rust-lang/crates.io-index" 959 + checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" 960 + dependencies = [ 961 + "ciborium-io", 962 + "half", 963 + ] 964 + 965 + [[package]] 631 966 name = "cid" 632 967 version = "0.11.1" 633 968 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 654 989 655 990 [[package]] 656 991 name = "clap" 657 - version = "4.5.35" 992 + version = "4.5.47" 658 993 source = "registry+https://github.com/rust-lang/crates.io-index" 659 - checksum = "d8aa86934b44c19c50f87cc2790e19f54f7a67aedb64101c2e1a2e5ecfb73944" 994 + checksum = "7eac00902d9d136acd712710d71823fb8ac8004ca445a89e73a41d45aa712931" 660 995 dependencies = [ 661 996 "clap_builder", 662 997 "clap_derive", ··· 664 999 665 1000 [[package]] 666 1001 name = "clap_builder" 667 - version = "4.5.35" 1002 + version = "4.5.47" 668 1003 source = "registry+https://github.com/rust-lang/crates.io-index" 669 - checksum = "2414dbb2dd0695280da6ea9261e327479e9d37b0630f6b53ba2a11c60c679fd9" 1004 + checksum = "2ad9bbf750e73b5884fb8a211a9424a1906c1e156724260fdae972f31d70e1d6" 670 1005 dependencies = [ 671 1006 "anstream", 672 1007 "anstyle", 673 1008 "clap_lex", 674 - "strsim", 1009 + "strsim 0.11.1", 675 1010 ] 676 1011 677 1012 [[package]] 678 1013 name = "clap_derive" 679 - version = "4.5.32" 1014 + version = "4.5.47" 680 1015 source = "registry+https://github.com/rust-lang/crates.io-index" 681 - checksum = "09176aae279615badda0765c0c0b3f6ed53f4709118af73cf4655d85d1530cd7" 1016 + checksum = "bbfd7eae0b0f1a6e63d4b13c9c478de77c2eb546fba158ad50b4203dc24b9f9c" 682 1017 dependencies = [ 683 1018 "heck", 684 1019 "proc-macro2", 685 1020 "quote", 686 - "syn", 1021 + "syn 2.0.103", 687 1022 ] 688 1023 689 1024 [[package]] ··· 704 1039 ] 705 1040 706 1041 [[package]] 1042 + name = "cmake" 1043 + version = "0.1.54" 1044 + source = "registry+https://github.com/rust-lang/crates.io-index" 1045 + checksum = "e7caa3f9de89ddbe2c607f4101924c5abec803763ae9534e4f4d7d8f84aa81f0" 1046 + dependencies = [ 1047 + "cc", 1048 + ] 1049 + 1050 + [[package]] 1051 + name = "cmsketch" 1052 + version = "0.2.2" 1053 + source = "registry+https://github.com/rust-lang/crates.io-index" 1054 + checksum = "553c840ee51da812c6cd621f9f7e07dfb00a49f91283a8e6380c78cba4f61aba" 1055 + dependencies = [ 1056 + "paste", 1057 + ] 1058 + 1059 + [[package]] 707 1060 name = "colorchoice" 708 1061 version = "1.0.3" 709 1062 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 725 1078 ] 726 1079 727 1080 [[package]] 1081 + name = "const-oid" 1082 + version = "0.9.6" 1083 + source = "registry+https://github.com/rust-lang/crates.io-index" 1084 + checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" 1085 + 1086 + [[package]] 728 1087 name = "constellation" 729 1088 version = "0.1.0" 730 1089 dependencies = [ ··· 737 1096 "clap", 738 1097 "ctrlc", 739 1098 "flume", 740 - "fs4", 1099 + "fs4 0.12.0", 741 1100 "headers-accept", 742 1101 "links", 743 1102 "mediatype", 744 1103 "metrics", 745 - "metrics-exporter-prometheus", 1104 + "metrics-exporter-prometheus 0.16.2", 746 1105 "metrics-process", 747 1106 "num-format", 748 1107 "ratelimit", ··· 755 1114 "tokio", 756 1115 "tokio-util", 757 1116 "tower-http", 758 - "tungstenite", 1117 + "tungstenite 0.26.2", 759 1118 "zstd", 760 1119 ] 761 1120 762 1121 [[package]] 1122 + name = "cookie" 1123 + version = "0.18.1" 1124 + source = "registry+https://github.com/rust-lang/crates.io-index" 1125 + checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747" 1126 + dependencies = [ 1127 + "base64 0.22.1", 1128 + "hmac", 1129 + "percent-encoding", 1130 + "rand 0.8.5", 1131 + "sha2", 1132 + "subtle", 1133 + "time", 1134 + "version_check", 1135 + ] 1136 + 1137 + [[package]] 763 1138 name = "core-foundation" 764 1139 version = "0.9.4" 765 1140 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 770 1145 ] 771 1146 772 1147 [[package]] 1148 + name = "core-foundation" 1149 + version = "0.10.1" 1150 + source = "registry+https://github.com/rust-lang/crates.io-index" 1151 + checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" 1152 + dependencies = [ 1153 + "core-foundation-sys", 1154 + "libc", 1155 + ] 1156 + 1157 + [[package]] 773 1158 name = "core-foundation-sys" 774 1159 version = "0.8.7" 775 1160 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 794 1179 ] 795 1180 796 1181 [[package]] 1182 + name = "crc32fast" 1183 + version = "1.4.2" 1184 + source = "registry+https://github.com/rust-lang/crates.io-index" 1185 + checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3" 1186 + dependencies = [ 1187 + "cfg-if", 1188 + ] 1189 + 1190 + [[package]] 1191 + name = "critical-section" 1192 + version = "1.2.0" 1193 + source = "registry+https://github.com/rust-lang/crates.io-index" 1194 + checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" 1195 + 1196 + [[package]] 797 1197 name = "crossbeam-channel" 798 1198 version = "0.5.15" 799 1199 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 828 1228 checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" 829 1229 830 1230 [[package]] 1231 + name = "crunchy" 1232 + version = "0.2.4" 1233 + source = "registry+https://github.com/rust-lang/crates.io-index" 1234 + checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" 1235 + 1236 + [[package]] 1237 + name = "crypto-bigint" 1238 + version = "0.5.5" 1239 + source = "registry+https://github.com/rust-lang/crates.io-index" 1240 + checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" 1241 + dependencies = [ 1242 + "generic-array", 1243 + "rand_core 0.6.4", 1244 + "subtle", 1245 + "zeroize", 1246 + ] 1247 + 1248 + [[package]] 831 1249 name = "crypto-common" 832 1250 version = "0.1.6" 833 1251 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 839 1257 840 1258 [[package]] 841 1259 name = "ctrlc" 842 - version = "3.4.6" 1260 + version = "3.4.7" 843 1261 source = "registry+https://github.com/rust-lang/crates.io-index" 844 - checksum = "697b5419f348fd5ae2478e8018cb016c00a5881c7f46c717de98ffd135a5651c" 1262 + checksum = "46f93780a459b7d656ef7f071fe699c4d3d2cb201c4b24d085b6ddc505276e73" 845 1263 dependencies = [ 846 1264 "nix", 847 1265 "windows-sys 0.59.0", ··· 849 1267 850 1268 [[package]] 851 1269 name = "darling" 1270 + version = "0.14.4" 1271 + source = "registry+https://github.com/rust-lang/crates.io-index" 1272 + checksum = "7b750cb3417fd1b327431a470f388520309479ab0bf5e323505daf0290cd3850" 1273 + dependencies = [ 1274 + "darling_core 0.14.4", 1275 + "darling_macro 0.14.4", 1276 + ] 1277 + 1278 + [[package]] 1279 + name = "darling" 852 1280 version = "0.20.11" 853 1281 source = "registry+https://github.com/rust-lang/crates.io-index" 854 1282 checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" 855 1283 dependencies = [ 856 - "darling_core", 857 - "darling_macro", 1284 + "darling_core 0.20.11", 1285 + "darling_macro 0.20.11", 1286 + ] 1287 + 1288 + [[package]] 1289 + name = "darling_core" 1290 + version = "0.14.4" 1291 + source = "registry+https://github.com/rust-lang/crates.io-index" 1292 + checksum = "109c1ca6e6b7f82cc233a97004ea8ed7ca123a9af07a8230878fcfda9b158bf0" 1293 + dependencies = [ 1294 + "fnv", 1295 + "ident_case", 1296 + "proc-macro2", 1297 + "quote", 1298 + "strsim 0.10.0", 1299 + "syn 1.0.109", 858 1300 ] 859 1301 860 1302 [[package]] ··· 867 1309 "ident_case", 868 1310 "proc-macro2", 869 1311 "quote", 870 - "strsim", 871 - "syn", 1312 + "strsim 0.11.1", 1313 + "syn 2.0.103", 1314 + ] 1315 + 1316 + [[package]] 1317 + name = "darling_macro" 1318 + version = "0.14.4" 1319 + source = "registry+https://github.com/rust-lang/crates.io-index" 1320 + checksum = "a4aab4dbc9f7611d8b55048a3a16d2d010c2c8334e46304b40ac1cc14bf3b48e" 1321 + dependencies = [ 1322 + "darling_core 0.14.4", 1323 + "quote", 1324 + "syn 1.0.109", 872 1325 ] 873 1326 874 1327 [[package]] ··· 877 1330 source = "registry+https://github.com/rust-lang/crates.io-index" 878 1331 checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" 879 1332 dependencies = [ 880 - "darling_core", 1333 + "darling_core 0.20.11", 881 1334 "quote", 882 - "syn", 1335 + "syn 2.0.103", 883 1336 ] 884 1337 885 1338 [[package]] ··· 919 1372 checksum = "18e4fdb82bd54a12e42fb58a800dcae6b9e13982238ce2296dc3570b92148e1f" 920 1373 dependencies = [ 921 1374 "data-encoding", 922 - "syn", 1375 + "syn 2.0.103", 923 1376 ] 924 1377 925 1378 [[package]] ··· 929 1382 checksum = "ffe7ed1d93f4553003e20b629abe9085e1e81b1429520f897f8f8860bc6dfc21" 930 1383 931 1384 [[package]] 1385 + name = "der" 1386 + version = "0.7.10" 1387 + source = "registry+https://github.com/rust-lang/crates.io-index" 1388 + checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" 1389 + dependencies = [ 1390 + "const-oid", 1391 + "pem-rfc7468", 1392 + "zeroize", 1393 + ] 1394 + 1395 + [[package]] 1396 + name = "der-parser" 1397 + version = "10.0.0" 1398 + source = "registry+https://github.com/rust-lang/crates.io-index" 1399 + checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" 1400 + dependencies = [ 1401 + "asn1-rs", 1402 + "displaydoc", 1403 + "nom", 1404 + "num-bigint", 1405 + "num-traits", 1406 + "rusticata-macros", 1407 + ] 1408 + 1409 + [[package]] 932 1410 name = "deranged" 933 1411 version = "0.4.0" 934 1412 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 939 1417 ] 940 1418 941 1419 [[package]] 1420 + name = "derive_builder" 1421 + version = "0.20.2" 1422 + source = "registry+https://github.com/rust-lang/crates.io-index" 1423 + checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947" 1424 + dependencies = [ 1425 + "derive_builder_macro", 1426 + ] 1427 + 1428 + [[package]] 1429 + name = "derive_builder_core" 1430 + version = "0.20.2" 1431 + source = "registry+https://github.com/rust-lang/crates.io-index" 1432 + checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8" 1433 + dependencies = [ 1434 + "darling 0.20.11", 1435 + "proc-macro2", 1436 + "quote", 1437 + "syn 2.0.103", 1438 + ] 1439 + 1440 + [[package]] 1441 + name = "derive_builder_macro" 1442 + version = "0.20.2" 1443 + source = "registry+https://github.com/rust-lang/crates.io-index" 1444 + checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" 1445 + dependencies = [ 1446 + "derive_builder_core", 1447 + "syn 2.0.103", 1448 + ] 1449 + 1450 + [[package]] 1451 + name = "derive_more" 1452 + version = "2.0.1" 1453 + source = "registry+https://github.com/rust-lang/crates.io-index" 1454 + checksum = "093242cf7570c207c83073cf82f79706fe7b8317e98620a47d5be7c3d8497678" 1455 + dependencies = [ 1456 + "derive_more-impl", 1457 + ] 1458 + 1459 + [[package]] 1460 + name = "derive_more-impl" 1461 + version = "2.0.1" 1462 + source = "registry+https://github.com/rust-lang/crates.io-index" 1463 + checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3" 1464 + dependencies = [ 1465 + "proc-macro2", 1466 + "quote", 1467 + "syn 2.0.103", 1468 + "unicode-xid", 1469 + ] 1470 + 1471 + [[package]] 1472 + name = "derive_utils" 1473 + version = "0.15.0" 1474 + source = "registry+https://github.com/rust-lang/crates.io-index" 1475 + checksum = "ccfae181bab5ab6c5478b2ccb69e4c68a02f8c3ec72f6616bfec9dbc599d2ee0" 1476 + dependencies = [ 1477 + "proc-macro2", 1478 + "quote", 1479 + "syn 2.0.103", 1480 + ] 1481 + 1482 + [[package]] 942 1483 name = "digest" 943 1484 version = "0.10.7" 944 1485 source = "registry+https://github.com/rust-lang/crates.io-index" 945 1486 checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" 946 1487 dependencies = [ 947 1488 "block-buffer", 1489 + "const-oid", 948 1490 "crypto-common", 1491 + "subtle", 949 1492 ] 950 1493 951 1494 [[package]] ··· 977 1520 dependencies = [ 978 1521 "proc-macro2", 979 1522 "quote", 980 - "syn", 1523 + "syn 2.0.103", 981 1524 ] 982 1525 983 1526 [[package]] ··· 987 1530 checksum = "c0d05e1c0dbad51b52c38bda7adceef61b9efc2baf04acfe8726a8c4630a6f57" 988 1531 989 1532 [[package]] 1533 + name = "downcast-rs" 1534 + version = "1.2.1" 1535 + source = "registry+https://github.com/rust-lang/crates.io-index" 1536 + checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" 1537 + 1538 + [[package]] 990 1539 name = "dropshot" 991 - version = "0.16.0" 1540 + version = "0.16.2" 992 1541 source = "registry+https://github.com/rust-lang/crates.io-index" 993 - checksum = "a37c505dad56e0c1fa5ed47e29fab1a1ab2d1a9d93e952024bb47168969705f6" 1542 + checksum = "50e8fed669e35e757646ad10f97c4d26dd22cce3da689b307954f7000d2719d0" 994 1543 dependencies = [ 995 1544 "async-stream", 996 1545 "async-trait", ··· 1012 1561 "openapiv3", 1013 1562 "paste", 1014 1563 "percent-encoding", 1015 - "rustls", 1564 + "rustls 0.22.4", 1016 1565 "rustls-pemfile", 1017 1566 "schemars", 1018 1567 "scopeguard", ··· 1027 1576 "slog-bunyan", 1028 1577 "slog-json", 1029 1578 "slog-term", 1030 - "thiserror 2.0.12", 1579 + "thiserror 2.0.16", 1031 1580 "tokio", 1032 - "tokio-rustls", 1581 + "tokio-rustls 0.25.0", 1033 1582 "toml", 1034 1583 "uuid", 1035 1584 "version_check", ··· 1038 1587 1039 1588 [[package]] 1040 1589 name = "dropshot_endpoint" 1041 - version = "0.16.0" 1590 + version = "0.16.2" 1042 1591 source = "registry+https://github.com/rust-lang/crates.io-index" 1043 - checksum = "8b1a6db3728f0195e3ad62807649913aaba06d45421e883416e555e51464ef67" 1592 + checksum = "acebb687581abdeaa2c89fa448818a5f803b0e68e5d7e7a1cf585a8f3c5c57ac" 1044 1593 dependencies = [ 1045 1594 "heck", 1046 1595 "proc-macro2", ··· 1048 1597 "semver", 1049 1598 "serde", 1050 1599 "serde_tokenstream", 1051 - "syn", 1600 + "syn 2.0.103", 1052 1601 ] 1053 1602 1054 1603 [[package]] 1604 + name = "dunce" 1605 + version = "1.0.5" 1606 + source = "registry+https://github.com/rust-lang/crates.io-index" 1607 + checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" 1608 + 1609 + [[package]] 1055 1610 name = "dyn-clone" 1056 1611 version = "1.0.19" 1057 1612 source = "registry+https://github.com/rust-lang/crates.io-index" 1058 1613 checksum = "1c7a8fb8a9fbf66c1f703fe16184d10ca0ee9d23be5b4436400408ba54a95005" 1059 1614 1060 1615 [[package]] 1616 + name = "ecdsa" 1617 + version = "0.16.9" 1618 + source = "registry+https://github.com/rust-lang/crates.io-index" 1619 + checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" 1620 + dependencies = [ 1621 + "der", 1622 + "digest", 1623 + "elliptic-curve", 1624 + "rfc6979", 1625 + "signature", 1626 + "spki", 1627 + ] 1628 + 1629 + [[package]] 1061 1630 name = "either" 1062 1631 version = "1.15.0" 1063 1632 source = "registry+https://github.com/rust-lang/crates.io-index" 1064 1633 checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" 1065 1634 1066 1635 [[package]] 1636 + name = "elliptic-curve" 1637 + version = "0.13.8" 1638 + source = "registry+https://github.com/rust-lang/crates.io-index" 1639 + checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" 1640 + dependencies = [ 1641 + "base16ct", 1642 + "crypto-bigint", 1643 + "digest", 1644 + "ff", 1645 + "generic-array", 1646 + "group", 1647 + "pem-rfc7468", 1648 + "pkcs8", 1649 + "rand_core 0.6.4", 1650 + "sec1", 1651 + "subtle", 1652 + "zeroize", 1653 + ] 1654 + 1655 + [[package]] 1067 1656 name = "encoding_rs" 1068 1657 version = "0.8.35" 1069 1658 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 1073 1662 ] 1074 1663 1075 1664 [[package]] 1665 + name = "enum-as-inner" 1666 + version = "0.6.1" 1667 + source = "registry+https://github.com/rust-lang/crates.io-index" 1668 + checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc" 1669 + dependencies = [ 1670 + "heck", 1671 + "proc-macro2", 1672 + "quote", 1673 + "syn 2.0.103", 1674 + ] 1675 + 1676 + [[package]] 1076 1677 name = "enum_dispatch" 1077 1678 version = "0.3.13" 1078 1679 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 1081 1682 "once_cell", 1082 1683 "proc-macro2", 1083 1684 "quote", 1084 - "syn", 1685 + "syn 2.0.103", 1085 1686 ] 1086 1687 1087 1688 [[package]] ··· 1145 1746 ] 1146 1747 1147 1748 [[package]] 1749 + name = "fallible-iterator" 1750 + version = "0.3.0" 1751 + source = "registry+https://github.com/rust-lang/crates.io-index" 1752 + checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" 1753 + 1754 + [[package]] 1755 + name = "fallible-streaming-iterator" 1756 + version = "0.1.9" 1757 + source = "registry+https://github.com/rust-lang/crates.io-index" 1758 + checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" 1759 + 1760 + [[package]] 1148 1761 name = "fastrand" 1149 1762 version = "2.3.0" 1150 1763 source = "registry+https://github.com/rust-lang/crates.io-index" 1151 1764 checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" 1152 1765 1153 1766 [[package]] 1767 + name = "ff" 1768 + version = "0.13.1" 1769 + source = "registry+https://github.com/rust-lang/crates.io-index" 1770 + checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" 1771 + dependencies = [ 1772 + "rand_core 0.6.4", 1773 + "subtle", 1774 + ] 1775 + 1776 + [[package]] 1154 1777 name = "fjall" 1155 - version = "2.8.0" 1778 + version = "2.11.2" 1156 1779 source = "registry+https://github.com/rust-lang/crates.io-index" 1157 - checksum = "26b2ced3483989a62b3533c9f99054d73b527c6c0045cf22b00fe87956f1a46f" 1780 + checksum = "0b25ad44cd4360a0448a9b5a0a6f1c7a621101cca4578706d43c9a821418aebc" 1781 + dependencies = [ 1782 + "byteorder", 1783 + "byteview", 1784 + "dashmap", 1785 + "log", 1786 + "lsm-tree", 1787 + "path-absolutize", 1788 + "std-semaphore", 1789 + "tempfile", 1790 + "xxhash-rust", 1791 + ] 1792 + 1793 + [[package]] 1794 + name = "fjall" 1795 + version = "2.11.2" 1796 + source = "git+https://github.com/fjall-rs/fjall.git#42d811f7c8cc9004407d520d37d2a1d8d246c03d" 1158 1797 dependencies = [ 1159 1798 "byteorder", 1160 1799 "byteview", ··· 1168 1807 ] 1169 1808 1170 1809 [[package]] 1810 + name = "flate2" 1811 + version = "1.1.2" 1812 + source = "registry+https://github.com/rust-lang/crates.io-index" 1813 + checksum = "4a3d7db9596fecd151c5f638c0ee5d5bd487b6e0ea232e5dc96d5250f6f94b1d" 1814 + dependencies = [ 1815 + "crc32fast", 1816 + "miniz_oxide", 1817 + ] 1818 + 1819 + [[package]] 1171 1820 name = "fluent-uri" 1172 1821 version = "0.3.2" 1173 1822 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 1183 1832 source = "registry+https://github.com/rust-lang/crates.io-index" 1184 1833 checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095" 1185 1834 dependencies = [ 1835 + "futures-core", 1836 + "futures-sink", 1837 + "nanorand", 1186 1838 "spin", 1187 1839 ] 1188 1840 ··· 1223 1875 ] 1224 1876 1225 1877 [[package]] 1878 + name = "foyer" 1879 + version = "0.18.0" 1880 + source = "registry+https://github.com/rust-lang/crates.io-index" 1881 + checksum = "0b4d8e96374206ff1b4265f2e2e6e1f80bc3048957b2a1e7fdeef929d68f318f" 1882 + dependencies = [ 1883 + "equivalent", 1884 + "foyer-common", 1885 + "foyer-memory", 1886 + "foyer-storage", 1887 + "madsim-tokio", 1888 + "mixtrics", 1889 + "pin-project", 1890 + "serde", 1891 + "thiserror 2.0.16", 1892 + "tokio", 1893 + "tracing", 1894 + ] 1895 + 1896 + [[package]] 1897 + name = "foyer-common" 1898 + version = "0.18.0" 1899 + source = "registry+https://github.com/rust-lang/crates.io-index" 1900 + checksum = "911b8e3f23d5fe55b0b240f75af1d2fa5cb7261d3f9b38ef1c57bbc9f0449317" 1901 + dependencies = [ 1902 + "bincode 1.3.3", 1903 + "bytes", 1904 + "cfg-if", 1905 + "itertools 0.14.0", 1906 + "madsim-tokio", 1907 + "mixtrics", 1908 + "parking_lot", 1909 + "pin-project", 1910 + "serde", 1911 + "thiserror 2.0.16", 1912 + "tokio", 1913 + "twox-hash", 1914 + ] 1915 + 1916 + [[package]] 1917 + name = "foyer-intrusive-collections" 1918 + version = "0.10.0-dev" 1919 + source = "registry+https://github.com/rust-lang/crates.io-index" 1920 + checksum = "6e4fee46bea69e0596130e3210e65d3424e0ac1e6df3bde6636304bdf1ca4a3b" 1921 + dependencies = [ 1922 + "memoffset", 1923 + ] 1924 + 1925 + [[package]] 1926 + name = "foyer-memory" 1927 + version = "0.18.0" 1928 + source = "registry+https://github.com/rust-lang/crates.io-index" 1929 + checksum = "506883d5a8500dea1b1662f7180f3534bdcbfa718d3253db7179552ef83612fa" 1930 + dependencies = [ 1931 + "arc-swap", 1932 + "bitflags", 1933 + "cmsketch", 1934 + "equivalent", 1935 + "foyer-common", 1936 + "foyer-intrusive-collections", 1937 + "hashbrown 0.15.2", 1938 + "itertools 0.14.0", 1939 + "madsim-tokio", 1940 + "mixtrics", 1941 + "parking_lot", 1942 + "pin-project", 1943 + "serde", 1944 + "thiserror 2.0.16", 1945 + "tokio", 1946 + "tracing", 1947 + ] 1948 + 1949 + [[package]] 1950 + name = "foyer-storage" 1951 + version = "0.18.0" 1952 + source = "registry+https://github.com/rust-lang/crates.io-index" 1953 + checksum = "1ba8403a54a2f2032fb647e49c442e5feeb33f3989f7024f1b178341a016f06d" 1954 + dependencies = [ 1955 + "allocator-api2", 1956 + "anyhow", 1957 + "auto_enums", 1958 + "bytes", 1959 + "equivalent", 1960 + "flume", 1961 + "foyer-common", 1962 + "foyer-memory", 1963 + "fs4 0.13.1", 1964 + "futures-core", 1965 + "futures-util", 1966 + "itertools 0.14.0", 1967 + "libc", 1968 + "lz4", 1969 + "madsim-tokio", 1970 + "ordered_hash_map", 1971 + "parking_lot", 1972 + "paste", 1973 + "pin-project", 1974 + "rand 0.9.1", 1975 + "serde", 1976 + "thiserror 2.0.16", 1977 + "tokio", 1978 + "tracing", 1979 + "twox-hash", 1980 + "zstd", 1981 + ] 1982 + 1983 + [[package]] 1226 1984 name = "fs4" 1227 1985 version = "0.12.0" 1228 1986 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 1233 1991 ] 1234 1992 1235 1993 [[package]] 1994 + name = "fs4" 1995 + version = "0.13.1" 1996 + source = "registry+https://github.com/rust-lang/crates.io-index" 1997 + checksum = "8640e34b88f7652208ce9e88b1a37a2ae95227d84abec377ccd3c5cfeb141ed4" 1998 + dependencies = [ 1999 + "rustix 1.0.5", 2000 + "windows-sys 0.59.0", 2001 + ] 2002 + 2003 + [[package]] 2004 + name = "fs_extra" 2005 + version = "1.3.0" 2006 + source = "registry+https://github.com/rust-lang/crates.io-index" 2007 + checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" 2008 + 2009 + [[package]] 1236 2010 name = "futures" 1237 2011 version = "0.3.31" 1238 2012 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 1288 2062 dependencies = [ 1289 2063 "proc-macro2", 1290 2064 "quote", 1291 - "syn", 2065 + "syn 2.0.103", 1292 2066 ] 1293 2067 1294 2068 [[package]] ··· 1342 2116 dependencies = [ 1343 2117 "typenum", 1344 2118 "version_check", 2119 + "zeroize", 1345 2120 ] 1346 2121 1347 2122 [[package]] ··· 1351 2126 checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" 1352 2127 dependencies = [ 1353 2128 "cfg-if", 2129 + "js-sys", 1354 2130 "libc", 1355 2131 "wasi 0.11.0+wasi-snapshot-preview1", 2132 + "wasm-bindgen", 1356 2133 ] 1357 2134 1358 2135 [[package]] ··· 1362 2139 checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" 1363 2140 dependencies = [ 1364 2141 "cfg-if", 2142 + "js-sys", 1365 2143 "libc", 1366 2144 "r-efi", 1367 2145 "wasi 0.14.2+wasi-0.2.4", 2146 + "wasm-bindgen", 1368 2147 ] 1369 2148 1370 2149 [[package]] ··· 1380 2159 checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2" 1381 2160 1382 2161 [[package]] 2162 + name = "group" 2163 + version = "0.13.0" 2164 + source = "registry+https://github.com/rust-lang/crates.io-index" 2165 + checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" 2166 + dependencies = [ 2167 + "ff", 2168 + "rand_core 0.6.4", 2169 + "subtle", 2170 + ] 2171 + 2172 + [[package]] 1383 2173 name = "guardian" 1384 2174 version = "1.3.0" 1385 2175 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 1405 2195 ] 1406 2196 1407 2197 [[package]] 2198 + name = "half" 2199 + version = "2.6.0" 2200 + source = "registry+https://github.com/rust-lang/crates.io-index" 2201 + checksum = "459196ed295495a68f7d7fe1d84f6c4b7ff0e21fe3017b2f283c6fac3ad803c9" 2202 + dependencies = [ 2203 + "cfg-if", 2204 + "crunchy", 2205 + ] 2206 + 2207 + [[package]] 2208 + name = "handlebars" 2209 + version = "6.3.2" 2210 + source = "registry+https://github.com/rust-lang/crates.io-index" 2211 + checksum = "759e2d5aea3287cb1190c8ec394f42866cb5bf74fcbf213f354e3c856ea26098" 2212 + dependencies = [ 2213 + "derive_builder", 2214 + "log", 2215 + "num-order", 2216 + "pest", 2217 + "pest_derive", 2218 + "serde", 2219 + "serde_json", 2220 + "thiserror 2.0.16", 2221 + "walkdir", 2222 + ] 2223 + 2224 + [[package]] 1408 2225 name = "hashbrown" 1409 2226 version = "0.12.3" 1410 2227 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 1412 2229 1413 2230 [[package]] 1414 2231 name = "hashbrown" 2232 + version = "0.13.2" 2233 + source = "registry+https://github.com/rust-lang/crates.io-index" 2234 + checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e" 2235 + dependencies = [ 2236 + "ahash", 2237 + ] 2238 + 2239 + [[package]] 2240 + name = "hashbrown" 1415 2241 version = "0.14.5" 1416 2242 source = "registry+https://github.com/rust-lang/crates.io-index" 1417 2243 checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" ··· 1428 2254 ] 1429 2255 1430 2256 [[package]] 2257 + name = "hashlink" 2258 + version = "0.10.0" 2259 + source = "registry+https://github.com/rust-lang/crates.io-index" 2260 + checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" 2261 + dependencies = [ 2262 + "hashbrown 0.15.2", 2263 + ] 2264 + 2265 + [[package]] 1431 2266 name = "headers" 1432 2267 version = "0.4.0" 1433 2268 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 1481 2316 checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" 1482 2317 1483 2318 [[package]] 2319 + name = "hex-conservative" 2320 + version = "0.2.1" 2321 + source = "registry+https://github.com/rust-lang/crates.io-index" 2322 + checksum = "5313b072ce3c597065a808dbf612c4c8e8590bdbf8b579508bf7a762c5eae6cd" 2323 + dependencies = [ 2324 + "arrayvec", 2325 + ] 2326 + 2327 + [[package]] 2328 + name = "hickory-proto" 2329 + version = "0.25.2" 2330 + source = "registry+https://github.com/rust-lang/crates.io-index" 2331 + checksum = "f8a6fe56c0038198998a6f217ca4e7ef3a5e51f46163bd6dd60b5c71ca6c6502" 2332 + dependencies = [ 2333 + "async-trait", 2334 + "cfg-if", 2335 + "data-encoding", 2336 + "enum-as-inner", 2337 + "futures-channel", 2338 + "futures-io", 2339 + "futures-util", 2340 + "idna", 2341 + "ipnet", 2342 + "once_cell", 2343 + "rand 0.9.1", 2344 + "ring", 2345 + "thiserror 2.0.16", 2346 + "tinyvec", 2347 + "tokio", 2348 + "tracing", 2349 + "url", 2350 + ] 2351 + 2352 + [[package]] 2353 + name = "hickory-resolver" 2354 + version = "0.25.2" 2355 + source = "registry+https://github.com/rust-lang/crates.io-index" 2356 + checksum = "dc62a9a99b0bfb44d2ab95a7208ac952d31060efc16241c87eaf36406fecf87a" 2357 + dependencies = [ 2358 + "cfg-if", 2359 + "futures-util", 2360 + "hickory-proto", 2361 + "ipconfig", 2362 + "moka", 2363 + "once_cell", 2364 + "parking_lot", 2365 + "rand 0.9.1", 2366 + "resolv-conf", 2367 + "smallvec", 2368 + "thiserror 2.0.16", 2369 + "tokio", 2370 + "tracing", 2371 + ] 2372 + 2373 + [[package]] 2374 + name = "hmac" 2375 + version = "0.12.1" 2376 + source = "registry+https://github.com/rust-lang/crates.io-index" 2377 + checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" 2378 + dependencies = [ 2379 + "digest", 2380 + ] 2381 + 2382 + [[package]] 2383 + name = "home" 2384 + version = "0.5.11" 2385 + source = "registry+https://github.com/rust-lang/crates.io-index" 2386 + checksum = "589533453244b0995c858700322199b2becb13b627df2851f64a2775d024abcf" 2387 + dependencies = [ 2388 + "windows-sys 0.59.0", 2389 + ] 2390 + 2391 + [[package]] 1484 2392 name = "hostname" 1485 2393 version = "0.3.1" 1486 2394 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 1579 2487 ] 1580 2488 1581 2489 [[package]] 2490 + name = "hyper-rustls" 2491 + version = "0.27.7" 2492 + source = "registry+https://github.com/rust-lang/crates.io-index" 2493 + checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58" 2494 + dependencies = [ 2495 + "http", 2496 + "hyper", 2497 + "hyper-util", 2498 + "rustls 0.23.31", 2499 + "rustls-native-certs", 2500 + "rustls-pki-types", 2501 + "tokio", 2502 + "tokio-rustls 0.26.2", 2503 + "tower-service", 2504 + ] 2505 + 2506 + [[package]] 2507 + name = "hyper-tls" 2508 + version = "0.6.0" 2509 + source = "registry+https://github.com/rust-lang/crates.io-index" 2510 + checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" 2511 + dependencies = [ 2512 + "bytes", 2513 + "http-body-util", 2514 + "hyper", 2515 + "hyper-util", 2516 + "native-tls", 2517 + "tokio", 2518 + "tokio-native-tls", 2519 + "tower-service", 2520 + ] 2521 + 2522 + [[package]] 1582 2523 name = "hyper-util" 1583 - version = "0.1.11" 2524 + version = "0.1.16" 1584 2525 source = "registry+https://github.com/rust-lang/crates.io-index" 1585 - checksum = "497bbc33a26fdd4af9ed9c70d63f61cf56a938375fbb32df34db9b1cd6d643f2" 2526 + checksum = "8d9b05277c7e8da2c93a568989bb6207bef0112e8d17df7a6eda4a3cf143bc5e" 1586 2527 dependencies = [ 2528 + "base64 0.22.1", 1587 2529 "bytes", 1588 2530 "futures-channel", 2531 + "futures-core", 1589 2532 "futures-util", 1590 2533 "http", 1591 2534 "http-body", 1592 2535 "hyper", 2536 + "ipnet", 1593 2537 "libc", 2538 + "percent-encoding", 1594 2539 "pin-project-lite", 1595 - "socket2", 2540 + "socket2 0.6.0", 2541 + "system-configuration", 1596 2542 "tokio", 1597 2543 "tower-service", 1598 2544 "tracing", 2545 + "windows-registry", 1599 2546 ] 1600 2547 1601 2548 [[package]] ··· 1737 2684 dependencies = [ 1738 2685 "proc-macro2", 1739 2686 "quote", 1740 - "syn", 2687 + "syn 2.0.103", 1741 2688 ] 1742 2689 1743 2690 [[package]] ··· 1799 2746 ] 1800 2747 1801 2748 [[package]] 2749 + name = "io-uring" 2750 + version = "0.7.9" 2751 + source = "registry+https://github.com/rust-lang/crates.io-index" 2752 + checksum = "d93587f37623a1a17d94ef2bc9ada592f5465fe7732084ab7beefabe5c77c0c4" 2753 + dependencies = [ 2754 + "bitflags", 2755 + "cfg-if", 2756 + "libc", 2757 + ] 2758 + 2759 + [[package]] 2760 + name = "ipconfig" 2761 + version = "0.3.2" 2762 + source = "registry+https://github.com/rust-lang/crates.io-index" 2763 + checksum = "b58db92f96b720de98181bbbe63c831e87005ab460c1bf306eb2622b4707997f" 2764 + dependencies = [ 2765 + "socket2 0.5.9", 2766 + "widestring", 2767 + "windows-sys 0.48.0", 2768 + "winreg", 2769 + ] 2770 + 2771 + [[package]] 1802 2772 name = "ipld-core" 1803 2773 version = "0.4.2" 1804 2774 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 1816 2786 checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130" 1817 2787 1818 2788 [[package]] 2789 + name = "iri-string" 2790 + version = "0.7.8" 2791 + source = "registry+https://github.com/rust-lang/crates.io-index" 2792 + checksum = "dbc5ebe9c3a1a7a5127f920a418f7585e9e758e911d0466ed004f393b0e380b2" 2793 + dependencies = [ 2794 + "memchr", 2795 + "serde", 2796 + ] 2797 + 2798 + [[package]] 1819 2799 name = "is-terminal" 1820 2800 version = "0.4.16" 1821 2801 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 1851 2831 ] 1852 2832 1853 2833 [[package]] 2834 + name = "itertools" 2835 + version = "0.14.0" 2836 + source = "registry+https://github.com/rust-lang/crates.io-index" 2837 + checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" 2838 + dependencies = [ 2839 + "either", 2840 + ] 2841 + 2842 + [[package]] 1854 2843 name = "itoa" 1855 2844 version = "1.0.15" 1856 2845 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 1862 2851 dependencies = [ 1863 2852 "anyhow", 1864 2853 "async-trait", 1865 - "atrium-api", 2854 + "atrium-api 0.25.4 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)", 1866 2855 "chrono", 1867 2856 "clap", 1868 2857 "futures-util", 1869 2858 "log", 2859 + "metrics", 1870 2860 "serde", 1871 2861 "serde_json", 1872 - "thiserror 2.0.12", 2862 + "thiserror 2.0.16", 1873 2863 "tokio", 1874 - "tokio-tungstenite", 2864 + "tokio-tungstenite 0.26.2", 1875 2865 "url", 1876 2866 "zstd", 1877 2867 ] ··· 1897 2887 dependencies = [ 1898 2888 "proc-macro2", 1899 2889 "quote", 1900 - "syn", 2890 + "syn 2.0.103", 1901 2891 ] 1902 2892 1903 2893 [[package]] ··· 1911 2901 ] 1912 2902 1913 2903 [[package]] 2904 + name = "jose-b64" 2905 + version = "0.1.2" 2906 + source = "registry+https://github.com/rust-lang/crates.io-index" 2907 + checksum = "bec69375368709666b21c76965ce67549f2d2db7605f1f8707d17c9656801b56" 2908 + dependencies = [ 2909 + "base64ct", 2910 + "serde", 2911 + "subtle", 2912 + "zeroize", 2913 + ] 2914 + 2915 + [[package]] 2916 + name = "jose-jwa" 2917 + version = "0.1.2" 2918 + source = "registry+https://github.com/rust-lang/crates.io-index" 2919 + checksum = "9ab78e053fe886a351d67cf0d194c000f9d0dcb92906eb34d853d7e758a4b3a7" 2920 + dependencies = [ 2921 + "serde", 2922 + ] 2923 + 2924 + [[package]] 2925 + name = "jose-jwk" 2926 + version = "0.1.2" 2927 + source = "registry+https://github.com/rust-lang/crates.io-index" 2928 + checksum = "280fa263807fe0782ecb6f2baadc28dffc04e00558a58e33bfdb801d11fd58e7" 2929 + dependencies = [ 2930 + "jose-b64", 2931 + "jose-jwa", 2932 + "p256", 2933 + "p384", 2934 + "rsa", 2935 + "serde", 2936 + "zeroize", 2937 + ] 2938 + 2939 + [[package]] 1914 2940 name = "js-sys" 1915 2941 version = "0.3.77" 1916 2942 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 1921 2947 ] 1922 2948 1923 2949 [[package]] 2950 + name = "jsonwebtoken" 2951 + version = "9.3.1" 2952 + source = "registry+https://github.com/rust-lang/crates.io-index" 2953 + checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde" 2954 + dependencies = [ 2955 + "base64 0.22.1", 2956 + "js-sys", 2957 + "pem", 2958 + "ring", 2959 + "serde", 2960 + "serde_json", 2961 + "simple_asn1", 2962 + ] 2963 + 2964 + [[package]] 2965 + name = "jwt-compact" 2966 + version = "0.9.0-beta.1" 2967 + source = "git+https://github.com/fatfingers23/jwt-compact.git#aed088b8ff5ad44ef2785c453f6a4b7916728b1c" 2968 + dependencies = [ 2969 + "anyhow", 2970 + "base64ct", 2971 + "chrono", 2972 + "ciborium", 2973 + "hmac", 2974 + "lazy_static", 2975 + "rand_core 0.6.4", 2976 + "secp256k1", 2977 + "serde", 2978 + "serde_json", 2979 + "sha2", 2980 + "smallvec", 2981 + "subtle", 2982 + "zeroize", 2983 + ] 2984 + 2985 + [[package]] 2986 + name = "k256" 2987 + version = "0.13.4" 2988 + source = "registry+https://github.com/rust-lang/crates.io-index" 2989 + checksum = "f6e3919bbaa2945715f0bb6d3934a173d1e9a59ac23767fbaaef277265a7411b" 2990 + dependencies = [ 2991 + "cfg-if", 2992 + "ecdsa", 2993 + "elliptic-curve", 2994 + "sha2", 2995 + ] 2996 + 2997 + [[package]] 1924 2998 name = "langtag" 1925 2999 version = "0.3.4" 1926 3000 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 1934 3008 version = "1.5.0" 1935 3009 source = "registry+https://github.com/rust-lang/crates.io-index" 1936 3010 checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" 3011 + dependencies = [ 3012 + "spin", 3013 + ] 1937 3014 1938 3015 [[package]] 1939 3016 name = "lazycell" ··· 1943 3020 1944 3021 [[package]] 1945 3022 name = "libc" 1946 - version = "0.2.171" 3023 + version = "0.2.174" 1947 3024 source = "registry+https://github.com/rust-lang/crates.io-index" 1948 - checksum = "c19937216e9d3aa9956d9bb8dfc0b0c8beb6058fc4f7a4dc4d850edf86a237d6" 3025 + checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776" 1949 3026 1950 3027 [[package]] 1951 3028 name = "libfuzzer-sys" ··· 1964 3041 checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34" 1965 3042 dependencies = [ 1966 3043 "cfg-if", 1967 - "windows-targets", 3044 + "windows-targets 0.52.6", 1968 3045 ] 1969 3046 1970 3047 [[package]] ··· 2010 3087 ] 2011 3088 2012 3089 [[package]] 3090 + name = "libsqlite3-sys" 3091 + version = "0.35.0" 3092 + source = "registry+https://github.com/rust-lang/crates.io-index" 3093 + checksum = "133c182a6a2c87864fe97778797e46c7e999672690dc9fa3ee8e241aa4a9c13f" 3094 + dependencies = [ 3095 + "pkg-config", 3096 + "vcpkg", 3097 + ] 3098 + 3099 + [[package]] 2013 3100 name = "libz-sys" 2014 3101 version = "1.1.22" 2015 3102 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 2027 3114 "anyhow", 2028 3115 "fluent-uri", 2029 3116 "nom", 2030 - "thiserror 2.0.12", 3117 + "thiserror 2.0.16", 2031 3118 "tinyjson", 2032 3119 ] 2033 3120 ··· 2061 3148 2062 3149 [[package]] 2063 3150 name = "log" 2064 - version = "0.4.27" 3151 + version = "0.4.28" 2065 3152 source = "registry+https://github.com/rust-lang/crates.io-index" 2066 - checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94" 3153 + checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432" 2067 3154 2068 3155 [[package]] 2069 3156 name = "loom" ··· 2086 3173 dependencies = [ 2087 3174 "hashbrown 0.15.2", 2088 3175 ] 3176 + 3177 + [[package]] 3178 + name = "lru-slab" 3179 + version = "0.1.2" 3180 + source = "registry+https://github.com/rust-lang/crates.io-index" 3181 + checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" 2089 3182 2090 3183 [[package]] 2091 3184 name = "lsm-tree" 2092 - version = "2.8.0" 3185 + version = "2.10.2" 2093 3186 source = "registry+https://github.com/rust-lang/crates.io-index" 2094 - checksum = "d0a63a5e98a38b51765274137d8aedfbd848da5f4d016867e186b673fcc06a8c" 3187 + checksum = "55b6d7475a8dd22e749186968daacf8e2a77932b061b1bd263157987bbfc0c6c" 2095 3188 dependencies = [ 2096 3189 "byteorder", 2097 3190 "crossbeam-skiplist", ··· 2112 3205 ] 2113 3206 2114 3207 [[package]] 3208 + name = "lz4" 3209 + version = "1.28.1" 3210 + source = "registry+https://github.com/rust-lang/crates.io-index" 3211 + checksum = "a20b523e860d03443e98350ceaac5e71c6ba89aea7d960769ec3ce37f4de5af4" 3212 + dependencies = [ 3213 + "lz4-sys", 3214 + ] 3215 + 3216 + [[package]] 2115 3217 name = "lz4-sys" 2116 3218 version = "1.11.1+lz4-1.10.0" 2117 3219 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 2137 3239 ] 2138 3240 2139 3241 [[package]] 3242 + name = "madsim" 3243 + version = "0.2.32" 3244 + source = "registry+https://github.com/rust-lang/crates.io-index" 3245 + checksum = "db6694555643da293dfb89e33c2880a13b62711d64b6588bc7df6ce4110b27f1" 3246 + dependencies = [ 3247 + "ahash", 3248 + "async-channel", 3249 + "async-stream", 3250 + "async-task", 3251 + "bincode 1.3.3", 3252 + "bytes", 3253 + "downcast-rs", 3254 + "futures-util", 3255 + "lazy_static", 3256 + "libc", 3257 + "madsim-macros", 3258 + "naive-timer", 3259 + "panic-message", 3260 + "rand 0.8.5", 3261 + "rand_xoshiro 0.6.0", 3262 + "rustversion", 3263 + "serde", 3264 + "spin", 3265 + "tokio", 3266 + "tokio-util", 3267 + "toml", 3268 + "tracing", 3269 + "tracing-subscriber", 3270 + ] 3271 + 3272 + [[package]] 3273 + name = "madsim-macros" 3274 + version = "0.2.12" 3275 + source = "registry+https://github.com/rust-lang/crates.io-index" 3276 + checksum = "f3d248e97b1a48826a12c3828d921e8548e714394bf17274dd0a93910dc946e1" 3277 + dependencies = [ 3278 + "darling 0.14.4", 3279 + "proc-macro2", 3280 + "quote", 3281 + "syn 1.0.109", 3282 + ] 3283 + 3284 + [[package]] 3285 + name = "madsim-tokio" 3286 + version = "0.2.30" 3287 + source = "registry+https://github.com/rust-lang/crates.io-index" 3288 + checksum = "7d3eb2acc57c82d21d699119b859e2df70a91dbdb84734885a1e72be83bdecb5" 3289 + dependencies = [ 3290 + "madsim", 3291 + "spin", 3292 + "tokio", 3293 + ] 3294 + 3295 + [[package]] 2140 3296 name = "match_cfg" 2141 3297 version = "0.1.0" 2142 3298 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 2144 3300 2145 3301 [[package]] 2146 3302 name = "matchers" 2147 - version = "0.1.0" 3303 + version = "0.2.0" 2148 3304 source = "registry+https://github.com/rust-lang/crates.io-index" 2149 - checksum = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558" 3305 + checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" 2150 3306 dependencies = [ 2151 - "regex-automata 0.1.10", 3307 + "regex-automata", 2152 3308 ] 2153 3309 2154 3310 [[package]] ··· 2170 3326 checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" 2171 3327 2172 3328 [[package]] 3329 + name = "memoffset" 3330 + version = "0.9.1" 3331 + source = "registry+https://github.com/rust-lang/crates.io-index" 3332 + checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" 3333 + dependencies = [ 3334 + "autocfg", 3335 + ] 3336 + 3337 + [[package]] 2173 3338 name = "metrics" 2174 - version = "0.24.1" 3339 + version = "0.24.2" 2175 3340 source = "registry+https://github.com/rust-lang/crates.io-index" 2176 - checksum = "7a7deb012b3b2767169ff203fadb4c6b0b82b947512e5eb9e0b78c2e186ad9e3" 3341 + checksum = "25dea7ac8057892855ec285c440160265225438c3c45072613c25a4b26e98ef5" 2177 3342 dependencies = [ 2178 3343 "ahash", 2179 3344 "portable-atomic", ··· 2192 3357 "indexmap 2.9.0", 2193 3358 "ipnet", 2194 3359 "metrics", 2195 - "metrics-util", 3360 + "metrics-util 0.19.0", 2196 3361 "quanta", 2197 3362 "thiserror 1.0.69", 2198 3363 "tokio", ··· 2200 3365 ] 2201 3366 2202 3367 [[package]] 3368 + name = "metrics-exporter-prometheus" 3369 + version = "0.17.2" 3370 + source = "registry+https://github.com/rust-lang/crates.io-index" 3371 + checksum = "2b166dea96003ee2531cf14833efedced545751d800f03535801d833313f8c15" 3372 + dependencies = [ 3373 + "base64 0.22.1", 3374 + "http-body-util", 3375 + "hyper", 3376 + "hyper-rustls", 3377 + "hyper-util", 3378 + "indexmap 2.9.0", 3379 + "ipnet", 3380 + "metrics", 3381 + "metrics-util 0.20.0", 3382 + "quanta", 3383 + "thiserror 2.0.16", 3384 + "tokio", 3385 + "tracing", 3386 + ] 3387 + 3388 + [[package]] 2203 3389 name = "metrics-process" 2204 3390 version = "2.4.0" 2205 3391 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 2227 3413 "metrics", 2228 3414 "quanta", 2229 3415 "rand 0.8.5", 2230 - "rand_xoshiro", 3416 + "rand_xoshiro 0.6.0", 3417 + "sketches-ddsketch", 3418 + ] 3419 + 3420 + [[package]] 3421 + name = "metrics-util" 3422 + version = "0.20.0" 3423 + source = "registry+https://github.com/rust-lang/crates.io-index" 3424 + checksum = "fe8db7a05415d0f919ffb905afa37784f71901c9a773188876984b4f769ab986" 3425 + dependencies = [ 3426 + "crossbeam-epoch", 3427 + "crossbeam-utils", 3428 + "hashbrown 0.15.2", 3429 + "metrics", 3430 + "quanta", 3431 + "rand 0.9.1", 3432 + "rand_xoshiro 0.7.0", 2231 3433 "sketches-ddsketch", 2232 3434 ] 2233 3435 ··· 2274 3476 ] 2275 3477 2276 3478 [[package]] 3479 + name = "mixtrics" 3480 + version = "0.2.0" 3481 + source = "registry+https://github.com/rust-lang/crates.io-index" 3482 + checksum = "adbcddf5a90b959eea97ae505e0391f5c6dd411fbf546d43b9c59ad1c3bd4391" 3483 + dependencies = [ 3484 + "itertools 0.14.0", 3485 + "parking_lot", 3486 + ] 3487 + 3488 + [[package]] 2277 3489 name = "moka" 2278 3490 version = "0.12.10" 2279 3491 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 2309 3521 "memchr", 2310 3522 "mime", 2311 3523 "spin", 3524 + "tokio", 2312 3525 "version_check", 2313 3526 ] 2314 3527 ··· 2335 3548 ] 2336 3549 2337 3550 [[package]] 3551 + name = "naive-timer" 3552 + version = "0.2.0" 3553 + source = "registry+https://github.com/rust-lang/crates.io-index" 3554 + checksum = "034a0ad7deebf0c2abcf2435950a6666c3c15ea9d8fad0c0f48efa8a7f843fed" 3555 + 3556 + [[package]] 3557 + name = "nanorand" 3558 + version = "0.7.0" 3559 + source = "registry+https://github.com/rust-lang/crates.io-index" 3560 + checksum = "6a51313c5820b0b02bd422f4b44776fbf47961755c74ce64afc73bfad10226c3" 3561 + dependencies = [ 3562 + "getrandom 0.2.15", 3563 + ] 3564 + 3565 + [[package]] 2338 3566 name = "native-tls" 2339 3567 version = "0.2.14" 2340 3568 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 2346 3574 "openssl-probe", 2347 3575 "openssl-sys", 2348 3576 "schannel", 2349 - "security-framework", 3577 + "security-framework 2.11.1", 2350 3578 "security-framework-sys", 2351 3579 "tempfile", 2352 3580 ] 2353 3581 2354 3582 [[package]] 2355 3583 name = "nix" 2356 - version = "0.29.0" 3584 + version = "0.30.1" 2357 3585 source = "registry+https://github.com/rust-lang/crates.io-index" 2358 - checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" 3586 + checksum = "74523f3a35e05aba87a1d978330aef40f67b0304ac79c1c00b294c9830543db6" 2359 3587 dependencies = [ 2360 3588 "bitflags", 2361 3589 "cfg-if", ··· 2375 3603 2376 3604 [[package]] 2377 3605 name = "nu-ansi-term" 2378 - version = "0.46.0" 3606 + version = "0.50.1" 2379 3607 source = "registry+https://github.com/rust-lang/crates.io-index" 2380 - checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84" 3608 + checksum = "d4a28e057d01f97e61255210fcff094d74ed0466038633e95017f5beb68e4399" 2381 3609 dependencies = [ 2382 - "overload", 2383 - "winapi", 3610 + "windows-sys 0.52.0", 3611 + ] 3612 + 3613 + [[package]] 3614 + name = "num-bigint" 3615 + version = "0.4.6" 3616 + source = "registry+https://github.com/rust-lang/crates.io-index" 3617 + checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" 3618 + dependencies = [ 3619 + "num-integer", 3620 + "num-traits", 3621 + ] 3622 + 3623 + [[package]] 3624 + name = "num-bigint-dig" 3625 + version = "0.8.4" 3626 + source = "registry+https://github.com/rust-lang/crates.io-index" 3627 + checksum = "dc84195820f291c7697304f3cbdadd1cb7199c0efc917ff5eafd71225c136151" 3628 + dependencies = [ 3629 + "byteorder", 3630 + "lazy_static", 3631 + "libm", 3632 + "num-integer", 3633 + "num-iter", 3634 + "num-traits", 3635 + "rand 0.8.5", 3636 + "smallvec", 3637 + "zeroize", 2384 3638 ] 2385 3639 2386 3640 [[package]] ··· 2400 3654 ] 2401 3655 2402 3656 [[package]] 3657 + name = "num-integer" 3658 + version = "0.1.46" 3659 + source = "registry+https://github.com/rust-lang/crates.io-index" 3660 + checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" 3661 + dependencies = [ 3662 + "num-traits", 3663 + ] 3664 + 3665 + [[package]] 3666 + name = "num-iter" 3667 + version = "0.1.45" 3668 + source = "registry+https://github.com/rust-lang/crates.io-index" 3669 + checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf" 3670 + dependencies = [ 3671 + "autocfg", 3672 + "num-integer", 3673 + "num-traits", 3674 + ] 3675 + 3676 + [[package]] 3677 + name = "num-modular" 3678 + version = "0.6.1" 3679 + source = "registry+https://github.com/rust-lang/crates.io-index" 3680 + checksum = "17bb261bf36fa7d83f4c294f834e91256769097b3cb505d44831e0a179ac647f" 3681 + 3682 + [[package]] 3683 + name = "num-order" 3684 + version = "1.2.0" 3685 + source = "registry+https://github.com/rust-lang/crates.io-index" 3686 + checksum = "537b596b97c40fcf8056d153049eb22f481c17ebce72a513ec9286e4986d1bb6" 3687 + dependencies = [ 3688 + "num-modular", 3689 + ] 3690 + 3691 + [[package]] 2403 3692 name = "num-traits" 2404 3693 version = "0.2.19" 2405 3694 source = "registry+https://github.com/rust-lang/crates.io-index" 2406 3695 checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" 2407 3696 dependencies = [ 2408 3697 "autocfg", 3698 + "libm", 2409 3699 ] 2410 3700 2411 3701 [[package]] ··· 2424 3714 checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87" 2425 3715 dependencies = [ 2426 3716 "memchr", 3717 + ] 3718 + 3719 + [[package]] 3720 + name = "oid-registry" 3721 + version = "0.8.1" 3722 + source = "registry+https://github.com/rust-lang/crates.io-index" 3723 + checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" 3724 + dependencies = [ 3725 + "asn1-rs", 2427 3726 ] 2428 3727 2429 3728 [[package]] ··· 2431 3730 version = "1.21.3" 2432 3731 source = "registry+https://github.com/rust-lang/crates.io-index" 2433 3732 checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" 3733 + dependencies = [ 3734 + "critical-section", 3735 + "portable-atomic", 3736 + ] 2434 3737 2435 3738 [[package]] 2436 3739 name = "openapiv3" ··· 2466 3769 dependencies = [ 2467 3770 "proc-macro2", 2468 3771 "quote", 2469 - "syn", 3772 + "syn 2.0.103", 2470 3773 ] 2471 3774 2472 3775 [[package]] ··· 2498 3801 ] 2499 3802 2500 3803 [[package]] 2501 - name = "overload" 2502 - version = "0.1.1" 3804 + name = "ordered_hash_map" 3805 + version = "0.4.0" 3806 + source = "registry+https://github.com/rust-lang/crates.io-index" 3807 + checksum = "ab0e5f22bf6dd04abd854a8874247813a8fa2c8c1260eba6fbb150270ce7c176" 3808 + dependencies = [ 3809 + "hashbrown 0.13.2", 3810 + ] 3811 + 3812 + [[package]] 3813 + name = "p256" 3814 + version = "0.13.2" 3815 + source = "registry+https://github.com/rust-lang/crates.io-index" 3816 + checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" 3817 + dependencies = [ 3818 + "ecdsa", 3819 + "elliptic-curve", 3820 + "primeorder", 3821 + "sha2", 3822 + ] 3823 + 3824 + [[package]] 3825 + name = "p384" 3826 + version = "0.13.1" 3827 + source = "registry+https://github.com/rust-lang/crates.io-index" 3828 + checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" 3829 + dependencies = [ 3830 + "elliptic-curve", 3831 + "primeorder", 3832 + ] 3833 + 3834 + [[package]] 3835 + name = "panic-message" 3836 + version = "0.3.0" 2503 3837 source = "registry+https://github.com/rust-lang/crates.io-index" 2504 - checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" 3838 + checksum = "384e52fd8fbd4cbe3c317e8216260c21a0f9134de108cea8a4dd4e7e152c472d" 2505 3839 2506 3840 [[package]] 2507 3841 name = "parking" ··· 2529 3863 "libc", 2530 3864 "redox_syscall", 2531 3865 "smallvec", 2532 - "windows-targets", 3866 + "windows-targets 0.52.6", 2533 3867 ] 2534 3868 2535 3869 [[package]] ··· 2557 3891 ] 2558 3892 2559 3893 [[package]] 3894 + name = "pem" 3895 + version = "3.0.5" 3896 + source = "registry+https://github.com/rust-lang/crates.io-index" 3897 + checksum = "38af38e8470ac9dee3ce1bae1af9c1671fffc44ddfd8bd1d0a3445bf349a8ef3" 3898 + dependencies = [ 3899 + "base64 0.22.1", 3900 + "serde", 3901 + ] 3902 + 3903 + [[package]] 3904 + name = "pem-rfc7468" 3905 + version = "0.7.0" 3906 + source = "registry+https://github.com/rust-lang/crates.io-index" 3907 + checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" 3908 + dependencies = [ 3909 + "base64ct", 3910 + ] 3911 + 3912 + [[package]] 2560 3913 name = "percent-encoding" 2561 3914 version = "2.3.1" 2562 3915 source = "registry+https://github.com/rust-lang/crates.io-index" 2563 3916 checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" 2564 3917 2565 3918 [[package]] 3919 + name = "pest" 3920 + version = "2.8.1" 3921 + source = "registry+https://github.com/rust-lang/crates.io-index" 3922 + checksum = "1db05f56d34358a8b1066f67cbb203ee3e7ed2ba674a6263a1d5ec6db2204323" 3923 + dependencies = [ 3924 + "memchr", 3925 + "thiserror 2.0.16", 3926 + "ucd-trie", 3927 + ] 3928 + 3929 + [[package]] 3930 + name = "pest_derive" 3931 + version = "2.8.1" 3932 + source = "registry+https://github.com/rust-lang/crates.io-index" 3933 + checksum = "bb056d9e8ea77922845ec74a1c4e8fb17e7c218cc4fc11a15c5d25e189aa40bc" 3934 + dependencies = [ 3935 + "pest", 3936 + "pest_generator", 3937 + ] 3938 + 3939 + [[package]] 3940 + name = "pest_generator" 3941 + version = "2.8.1" 3942 + source = "registry+https://github.com/rust-lang/crates.io-index" 3943 + checksum = "87e404e638f781eb3202dc82db6760c8ae8a1eeef7fb3fa8264b2ef280504966" 3944 + dependencies = [ 3945 + "pest", 3946 + "pest_meta", 3947 + "proc-macro2", 3948 + "quote", 3949 + "syn 2.0.103", 3950 + ] 3951 + 3952 + [[package]] 3953 + name = "pest_meta" 3954 + version = "2.8.1" 3955 + source = "registry+https://github.com/rust-lang/crates.io-index" 3956 + checksum = "edd1101f170f5903fde0914f899bb503d9ff5271d7ba76bbb70bea63690cc0d5" 3957 + dependencies = [ 3958 + "pest", 3959 + "sha2", 3960 + ] 3961 + 3962 + [[package]] 3963 + name = "pin-project" 3964 + version = "1.1.10" 3965 + source = "registry+https://github.com/rust-lang/crates.io-index" 3966 + checksum = "677f1add503faace112b9f1373e43e9e054bfdd22ff1a63c1bc485eaec6a6a8a" 3967 + dependencies = [ 3968 + "pin-project-internal", 3969 + ] 3970 + 3971 + [[package]] 3972 + name = "pin-project-internal" 3973 + version = "1.1.10" 3974 + source = "registry+https://github.com/rust-lang/crates.io-index" 3975 + checksum = "6e918e4ff8c4549eb882f14b3a4bc8c8bc93de829416eacf579f1207a8fbf861" 3976 + dependencies = [ 3977 + "proc-macro2", 3978 + "quote", 3979 + "syn 2.0.103", 3980 + ] 3981 + 3982 + [[package]] 2566 3983 name = "pin-project-lite" 2567 3984 version = "0.2.16" 2568 3985 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 2575 3992 checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" 2576 3993 2577 3994 [[package]] 3995 + name = "pkcs1" 3996 + version = "0.7.5" 3997 + source = "registry+https://github.com/rust-lang/crates.io-index" 3998 + checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" 3999 + dependencies = [ 4000 + "der", 4001 + "pkcs8", 4002 + "spki", 4003 + ] 4004 + 4005 + [[package]] 4006 + name = "pkcs8" 4007 + version = "0.10.2" 4008 + source = "registry+https://github.com/rust-lang/crates.io-index" 4009 + checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" 4010 + dependencies = [ 4011 + "der", 4012 + "spki", 4013 + ] 4014 + 4015 + [[package]] 2578 4016 name = "pkg-config" 2579 4017 version = "0.3.32" 2580 4018 source = "registry+https://github.com/rust-lang/crates.io-index" 2581 4019 checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" 2582 4020 2583 4021 [[package]] 4022 + name = "pocket" 4023 + version = "0.1.0" 4024 + dependencies = [ 4025 + "atrium-crypto", 4026 + "clap", 4027 + "jwt-compact", 4028 + "log", 4029 + "poem", 4030 + "poem-openapi", 4031 + "reqwest", 4032 + "rusqlite", 4033 + "serde", 4034 + "serde_json", 4035 + "thiserror 2.0.16", 4036 + "tokio", 4037 + "tracing-subscriber", 4038 + ] 4039 + 4040 + [[package]] 4041 + name = "poem" 4042 + version = "3.1.12" 4043 + source = "registry+https://github.com/rust-lang/crates.io-index" 4044 + checksum = "9f977080932c87287147dca052951c3e2696f8759863f6b4e4c0c9ffe7a4cc8b" 4045 + dependencies = [ 4046 + "base64 0.22.1", 4047 + "bytes", 4048 + "chrono", 4049 + "futures-util", 4050 + "headers", 4051 + "http", 4052 + "http-body-util", 4053 + "httpdate", 4054 + "hyper", 4055 + "hyper-util", 4056 + "mime", 4057 + "mime_guess", 4058 + "multer", 4059 + "nix", 4060 + "parking_lot", 4061 + "percent-encoding", 4062 + "pin-project-lite", 4063 + "poem-derive", 4064 + "quick-xml", 4065 + "rcgen", 4066 + "regex", 4067 + "reqwest", 4068 + "rfc7239", 4069 + "ring", 4070 + "rustls-pemfile", 4071 + "serde", 4072 + "serde_json", 4073 + "serde_urlencoded", 4074 + "serde_yaml", 4075 + "smallvec", 4076 + "sync_wrapper", 4077 + "tempfile", 4078 + "thiserror 2.0.16", 4079 + "tokio", 4080 + "tokio-rustls 0.26.2", 4081 + "tokio-stream", 4082 + "tokio-util", 4083 + "tracing", 4084 + "wildmatch", 4085 + "x509-parser", 4086 + ] 4087 + 4088 + [[package]] 4089 + name = "poem-derive" 4090 + version = "3.1.12" 4091 + source = "registry+https://github.com/rust-lang/crates.io-index" 4092 + checksum = "056e2fea6de1cb240ffe23cfc4fc370b629f8be83b5f27e16b7acd5231a72de4" 4093 + dependencies = [ 4094 + "proc-macro-crate", 4095 + "proc-macro2", 4096 + "quote", 4097 + "syn 2.0.103", 4098 + ] 4099 + 4100 + [[package]] 4101 + name = "poem-openapi" 4102 + version = "5.1.16" 4103 + source = "registry+https://github.com/rust-lang/crates.io-index" 4104 + checksum = "1ccbcc395bf4dd03df1da32da351b6b6732e4074ce27ddec315650e52a2be44c" 4105 + dependencies = [ 4106 + "base64 0.22.1", 4107 + "bytes", 4108 + "derive_more", 4109 + "futures-util", 4110 + "indexmap 2.9.0", 4111 + "itertools 0.14.0", 4112 + "mime", 4113 + "num-traits", 4114 + "poem", 4115 + "poem-openapi-derive", 4116 + "quick-xml", 4117 + "regex", 4118 + "serde", 4119 + "serde_json", 4120 + "serde_urlencoded", 4121 + "serde_yaml", 4122 + "thiserror 2.0.16", 4123 + "tokio", 4124 + ] 4125 + 4126 + [[package]] 4127 + name = "poem-openapi-derive" 4128 + version = "5.1.16" 4129 + source = "registry+https://github.com/rust-lang/crates.io-index" 4130 + checksum = "41273b691a3d467a8c44d05506afba9f7b6bd56c9cdf80123de13fe52d7ec587" 4131 + dependencies = [ 4132 + "darling 0.20.11", 4133 + "http", 4134 + "indexmap 2.9.0", 4135 + "mime", 4136 + "proc-macro-crate", 4137 + "proc-macro2", 4138 + "quote", 4139 + "regex", 4140 + "syn 2.0.103", 4141 + "thiserror 2.0.16", 4142 + ] 4143 + 4144 + [[package]] 2584 4145 name = "portable-atomic" 2585 4146 version = "1.11.0" 2586 4147 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 2611 4172 ] 2612 4173 2613 4174 [[package]] 4175 + name = "prettyplease" 4176 + version = "0.2.34" 4177 + source = "registry+https://github.com/rust-lang/crates.io-index" 4178 + checksum = "6837b9e10d61f45f987d50808f83d1ee3d206c66acf650c3e4ae2e1f6ddedf55" 4179 + dependencies = [ 4180 + "proc-macro2", 4181 + "syn 2.0.103", 4182 + ] 4183 + 4184 + [[package]] 4185 + name = "primeorder" 4186 + version = "0.13.6" 4187 + source = "registry+https://github.com/rust-lang/crates.io-index" 4188 + checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" 4189 + dependencies = [ 4190 + "elliptic-curve", 4191 + ] 4192 + 4193 + [[package]] 4194 + name = "proc-macro-crate" 4195 + version = "3.3.0" 4196 + source = "registry+https://github.com/rust-lang/crates.io-index" 4197 + checksum = "edce586971a4dfaa28950c6f18ed55e0406c1ab88bbce2c6f6293a7aaba73d35" 4198 + dependencies = [ 4199 + "toml_edit", 4200 + ] 4201 + 4202 + [[package]] 2614 4203 name = "proc-macro2" 2615 4204 version = "1.0.94" 2616 4205 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 2657 4246 ] 2658 4247 2659 4248 [[package]] 4249 + name = "quasar" 4250 + version = "0.1.0" 4251 + dependencies = [ 4252 + "clap", 4253 + "fjall 2.11.2 (registry+https://github.com/rust-lang/crates.io-index)", 4254 + ] 4255 + 4256 + [[package]] 4257 + name = "quick-xml" 4258 + version = "0.36.2" 4259 + source = "registry+https://github.com/rust-lang/crates.io-index" 4260 + checksum = "f7649a7b4df05aed9ea7ec6f628c67c9953a43869b8bc50929569b2999d443fe" 4261 + dependencies = [ 4262 + "memchr", 4263 + "serde", 4264 + ] 4265 + 4266 + [[package]] 2660 4267 name = "quick_cache" 2661 4268 version = "0.6.12" 2662 4269 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 2667 4274 ] 2668 4275 2669 4276 [[package]] 4277 + name = "quinn" 4278 + version = "0.11.8" 4279 + source = "registry+https://github.com/rust-lang/crates.io-index" 4280 + checksum = "626214629cda6781b6dc1d316ba307189c85ba657213ce642d9c77670f8202c8" 4281 + dependencies = [ 4282 + "bytes", 4283 + "cfg_aliases", 4284 + "pin-project-lite", 4285 + "quinn-proto", 4286 + "quinn-udp", 4287 + "rustc-hash 2.1.1", 4288 + "rustls 0.23.31", 4289 + "socket2 0.5.9", 4290 + "thiserror 2.0.16", 4291 + "tokio", 4292 + "tracing", 4293 + "web-time", 4294 + ] 4295 + 4296 + [[package]] 4297 + name = "quinn-proto" 4298 + version = "0.11.12" 4299 + source = "registry+https://github.com/rust-lang/crates.io-index" 4300 + checksum = "49df843a9161c85bb8aae55f101bc0bac8bcafd637a620d9122fd7e0b2f7422e" 4301 + dependencies = [ 4302 + "bytes", 4303 + "getrandom 0.3.3", 4304 + "lru-slab", 4305 + "rand 0.9.1", 4306 + "ring", 4307 + "rustc-hash 2.1.1", 4308 + "rustls 0.23.31", 4309 + "rustls-pki-types", 4310 + "slab", 4311 + "thiserror 2.0.16", 4312 + "tinyvec", 4313 + "tracing", 4314 + "web-time", 4315 + ] 4316 + 4317 + [[package]] 4318 + name = "quinn-udp" 4319 + version = "0.5.13" 4320 + source = "registry+https://github.com/rust-lang/crates.io-index" 4321 + checksum = "fcebb1209ee276352ef14ff8732e24cc2b02bbac986cd74a4c81bcb2f9881970" 4322 + dependencies = [ 4323 + "cfg_aliases", 4324 + "libc", 4325 + "once_cell", 4326 + "socket2 0.5.9", 4327 + "tracing", 4328 + "windows-sys 0.59.0", 4329 + ] 4330 + 4331 + [[package]] 2670 4332 name = "quote" 2671 4333 version = "1.0.40" 2672 4334 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 2750 4412 ] 2751 4413 2752 4414 [[package]] 4415 + name = "rand_xoshiro" 4416 + version = "0.7.0" 4417 + source = "registry+https://github.com/rust-lang/crates.io-index" 4418 + checksum = "f703f4665700daf5512dcca5f43afa6af89f09db47fb56be587f80636bda2d41" 4419 + dependencies = [ 4420 + "rand_core 0.9.3", 4421 + ] 4422 + 4423 + [[package]] 2753 4424 name = "ratelimit" 2754 4425 version = "0.10.0" 2755 4426 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 2770 4441 ] 2771 4442 2772 4443 [[package]] 4444 + name = "rcgen" 4445 + version = "0.12.1" 4446 + source = "registry+https://github.com/rust-lang/crates.io-index" 4447 + checksum = "48406db8ac1f3cbc7dcdb56ec355343817958a356ff430259bb07baf7607e1e1" 4448 + dependencies = [ 4449 + "pem", 4450 + "ring", 4451 + "time", 4452 + "yasna", 4453 + ] 4454 + 4455 + [[package]] 2773 4456 name = "redox_syscall" 2774 4457 version = "0.5.11" 2775 4458 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 2806 4489 dependencies = [ 2807 4490 "proc-macro2", 2808 4491 "quote", 2809 - "syn", 4492 + "syn 2.0.103", 4493 + ] 4494 + 4495 + [[package]] 4496 + name = "reflector" 4497 + version = "0.1.0" 4498 + dependencies = [ 4499 + "clap", 4500 + "log", 4501 + "poem", 4502 + "serde", 4503 + "tokio", 4504 + "tracing-subscriber", 2810 4505 ] 2811 4506 2812 4507 [[package]] ··· 2817 4512 dependencies = [ 2818 4513 "aho-corasick", 2819 4514 "memchr", 2820 - "regex-automata 0.4.9", 2821 - "regex-syntax 0.8.5", 4515 + "regex-automata", 4516 + "regex-syntax", 2822 4517 ] 2823 4518 2824 4519 [[package]] 2825 4520 name = "regex-automata" 2826 - version = "0.1.10" 4521 + version = "0.4.9" 2827 4522 source = "registry+https://github.com/rust-lang/crates.io-index" 2828 - checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" 4523 + checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" 2829 4524 dependencies = [ 2830 - "regex-syntax 0.6.29", 4525 + "aho-corasick", 4526 + "memchr", 4527 + "regex-syntax", 2831 4528 ] 2832 4529 2833 4530 [[package]] 2834 - name = "regex-automata" 2835 - version = "0.4.9" 4531 + name = "regex-syntax" 4532 + version = "0.8.5" 4533 + source = "registry+https://github.com/rust-lang/crates.io-index" 4534 + checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" 4535 + 4536 + [[package]] 4537 + name = "reqwest" 4538 + version = "0.12.22" 2836 4539 source = "registry+https://github.com/rust-lang/crates.io-index" 2837 - checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" 4540 + checksum = "cbc931937e6ca3a06e3b6c0aa7841849b160a90351d6ab467a8b9b9959767531" 2838 4541 dependencies = [ 2839 - "aho-corasick", 2840 - "memchr", 2841 - "regex-syntax 0.8.5", 4542 + "async-compression", 4543 + "base64 0.22.1", 4544 + "bytes", 4545 + "encoding_rs", 4546 + "futures-core", 4547 + "futures-util", 4548 + "h2", 4549 + "http", 4550 + "http-body", 4551 + "http-body-util", 4552 + "hyper", 4553 + "hyper-rustls", 4554 + "hyper-tls", 4555 + "hyper-util", 4556 + "js-sys", 4557 + "log", 4558 + "mime", 4559 + "native-tls", 4560 + "percent-encoding", 4561 + "pin-project-lite", 4562 + "quinn", 4563 + "rustls 0.23.31", 4564 + "rustls-native-certs", 4565 + "rustls-pki-types", 4566 + "serde", 4567 + "serde_json", 4568 + "serde_urlencoded", 4569 + "sync_wrapper", 4570 + "tokio", 4571 + "tokio-native-tls", 4572 + "tokio-rustls 0.26.2", 4573 + "tokio-util", 4574 + "tower", 4575 + "tower-http", 4576 + "tower-service", 4577 + "url", 4578 + "wasm-bindgen", 4579 + "wasm-bindgen-futures", 4580 + "web-sys", 2842 4581 ] 2843 4582 2844 4583 [[package]] 2845 - name = "regex-syntax" 2846 - version = "0.6.29" 4584 + name = "resolv-conf" 4585 + version = "0.7.4" 2847 4586 source = "registry+https://github.com/rust-lang/crates.io-index" 2848 - checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" 4587 + checksum = "95325155c684b1c89f7765e30bc1c42e4a6da51ca513615660cb8a62ef9a88e3" 2849 4588 2850 4589 [[package]] 2851 - name = "regex-syntax" 2852 - version = "0.8.5" 4590 + name = "rfc6979" 4591 + version = "0.4.0" 2853 4592 source = "registry+https://github.com/rust-lang/crates.io-index" 2854 - checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" 4593 + checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" 4594 + dependencies = [ 4595 + "hmac", 4596 + "subtle", 4597 + ] 4598 + 4599 + [[package]] 4600 + name = "rfc7239" 4601 + version = "0.1.3" 4602 + source = "registry+https://github.com/rust-lang/crates.io-index" 4603 + checksum = "4a82f1d1e38e9a85bb58ffcfadf22ed6f2c94e8cd8581ec2b0f80a2a6858350f" 4604 + dependencies = [ 4605 + "uncased", 4606 + ] 2855 4607 2856 4608 [[package]] 2857 4609 name = "ring" ··· 2887 4639 ] 2888 4640 2889 4641 [[package]] 4642 + name = "rsa" 4643 + version = "0.9.8" 4644 + source = "registry+https://github.com/rust-lang/crates.io-index" 4645 + checksum = "78928ac1ed176a5ca1d17e578a1825f3d81ca54cf41053a592584b020cfd691b" 4646 + dependencies = [ 4647 + "const-oid", 4648 + "digest", 4649 + "num-bigint-dig", 4650 + "num-integer", 4651 + "num-traits", 4652 + "pkcs1", 4653 + "pkcs8", 4654 + "rand_core 0.6.4", 4655 + "signature", 4656 + "spki", 4657 + "subtle", 4658 + "zeroize", 4659 + ] 4660 + 4661 + [[package]] 4662 + name = "rusqlite" 4663 + version = "0.37.0" 4664 + source = "registry+https://github.com/rust-lang/crates.io-index" 4665 + checksum = "165ca6e57b20e1351573e3729b958bc62f0e48025386970b6e4d29e7a7e71f3f" 4666 + dependencies = [ 4667 + "bitflags", 4668 + "fallible-iterator", 4669 + "fallible-streaming-iterator", 4670 + "hashlink", 4671 + "libsqlite3-sys", 4672 + "smallvec", 4673 + ] 4674 + 4675 + [[package]] 2890 4676 name = "rustc-demangle" 2891 4677 version = "0.1.24" 2892 4678 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 2914 4700 ] 2915 4701 2916 4702 [[package]] 4703 + name = "rusticata-macros" 4704 + version = "4.1.0" 4705 + source = "registry+https://github.com/rust-lang/crates.io-index" 4706 + checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" 4707 + dependencies = [ 4708 + "nom", 4709 + ] 4710 + 4711 + [[package]] 2917 4712 name = "rustix" 2918 4713 version = "0.38.44" 2919 4714 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 2948 4743 "log", 2949 4744 "ring", 2950 4745 "rustls-pki-types", 2951 - "rustls-webpki", 4746 + "rustls-webpki 0.102.8", 4747 + "subtle", 4748 + "zeroize", 4749 + ] 4750 + 4751 + [[package]] 4752 + name = "rustls" 4753 + version = "0.23.31" 4754 + source = "registry+https://github.com/rust-lang/crates.io-index" 4755 + checksum = "c0ebcbd2f03de0fc1122ad9bb24b127a5a6cd51d72604a3f3c50ac459762b6cc" 4756 + dependencies = [ 4757 + "aws-lc-rs", 4758 + "log", 4759 + "once_cell", 4760 + "ring", 4761 + "rustls-pki-types", 4762 + "rustls-webpki 0.103.4", 2952 4763 "subtle", 2953 4764 "zeroize", 2954 4765 ] 2955 4766 2956 4767 [[package]] 4768 + name = "rustls-native-certs" 4769 + version = "0.8.1" 4770 + source = "registry+https://github.com/rust-lang/crates.io-index" 4771 + checksum = "7fcff2dd52b58a8d98a70243663a0d234c4e2b79235637849d15913394a247d3" 4772 + dependencies = [ 4773 + "openssl-probe", 4774 + "rustls-pki-types", 4775 + "schannel", 4776 + "security-framework 3.2.0", 4777 + ] 4778 + 4779 + [[package]] 2957 4780 name = "rustls-pemfile" 2958 4781 version = "2.2.0" 2959 4782 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 2964 4787 2965 4788 [[package]] 2966 4789 name = "rustls-pki-types" 2967 - version = "1.11.0" 4790 + version = "1.12.0" 2968 4791 source = "registry+https://github.com/rust-lang/crates.io-index" 2969 - checksum = "917ce264624a4b4db1c364dcc35bfca9ded014d0a958cd47ad3e960e988ea51c" 4792 + checksum = "229a4a4c221013e7e1f1a043678c5cc39fe5171437c88fb47151a21e6f5b5c79" 4793 + dependencies = [ 4794 + "web-time", 4795 + "zeroize", 4796 + ] 2970 4797 2971 4798 [[package]] 2972 4799 name = "rustls-webpki" ··· 2980 4807 ] 2981 4808 2982 4809 [[package]] 4810 + name = "rustls-webpki" 4811 + version = "0.103.4" 4812 + source = "registry+https://github.com/rust-lang/crates.io-index" 4813 + checksum = "0a17884ae0c1b773f1ccd2bd4a8c72f16da897310a98b0e84bf349ad5ead92fc" 4814 + dependencies = [ 4815 + "aws-lc-rs", 4816 + "ring", 4817 + "rustls-pki-types", 4818 + "untrusted", 4819 + ] 4820 + 4821 + [[package]] 2983 4822 name = "rustversion" 2984 4823 version = "1.0.20" 2985 4824 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 2992 4831 checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" 2993 4832 2994 4833 [[package]] 4834 + name = "same-file" 4835 + version = "1.0.6" 4836 + source = "registry+https://github.com/rust-lang/crates.io-index" 4837 + checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" 4838 + dependencies = [ 4839 + "winapi-util", 4840 + ] 4841 + 4842 + [[package]] 2995 4843 name = "schannel" 2996 4844 version = "0.1.27" 2997 4845 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 3023 4871 "proc-macro2", 3024 4872 "quote", 3025 4873 "serde_derive_internals", 3026 - "syn", 4874 + "syn 2.0.103", 3027 4875 ] 3028 4876 3029 4877 [[package]] ··· 3039 4887 checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" 3040 4888 3041 4889 [[package]] 4890 + name = "sec1" 4891 + version = "0.7.3" 4892 + source = "registry+https://github.com/rust-lang/crates.io-index" 4893 + checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" 4894 + dependencies = [ 4895 + "base16ct", 4896 + "der", 4897 + "generic-array", 4898 + "pkcs8", 4899 + "subtle", 4900 + "zeroize", 4901 + ] 4902 + 4903 + [[package]] 4904 + name = "secp256k1" 4905 + version = "0.30.0" 4906 + source = "registry+https://github.com/rust-lang/crates.io-index" 4907 + checksum = "b50c5943d326858130af85e049f2661ba3c78b26589b8ab98e65e80ae44a1252" 4908 + dependencies = [ 4909 + "bitcoin_hashes", 4910 + "rand 0.8.5", 4911 + "secp256k1-sys", 4912 + ] 4913 + 4914 + [[package]] 4915 + name = "secp256k1-sys" 4916 + version = "0.10.1" 4917 + source = "registry+https://github.com/rust-lang/crates.io-index" 4918 + checksum = "d4387882333d3aa8cb20530a17c69a3752e97837832f34f6dccc760e715001d9" 4919 + dependencies = [ 4920 + "cc", 4921 + ] 4922 + 4923 + [[package]] 3042 4924 name = "security-framework" 3043 4925 version = "2.11.1" 3044 4926 source = "registry+https://github.com/rust-lang/crates.io-index" 3045 4927 checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" 3046 4928 dependencies = [ 3047 4929 "bitflags", 3048 - "core-foundation", 4930 + "core-foundation 0.9.4", 4931 + "core-foundation-sys", 4932 + "libc", 4933 + "security-framework-sys", 4934 + ] 4935 + 4936 + [[package]] 4937 + name = "security-framework" 4938 + version = "3.2.0" 4939 + source = "registry+https://github.com/rust-lang/crates.io-index" 4940 + checksum = "271720403f46ca04f7ba6f55d438f8bd878d6b8ca0a1046e8228c4145bcbb316" 4941 + dependencies = [ 4942 + "bitflags", 4943 + "core-foundation 0.10.1", 3049 4944 "core-foundation-sys", 3050 4945 "libc", 3051 4946 "security-framework-sys", ··· 3099 4994 dependencies = [ 3100 4995 "proc-macro2", 3101 4996 "quote", 3102 - "syn", 4997 + "syn 2.0.103", 3103 4998 ] 3104 4999 3105 5000 [[package]] ··· 3110 5005 dependencies = [ 3111 5006 "proc-macro2", 3112 5007 "quote", 3113 - "syn", 5008 + "syn 2.0.103", 3114 5009 ] 3115 5010 3116 5011 [[package]] ··· 3128 5023 3129 5024 [[package]] 3130 5025 name = "serde_json" 3131 - version = "1.0.140" 5026 + version = "1.0.141" 3132 5027 source = "registry+https://github.com/rust-lang/crates.io-index" 3133 - checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" 5028 + checksum = "30b9eff21ebe718216c6ec64e1d9ac57087aad11efc64e32002bce4a0d4c03d3" 3134 5029 dependencies = [ 3135 5030 "itoa", 3136 5031 "memchr", ··· 3158 5053 "percent-encoding", 3159 5054 "ryu", 3160 5055 "serde", 3161 - "thiserror 2.0.12", 5056 + "thiserror 2.0.16", 3162 5057 ] 3163 5058 3164 5059 [[package]] 3165 5060 name = "serde_spanned" 3166 - version = "0.6.8" 5061 + version = "0.6.9" 3167 5062 source = "registry+https://github.com/rust-lang/crates.io-index" 3168 - checksum = "87607cb1398ed59d48732e575a4c28a7a8ebf2454b964fe3f224f2afc07909e1" 5063 + checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" 3169 5064 dependencies = [ 3170 5065 "serde", 3171 5066 ] ··· 3179 5074 "proc-macro2", 3180 5075 "quote", 3181 5076 "serde", 3182 - "syn", 5077 + "syn 2.0.103", 3183 5078 ] 3184 5079 3185 5080 [[package]] ··· 3218 5113 source = "registry+https://github.com/rust-lang/crates.io-index" 3219 5114 checksum = "8d00caa5193a3c8362ac2b73be6b9e768aa5a4b2f721d8f4b339600c3cb51f8e" 3220 5115 dependencies = [ 3221 - "darling", 5116 + "darling 0.20.11", 3222 5117 "proc-macro2", 3223 5118 "quote", 3224 - "syn", 5119 + "syn 2.0.103", 5120 + ] 5121 + 5122 + [[package]] 5123 + name = "serde_yaml" 5124 + version = "0.9.34+deprecated" 5125 + source = "registry+https://github.com/rust-lang/crates.io-index" 5126 + checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" 5127 + dependencies = [ 5128 + "indexmap 2.9.0", 5129 + "itoa", 5130 + "ryu", 5131 + "serde", 5132 + "unsafe-libyaml", 3225 5133 ] 3226 5134 3227 5135 [[package]] ··· 3271 5179 ] 3272 5180 3273 5181 [[package]] 5182 + name = "signature" 5183 + version = "2.2.0" 5184 + source = "registry+https://github.com/rust-lang/crates.io-index" 5185 + checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" 5186 + dependencies = [ 5187 + "digest", 5188 + "rand_core 0.6.4", 5189 + ] 5190 + 5191 + [[package]] 5192 + name = "simple_asn1" 5193 + version = "0.6.3" 5194 + source = "registry+https://github.com/rust-lang/crates.io-index" 5195 + checksum = "297f631f50729c8c99b84667867963997ec0b50f32b2a7dbcab828ef0541e8bb" 5196 + dependencies = [ 5197 + "num-bigint", 5198 + "num-traits", 5199 + "thiserror 2.0.16", 5200 + "time", 5201 + ] 5202 + 5203 + [[package]] 3274 5204 name = "sketches-ddsketch" 3275 5205 version = "0.3.0" 3276 5206 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 3283 5213 checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" 3284 5214 dependencies = [ 3285 5215 "autocfg", 5216 + ] 5217 + 5218 + [[package]] 5219 + name = "slingshot" 5220 + version = "0.1.0" 5221 + dependencies = [ 5222 + "atrium-api 0.25.4 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)", 5223 + "atrium-common 0.1.2 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)", 5224 + "atrium-identity 0.1.5 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)", 5225 + "atrium-oauth 0.1.3 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)", 5226 + "clap", 5227 + "ctrlc", 5228 + "foyer", 5229 + "hickory-resolver", 5230 + "jetstream", 5231 + "links", 5232 + "log", 5233 + "metrics", 5234 + "metrics-exporter-prometheus 0.17.2", 5235 + "poem", 5236 + "poem-openapi", 5237 + "reqwest", 5238 + "rustls 0.23.31", 5239 + "serde", 5240 + "serde_json", 5241 + "thiserror 2.0.16", 5242 + "time", 5243 + "tokio", 5244 + "tokio-util", 5245 + "tracing-subscriber", 5246 + "url", 3286 5247 ] 3287 5248 3288 5249 [[package]] ··· 3357 5318 ] 3358 5319 3359 5320 [[package]] 5321 + name = "socket2" 5322 + version = "0.6.0" 5323 + source = "registry+https://github.com/rust-lang/crates.io-index" 5324 + checksum = "233504af464074f9d066d7b5416c5f9b894a5862a6506e306f7b816cdd6f1807" 5325 + dependencies = [ 5326 + "libc", 5327 + "windows-sys 0.59.0", 5328 + ] 5329 + 5330 + [[package]] 5331 + name = "spacedust" 5332 + version = "0.1.0" 5333 + dependencies = [ 5334 + "async-trait", 5335 + "clap", 5336 + "ctrlc", 5337 + "dropshot", 5338 + "env_logger", 5339 + "futures", 5340 + "http", 5341 + "jetstream", 5342 + "links", 5343 + "log", 5344 + "metrics", 5345 + "metrics-exporter-prometheus 0.17.2", 5346 + "rand 0.9.1", 5347 + "schemars", 5348 + "semver", 5349 + "serde", 5350 + "serde_json", 5351 + "serde_qs", 5352 + "thiserror 2.0.16", 5353 + "tinyjson", 5354 + "tokio", 5355 + "tokio-tungstenite 0.27.0", 5356 + "tokio-util", 5357 + ] 5358 + 5359 + [[package]] 3360 5360 name = "spin" 3361 5361 version = "0.9.8" 3362 5362 source = "registry+https://github.com/rust-lang/crates.io-index" 3363 5363 checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" 3364 5364 dependencies = [ 3365 5365 "lock_api", 5366 + ] 5367 + 5368 + [[package]] 5369 + name = "spki" 5370 + version = "0.7.3" 5371 + source = "registry+https://github.com/rust-lang/crates.io-index" 5372 + checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" 5373 + dependencies = [ 5374 + "base64ct", 5375 + "der", 3366 5376 ] 3367 5377 3368 5378 [[package]] ··· 3379 5389 3380 5390 [[package]] 3381 5391 name = "strsim" 5392 + version = "0.10.0" 5393 + source = "registry+https://github.com/rust-lang/crates.io-index" 5394 + checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" 5395 + 5396 + [[package]] 5397 + name = "strsim" 3382 5398 version = "0.11.1" 3383 5399 source = "registry+https://github.com/rust-lang/crates.io-index" 3384 5400 checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" ··· 3391 5407 3392 5408 [[package]] 3393 5409 name = "syn" 3394 - version = "2.0.100" 5410 + version = "1.0.109" 3395 5411 source = "registry+https://github.com/rust-lang/crates.io-index" 3396 - checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0" 5412 + checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" 5413 + dependencies = [ 5414 + "proc-macro2", 5415 + "quote", 5416 + "unicode-ident", 5417 + ] 5418 + 5419 + [[package]] 5420 + name = "syn" 5421 + version = "2.0.103" 5422 + source = "registry+https://github.com/rust-lang/crates.io-index" 5423 + checksum = "e4307e30089d6fd6aff212f2da3a1f9e32f3223b1f010fb09b7c95f90f3ca1e8" 3397 5424 dependencies = [ 3398 5425 "proc-macro2", 3399 5426 "quote", ··· 3405 5432 version = "1.0.2" 3406 5433 source = "registry+https://github.com/rust-lang/crates.io-index" 3407 5434 checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" 5435 + dependencies = [ 5436 + "futures-core", 5437 + ] 3408 5438 3409 5439 [[package]] 3410 5440 name = "synstructure" ··· 3414 5444 dependencies = [ 3415 5445 "proc-macro2", 3416 5446 "quote", 3417 - "syn", 5447 + "syn 2.0.103", 5448 + ] 5449 + 5450 + [[package]] 5451 + name = "system-configuration" 5452 + version = "0.6.1" 5453 + source = "registry+https://github.com/rust-lang/crates.io-index" 5454 + checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b" 5455 + dependencies = [ 5456 + "bitflags", 5457 + "core-foundation 0.9.4", 5458 + "system-configuration-sys", 5459 + ] 5460 + 5461 + [[package]] 5462 + name = "system-configuration-sys" 5463 + version = "0.6.0" 5464 + source = "registry+https://github.com/rust-lang/crates.io-index" 5465 + checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" 5466 + dependencies = [ 5467 + "core-foundation-sys", 5468 + "libc", 3418 5469 ] 3419 5470 3420 5471 [[package]] ··· 3464 5515 3465 5516 [[package]] 3466 5517 name = "thiserror" 3467 - version = "2.0.12" 5518 + version = "2.0.16" 3468 5519 source = "registry+https://github.com/rust-lang/crates.io-index" 3469 - checksum = "567b8a2dae586314f7be2a752ec7474332959c6460e02bde30d702a66d488708" 5520 + checksum = "3467d614147380f2e4e374161426ff399c91084acd2363eaf549172b3d5e60c0" 3470 5521 dependencies = [ 3471 - "thiserror-impl 2.0.12", 5522 + "thiserror-impl 2.0.16", 3472 5523 ] 3473 5524 3474 5525 [[package]] ··· 3479 5530 dependencies = [ 3480 5531 "proc-macro2", 3481 5532 "quote", 3482 - "syn", 5533 + "syn 2.0.103", 3483 5534 ] 3484 5535 3485 5536 [[package]] 3486 5537 name = "thiserror-impl" 3487 - version = "2.0.12" 5538 + version = "2.0.16" 3488 5539 source = "registry+https://github.com/rust-lang/crates.io-index" 3489 - checksum = "7f7cf42b4507d8ea322120659672cf1b9dbb93f8f2d4ecfd6e51350ff5b17a1d" 5540 + checksum = "6c5e1be1c48b9172ee610da68fd9cd2770e7a4056cb3fc98710ee6906f0c7960" 3490 5541 dependencies = [ 3491 5542 "proc-macro2", 3492 5543 "quote", 3493 - "syn", 5544 + "syn 2.0.103", 3494 5545 ] 3495 5546 3496 5547 [[package]] ··· 3573 5624 ] 3574 5625 3575 5626 [[package]] 5627 + name = "tinyvec" 5628 + version = "1.9.0" 5629 + source = "registry+https://github.com/rust-lang/crates.io-index" 5630 + checksum = "09b3661f17e86524eccd4371ab0429194e0d7c008abb45f7a7495b1719463c71" 5631 + dependencies = [ 5632 + "tinyvec_macros", 5633 + ] 5634 + 5635 + [[package]] 5636 + name = "tinyvec_macros" 5637 + version = "0.1.1" 5638 + source = "registry+https://github.com/rust-lang/crates.io-index" 5639 + checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" 5640 + 5641 + [[package]] 3576 5642 name = "tokio" 3577 - version = "1.44.2" 5643 + version = "1.47.1" 3578 5644 source = "registry+https://github.com/rust-lang/crates.io-index" 3579 - checksum = "e6b88822cbe49de4185e3a4cbf8321dd487cf5fe0c5c65695fef6346371e9c48" 5645 + checksum = "89e49afdadebb872d3145a5638b59eb0691ea23e46ca484037cfab3b76b95038" 3580 5646 dependencies = [ 3581 5647 "backtrace", 3582 5648 "bytes", 5649 + "io-uring", 3583 5650 "libc", 3584 5651 "mio", 3585 5652 "parking_lot", 3586 5653 "pin-project-lite", 3587 5654 "signal-hook-registry", 3588 - "socket2", 5655 + "slab", 5656 + "socket2 0.6.0", 3589 5657 "tokio-macros", 3590 - "windows-sys 0.52.0", 5658 + "windows-sys 0.59.0", 3591 5659 ] 3592 5660 3593 5661 [[package]] ··· 3598 5666 dependencies = [ 3599 5667 "proc-macro2", 3600 5668 "quote", 3601 - "syn", 5669 + "syn 2.0.103", 3602 5670 ] 3603 5671 3604 5672 [[package]] ··· 3617 5685 source = "registry+https://github.com/rust-lang/crates.io-index" 3618 5686 checksum = "775e0c0f0adb3a2f22a00c4745d728b479985fc15ee7ca6a2608388c5569860f" 3619 5687 dependencies = [ 3620 - "rustls", 5688 + "rustls 0.22.4", 3621 5689 "rustls-pki-types", 3622 5690 "tokio", 3623 5691 ] 3624 5692 3625 5693 [[package]] 5694 + name = "tokio-rustls" 5695 + version = "0.26.2" 5696 + source = "registry+https://github.com/rust-lang/crates.io-index" 5697 + checksum = "8e727b36a1a0e8b74c376ac2211e40c2c8af09fb4013c60d910495810f008e9b" 5698 + dependencies = [ 5699 + "rustls 0.23.31", 5700 + "tokio", 5701 + ] 5702 + 5703 + [[package]] 5704 + name = "tokio-stream" 5705 + version = "0.1.17" 5706 + source = "registry+https://github.com/rust-lang/crates.io-index" 5707 + checksum = "eca58d7bba4a75707817a2c44174253f9236b2d5fbd055602e9d5c07c139a047" 5708 + dependencies = [ 5709 + "futures-core", 5710 + "pin-project-lite", 5711 + "tokio", 5712 + ] 5713 + 5714 + [[package]] 3626 5715 name = "tokio-tungstenite" 3627 5716 version = "0.26.2" 3628 5717 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 3633 5722 "native-tls", 3634 5723 "tokio", 3635 5724 "tokio-native-tls", 3636 - "tungstenite", 5725 + "tungstenite 0.26.2", 5726 + ] 5727 + 5728 + [[package]] 5729 + name = "tokio-tungstenite" 5730 + version = "0.27.0" 5731 + source = "registry+https://github.com/rust-lang/crates.io-index" 5732 + checksum = "489a59b6730eda1b0171fcfda8b121f4bee2b35cba8645ca35c5f7ba3eb736c1" 5733 + dependencies = [ 5734 + "futures-util", 5735 + "log", 5736 + "tokio", 5737 + "tungstenite 0.27.0", 3637 5738 ] 3638 5739 3639 5740 [[package]] ··· 3651 5752 3652 5753 [[package]] 3653 5754 name = "toml" 3654 - version = "0.8.20" 5755 + version = "0.8.23" 3655 5756 source = "registry+https://github.com/rust-lang/crates.io-index" 3656 - checksum = "cd87a5cdd6ffab733b2f74bc4fd7ee5fff6634124999ac278c35fc78c6120148" 5757 + checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" 3657 5758 dependencies = [ 3658 5759 "serde", 3659 5760 "serde_spanned", ··· 3663 5764 3664 5765 [[package]] 3665 5766 name = "toml_datetime" 3666 - version = "0.6.8" 5767 + version = "0.6.11" 3667 5768 source = "registry+https://github.com/rust-lang/crates.io-index" 3668 - checksum = "0dd7358ecb8fc2f8d014bf86f6f638ce72ba252a2c3a2572f2a795f1d23efb41" 5769 + checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" 3669 5770 dependencies = [ 3670 5771 "serde", 3671 5772 ] 3672 5773 3673 5774 [[package]] 3674 5775 name = "toml_edit" 3675 - version = "0.22.24" 5776 + version = "0.22.27" 3676 5777 source = "registry+https://github.com/rust-lang/crates.io-index" 3677 - checksum = "17b4795ff5edd201c7cd6dca065ae59972ce77d1b80fa0a84d94950ece7d1474" 5778 + checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" 3678 5779 dependencies = [ 3679 5780 "indexmap 2.9.0", 3680 5781 "serde", 3681 5782 "serde_spanned", 3682 5783 "toml_datetime", 5784 + "toml_write", 3683 5785 "winnow", 3684 5786 ] 3685 5787 3686 5788 [[package]] 5789 + name = "toml_write" 5790 + version = "0.1.2" 5791 + source = "registry+https://github.com/rust-lang/crates.io-index" 5792 + checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" 5793 + 5794 + [[package]] 3687 5795 name = "tower" 3688 5796 version = "0.5.2" 3689 5797 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 3701 5809 3702 5810 [[package]] 3703 5811 name = "tower-http" 3704 - version = "0.6.2" 5812 + version = "0.6.6" 3705 5813 source = "registry+https://github.com/rust-lang/crates.io-index" 3706 - checksum = "403fa3b783d4b626a8ad51d766ab03cb6d2dbfc46b1c5d4448395e6628dc9697" 5814 + checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2" 3707 5815 dependencies = [ 3708 5816 "bitflags", 3709 5817 "bytes", 5818 + "futures-util", 3710 5819 "http", 5820 + "http-body", 5821 + "iri-string", 3711 5822 "pin-project-lite", 5823 + "tower", 3712 5824 "tower-layer", 3713 5825 "tower-service", 3714 5826 ] ··· 3733 5845 dependencies = [ 3734 5846 "log", 3735 5847 "pin-project-lite", 5848 + "tracing-attributes", 3736 5849 "tracing-core", 3737 5850 ] 3738 5851 3739 5852 [[package]] 5853 + name = "tracing-attributes" 5854 + version = "0.1.30" 5855 + source = "registry+https://github.com/rust-lang/crates.io-index" 5856 + checksum = "81383ab64e72a7a8b8e13130c49e3dab29def6d0c7d76a03087b3cf71c5c6903" 5857 + dependencies = [ 5858 + "proc-macro2", 5859 + "quote", 5860 + "syn 2.0.103", 5861 + ] 5862 + 5863 + [[package]] 3740 5864 name = "tracing-core" 3741 5865 version = "0.1.33" 3742 5866 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 3759 5883 3760 5884 [[package]] 3761 5885 name = "tracing-subscriber" 3762 - version = "0.3.19" 5886 + version = "0.3.20" 3763 5887 source = "registry+https://github.com/rust-lang/crates.io-index" 3764 - checksum = "e8189decb5ac0fa7bc8b96b7cb9b2701d60d48805aca84a238004d665fcc4008" 5888 + checksum = "2054a14f5307d601f88daf0553e1cbf472acc4f2c51afab632431cdcd72124d5" 3765 5889 dependencies = [ 3766 5890 "matchers", 3767 5891 "nu-ansi-term", 3768 5892 "once_cell", 3769 - "regex", 5893 + "regex-automata", 3770 5894 "sharded-slab", 3771 5895 "smallvec", 3772 5896 "thread_local", ··· 3783 5907 dependencies = [ 3784 5908 "proc-macro2", 3785 5909 "quote", 3786 - "syn", 5910 + "syn 2.0.103", 3787 5911 ] 3788 5912 3789 5913 [[package]] ··· 3806 5930 "native-tls", 3807 5931 "rand 0.9.1", 3808 5932 "sha1", 3809 - "thiserror 2.0.12", 5933 + "thiserror 2.0.16", 3810 5934 "url", 3811 5935 "utf-8", 3812 5936 ] 3813 5937 3814 5938 [[package]] 5939 + name = "tungstenite" 5940 + version = "0.27.0" 5941 + source = "registry+https://github.com/rust-lang/crates.io-index" 5942 + checksum = "eadc29d668c91fcc564941132e17b28a7ceb2f3ebf0b9dae3e03fd7a6748eb0d" 5943 + dependencies = [ 5944 + "bytes", 5945 + "data-encoding", 5946 + "http", 5947 + "httparse", 5948 + "log", 5949 + "rand 0.9.1", 5950 + "sha1", 5951 + "thiserror 2.0.16", 5952 + "utf-8", 5953 + ] 5954 + 5955 + [[package]] 5956 + name = "twox-hash" 5957 + version = "2.1.1" 5958 + source = "registry+https://github.com/rust-lang/crates.io-index" 5959 + checksum = "8b907da542cbced5261bd3256de1b3a1bf340a3d37f93425a07362a1d687de56" 5960 + dependencies = [ 5961 + "rand 0.9.1", 5962 + ] 5963 + 5964 + [[package]] 3815 5965 name = "typenum" 3816 5966 version = "1.18.0" 3817 5967 source = "registry+https://github.com/rust-lang/crates.io-index" 3818 5968 checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f" 5969 + 5970 + [[package]] 5971 + name = "ucd-trie" 5972 + version = "0.1.7" 5973 + source = "registry+https://github.com/rust-lang/crates.io-index" 5974 + checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" 3819 5975 3820 5976 [[package]] 3821 5977 name = "ufos" ··· 3830 5986 "clap", 3831 5987 "dropshot", 3832 5988 "env_logger", 3833 - "fjall", 5989 + "fjall 2.11.2 (git+https://github.com/fjall-rs/fjall.git)", 3834 5990 "getrandom 0.3.3", 3835 5991 "http", 3836 5992 "jetstream", 3837 5993 "log", 3838 5994 "lsm-tree", 5995 + "metrics", 5996 + "metrics-exporter-prometheus 0.17.2", 3839 5997 "schemars", 3840 5998 "semver", 3841 5999 "serde", ··· 3843 6001 "serde_qs", 3844 6002 "sha2", 3845 6003 "tempfile", 3846 - "thiserror 2.0.12", 6004 + "thiserror 2.0.16", 3847 6005 "tikv-jemallocator", 3848 6006 "tokio", 3849 6007 "tokio-util", ··· 3862 6020 ] 3863 6021 3864 6022 [[package]] 6023 + name = "uncased" 6024 + version = "0.9.10" 6025 + source = "registry+https://github.com/rust-lang/crates.io-index" 6026 + checksum = "e1b88fcfe09e89d3866a5c11019378088af2d24c3fbd4f0543f96b479ec90697" 6027 + dependencies = [ 6028 + "version_check", 6029 + ] 6030 + 6031 + [[package]] 3865 6032 name = "unicase" 3866 6033 version = "2.8.1" 3867 6034 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 3874 6041 checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" 3875 6042 3876 6043 [[package]] 6044 + name = "unicode-xid" 6045 + version = "0.2.6" 6046 + source = "registry+https://github.com/rust-lang/crates.io-index" 6047 + checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" 6048 + 6049 + [[package]] 6050 + name = "unsafe-libyaml" 6051 + version = "0.2.11" 6052 + source = "registry+https://github.com/rust-lang/crates.io-index" 6053 + checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" 6054 + 6055 + [[package]] 3877 6056 name = "unsigned-varint" 3878 6057 version = "0.8.0" 3879 6058 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 3944 6123 3945 6124 [[package]] 3946 6125 name = "value-log" 3947 - version = "1.8.0" 6126 + version = "1.9.0" 3948 6127 source = "registry+https://github.com/rust-lang/crates.io-index" 3949 - checksum = "fd29b17c041f94e0885179637289815cd038f0c9fc19c4549d5a97017404fb7d" 6128 + checksum = "62fc7c4ce161f049607ecea654dca3f2d727da5371ae85e2e4f14ce2b98ed67c" 3950 6129 dependencies = [ 3951 6130 "byteorder", 3952 6131 "byteview", ··· 3993 6172 ] 3994 6173 3995 6174 [[package]] 6175 + name = "walkdir" 6176 + version = "2.5.0" 6177 + source = "registry+https://github.com/rust-lang/crates.io-index" 6178 + checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" 6179 + dependencies = [ 6180 + "same-file", 6181 + "winapi-util", 6182 + ] 6183 + 6184 + [[package]] 3996 6185 name = "want" 3997 6186 version = "0.3.1" 3998 6187 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 4038 6227 "log", 4039 6228 "proc-macro2", 4040 6229 "quote", 4041 - "syn", 6230 + "syn 2.0.103", 4042 6231 "wasm-bindgen-shared", 4043 6232 ] 4044 6233 4045 6234 [[package]] 6235 + name = "wasm-bindgen-futures" 6236 + version = "0.4.50" 6237 + source = "registry+https://github.com/rust-lang/crates.io-index" 6238 + checksum = "555d470ec0bc3bb57890405e5d4322cc9ea83cebb085523ced7be4144dac1e61" 6239 + dependencies = [ 6240 + "cfg-if", 6241 + "js-sys", 6242 + "once_cell", 6243 + "wasm-bindgen", 6244 + "web-sys", 6245 + ] 6246 + 6247 + [[package]] 4046 6248 name = "wasm-bindgen-macro" 4047 6249 version = "0.2.100" 4048 6250 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 4060 6262 dependencies = [ 4061 6263 "proc-macro2", 4062 6264 "quote", 4063 - "syn", 6265 + "syn 2.0.103", 4064 6266 "wasm-bindgen-backend", 4065 6267 "wasm-bindgen-shared", 4066 6268 ] ··· 4095 6297 ] 4096 6298 4097 6299 [[package]] 6300 + name = "which" 6301 + version = "4.4.2" 6302 + source = "registry+https://github.com/rust-lang/crates.io-index" 6303 + checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" 6304 + dependencies = [ 6305 + "either", 6306 + "home", 6307 + "once_cell", 6308 + "rustix 0.38.44", 6309 + ] 6310 + 6311 + [[package]] 6312 + name = "who-am-i" 6313 + version = "0.1.0" 6314 + dependencies = [ 6315 + "atrium-api 0.25.4 (registry+https://github.com/rust-lang/crates.io-index)", 6316 + "atrium-common 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", 6317 + "atrium-identity 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", 6318 + "atrium-oauth 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", 6319 + "axum", 6320 + "axum-extra", 6321 + "axum-template", 6322 + "clap", 6323 + "ctrlc", 6324 + "dashmap", 6325 + "elliptic-curve", 6326 + "handlebars", 6327 + "hickory-resolver", 6328 + "jose-jwk", 6329 + "jsonwebtoken", 6330 + "metrics", 6331 + "metrics-exporter-prometheus 0.17.2", 6332 + "p256", 6333 + "pkcs8", 6334 + "rand 0.9.1", 6335 + "reqwest", 6336 + "serde", 6337 + "serde_json", 6338 + "thiserror 2.0.16", 6339 + "tokio", 6340 + "tokio-util", 6341 + "url", 6342 + ] 6343 + 6344 + [[package]] 6345 + name = "widestring" 6346 + version = "1.2.0" 6347 + source = "registry+https://github.com/rust-lang/crates.io-index" 6348 + checksum = "dd7cf3379ca1aac9eea11fba24fd7e315d621f8dfe35c8d7d2be8b793726e07d" 6349 + 6350 + [[package]] 6351 + name = "wildmatch" 6352 + version = "2.4.0" 6353 + source = "registry+https://github.com/rust-lang/crates.io-index" 6354 + checksum = "68ce1ab1f8c62655ebe1350f589c61e505cf94d385bc6a12899442d9081e71fd" 6355 + 6356 + [[package]] 4098 6357 name = "winapi" 4099 6358 version = "0.3.9" 4100 6359 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 4111 6370 checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 4112 6371 4113 6372 [[package]] 6373 + name = "winapi-util" 6374 + version = "0.1.9" 6375 + source = "registry+https://github.com/rust-lang/crates.io-index" 6376 + checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" 6377 + dependencies = [ 6378 + "windows-sys 0.59.0", 6379 + ] 6380 + 6381 + [[package]] 4114 6382 name = "winapi-x86_64-pc-windows-gnu" 4115 6383 version = "0.4.0" 4116 6384 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 4123 6391 checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6" 4124 6392 dependencies = [ 4125 6393 "windows-core 0.58.0", 4126 - "windows-targets", 6394 + "windows-targets 0.52.6", 4127 6395 ] 4128 6396 4129 6397 [[package]] ··· 4136 6404 "windows-interface 0.58.0", 4137 6405 "windows-result 0.2.0", 4138 6406 "windows-strings 0.1.0", 4139 - "windows-targets", 6407 + "windows-targets 0.52.6", 4140 6408 ] 4141 6409 4142 6410 [[package]] ··· 4148 6416 "windows-implement 0.60.0", 4149 6417 "windows-interface 0.59.1", 4150 6418 "windows-link", 4151 - "windows-result 0.3.2", 4152 - "windows-strings 0.4.0", 6419 + "windows-result 0.3.4", 6420 + "windows-strings 0.4.2", 4153 6421 ] 4154 6422 4155 6423 [[package]] ··· 4160 6428 dependencies = [ 4161 6429 "proc-macro2", 4162 6430 "quote", 4163 - "syn", 6431 + "syn 2.0.103", 4164 6432 ] 4165 6433 4166 6434 [[package]] ··· 4171 6439 dependencies = [ 4172 6440 "proc-macro2", 4173 6441 "quote", 4174 - "syn", 6442 + "syn 2.0.103", 4175 6443 ] 4176 6444 4177 6445 [[package]] ··· 4182 6450 dependencies = [ 4183 6451 "proc-macro2", 4184 6452 "quote", 4185 - "syn", 6453 + "syn 2.0.103", 4186 6454 ] 4187 6455 4188 6456 [[package]] ··· 4193 6461 dependencies = [ 4194 6462 "proc-macro2", 4195 6463 "quote", 4196 - "syn", 6464 + "syn 2.0.103", 4197 6465 ] 4198 6466 4199 6467 [[package]] ··· 4203 6471 checksum = "76840935b766e1b0a05c0066835fb9ec80071d4c09a16f6bd5f7e655e3c14c38" 4204 6472 4205 6473 [[package]] 6474 + name = "windows-registry" 6475 + version = "0.5.2" 6476 + source = "registry+https://github.com/rust-lang/crates.io-index" 6477 + checksum = "b3bab093bdd303a1240bb99b8aba8ea8a69ee19d34c9e2ef9594e708a4878820" 6478 + dependencies = [ 6479 + "windows-link", 6480 + "windows-result 0.3.4", 6481 + "windows-strings 0.4.2", 6482 + ] 6483 + 6484 + [[package]] 4206 6485 name = "windows-result" 4207 6486 version = "0.2.0" 4208 6487 source = "registry+https://github.com/rust-lang/crates.io-index" 4209 6488 checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e" 4210 6489 dependencies = [ 4211 - "windows-targets", 6490 + "windows-targets 0.52.6", 4212 6491 ] 4213 6492 4214 6493 [[package]] 4215 6494 name = "windows-result" 4216 - version = "0.3.2" 6495 + version = "0.3.4" 4217 6496 source = "registry+https://github.com/rust-lang/crates.io-index" 4218 - checksum = "c64fd11a4fd95df68efcfee5f44a294fe71b8bc6a91993e2791938abcc712252" 6497 + checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" 4219 6498 dependencies = [ 4220 6499 "windows-link", 4221 6500 ] ··· 4227 6506 checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10" 4228 6507 dependencies = [ 4229 6508 "windows-result 0.2.0", 4230 - "windows-targets", 6509 + "windows-targets 0.52.6", 4231 6510 ] 4232 6511 4233 6512 [[package]] 4234 6513 name = "windows-strings" 4235 - version = "0.4.0" 6514 + version = "0.4.2" 4236 6515 source = "registry+https://github.com/rust-lang/crates.io-index" 4237 - checksum = "7a2ba9642430ee452d5a7aa78d72907ebe8cfda358e8cb7918a2050581322f97" 6516 + checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57" 4238 6517 dependencies = [ 4239 6518 "windows-link", 4240 6519 ] 4241 6520 4242 6521 [[package]] 4243 6522 name = "windows-sys" 6523 + version = "0.48.0" 6524 + source = "registry+https://github.com/rust-lang/crates.io-index" 6525 + checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" 6526 + dependencies = [ 6527 + "windows-targets 0.48.5", 6528 + ] 6529 + 6530 + [[package]] 6531 + name = "windows-sys" 4244 6532 version = "0.52.0" 4245 6533 source = "registry+https://github.com/rust-lang/crates.io-index" 4246 6534 checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" 4247 6535 dependencies = [ 4248 - "windows-targets", 6536 + "windows-targets 0.52.6", 4249 6537 ] 4250 6538 4251 6539 [[package]] ··· 4254 6542 source = "registry+https://github.com/rust-lang/crates.io-index" 4255 6543 checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" 4256 6544 dependencies = [ 4257 - "windows-targets", 6545 + "windows-targets 0.52.6", 6546 + ] 6547 + 6548 + [[package]] 6549 + name = "windows-targets" 6550 + version = "0.48.5" 6551 + source = "registry+https://github.com/rust-lang/crates.io-index" 6552 + checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" 6553 + dependencies = [ 6554 + "windows_aarch64_gnullvm 0.48.5", 6555 + "windows_aarch64_msvc 0.48.5", 6556 + "windows_i686_gnu 0.48.5", 6557 + "windows_i686_msvc 0.48.5", 6558 + "windows_x86_64_gnu 0.48.5", 6559 + "windows_x86_64_gnullvm 0.48.5", 6560 + "windows_x86_64_msvc 0.48.5", 4258 6561 ] 4259 6562 4260 6563 [[package]] ··· 4263 6566 source = "registry+https://github.com/rust-lang/crates.io-index" 4264 6567 checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" 4265 6568 dependencies = [ 4266 - "windows_aarch64_gnullvm", 4267 - "windows_aarch64_msvc", 4268 - "windows_i686_gnu", 6569 + "windows_aarch64_gnullvm 0.52.6", 6570 + "windows_aarch64_msvc 0.52.6", 6571 + "windows_i686_gnu 0.52.6", 4269 6572 "windows_i686_gnullvm", 4270 - "windows_i686_msvc", 4271 - "windows_x86_64_gnu", 4272 - "windows_x86_64_gnullvm", 4273 - "windows_x86_64_msvc", 6573 + "windows_i686_msvc 0.52.6", 6574 + "windows_x86_64_gnu 0.52.6", 6575 + "windows_x86_64_gnullvm 0.52.6", 6576 + "windows_x86_64_msvc 0.52.6", 4274 6577 ] 4275 6578 4276 6579 [[package]] 4277 6580 name = "windows_aarch64_gnullvm" 6581 + version = "0.48.5" 6582 + source = "registry+https://github.com/rust-lang/crates.io-index" 6583 + checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" 6584 + 6585 + [[package]] 6586 + name = "windows_aarch64_gnullvm" 4278 6587 version = "0.52.6" 4279 6588 source = "registry+https://github.com/rust-lang/crates.io-index" 4280 6589 checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" 4281 6590 4282 6591 [[package]] 4283 6592 name = "windows_aarch64_msvc" 6593 + version = "0.48.5" 6594 + source = "registry+https://github.com/rust-lang/crates.io-index" 6595 + checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" 6596 + 6597 + [[package]] 6598 + name = "windows_aarch64_msvc" 4284 6599 version = "0.52.6" 4285 6600 source = "registry+https://github.com/rust-lang/crates.io-index" 4286 6601 checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" 6602 + 6603 + [[package]] 6604 + name = "windows_i686_gnu" 6605 + version = "0.48.5" 6606 + source = "registry+https://github.com/rust-lang/crates.io-index" 6607 + checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" 4287 6608 4288 6609 [[package]] 4289 6610 name = "windows_i686_gnu" ··· 4299 6620 4300 6621 [[package]] 4301 6622 name = "windows_i686_msvc" 6623 + version = "0.48.5" 6624 + source = "registry+https://github.com/rust-lang/crates.io-index" 6625 + checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" 6626 + 6627 + [[package]] 6628 + name = "windows_i686_msvc" 4302 6629 version = "0.52.6" 4303 6630 source = "registry+https://github.com/rust-lang/crates.io-index" 4304 6631 checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" 4305 6632 4306 6633 [[package]] 4307 6634 name = "windows_x86_64_gnu" 6635 + version = "0.48.5" 6636 + source = "registry+https://github.com/rust-lang/crates.io-index" 6637 + checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" 6638 + 6639 + [[package]] 6640 + name = "windows_x86_64_gnu" 4308 6641 version = "0.52.6" 4309 6642 source = "registry+https://github.com/rust-lang/crates.io-index" 4310 6643 checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" 4311 6644 4312 6645 [[package]] 4313 6646 name = "windows_x86_64_gnullvm" 6647 + version = "0.48.5" 6648 + source = "registry+https://github.com/rust-lang/crates.io-index" 6649 + checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" 6650 + 6651 + [[package]] 6652 + name = "windows_x86_64_gnullvm" 4314 6653 version = "0.52.6" 4315 6654 source = "registry+https://github.com/rust-lang/crates.io-index" 4316 6655 checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" 4317 6656 4318 6657 [[package]] 4319 6658 name = "windows_x86_64_msvc" 6659 + version = "0.48.5" 6660 + source = "registry+https://github.com/rust-lang/crates.io-index" 6661 + checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" 6662 + 6663 + [[package]] 6664 + name = "windows_x86_64_msvc" 4320 6665 version = "0.52.6" 4321 6666 source = "registry+https://github.com/rust-lang/crates.io-index" 4322 6667 checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" 4323 6668 4324 6669 [[package]] 4325 6670 name = "winnow" 4326 - version = "0.7.6" 6671 + version = "0.7.11" 4327 6672 source = "registry+https://github.com/rust-lang/crates.io-index" 4328 - checksum = "63d3fcd9bba44b03821e7d699eeee959f3126dcc4aa8e4ae18ec617c2a5cea10" 6673 + checksum = "74c7b26e3480b707944fc872477815d29a8e429d2f93a1ce000f5fa84a15cbcd" 4329 6674 dependencies = [ 4330 6675 "memchr", 6676 + ] 6677 + 6678 + [[package]] 6679 + name = "winreg" 6680 + version = "0.50.0" 6681 + source = "registry+https://github.com/rust-lang/crates.io-index" 6682 + checksum = "524e57b2c537c0f9b1e69f1965311ec12182b4122e45035b1508cd24d2adadb1" 6683 + dependencies = [ 6684 + "cfg-if", 6685 + "windows-sys 0.48.0", 4331 6686 ] 4332 6687 4333 6688 [[package]] ··· 4361 6716 ] 4362 6717 4363 6718 [[package]] 6719 + name = "x509-parser" 6720 + version = "0.17.0" 6721 + source = "registry+https://github.com/rust-lang/crates.io-index" 6722 + checksum = "4569f339c0c402346d4a75a9e39cf8dad310e287eef1ff56d4c68e5067f53460" 6723 + dependencies = [ 6724 + "asn1-rs", 6725 + "data-encoding", 6726 + "der-parser", 6727 + "lazy_static", 6728 + "nom", 6729 + "oid-registry", 6730 + "rusticata-macros", 6731 + "thiserror 2.0.16", 6732 + "time", 6733 + ] 6734 + 6735 + [[package]] 4364 6736 name = "xxhash-rust" 4365 6737 version = "0.8.15" 4366 6738 source = "registry+https://github.com/rust-lang/crates.io-index" 4367 6739 checksum = "fdd20c5420375476fbd4394763288da7eb0cc0b8c11deed431a91562af7335d3" 4368 6740 4369 6741 [[package]] 6742 + name = "yasna" 6743 + version = "0.5.2" 6744 + source = "registry+https://github.com/rust-lang/crates.io-index" 6745 + checksum = "e17bb3549cc1321ae1296b9cdc2698e2b6cb1992adfa19a8c72e5b7a738f44cd" 6746 + dependencies = [ 6747 + "time", 6748 + ] 6749 + 6750 + [[package]] 4370 6751 name = "yoke" 4371 6752 version = "0.7.5" 4372 6753 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 4386 6767 dependencies = [ 4387 6768 "proc-macro2", 4388 6769 "quote", 4389 - "syn", 6770 + "syn 2.0.103", 4390 6771 "synstructure", 4391 6772 ] 4392 6773 ··· 4416 6797 dependencies = [ 4417 6798 "proc-macro2", 4418 6799 "quote", 4419 - "syn", 6800 + "syn 2.0.103", 4420 6801 ] 4421 6802 4422 6803 [[package]] ··· 4427 6808 dependencies = [ 4428 6809 "proc-macro2", 4429 6810 "quote", 4430 - "syn", 6811 + "syn 2.0.103", 4431 6812 ] 4432 6813 4433 6814 [[package]] ··· 4447 6828 dependencies = [ 4448 6829 "proc-macro2", 4449 6830 "quote", 4450 - "syn", 6831 + "syn 2.0.103", 4451 6832 "synstructure", 4452 6833 ] 4453 6834 ··· 4456 6837 version = "1.8.1" 4457 6838 source = "registry+https://github.com/rust-lang/crates.io-index" 4458 6839 checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" 6840 + dependencies = [ 6841 + "serde", 6842 + "zeroize_derive", 6843 + ] 6844 + 6845 + [[package]] 6846 + name = "zeroize_derive" 6847 + version = "1.4.2" 6848 + source = "registry+https://github.com/rust-lang/crates.io-index" 6849 + checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" 6850 + dependencies = [ 6851 + "proc-macro2", 6852 + "quote", 6853 + "syn 2.0.103", 6854 + ] 4459 6855 4460 6856 [[package]] 4461 6857 name = "zerovec" ··· 4476 6872 dependencies = [ 4477 6873 "proc-macro2", 4478 6874 "quote", 4479 - "syn", 6875 + "syn 2.0.103", 4480 6876 ] 4481 6877 4482 6878 [[package]]
+6
Cargo.toml
··· 6 6 "jetstream", 7 7 "ufos", 8 8 "ufos/fuzz", 9 + "spacedust", 10 + "who-am-i", 11 + "slingshot", 12 + "quasar", 13 + "pocket", 14 + "reflector", 9 15 ]
+9 -2
Makefile
··· 2 2 all: check 3 3 4 4 test: 5 - cargo test 5 + cargo test --all-features 6 6 7 7 fmt: 8 - cargo fmt --package links --package constellation --package ufos 8 + cargo fmt --package links \ 9 + --package constellation \ 10 + --package ufos \ 11 + --package spacedust \ 12 + --package who-am-i \ 13 + --package slingshot \ 14 + --package pocket \ 15 + --package reflector 9 16 cargo +nightly fmt --package jetstream 10 17 11 18 clippy:
+1 -1
cozy-setup (move to another repo).md legacy/cozy-setup (move to another repo).md
··· 339 339 340 340 - systemd unit for running: `sudo nano /etc/systemd/system/constellation.service` 341 341 342 - ```toml 342 + ```ini 343 343 [Unit] 344 344 Description=Constellation backlinks index 345 345 After=network.target
+6 -1
jetstream/Cargo.toml
··· 10 10 11 11 [dependencies] 12 12 async-trait = "0.1.83" 13 - atrium-api = { git = "https://github.com/uniphil/atrium", branch = "fix/nsid-allow-nonleading-name-digits", default-features = false, features = [ 13 + atrium-api = { git = "https://github.com/uniphil/atrium.git", branch = "fix/resolve-handle-https-accept-whitespace", default-features = false, features = [ 14 14 "namespace-appbsky", 15 15 ] } 16 16 tokio = { version = "1.44.2", features = ["full", "sync", "time"] } ··· 20 20 "url", 21 21 ] } 22 22 futures-util = "0.3.31" 23 + metrics = { version = "0.24.2", optional = true } 23 24 url = "2.5.4" 24 25 serde = { version = "1.0.215", features = ["derive"] } 25 26 serde_json = { version = "1.0.140", features = ["raw_value"] } ··· 31 32 [dev-dependencies] 32 33 anyhow = "1.0.93" 33 34 clap = { version = "4.5.20", features = ["derive"] } 35 + 36 + [features] 37 + default = [] 38 + metrics = ["dep:metrics"]
+2 -6
jetstream/src/error.rs
··· 36 36 /// See [websocket_task](crate::websocket_task). 37 37 #[derive(Error, Debug)] 38 38 pub enum JetstreamEventError { 39 - #[error("received websocket message that could not be deserialized as JSON: {0}")] 40 - ReceivedMalformedJSON(#[from] serde_json::Error), 41 39 #[error("failed to load built-in zstd dictionary for decoding: {0}")] 42 40 CompressionDictionaryError(io::Error), 43 - #[error("failed to decode zstd-compressed message: {0}")] 44 - CompressionDecoderError(io::Error), 45 - #[error("all receivers were dropped but the websocket connection failed to close cleanly")] 46 - WebSocketCloseFailure, 47 41 #[error("failed to send ping or pong: {0}")] 48 42 PingPongError(#[from] tokio_tungstenite::tungstenite::Error), 43 + #[error("no messages received within ttl")] 44 + NoMessagesReceived, 49 45 #[error("jetstream event receiver closed")] 50 46 ReceiverClosedError, 51 47 }
+11
jetstream/src/events.rs
··· 142 142 let t: SystemTime = self.into(); 143 143 t.elapsed() 144 144 } 145 + /// Compute the age of the cursor vs the local clock 146 + /// 147 + /// Converts the resulting duration into an f64, which can be negative! 148 + /// 149 + /// Warning: this exploits the internal implementation detail of jetstream cursors 150 + pub fn elapsed_micros_f64(&self) -> f64 { 151 + match self.elapsed() { 152 + Ok(d) => d.as_micros() as f64, 153 + Err(e) => -(e.duration().as_micros() as f64), 154 + } 155 + } 145 156 /// Get the immediate next cursor value 146 157 /// 147 158 /// This is possible for the implementation of jetstream cursors
+128 -8
jetstream/src/lib.rs
··· 14 14 stream::StreamExt, 15 15 SinkExt, 16 16 }; 17 + #[cfg(feature = "metrics")] 18 + use metrics::{ 19 + counter, 20 + describe_counter, 21 + Unit, 22 + }; 17 23 use tokio::{ 18 24 net::TcpStream, 19 25 sync::mpsc::{ ··· 21 27 Receiver, 22 28 Sender, 23 29 }, 30 + time::timeout, 24 31 }; 25 32 use tokio_tungstenite::{ 26 33 connect_async, ··· 194 201 /// can help prevent that if your consumer sometimes pauses, at a cost of higher memory 195 202 /// usage while events are buffered. 196 203 pub channel_size: usize, 204 + /// How long since the last jetstream message before we consider the connection dead 205 + /// 206 + /// Default: 15s 207 + pub liveliness_ttl: Duration, 197 208 } 198 209 199 210 impl Default for JetstreamConfig { ··· 207 218 omit_user_agent_jetstream_info: false, 208 219 replay_on_reconnect: false, 209 220 channel_size: 4096, // a few seconds of firehose buffer 221 + liveliness_ttl: Duration::from_secs(15), 210 222 } 211 223 } 212 224 } ··· 299 311 } 300 312 } 301 313 314 + #[cfg(feature = "metrics")] 315 + fn describe_metrics() { 316 + describe_counter!( 317 + "jetstream_connects", 318 + Unit::Count, 319 + "how many times we've tried to connect" 320 + ); 321 + describe_counter!( 322 + "jetstream_disconnects", 323 + Unit::Count, 324 + "how many times we've been disconnected" 325 + ); 326 + describe_counter!( 327 + "jetstream_total_events_received", 328 + Unit::Count, 329 + "total number of events received" 330 + ); 331 + describe_counter!( 332 + "jetstream_total_bytes_received", 333 + Unit::Count, 334 + "total uncompressed bytes received, not including websocket overhead" 335 + ); 336 + describe_counter!( 337 + "jetstream_total_event_errors", 338 + Unit::Count, 339 + "total errors when handling events" 340 + ); 341 + describe_counter!( 342 + "jetstream_total_events_sent", 343 + Unit::Count, 344 + "total events sent to the consumer" 345 + ); 346 + } 347 + 302 348 impl JetstreamConnector { 303 349 /// Create a Jetstream connector with a valid [JetstreamConfig]. 304 350 /// 305 351 /// After creation, you can call [connect] to connect to the provided Jetstream instance. 306 352 pub fn new(config: JetstreamConfig) -> Result<Self, ConfigValidationError> { 353 + #[cfg(feature = "metrics")] 354 + describe_metrics(); 355 + 307 356 // We validate the configuration here so any issues are caught early. 308 357 config.validate()?; 309 358 Ok(JetstreamConnector { config }) ··· 337 386 338 387 let (send_channel, receive_channel) = channel(self.config.channel_size); 339 388 let replay_on_reconnect = self.config.replay_on_reconnect; 389 + let liveliness_ttl = self.config.liveliness_ttl; 340 390 let build_request = self.config.get_request_builder(); 341 391 342 392 tokio::task::spawn(async move { ··· 359 409 } 360 410 }; 361 411 412 + #[cfg(feature = "metrics")] 413 + if let Some(host) = req.uri().host() { 414 + let retry = if retry_attempt > 0 { "yes" } else { "no" }; 415 + counter!("jetstream_connects", "host" => host.to_string(), "retry" => retry) 416 + .increment(1); 417 + } 418 + 362 419 let mut last_cursor = connect_cursor; 363 420 retry_attempt += 1; 364 421 if let Ok((ws_stream, _)) = connect_async(req).await { 365 422 let t_connected = Instant::now(); 366 423 log::info!("jetstream connected. starting websocket task..."); 367 - if let Err(e) = 368 - websocket_task(dict, ws_stream, send_channel.clone(), &mut last_cursor) 369 - .await 424 + if let Err(e) = websocket_task( 425 + dict, 426 + ws_stream, 427 + send_channel.clone(), 428 + &mut last_cursor, 429 + liveliness_ttl, 430 + ) 431 + .await 370 432 { 371 - if let JetstreamEventError::ReceiverClosedError = e { 372 - log::error!("Jetstream receiver channel closed. Exiting consumer."); 373 - return; 433 + match e { 434 + JetstreamEventError::ReceiverClosedError => { 435 + #[cfg(feature="metrics")] 436 + counter!("jetstream_disconnects", "reason" => "channel", "fatal" => "yes").increment(1); 437 + log::error!("Jetstream receiver channel closed. Exiting consumer."); 438 + return; 439 + } 440 + JetstreamEventError::CompressionDictionaryError(_) => { 441 + #[cfg(feature="metrics")] 442 + counter!("jetstream_disconnects", "reason" => "zstd", "fatal" => "no").increment(1); 443 + } 444 + JetstreamEventError::NoMessagesReceived => { 445 + #[cfg(feature="metrics")] 446 + counter!("jetstream_disconnects", "reason" => "ttl", "fatal" => "no").increment(1); 447 + } 448 + JetstreamEventError::PingPongError(_) => { 449 + #[cfg(feature="metrics")] 450 + counter!("jetstream_disconnects", "reason" => "pingpong", "fatal" => "no").increment(1); 451 + } 374 452 } 375 - log::error!("Jetstream closed after encountering error: {e:?}"); 453 + log::warn!("Jetstream closed after encountering error: {e:?}"); 376 454 } else { 455 + #[cfg(feature = "metrics")] 456 + counter!("jetstream_disconnects", "reason" => "close", "fatal" => "no") 457 + .increment(1); 377 458 log::warn!("Jetstream connection closed cleanly"); 378 459 } 379 460 if t_connected.elapsed() > Duration::from_secs(success_threshold_s) { ··· 416 497 ws: WebSocketStream<MaybeTlsStream<TcpStream>>, 417 498 send_channel: JetstreamSender, 418 499 last_cursor: &mut Option<Cursor>, 500 + liveliness_ttl: Duration, 419 501 ) -> Result<(), JetstreamEventError> { 420 502 // TODO: Use the write half to allow the user to change configuration settings on the fly. 421 503 let (mut socket_write, mut socket_read) = ws.split(); 422 504 423 505 let mut closing_connection = false; 424 506 loop { 425 - match socket_read.next().await { 507 + let next = match timeout(liveliness_ttl, socket_read.next()).await { 508 + Ok(n) => n, 509 + Err(_) => { 510 + log::warn!("jetstream no events for {liveliness_ttl:?}, closing"); 511 + _ = socket_write.close().await; 512 + return Err(JetstreamEventError::NoMessagesReceived); 513 + } 514 + }; 515 + match next { 426 516 Some(Ok(message)) => match message { 427 517 Message::Text(json) => { 518 + #[cfg(feature = "metrics")] 519 + { 520 + counter!("jetstream_total_events_received", "compressed" => "false") 521 + .increment(1); 522 + counter!("jetstream_total_bytes_received", "compressed" => "false") 523 + .increment(json.len() as u64); 524 + } 428 525 let event: JetstreamEvent = match serde_json::from_str(&json) { 429 526 Ok(ev) => ev, 430 527 Err(e) => { 528 + #[cfg(feature = "metrics")] 529 + counter!("jetstream_total_event_errors", "reason" => "deserialize") 530 + .increment(1); 431 531 log::warn!( 432 532 "failed to parse json: {e:?} (from {})", 433 533 json.get(..24).unwrap_or(&json) ··· 439 539 440 540 if let Some(last) = last_cursor { 441 541 if event_cursor <= *last { 542 + #[cfg(feature = "metrics")] 543 + counter!("jetstream_total_event_errors", "reason" => "old") 544 + .increment(1); 442 545 log::warn!("event cursor {event_cursor:?} was not newer than the last one: {last:?}. dropping event."); 443 546 continue; 444 547 } ··· 453 556 } else if let Some(last) = last_cursor.as_mut() { 454 557 *last = event_cursor; 455 558 } 559 + #[cfg(feature = "metrics")] 560 + counter!("jetstream_total_events_sent").increment(1); 456 561 } 457 562 Message::Binary(zstd_json) => { 563 + #[cfg(feature = "metrics")] 564 + { 565 + counter!("jetstream_total_events_received", "compressed" => "true") 566 + .increment(1); 567 + counter!("jetstream_total_bytes_received", "compressed" => "true") 568 + .increment(zstd_json.len() as u64); 569 + } 458 570 let mut cursor = IoCursor::new(zstd_json); 459 571 let decoder = 460 572 zstd::stream::Decoder::with_prepared_dictionary(&mut cursor, &dictionary) ··· 463 575 let event: JetstreamEvent = match serde_json::from_reader(decoder) { 464 576 Ok(ev) => ev, 465 577 Err(e) => { 578 + #[cfg(feature = "metrics")] 579 + counter!("jetstream_total_event_errors", "reason" => "deserialize") 580 + .increment(1); 466 581 log::warn!("failed to parse json: {e:?}"); 467 582 continue; 468 583 } ··· 471 586 472 587 if let Some(last) = last_cursor { 473 588 if event_cursor <= *last { 589 + #[cfg(feature = "metrics")] 590 + counter!("jetstream_total_event_errors", "reason" => "old") 591 + .increment(1); 474 592 log::warn!("event cursor {event_cursor:?} was not newer than the last one: {last:?}. dropping event."); 475 593 continue; 476 594 } ··· 485 603 } else if let Some(last) = last_cursor.as_mut() { 486 604 *last = event_cursor; 487 605 } 606 + #[cfg(feature = "metrics")] 607 + counter!("jetstream_total_events_sent").increment(1); 488 608 } 489 609 Message::Ping(vec) => { 490 610 log::trace!("Ping recieved, responding");
+35
legacy/old-readme-details.md
··· 1 + [Constellation](./constellation/) 2 + -------------------------------------------- 3 + 4 + A global atproto backlink index ✨ 5 + 6 + - Self hostable: handles the full write throughput of the global atproto firehose on a raspberry pi 4b + single SSD 7 + - Storage efficient: less than 2GB/day disk consumption indexing all references in all lexicons and all non-atproto URLs 8 + - Handles record deletion, account de/re-activation, and account deletion, ensuring accurate link counts and respecting users data choices 9 + - Simple JSON API 10 + 11 + All social interactions in atproto tend to be represented by links (or references) between PDS records. This index can answer questions like "how many likes does a bsky post have", "who follows an account", "what are all the comments on a [frontpage](https://frontpage.fyi/) post", and more. 12 + 13 + - **status**: works! api is unstable and likely to change, and no known instances have a full network backfill yet. 14 + - source: [./constellation/](./constellation/) 15 + - public instance: [constellation.microcosm.blue](https://constellation.microcosm.blue/) 16 + 17 + _note: the public instance currently runs on a little raspberry pi in my house, feel free to use it! it comes with only with best-effort uptime, no commitment to not breaking the api for now, and possible rate-limiting. if you want to be nice you can put your project name and bsky username (or email) in your user-agent header for api requests._ 18 + 19 + 20 + App: Spacedust 21 + -------------- 22 + 23 + A notification subscription service 💫 24 + 25 + using the same "link source" concept as [constellation](./constellation/), offer webhook notifications for new references created to records 26 + 27 + - **status**: in design 28 + 29 + 30 + Library: [links](./links/) 31 + ------------------------------------ 32 + 33 + A rust crate (not published on crates.io yet) for optimistically parsing links out of arbitrary atproto PDS records, and potentially canonicalizing them 34 + 35 + - **status**: unstable, might remain an internal lib for constellation (and spacedust, soon)
+123
legacy/original-notes.md
··· 1 + --- 2 + 3 + 4 + old notes follow, ignore 5 + ------------------------ 6 + 7 + 8 + as far as i can tell, atproto lexicons today don't follow much of a convention for referencing across documents: sometimes it's a StrongRef, sometimes it's a DID, sometimes it's a bare at-uri. lexicon authors choose any old link-sounding key name for the key in their document. 9 + 10 + it's pretty messy so embrace the mess: atproto wants to be part of the web, so this library will also extract URLs and other URIs if you want it to. all the links. 11 + 12 + 13 + why 14 + --- 15 + 16 + the atproto firehose that bluesky sprays at you will contain raw _contents_ from peoples' pdses. these are isolated, decontextualized updates. it's very easy to build some kinds of interesting downstream apps off of this feed. 17 + 18 + - bluesky posts (firesky, deletions, ) 19 + - blueksy post stats (emojis, ) 20 + - trending keywords () 21 + 22 + but bringing almost kind of _context_ into your project requires a big step up in complexity and potentially cost: you're entering "appview" territory. _how many likes does a post have? who follows this account?_ 23 + 24 + you own your atproto data: it's kept in your personal data repository (PDS) and noone else can write to it. when someone likes your post, they create a "like" record in their _own_ pds, and that like belongs to _them_, not to you/your post. 25 + 26 + in the firehose you'll see a `app.bsky.feed.post` record created, with no details about who has liked it. then you'll see separate `app.bsky.feed.like` records show up for each like that comes in on that post, with no context about the post except a random-looking reference to it. storing these in order to do so is up to you! 27 + 28 + **so, why** 29 + 30 + everything is links, and they're a mess, but they all kinda work the same, so maybe some tooling can bring down that big step in complexity from firehose raw-content apps -> apps requiring any social context. 31 + 32 + everything is links: 33 + 34 + - likes 35 + - follows 36 + - blocks 37 + - reposts 38 + - quotes 39 + 40 + some low-level things you could make from links: 41 + 42 + - notification streams (part of ucosm) 43 + - a global reverse index (part of ucosm) 44 + 45 + i think that making these low-level services as easy to use as jetstream could open up pathways for building more atproto apps that operate at full scale with interesting features for reasonable effort at low cost to operate. 46 + 47 + 48 + extracting links 49 + --------------- 50 + 51 + 52 + - low-level: pass a &str of a field value and get a parsed link back 53 + 54 + - med-level: pass a &str of record in json form and get a list of parsed links + json paths back. (todo: should also handle dag-cbor prob?) 55 + 56 + - high-ish level: pass the json record and maybe apply some pre-loaded rules based on known lexicons to get the best result. 57 + 58 + for now, a link is only considered if it matches for the entire value of the record's field -- links embedded in text content are not included. note that urls in bluesky posts _will_ still be extracted, since they are broken out into facets. 59 + 60 + 61 + resolving / canonicalizing links 62 + -------------------------------- 63 + 64 + 65 + ### at-uris 66 + 67 + every at-uri has at least two equivalent forms, one with a `DID`, and one with an account handle. the at-uri spec [illustrates this by example](https://atproto.com/specs/at-uri-scheme): 68 + 69 + - `at://did:plc:44ybard66vv44zksje25o7dz/app.bsky.feed.post/3jwdwj2ctlk26` 70 + - `at://bnewbold.bsky.team/app.bsky.feed.post/3jwdwj2ctlk26` 71 + 72 + some applications, like a reverse link index, may wish to canonicalize at-uris to a single form. the `DID`-form is stable as an account changes its handle and probably the right choice to canonicalize to, but maybe some apps would actually perfer to canonicalise to handles? 73 + 74 + hopefully atrium will make it easy to resolve at-uris. 75 + 76 + 77 + ### urls 78 + 79 + canonicalizing URLs is more annoying but also a bit more established. lots of details. 80 + 81 + - do we have to deal with punycode? 82 + - follow redirects (todo: only permanent ones, or all?) 83 + - check for rel=canonical http header and possibly follow it 84 + - check link rel=canonical meta tag and possibly follow it 85 + - do we need to check site maps?? 86 + - do we have to care at all about AMP? 87 + - do we want anything to do with url shorteners?? 88 + - how do multilingual sites affect this? 89 + - do we have to care about `script type="application/ld+json"` ??? 90 + 91 + ugh. is there a crate for this. 92 + 93 + 94 + ### relative uris? 95 + 96 + links might be relative, in which case they might need to be made absolute before being useful. is that a concern for this library, or up to the user? (seems like we might not have context here to determine its absolute) 97 + 98 + 99 + ### canonicalizing 100 + 101 + there should be a few async functions available to canonicalize already-parsed links. 102 + 103 + - what happens if a link can't be resolved? 104 + 105 + 106 + --- 107 + 108 + - using `tinyjson` because it's nice -- maybe should switch to serde_json to share deps with atrium? 109 + 110 + - would use atrium for parsing at-uris, but it's not in there. there's a did-only version in the non-lib commands.rs. its identifier parser is strict to did + handle, which makes sense, but for our purposes we might want to allow unknown methods too? 111 + 112 + - rsky-syntax has an aturi 113 + - adenosyne also 114 + - might come back to these 115 + 116 + 117 + ------- 118 + 119 + rocks 120 + 121 + ```bash 122 + ROCKSDB_LIB_DIR=/nix/store/z2chn0hsik0clridr8mlprx1cngh1g3c-rocksdb-9.7.3/lib/ cargo build 123 + ```
+196
legacy/ufos ops (move to micro-ops).md
··· 1 + ufos ops 2 + 3 + btrfs snapshots: snapper 4 + 5 + ```bash 6 + sudo apt install snapper 7 + sudo snapper -c ufos-db create-config /mnt/ufos-db 8 + 9 + # edit /etc/snapper/configs/ufos-db 10 + # change 11 + TIMELINE_MIN_AGE="1800" 12 + TIMELINE_LIMIT_HOURLY="10" 13 + TIMELINE_LIMIT_DAILY="10" 14 + TIMELINE_LIMIT_WEEKLY="0" 15 + TIMELINE_LIMIT_MONTHLY="10" 16 + TIMELINE_LIMIT_YEARLY="10" 17 + # to 18 + TIMELINE_MIN_AGE="1800" 19 + TIMELINE_LIMIT_HOURLY="22" 20 + TIMELINE_LIMIT_DAILY="4" 21 + TIMELINE_LIMIT_WEEKLY="0" 22 + TIMELINE_LIMIT_MONTHLY="0" 23 + TIMELINE_LIMIT_YEARLY="0" 24 + ``` 25 + 26 + this should be enough? 27 + 28 + list snapshots: 29 + 30 + ```bash 31 + sudo snapper -c ufos-db list 32 + ``` 33 + 34 + systemd 35 + 36 + create file: `/etc/systemd/system/ufos.service` 37 + 38 + ```ini 39 + [Unit] 40 + Description=UFOs-API 41 + After=network.target 42 + 43 + [Service] 44 + User=pi 45 + WorkingDirectory=/home/pi/ 46 + ExecStart=/home/pi/ufos --jetstream us-west-2 --data /mnt/ufos-db/ 47 + Environment="RUST_LOG=info" 48 + LimitNOFILE=16384 49 + Restart=always 50 + 51 + [Install] 52 + WantedBy=multi-user.target 53 + ``` 54 + 55 + then 56 + 57 + ```bash 58 + sudo systemctl daemon-reload 59 + sudo systemctl enable ufos 60 + sudo systemctl start ufos 61 + ``` 62 + 63 + monitor with 64 + 65 + ```bash 66 + journalctl -u ufos -f 67 + ``` 68 + 69 + make sure a backup dir exists 70 + 71 + ```bash 72 + mkdir /home/pi/backup 73 + ``` 74 + 75 + mount the NAS 76 + 77 + ```bash 78 + sudo mount.cifs "//truenas.local/folks data" /home/pi/backup -o user=phil,uid=pi 79 + ``` 80 + 81 + manual rsync 82 + 83 + ```bash 84 + sudo rsync -ahP --delete /mnt/ufos-db/.snapshots/1/snapshot/ backup/ufos/ 85 + ``` 86 + 87 + backup script sketch 88 + 89 + ```bash 90 + NUM=$(sudo snapper --csvout -c ufos-db list --type single --columns number | tail -n1) 91 + sudo rsync -ahP --delete "/mnt/ufos-db/.snapshots/${NUM}/snapshot/" backup/ufos/ 92 + ``` 93 + 94 + just crontab it? 95 + 96 + `sudo crontab -e` 97 + ```bash 98 + 0 1/6 * * * rsync -ahP --delete "/mnt/ufos-db/.snapshots/$(sudo snapper --csvout -c ufos-db list --columns number | tail -n1)/snapshot/" backup/ufos/ 99 + ``` 100 + 101 + ^^ try once initial backup is done 102 + 103 + 104 + --columns subvolume,number 105 + 106 + subvolume 107 + number 108 + 109 + 110 + 111 + 112 + gateway: follow constellation for nginx->prom thing 113 + 114 + config at `/etc/prometheus-nginxlog-exporter.hcl` 115 + 116 + before: `/etc/prometheus-nginxlog-exporter.hcl` 117 + 118 + ```hcl 119 + listen { 120 + port = 4044 121 + } 122 + 123 + namespace "nginx" { 124 + source = { 125 + files = [ 126 + "/var/log/nginx/constellation-access.log" 127 + ] 128 + } 129 + 130 + format = "$remote_addr - $remote_user [$time_local] \"$request\" $status $upstream_cache_status $body_bytes_sent \"$http_referer\" \"$http_user_agent\" \"$http_x_forwarded_for\"" 131 + 132 + labels { 133 + app = "constellation" 134 + } 135 + 136 + relabel "cache_status" { 137 + from = "upstream_cache_status" 138 + } 139 + } 140 + ``` 141 + 142 + after: 143 + 144 + ```hcl 145 + listen { 146 + port = 4044 147 + } 148 + 149 + namespace "constellation" { 150 + source = { 151 + files = [ 152 + "/var/log/nginx/constellation-access.log" 153 + ] 154 + } 155 + 156 + format = "$remote_addr - $remote_user [$time_local] \"$request\" $status $upstream_cache_status $body_bytes_sent \"$http_referer\" \"$http_user_agent\" \"$http_x_forwarded_for\"" 157 + 158 + labels { 159 + app = "constellation" 160 + } 161 + 162 + relabel "cache_status" { 163 + from = "upstream_cache_status" 164 + } 165 + 166 + namespace_label = "vhost" 167 + metrics_override = { prefix = "nginx" } 168 + } 169 + 170 + namespace "ufos" { 171 + source = { 172 + files = [ 173 + "/var/log/nginx/ufos-access.log" 174 + ] 175 + } 176 + 177 + format = "$remote_addr - $remote_user [$time_local] \"$request\" $status $upstream_cache_status $body_bytes_sent \"$http_referer\" \"$http_user_agent\" \"$http_x_forwarded_for\"" 178 + 179 + labels { 180 + app = "ufos" 181 + } 182 + 183 + relabel "cache_status" { 184 + from = "upstream_cache_status" 185 + } 186 + 187 + namespace_label = "vhost" 188 + metrics_override = { prefix = "nginx" } 189 + } 190 + ``` 191 + 192 + 193 + ```bash 194 + systemctl start prometheus-nginxlog-exporter.service 195 + ``` 196 +
+15
links/src/lib.rs
··· 42 42 None 43 43 } 44 44 } 45 + pub fn did(&self) -> Option<String> { 46 + let did = match self { 47 + Link::AtUri(s) => { 48 + let rest = s.strip_prefix("at://")?; // todo: this might be safe to unwrap? 49 + if let Some((did, _)) = rest.split_once("/") { 50 + did 51 + } else { 52 + rest 53 + } 54 + } 55 + Link::Uri(_) => return None, 56 + Link::Did(did) => did, 57 + }; 58 + Some(did.to_string()) 59 + } 45 60 } 46 61 47 62 #[derive(Debug, PartialEq)]
+1
pocket/.gitignore
··· 1 + prefs.sqlite3*
+19
pocket/Cargo.toml
··· 1 + [package] 2 + name = "pocket" 3 + version = "0.1.0" 4 + edition = "2024" 5 + 6 + [dependencies] 7 + atrium-crypto = "0.1.2" 8 + clap = { version = "4.5.41", features = ["derive"] } 9 + jwt-compact = { git = "https://github.com/fatfingers23/jwt-compact.git", features = ["es256k"] } 10 + log = "0.4.27" 11 + poem = { version = "3.1.12", features = ["acme", "static-files"] } 12 + poem-openapi = { version = "5.1.16", features = ["scalar"] } 13 + reqwest = { version = "0.12.22", features = ["json"] } 14 + rusqlite = "0.37.0" 15 + serde = { version = "1.0.219", features = ["derive"] } 16 + serde_json = { version = "1.0.141" } 17 + thiserror = "2.0.16" 18 + tokio = { version = "1.47.0", features = ["full"] } 19 + tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }
+17
pocket/api-description.md
··· 1 + _A pocket dimension to stash a bit of non-public user data._ 2 + 3 + 4 + # Pocket: user preference storage 5 + 6 + This API leverages atproto service proxying to offer a bit of per-user per-app non-public data storage. 7 + Perfect for things like application preferences that might be better left out of the public PDS data. 8 + 9 + The intent is to use oauth scopes to isolate storage on a per-application basis, and to allow easy data migration from a community hosted instance to your own if you end up needing that. 10 + 11 + 12 + ### Current status 13 + 14 + > [!important] 15 + > Pocket is currently in a **v0, pre-release state**. There is one production instance and you can use it! Expect short downtimes for restarts as development progresses and occaisional data loss until it's stable. 16 + 17 + ATProto might end up adding a similar feature to [PDSs](https://atproto.com/guides/glossary#pds-personal-data-server). If/when that happens, you should use it instead of this!
+7
pocket/src/lib.rs
··· 1 + mod server; 2 + mod storage; 3 + mod token; 4 + 5 + pub use server::serve; 6 + pub use storage::Storage; 7 + pub use token::TokenVerifier;
+34
pocket/src/main.rs
··· 1 + use clap::Parser; 2 + use pocket::{Storage, serve}; 3 + use std::path::PathBuf; 4 + 5 + /// Slingshot record edge cache 6 + #[derive(Parser, Debug, Clone)] 7 + #[command(version, about, long_about = None)] 8 + struct Args { 9 + /// path to the sqlite db file 10 + #[arg(long)] 11 + db: Option<PathBuf>, 12 + /// just initialize the db and exit 13 + #[arg(long, action)] 14 + init_db: bool, 15 + /// the domain for serving a did doc (unused if running behind reflector) 16 + #[arg(long)] 17 + domain: Option<String>, 18 + } 19 + 20 + #[tokio::main] 21 + async fn main() { 22 + tracing_subscriber::fmt::init(); 23 + log::info!("👖 hi"); 24 + let args = Args::parse(); 25 + let domain = args.domain.unwrap_or("bad-example.com".into()); 26 + let db_path = args.db.unwrap_or("prefs.sqlite3".into()); 27 + if args.init_db { 28 + Storage::init(&db_path).unwrap(); 29 + log::info!("👖 initialized db at {db_path:?}. bye") 30 + } else { 31 + let storage = Storage::connect(db_path).unwrap(); 32 + serve(&domain, storage).await 33 + } 34 + }
+265
pocket/src/server.rs
··· 1 + use crate::{Storage, TokenVerifier}; 2 + use poem::{ 3 + Endpoint, EndpointExt, Route, Server, 4 + endpoint::{StaticFileEndpoint, make_sync}, 5 + http::Method, 6 + listener::TcpListener, 7 + middleware::{CatchPanic, Cors, Tracing}, 8 + }; 9 + use poem_openapi::{ 10 + ApiResponse, ContactObject, ExternalDocumentObject, Object, OpenApi, OpenApiService, 11 + SecurityScheme, Tags, 12 + auth::Bearer, 13 + payload::{Json, PlainText}, 14 + types::Example, 15 + }; 16 + use serde::Serialize; 17 + use serde_json::{Value, json}; 18 + use std::sync::{Arc, Mutex}; 19 + 20 + #[derive(Debug, SecurityScheme)] 21 + #[oai(ty = "bearer")] 22 + struct XrpcAuth(Bearer); 23 + 24 + #[derive(Tags)] 25 + enum ApiTags { 26 + /// Custom pocket APIs 27 + #[oai(rename = "Pocket APIs")] 28 + Pocket, 29 + } 30 + 31 + #[derive(Object)] 32 + #[oai(example = true)] 33 + struct XrpcErrorResponseObject { 34 + /// Should correspond an error `name` in the lexicon errors array 35 + error: String, 36 + /// Human-readable description and possibly additonal context 37 + message: String, 38 + } 39 + impl Example for XrpcErrorResponseObject { 40 + fn example() -> Self { 41 + Self { 42 + error: "PreferencesNotFound".to_string(), 43 + message: "No preferences were found for this user".to_string(), 44 + } 45 + } 46 + } 47 + type XrpcError = Json<XrpcErrorResponseObject>; 48 + fn xrpc_error(error: impl AsRef<str>, message: impl AsRef<str>) -> XrpcError { 49 + Json(XrpcErrorResponseObject { 50 + error: error.as_ref().to_string(), 51 + message: message.as_ref().to_string(), 52 + }) 53 + } 54 + 55 + #[derive(Debug, Object)] 56 + #[oai(example = true)] 57 + struct BskyPrefsObject { 58 + /// at-uri for this record 59 + preferences: Value, 60 + } 61 + impl Example for BskyPrefsObject { 62 + fn example() -> Self { 63 + Self { 64 + preferences: json!({ 65 + "hello": "world", 66 + }), 67 + } 68 + } 69 + } 70 + 71 + #[derive(ApiResponse)] 72 + enum GetBskyPrefsResponse { 73 + /// Record found 74 + #[oai(status = 200)] 75 + Ok(Json<BskyPrefsObject>), 76 + /// Bad request or no preferences to return 77 + #[oai(status = 400)] 78 + BadRequest(XrpcError), 79 + } 80 + 81 + #[derive(ApiResponse)] 82 + enum PutBskyPrefsResponse { 83 + /// Record found 84 + #[oai(status = 200)] 85 + Ok(PlainText<String>), 86 + /// Bad request or no preferences to return 87 + #[oai(status = 400)] 88 + BadRequest(XrpcError), 89 + // /// Server errors 90 + // #[oai(status = 500)] 91 + // ServerError(XrpcError), 92 + } 93 + 94 + struct Xrpc { 95 + verifier: TokenVerifier, 96 + storage: Arc<Mutex<Storage>>, 97 + } 98 + 99 + #[OpenApi] 100 + impl Xrpc { 101 + /// com.bad-example.pocket.getPreferences 102 + /// 103 + /// get stored preferencess 104 + #[oai( 105 + path = "/com.bad-example.pocket.getPreferences", 106 + method = "get", 107 + tag = "ApiTags::Pocket" 108 + )] 109 + async fn pocket_get_prefs(&self, XrpcAuth(auth): XrpcAuth) -> GetBskyPrefsResponse { 110 + let (did, aud) = match self 111 + .verifier 112 + .verify("com.bad-example.pocket.getPreferences", &auth.token) 113 + .await 114 + { 115 + Ok(d) => d, 116 + Err(e) => return GetBskyPrefsResponse::BadRequest(xrpc_error("boooo", e.to_string())), 117 + }; 118 + log::info!("verified did: {did}/{aud}"); 119 + 120 + let storage = self.storage.clone(); 121 + 122 + let Ok(Ok(res)) = tokio::task::spawn_blocking(move || { 123 + storage 124 + .lock() 125 + .unwrap() 126 + .get(&did, &aud) 127 + .inspect_err(|e| log::error!("failed to get prefs: {e}")) 128 + }) 129 + .await 130 + else { 131 + return GetBskyPrefsResponse::BadRequest(xrpc_error("boooo", "failed to get from db")); 132 + }; 133 + 134 + let Some(serialized) = res else { 135 + return GetBskyPrefsResponse::BadRequest(xrpc_error( 136 + "NotFound", 137 + "could not find prefs for u", 138 + )); 139 + }; 140 + 141 + let preferences = match serde_json::from_str(&serialized) { 142 + Ok(v) => v, 143 + Err(e) => { 144 + log::error!("failed to deserialize prefs: {e}"); 145 + return GetBskyPrefsResponse::BadRequest(xrpc_error( 146 + "boooo", 147 + "failed to deserialize prefs", 148 + )); 149 + } 150 + }; 151 + 152 + GetBskyPrefsResponse::Ok(Json(BskyPrefsObject { preferences })) 153 + } 154 + 155 + /// com.bad-example.pocket.putPreferences 156 + /// 157 + /// store bluesky prefs 158 + #[oai( 159 + path = "/com.bad-example.pocket.putPreferences", 160 + method = "post", 161 + tag = "ApiTags::Pocket" 162 + )] 163 + async fn pocket_put_prefs( 164 + &self, 165 + XrpcAuth(auth): XrpcAuth, 166 + Json(prefs): Json<BskyPrefsObject>, 167 + ) -> PutBskyPrefsResponse { 168 + let (did, aud) = match self 169 + .verifier 170 + .verify("com.bad-example.pocket.putPreferences", &auth.token) 171 + .await 172 + { 173 + Ok(d) => d, 174 + Err(e) => return PutBskyPrefsResponse::BadRequest(xrpc_error("boooo", e.to_string())), 175 + }; 176 + log::info!("verified did: {did}/{aud}"); 177 + log::warn!("received prefs: {prefs:?}"); 178 + 179 + let storage = self.storage.clone(); 180 + let serialized = prefs.preferences.to_string(); 181 + 182 + let Ok(Ok(())) = tokio::task::spawn_blocking(move || { 183 + storage 184 + .lock() 185 + .unwrap() 186 + .put(&did, &aud, &serialized) 187 + .inspect_err(|e| log::error!("failed to insert prefs: {e}")) 188 + }) 189 + .await 190 + else { 191 + return PutBskyPrefsResponse::BadRequest(xrpc_error("boooo", "failed to put to db")); 192 + }; 193 + 194 + PutBskyPrefsResponse::Ok(PlainText("saved.".to_string())) 195 + } 196 + } 197 + 198 + #[derive(Debug, Clone, Serialize)] 199 + #[serde(rename_all = "camelCase")] 200 + struct AppViewService { 201 + id: String, 202 + r#type: String, 203 + service_endpoint: String, 204 + } 205 + #[derive(Debug, Clone, Serialize)] 206 + struct AppViewDoc { 207 + id: String, 208 + service: [AppViewService; 2], 209 + } 210 + /// Serve a did document for did:web for this to be an xrpc appview 211 + fn get_did_doc(domain: &str) -> impl Endpoint + use<> { 212 + let doc = poem::web::Json(AppViewDoc { 213 + id: format!("did:web:{domain}"), 214 + service: [ 215 + AppViewService { 216 + id: "#pocket_prefs".to_string(), 217 + r#type: "PocketPreferences".to_string(), 218 + service_endpoint: format!("https://{domain}"), 219 + }, 220 + AppViewService { 221 + id: "#bsky_appview".to_string(), 222 + r#type: "BlueskyAppview".to_string(), 223 + service_endpoint: format!("https://{domain}"), 224 + }, 225 + ], 226 + }); 227 + make_sync(move |_| doc.clone()) 228 + } 229 + 230 + pub async fn serve(domain: &str, storage: Storage) -> () { 231 + let verifier = TokenVerifier::default(); 232 + let api_service = OpenApiService::new( 233 + Xrpc { 234 + verifier, 235 + storage: Arc::new(Mutex::new(storage)), 236 + }, 237 + "Pocket", 238 + env!("CARGO_PKG_VERSION"), 239 + ) 240 + .server(domain) 241 + .url_prefix("/xrpc") 242 + .contact( 243 + ContactObject::new() 244 + .name("@microcosm.blue") 245 + .url("https://bsky.app/profile/microcosm.blue"), 246 + ) 247 + .description(include_str!("../api-description.md")) 248 + .external_document(ExternalDocumentObject::new("https://microcosm.blue/pocket")); 249 + 250 + let app = Route::new() 251 + .nest("/openapi", api_service.spec_endpoint()) 252 + .nest("/xrpc/", api_service) 253 + .at("/.well-known/did.json", get_did_doc(domain)) 254 + .at("/", StaticFileEndpoint::new("./static/index.html")) 255 + .with( 256 + Cors::new() 257 + .allow_method(Method::GET) 258 + .allow_method(Method::POST), 259 + ) 260 + .with(CatchPanic::new()) 261 + .with(Tracing); 262 + 263 + let listener = TcpListener::bind("127.0.0.1:3000"); 264 + Server::new(listener).name("pocket").run(app).await.unwrap(); 265 + }
+50
pocket/src/storage.rs
··· 1 + use rusqlite::{Connection, OptionalExtension, Result}; 2 + use std::path::Path; 3 + 4 + pub struct Storage { 5 + con: Connection, 6 + } 7 + 8 + impl Storage { 9 + pub fn connect(path: impl AsRef<Path>) -> Result<Self> { 10 + let con = Connection::open(path)?; 11 + con.pragma_update(None, "journal_mode", "WAL")?; 12 + con.pragma_update(None, "synchronous", "NORMAL")?; 13 + con.pragma_update(None, "busy_timeout", "100")?; 14 + con.pragma_update(None, "foreign_keys", "ON")?; 15 + Ok(Self { con }) 16 + } 17 + pub fn init(path: impl AsRef<Path>) -> Result<Self> { 18 + let me = Self::connect(path)?; 19 + me.con.execute( 20 + r#" 21 + create table prefs ( 22 + actor text not null, 23 + aud text not null, 24 + pref text not null, 25 + primary key (actor, aud) 26 + ) strict"#, 27 + (), 28 + )?; 29 + Ok(me) 30 + } 31 + pub fn put(&self, actor: &str, aud: &str, pref: &str) -> Result<()> { 32 + self.con.execute( 33 + r#"insert into prefs (actor, aud, pref) 34 + values (?1, ?2, ?3) 35 + on conflict do update set pref = excluded.pref"#, 36 + [actor, aud, pref], 37 + )?; 38 + Ok(()) 39 + } 40 + pub fn get(&self, actor: &str, aud: &str) -> Result<Option<String>> { 41 + self.con 42 + .query_one( 43 + r#"select pref from prefs 44 + where actor = ?1 and aud = ?2"#, 45 + [actor, aud], 46 + |row| row.get(0), 47 + ) 48 + .optional() 49 + } 50 + }
+143
pocket/src/token.rs
··· 1 + use atrium_crypto::did::parse_multikey; 2 + use atrium_crypto::verify::Verifier; 3 + use jwt_compact::UntrustedToken; 4 + use serde::Deserialize; 5 + use std::collections::HashMap; 6 + use std::time::Duration; 7 + use thiserror::Error; 8 + 9 + #[derive(Debug, Deserialize)] 10 + struct MiniDoc { 11 + signing_key: String, 12 + did: String, 13 + } 14 + 15 + #[derive(Error, Debug)] 16 + pub enum VerifyError { 17 + #[error("The cross-service authorization token failed verification: {0}")] 18 + VerificationFailed(&'static str), 19 + #[error("Error trying to resolve the DID to a signing key, retry in a moment: {0}")] 20 + ResolutionFailed(&'static str), 21 + } 22 + 23 + pub struct TokenVerifier { 24 + client: reqwest::Client, 25 + } 26 + 27 + impl TokenVerifier { 28 + pub fn new() -> Self { 29 + let client = reqwest::Client::builder() 30 + .user_agent(format!( 31 + "microcosm pocket v{} (dev: @bad-example.com)", 32 + env!("CARGO_PKG_VERSION") 33 + )) 34 + .no_proxy() 35 + .timeout(Duration::from_secs(12)) // slingshot timeout is 10s 36 + .build() 37 + .unwrap(); 38 + Self { client } 39 + } 40 + 41 + pub async fn verify( 42 + &self, 43 + expected_lxm: &str, 44 + token: &str, 45 + ) -> Result<(String, String), VerifyError> { 46 + let untrusted = UntrustedToken::new(token).unwrap(); 47 + 48 + // danger! unfortunately we need to decode the DID from the jwt body before we have a public key to verify the jwt with 49 + let Ok(untrusted_claims) = 50 + untrusted.deserialize_claims_unchecked::<HashMap<String, String>>() 51 + else { 52 + return Err(VerifyError::VerificationFailed( 53 + "could not deserialize jtw claims", 54 + )); 55 + }; 56 + 57 + // get the (untrusted!) claimed DID 58 + let Some(untrusted_did) = untrusted_claims.custom.get("iss") else { 59 + return Err(VerifyError::VerificationFailed( 60 + "jwt must include the user's did in `iss`", 61 + )); 62 + }; 63 + 64 + // bail if it's not even a user-ish did 65 + if !untrusted_did.starts_with("did:") { 66 + return Err(VerifyError::VerificationFailed("iss should be a did")); 67 + } 68 + if untrusted_did.contains("#") { 69 + return Err(VerifyError::VerificationFailed( 70 + "iss should be a user did without a service identifier", 71 + )); 72 + } 73 + 74 + let endpoint = 75 + "https://slingshot.microcosm.blue/xrpc/com.bad-example.identity.resolveMiniDoc"; 76 + let doc: MiniDoc = self 77 + .client 78 + .get(format!("{endpoint}?identifier={untrusted_did}")) 79 + .send() 80 + .await 81 + .map_err(|_| VerifyError::ResolutionFailed("failed to fetch minidoc"))? 82 + .error_for_status() 83 + .map_err(|_| VerifyError::ResolutionFailed("non-ok response for minidoc"))? 84 + .json() 85 + .await 86 + .map_err(|_| VerifyError::ResolutionFailed("failed to parse json to minidoc"))?; 87 + 88 + // sanity check before we go ahead with this signing key 89 + if doc.did != *untrusted_did { 90 + return Err(VerifyError::VerificationFailed( 91 + "wtf, resolveMiniDoc returned a doc for a different DID, slingshot bug", 92 + )); 93 + } 94 + 95 + let Ok((alg, public_key)) = parse_multikey(&doc.signing_key) else { 96 + return Err(VerifyError::VerificationFailed( 97 + "could not parse signing key form minidoc", 98 + )); 99 + }; 100 + 101 + // i _guess_ we've successfully bootstrapped the verification of the jwt unless this fails 102 + if let Err(e) = Verifier::default().verify( 103 + alg, 104 + &public_key, 105 + &untrusted.signed_data, 106 + untrusted.signature_bytes(), 107 + ) { 108 + log::warn!("jwt verification failed: {e}"); 109 + return Err(VerifyError::VerificationFailed( 110 + "jwt signature verification failed", 111 + )); 112 + } 113 + 114 + // past this point we're should have established trust. crossing ts and dotting is. 115 + let did = &untrusted_did; 116 + let claims = &untrusted_claims; 117 + 118 + let Some(aud) = claims.custom.get("aud") else { 119 + return Err(VerifyError::VerificationFailed("missing aud")); 120 + }; 121 + let Some(mut aud) = aud.strip_prefix("did:web:") else { 122 + return Err(VerifyError::VerificationFailed("expected a did:web aud")); 123 + }; 124 + if let Some((aud_without_hash, _)) = aud.split_once("#") { 125 + log::warn!("aud claim is missing service id fragment: {aud:?}"); 126 + aud = aud_without_hash; 127 + } 128 + let Some(lxm) = claims.custom.get("lxm") else { 129 + return Err(VerifyError::VerificationFailed("missing lxm")); 130 + }; 131 + if lxm != expected_lxm { 132 + return Err(VerifyError::VerificationFailed("wrong lxm")); 133 + } 134 + 135 + Ok((did.to_string(), aud.to_string())) 136 + } 137 + } 138 + 139 + impl Default for TokenVerifier { 140 + fn default() -> Self { 141 + Self::new() 142 + } 143 + }
+67
pocket/static/index.html
··· 1 + <!doctype html> 2 + <html lang="en"> 3 + <head> 4 + <meta charset="utf-8" /> 5 + <title>Pocket: atproto user preference storage</title> 6 + <meta name="viewport" content="width=device-width, initial-scale=1" /> 7 + <meta name="description" content="API Documentation for Pocket, a simple user-preference storage system for atproto" /> 8 + <style> 9 + :root { 10 + --scalar-small: 13px; 11 + } 12 + .scalar-app .markdown .markdown-alert { 13 + font-size: var(--scalar-small); 14 + } 15 + .sidebar-heading-link-title { 16 + line-height: 1.2; 17 + } 18 + .custom-header { 19 + height: 42px; 20 + background-color: #221828; 21 + box-shadow: inset 0 -1px 0 var(--scalar-border-color); 22 + color: var(--scalar-color-1); 23 + font-size: var(--scalar-font-size-3); 24 + font-family: 'Iowan Old Style', 'Palatino Linotype', 'URW Palladio L', P052, serif; 25 + padding: 0 18px; 26 + justify-content: space-between; 27 + } 28 + .custom-header, 29 + .custom-header nav { 30 + display: flex; 31 + align-items: center; 32 + gap: 18px; 33 + } 34 + .custom-header a:hover { 35 + color: var(--scalar-color-2); 36 + } 37 + 38 + .light-mode .custom-header { 39 + background-color: thistle; 40 + } 41 + </style> 42 + </head> 43 + <body> 44 + <header class="custom-header scalar-app"> 45 + <p> 46 + TODO: thing 47 + </p> 48 + <nav> 49 + <b>a <a href="https://microcosm.blue">microcosm</a> project</b> 50 + <a href="https://bsky.app/profile/microcosm.blue">@microcosm.blue</a> 51 + <a href="https://github.com/at-microcosm">github</a> 52 + </nav> 53 + </header> 54 + 55 + <script id="api-reference" type="application/json" data-url="/openapi"></script> 56 + 57 + <script> 58 + var configuration = { 59 + theme: 'purple', 60 + hideModels: true, 61 + } 62 + document.getElementById('api-reference').dataset.configuration = JSON.stringify(configuration) 63 + </script> 64 + 65 + <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script> 66 + </body> 67 + </html>
+8
quasar/Cargo.toml
··· 1 + [package] 2 + name = "quasar" 3 + version = "0.1.0" 4 + edition = "2024" 5 + 6 + [dependencies] 7 + clap = { version = "4.5.46", features = ["derive"] } 8 + fjall = "2.11.2"
+3
quasar/readme.md
··· 1 + # quasar 2 + 3 + indexed replay and fan-out for event stream services (wip)
+3
quasar/src/lib.rs
··· 1 + mod storage; 2 + 3 + pub use storage::Storage;
+3
quasar/src/main.rs
··· 1 + fn main() { 2 + println!("Hello, world!"); 3 + }
+4
quasar/src/storage.rs
··· 1 + 2 + pub trait Storage { 3 + 4 + }
+57 -129
readme.md
··· 1 - microcosm: links 2 - ================ 3 - 4 - this repo contains libraries and apps for working with cross-record references in at-protocol. 5 - 1 + microcosm HTTP APIs + rust crates 2 + ================================= 3 + [![@microcosm.blue: bluesky](https://img.shields.io/badge/@microcosm.blue-bluesky-blue)](https://bsky.app/profile/microcosm.blue) 4 + [![microcosm discord: join](https://img.shields.io/badge/microcosm_discord-join-purple)](https://discord.gg/tcDfe4PGVB) 5 + [![github sponsors: support](https://img.shields.io/badge/github_sponsors-support-pink)](https://github.com/sponsors/uniphil/) 6 + [![ko-fi: support](https://img.shields.io/badge/ko--fi-support-pink)](https://ko-fi.com/bad_example) 6 7 7 - App: [Constellation](./constellation/) 8 - -------------------------------------------- 8 + Welcome! Documentation is under active development. If you like reading API docs, you'll probably hit the ground running! 9 9 10 - A global atproto backlink index ✨ 10 + Tutorials, how-to guides, and client SDK libraries are all in the works for gentler on-ramps, but are not quite ready yet. But don't let that stop you! Hop in the [microcosm discord](https://discord.gg/tcDfe4PGVB), or post questions and tag [@bad-example.com](https://bsky.app/profile/bad-example.com) on Bluesky if you get stuck anywhere. 11 11 12 - - Self hostable: handles the full write throughput of the global atproto firehose on a raspberry pi 4b + single SSD 13 - - Storage efficient: less than 2GB/day disk consumption indexing all references in all lexicons and all non-atproto URLs 14 - - Handles record deletion, account de/re-activation, and account deletion, ensuring accurate link counts and respecting users data choices 15 - - Simple JSON API 12 + > [!tip] 13 + > This repository's primary home is moving to tangled: [@microcosm.blue/microcosm-rs](https://tangled.sh/@microcosm.blue/microcosm-rs). It will continue to be mirrored on [github](https://github.com/at-microcosm/microcosm-rs) for the forseeable future, and it's fine to open issues or pulls in either place! 16 14 17 - All social interactions in atproto tend to be represented by links (or references) between PDS records. This index can answer questions like "how many likes does a bsky post have", "who follows an account", "what are all the comments on a [frontpage](https://frontpage.fyi/) post", and more. 18 15 19 - - **status**: works! api is unstable and likely to change, and no known instances have a full network backfill yet. 20 - - source: [./constellation/](./constellation/) 21 - - public instance: [constellation.microcosm.blue](https://constellation.microcosm.blue/) 22 - 23 - _note: the public instance currently runs on a little raspberry pi in my house, feel free to use it! it comes with only with best-effort uptime, no commitment to not breaking the api for now, and possible rate-limiting. if you want to be nice you can put your project name and bsky username (or email) in your user-agent header for api requests._ 24 - 25 - 26 - App: Spacedust 27 - -------------- 28 - 29 - A notification subscription service 💫 30 - 31 - using the same "link source" concept as [constellation](./constellation/), offer webhook notifications for new references created to records 32 - 33 - - **status**: in design 34 - 35 - 36 - Library: [links](./links/) 16 + 🌌 [Constellation](./constellation/) 37 17 ------------------------------------ 38 18 39 - A rust crate (not published on crates.io yet) for optimistically parsing links out of arbitrary atproto PDS records, and potentially canonicalizing them 40 - 41 - - **status**: unstable, might remain an internal lib for constellation (and spacedust, soon) 42 - 43 - 44 - 45 - --- 46 - 47 - 48 - old notes follow, ignore 49 - ------------------------ 50 - 51 - 52 - as far as i can tell, atproto lexicons today don't follow much of a convention for referencing across documents: sometimes it's a StrongRef, sometimes it's a DID, sometimes it's a bare at-uri. lexicon authors choose any old link-sounding key name for the key in their document. 53 - 54 - it's pretty messy so embrace the mess: atproto wants to be part of the web, so this library will also extract URLs and other URIs if you want it to. all the links. 55 - 56 - 57 - why 58 - --- 59 - 60 - the atproto firehose that bluesky sprays at you will contain raw _contents_ from peoples' pdses. these are isolated, decontextualized updates. it's very easy to build some kinds of interesting downstream apps off of this feed. 61 - 62 - - bluesky posts (firesky, deletions, ) 63 - - blueksy post stats (emojis, ) 64 - - trending keywords () 65 - 66 - but bringing almost kind of _context_ into your project requires a big step up in complexity and potentially cost: you're entering "appview" territory. _how many likes does a post have? who follows this account?_ 67 - 68 - you own your atproto data: it's kept in your personal data repository (PDS) and noone else can write to it. when someone likes your post, they create a "like" record in their _own_ pds, and that like belongs to _them_, not to you/your post. 69 - 70 - in the firehose you'll see a `app.bsky.feed.post` record created, with no details about who has liked it. then you'll see separate `app.bsky.feed.like` records show up for each like that comes in on that post, with no context about the post except a random-looking reference to it. storing these in order to do so is up to you! 71 - 72 - **so, why** 73 - 74 - everything is links, and they're a mess, but they all kinda work the same, so maybe some tooling can bring down that big step in complexity from firehose raw-content apps -> apps requiring any social context. 75 - 76 - everything is links: 77 - 78 - - likes 79 - - follows 80 - - blocks 81 - - reposts 82 - - quotes 83 - 84 - some low-level things you could make from links: 85 - 86 - - notification streams (part of ucosm) 87 - - a global reverse index (part of ucosm) 88 - 89 - i think that making these low-level services as easy to use as jetstream could open up pathways for building more atproto apps that operate at full scale with interesting features for reasonable effort at low cost to operate. 19 + A global atproto interactions backlink index as a simple JSON API. Works with every lexicon, runs on a raspberry pi, consumes less than 2GiB of disk per day. Handles record deletion, account de/re-activation, and account deletion, ensuring accurate link counts while respecting users' data choices. 90 20 21 + - Source: [./constellation/](./constellation/) 22 + - [Public instance/API docs](https://constellation.microcosm.blue/) 23 + - Status: used in production. APIs will change but backwards compatibility will be maintained as long as needed. 91 24 92 - extracting links 93 - --------------- 94 25 26 + 🎇 [Spacedust](./spacedust/) 27 + ---------------------------- 95 28 96 - - low-level: pass a &str of a field value and get a parsed link back 29 + A global atproto interactions firehose. Extracts all at-uris, DIDs, and URLs from every lexicon in the firehose, and exposes them over a websocket modelled after [jetstream](github.com/bluesky-social/jetstream). 97 30 98 - - med-level: pass a &str of record in json form and get a list of parsed links + json paths back. (todo: should also handle dag-cbor prob?) 31 + - Source: [./spacedust/](./spacedust/) 32 + - [Public instance/API docs](https://spacedust.microcosm.blue/) 33 + - Status: v0: the basics work and the APIs are in place! missing cursor replay, forward link storage, and delete event link hydration. 99 34 100 - - high-ish level: pass the json record and maybe apply some pre-loaded rules based on known lexicons to get the best result. 35 + ### Demos: 101 36 102 - for now, a link is only considered if it matches for the entire value of the record's field -- links embedded in text content are not included. note that urls in bluesky posts _will_ still be extracted, since they are broken out into facets. 37 + - [Spacedust notifications](https://notifications.microcosm.blue/): web push notifications for _every_ atproto app 38 + - [Zero-Bluesky real-time interaction-updating post embed](https://bsky.bad-example.com/zero-bluesky-realtime-embed/) 103 39 104 40 105 - resolving / canonicalizing links 106 - -------------------------------- 41 + 🛰️ [Slingshot](./slingshot) 42 + --------------------------- 107 43 44 + A fast, eager, production-grade edge cache for atproto records and identities. Pre-caches all records from the firehose and maintains a longer-term cache of requested records on disk. 108 45 109 - ### at-uris 46 + - Source: [./slingshot/](./slingshot/) 47 + - [Public instance/API docs](https://slingshot.microcosm.blue/) 48 + - Status: v0: most XRPC APIs are working. cache storage is being reworked. 110 49 111 - every at-uri has at least two equivalent forms, one with a `DID`, and one with an account handle. the at-uri spec [illustrates this by example](https://atproto.com/specs/at-uri-scheme): 112 50 113 - - `at://did:plc:44ybard66vv44zksje25o7dz/app.bsky.feed.post/3jwdwj2ctlk26` 114 - - `at://bnewbold.bsky.team/app.bsky.feed.post/3jwdwj2ctlk26` 51 + 🛸 [UFOs API](./ufos) 52 + --------------------- 115 53 116 - some applications, like a reverse link index, may wish to canonicalize at-uris to a single form. the `DID`-form is stable as an account changes its handle and probably the right choice to canonicalize to, but maybe some apps would actually perfer to canonicalise to handles? 54 + Timeseries stats and sample records for every [collection](https://atproto.com/guides/glossary#collection) ever seen in the atproto firehose. Unique users are counted in hyperloglog sketches enabling arbitrary cardinality aggregation across time buckets and/or NSIDs. 117 55 118 - hopefully atrium will make it easy to resolve at-uris. 56 + - Source: [./ufos/](./ufos/) 57 + - [Public instance/API docs](https://ufos-api.microcosm.blue/) 58 + - Status: Used in production. It has APIs and they work! Needs improvement on indexing; needs more indexes and some more APIs to the data exposed. 119 59 60 + > [!tip] 61 + > See also: [UFOs atproto explorer](https://ufos.microcosm.blue/) built on UFOs API. ([source](github.com/at-microcosm/spacedust-utils)) 120 62 121 - ### urls 122 63 123 - canonicalizing URLs is more annoying but also a bit more established. lots of details. 64 + 💫 [Links](./links) 65 + ------------------- 124 66 125 - - do we have to deal with punycode? 126 - - follow redirects (todo: only permanent ones, or all?) 127 - - check for rel=canonical http header and possibly follow it 128 - - check link rel=canonical meta tag and possibly follow it 129 - - do we need to check site maps?? 130 - - do we have to care at all about AMP? 131 - - do we want anything to do with url shorteners?? 132 - - how do multilingual sites affect this? 133 - - do we have to care about `script type="application/ld+json"` ??? 67 + Rust library for parsing and extracting links (at-uris, DIDs, and URLs) from atproto records. 134 68 135 - ugh. is there a crate for this. 69 + - Source: [./links/](./links/) 70 + - Status: not yet published to crates.io; needs some rework 136 71 137 72 138 - ### relative uris? 139 - 140 - links might be relative, in which case they might need to be made absolute before being useful. is that a concern for this library, or up to the user? (seems like we might not have context here to determine its absolute) 141 - 142 - 143 - ### canonicalizing 144 - 145 - there should be a few async functions available to canonicalize already-parsed links. 146 - 147 - - what happens if a link can't be resolved? 73 + 🛩️ [Jetstream](./jetstream) 74 + --------------------------- 148 75 76 + A low-overhead jetstream client with cursor handling and automatic reconnect. 149 77 150 - --- 78 + - Source: [./links/](./links/) 79 + - Status: used in multiple apps in production, but not yet published to crates.io; some rework planned 151 80 152 - - using `tinyjson` because it's nice -- maybe should switch to serde_json to share deps with atrium? 81 + > [!tip] 82 + > See also: [Rocketman](https://github.com/teal-fm/cadet/tree/main/rocketman), another excellent rust jetstream client which shares some lineage and _is_ published on crates.io. 153 83 154 - - would use atrium for parsing at-uris, but it's not in there. there's a did-only version in the non-lib commands.rs. its identifier parser is strict to did + handle, which makes sense, but for our purposes we might want to allow unknown methods too? 155 84 156 - - rsky-syntax has an aturi 157 - - adenosyne also 158 - - might come back to these 159 85 86 + 🔭 Deprecated: [Who am I](./who-am-i) 87 + ------------------------------------- 160 88 161 - ------- 89 + An identity bridge for microcosm demos, that kinda worked. Fixing its problems is about equivalent to reinventing a lot of OIDC, so it's being retired. 162 90 163 - rocks 91 + - Source: [./who-am-i/](./who-am-i/) 92 + - Status: ready for retirement. 164 93 165 - ```bash 166 - ROCKSDB_LIB_DIR=/nix/store/z2chn0hsik0clridr8mlprx1cngh1g3c-rocksdb-9.7.3/lib/ cargo build 167 - ``` 94 + > [!warning] 95 + > `who-am-i` is still in use for the Spacedust Notifications demo, but that will hopefully be migrated to use atproto oauth directly instead.
+12
reflector/Cargo.toml
··· 1 + [package] 2 + name = "reflector" 3 + version = "0.1.0" 4 + edition = "2024" 5 + 6 + [dependencies] 7 + clap = { version = "4.5.47", features = ["derive"] } 8 + log = "0.4.28" 9 + poem = "3.1.12" 10 + serde = { version = "1.0.219", features = ["derive"] } 11 + tokio = "1.47.1" 12 + tracing-subscriber = { version = "0.3.20", features = ["env-filter"] }
+9
reflector/readme.md
··· 1 + # reflector 2 + 3 + a tiny did:web service server that maps subdomains to a single service endpoint 4 + 5 + receiving requests from multiple subdomains is left as a problem for the reverse proxy to solve, since acme wildcard certificates (ie. letsencrypt) require the most complicated and involved challenge type (DNS). 6 + 7 + caddy [has good support for](https://caddyserver.com/docs/caddyfile/patterns#wildcard-certificates) configuring the wildcard DNS challenge with various DNS providers, and also supports [on-demand](https://caddyserver.com/docs/automatic-https#using-on-demand-tls) provisioning via the simpler methods. 8 + 9 + if you only need a small fixed number of subdomains, you can also use certbot or otherwise individually configure them in your reverse proxy.
+113
reflector/src/main.rs
··· 1 + use clap::Parser; 2 + use poem::{ 3 + EndpointExt, Response, Route, Server, get, handler, 4 + http::StatusCode, 5 + listener::TcpListener, 6 + middleware::{AddData, Tracing}, 7 + web::{Data, Json, Query, TypedHeader, headers::Host}, 8 + }; 9 + use serde::{Deserialize, Serialize}; 10 + 11 + #[handler] 12 + fn hello() -> String { 13 + "ɹoʇɔǝʅⅎǝɹ".to_string() 14 + } 15 + 16 + #[derive(Debug, Serialize)] 17 + struct DidDoc { 18 + id: String, 19 + service: [DidService; 1], 20 + } 21 + 22 + #[derive(Debug, Clone, Serialize)] 23 + #[serde(rename_all = "camelCase")] 24 + struct DidService { 25 + id: String, 26 + r#type: String, 27 + service_endpoint: String, 28 + } 29 + 30 + #[handler] 31 + fn did_doc(TypedHeader(host): TypedHeader<Host>, service: Data<&DidService>) -> Json<DidDoc> { 32 + Json(DidDoc { 33 + id: format!("did:web:{}", host.hostname()), 34 + service: [service.clone()], 35 + }) 36 + } 37 + 38 + #[derive(Deserialize)] 39 + struct AskQuery { 40 + domain: String, 41 + } 42 + #[handler] 43 + fn ask_caddy( 44 + Data(parent): Data<&Option<String>>, 45 + Query(AskQuery { domain }): Query<AskQuery>, 46 + ) -> Response { 47 + if let Some(parent) = parent { 48 + if let Some(prefix) = domain.strip_suffix(&format!(".{parent}")) { 49 + if !prefix.contains('.') { 50 + // no sub-sub-domains allowed 51 + return Response::builder().body("ok"); 52 + } 53 + } 54 + }; 55 + Response::builder() 56 + .status(StatusCode::FORBIDDEN) 57 + .body("nope") 58 + } 59 + 60 + /// Slingshot record edge cache 61 + #[derive(Parser, Debug, Clone)] 62 + #[command(version, about, long_about = None)] 63 + struct Args { 64 + /// The DID document service ID to serve 65 + /// 66 + /// must start with a '#', like `#bsky_appview' 67 + #[arg(long)] 68 + id: String, 69 + /// Service type 70 + /// 71 + /// Not sure exactly what its requirements are. 'BlueskyAppview' for example 72 + #[arg(long)] 73 + r#type: String, 74 + /// The HTTPS endpoint for the service 75 + #[arg(long)] 76 + service_endpoint: String, 77 + /// The parent domain; requests should come from subdomains of this 78 + #[arg(long)] 79 + domain: Option<String>, 80 + } 81 + 82 + impl From<Args> for DidService { 83 + fn from(a: Args) -> Self { 84 + Self { 85 + id: a.id, 86 + r#type: a.r#type, 87 + service_endpoint: a.service_endpoint, 88 + } 89 + } 90 + } 91 + 92 + #[tokio::main(flavor = "current_thread")] 93 + async fn main() { 94 + tracing_subscriber::fmt::init(); 95 + log::info!("ɹoʇɔǝʅⅎǝɹ"); 96 + 97 + let args = Args::parse(); 98 + let domain = args.domain.clone(); 99 + let service: DidService = args.into(); 100 + 101 + Server::new(TcpListener::bind("0.0.0.0:3001")) 102 + .run( 103 + Route::new() 104 + .at("/", get(hello)) 105 + .at("/.well-known/did.json", get(did_doc)) 106 + .at("/ask", get(ask_caddy)) 107 + .with(AddData::new(service)) 108 + .with(AddData::new(domain)) 109 + .with(Tracing), 110 + ) 111 + .await 112 + .unwrap() 113 + }
+1
slingshot/.gitignore
··· 1 + foyer
+31
slingshot/Cargo.toml
··· 1 + [package] 2 + name = "slingshot" 3 + version = "0.1.0" 4 + edition = "2024" 5 + 6 + [dependencies] 7 + atrium-api = { git = "https://github.com/uniphil/atrium.git", branch = "fix/resolve-handle-https-accept-whitespace", default-features = false } 8 + atrium-common = { git = "https://github.com/uniphil/atrium.git", branch = "fix/resolve-handle-https-accept-whitespace" } 9 + atrium-identity = { git = "https://github.com/uniphil/atrium.git", branch = "fix/resolve-handle-https-accept-whitespace" } 10 + atrium-oauth = { git = "https://github.com/uniphil/atrium.git", branch = "fix/resolve-handle-https-accept-whitespace" } 11 + clap = { version = "4.5.41", features = ["derive"] } 12 + ctrlc = "3.4.7" 13 + foyer = { version = "0.18.0", features = ["serde"] } 14 + hickory-resolver = "0.25.2" 15 + jetstream = { path = "../jetstream", features = ["metrics"] } 16 + links = { path = "../links" } 17 + log = "0.4.27" 18 + metrics = "0.24.2" 19 + metrics-exporter-prometheus = { version = "0.17.1", features = ["http-listener"] } 20 + poem = { version = "3.1.12", features = ["acme", "static-files"] } 21 + poem-openapi = { version = "5.1.16", features = ["scalar"] } 22 + reqwest = { version = "0.12.22", features = ["json"] } 23 + rustls = "0.23.31" 24 + serde = { version = "1.0.219", features = ["derive"] } 25 + serde_json = { version = "1.0.141", features = ["raw_value"] } 26 + thiserror = "2.0.12" 27 + time = { version = "0.3.41", features = ["serde"] } 28 + tokio = { version = "1.47.0", features = ["full"] } 29 + tokio-util = "0.7.15" 30 + tracing-subscriber = { version = "0.3.19", features = ["env-filter"] } 31 + url = "2.5.4"
+93
slingshot/api-description.md
··· 1 + _A [gravitational slingshot](https://en.wikipedia.org/wiki/Gravity_assist) makes use of the gravity and relative movements of celestial bodies to accelerate a spacecraft and change its trajectory._ 2 + 3 + 4 + # Slingshot: edge record cache 5 + 6 + Applications in [ATProtocol](https://atproto.com/) store data in users' own [PDS](https://atproto.com/guides/self-hosting) (Personal Data Server), which are distributed across thousands of independently-run servers all over the world. Trying to access this data poses challenges for client applications: 7 + 8 + - A PDS might be far away with long network latency 9 + - or may be on an unreliable connection 10 + - or overloaded when you need it, or offline, or… 11 + 12 + Large projects like [Bluesky](https://bsky.app/) control their performance and reliability by syncing all app-relevant data from PDSs into first-party databases. But for new apps, building out this additional data infrastructure adds significant effort and complexity up front. 13 + 14 + **Slingshot is a fast, eager, production-grade cache of data in the [ATmosphere](https://atproto.com/)**, offering performance and reliability without custom infrastructure. 15 + 16 + 17 + ### Current status 18 + 19 + > [!important] 20 + > Slingshot is currently in a **v0, pre-release state**. There is one production instance and you can use it! Expect short downtimes for restarts as development progresses and lower cache hit-rates as the internal storage caches are adjusted and reset. 21 + 22 + The core APIs will not change, since they are standard third-party `com.atproto` query APIs from ATProtocol. 23 + 24 + 25 + ## Eager caching 26 + 27 + In many cases, Slingshot can cache the data you need *before* first request! 28 + 29 + Slingshot subscribes to the global [Firehose](https://atproto.com/specs/sync#firehose) of data updates. It keeps a short-term rolling indexed window of *all* data, and automatically promotes content likely to be requested to its longer-term main cache. _(automatic promotion is still a work in progress)_ 30 + 31 + When there is a cache miss, Slingshot can often still accelerate record fetching, since it keeps a large cache of resolved identities: it can usually request from the correct PDS without extra lookups. 32 + 33 + 34 + ## Precise invalidation 35 + 36 + The fireshose includes **update** and **delete** events, which Slingshot uses to ensure stale and deleted data is removed within a very short window. Additonally, identity and account-level events can trigger rapid cleanup of data for deactivated and deleted accounts. _(some of this is still a work in progress)_ 37 + 38 + 39 + ## Low-trust 40 + 41 + The "AT" in ATProtocol [stands for _Authenticated Transfer_](https://atproto.com/guides/glossary#at-protocol): all data is cryptographically signed, which makes it possible to broadcast data through third parties and trust that it's real _without_ having to directly contact the originating server. 42 + 43 + Two core standard query APIs are supported to balance convenience and trust. They both fetch [records](https://atproto.com/guides/glossary#record): 44 + 45 + ### [`com.atproto.repo.getRecord`](#tag/comatproto-queries/get/xrpc/com.atproto.repo.getRecord) 46 + 47 + - convenient `JSON` response format 48 + - cannot be proven authentic 49 + 50 + ### [`com.atproto.sync.getRecord`](#tag/comatproto-queries/get/xrpc/com.atproto.sync.getRecord) 51 + 52 + - [`DAG-CBOR`](https://atproto.com/specs/data-model)-encoded response requires extra libraries to decode, but 53 + - includes a cryptographic proof of authenticity! 54 + 55 + _(work on this endpoint is in progress)_ 56 + 57 + 58 + ## Service proxying 59 + 60 + Clients can proxy atproto queries through their own PDS with [Service Proxying](https://atproto.com/specs/xrpc#service-proxying), and this is supported by Slingshot. The Slingshot instance must be started the `--domain` argument specified. 61 + 62 + Service-proxied requests can specify a Slingshot instance via the `atproto-proxy` header: 63 + 64 + ```http 65 + GET /xrpc/com.bad-example.identity.resolveMiniDoc?identifier=bad-example.com 66 + Host: <your pds> 67 + atproto-proxy: did:web:<slingshot domain>#slingshot 68 + ``` 69 + 70 + Where `<your pds>` is the user's own PDS host, and `<slingshot domain>` is the domain that the slingshot instance is deployed at (eg. `slingshot.microcosm.blue`). See the [Service Proxying](https://atproto.com/specs/xrpc#service-proxying) docs for more. 71 + 72 + > [!tip] 73 + > Service proxying is supported but completely optional. All APIs are directly accessible over the public internet, and GeoDNS helps route users to the closest instance to them for the lowest possible latency. (_note: deploying multiple slingshot instances with GeoDNS is still TODO_) 74 + 75 + 76 + ## Ergonomic APIs 77 + 78 + - Slingshot also offers variants of the `getRecord` endpoints that accept a full `at-uri` as a parameter, to save clients from needing to parse and validate all parts of a record location. 79 + 80 + - Bi-directionally verifying identity endpoints, so you can directly exchange atproto [`handle`](https://atproto.com/guides/glossary#handle)s for [`DID`](https://atproto.com/guides/glossary#did-decentralized-id)s without extra steps, plus a convenient [Mini-Doc](#tag/slingshot-specific-queries/get/xrpc/com.bad-example.identity.resolveMiniDoc) verified identity summary. 81 + 82 + 83 + ## Part of microcosm 84 + 85 + [Microcosm](https://www.microcosm.blue/) is a collection of services and independent community-run infrastructure for ATProtocol. 86 + 87 + Slingshot excels when combined with _shallow indexing_ services, which offer fast queries of global data relationships but with only references to the data records. Microcosm has a few! 88 + 89 + - [🌌 Constellation](https://constellation.microcosm.blue/), a global backlink index (all social interactions in atproto are links!) 90 + - [🎇 Spacedust](https://spacedust.microcosm.blue/), a firehose of all social interactions 91 + 92 + > [!success] 93 + > All microcosm projects are [open source](https://tangled.sh/@bad-example.com/microcosm-links). **You can help sustain Slingshot** and all of microcosm by becoming a [Github sponsor](https://github.com/sponsors/uniphil/) or a [Ko-fi supporter](https://ko-fi.com/bad_example)!
+7
slingshot/readme.md
··· 1 + # slingshot: atproto record edge cache 2 + 3 + local dev running: 4 + 5 + ```bash 6 + RUST_LOG=info,slingshot=trace ulimit -n 4096 && RUST_LOG=info cargo run -- --jetstream us-east-1 --cache-dir ./foyer 7 + ```
+80
slingshot/src/consumer.rs
··· 1 + use crate::CachedRecord; 2 + use crate::error::ConsumerError; 3 + use foyer::HybridCache; 4 + use jetstream::{ 5 + DefaultJetstreamEndpoints, JetstreamCompression, JetstreamConfig, JetstreamConnector, 6 + events::{CommitOp, Cursor, EventKind}, 7 + }; 8 + use tokio_util::sync::CancellationToken; 9 + 10 + pub async fn consume( 11 + jetstream_endpoint: String, 12 + cursor: Option<Cursor>, 13 + no_zstd: bool, 14 + shutdown: CancellationToken, 15 + cache: HybridCache<String, CachedRecord>, 16 + ) -> Result<(), ConsumerError> { 17 + let endpoint = DefaultJetstreamEndpoints::endpoint_or_shortcut(&jetstream_endpoint); 18 + if endpoint == jetstream_endpoint { 19 + log::info!("consumer: connecting jetstream at {endpoint}"); 20 + } else { 21 + log::info!("consumer: connecting jetstream at {jetstream_endpoint} => {endpoint}"); 22 + } 23 + let config: JetstreamConfig = JetstreamConfig { 24 + endpoint, 25 + compression: if no_zstd { 26 + JetstreamCompression::None 27 + } else { 28 + JetstreamCompression::Zstd 29 + }, 30 + replay_on_reconnect: true, 31 + channel_size: 1024, // buffer up to ~1s of jetstream events 32 + ..Default::default() 33 + }; 34 + let mut receiver = JetstreamConnector::new(config)? 35 + .connect_cursor(cursor) 36 + .await?; 37 + 38 + log::info!("consumer: receiving messages.."); 39 + loop { 40 + if shutdown.is_cancelled() { 41 + log::info!("consumer: exiting for shutdown"); 42 + return Ok(()); 43 + } 44 + let Some(mut event) = receiver.recv().await else { 45 + log::error!("consumer: could not receive event, bailing"); 46 + break; 47 + }; 48 + 49 + if event.kind != EventKind::Commit { 50 + continue; 51 + } 52 + let Some(ref mut commit) = event.commit else { 53 + log::warn!("consumer: commit event missing commit data, ignoring"); 54 + continue; 55 + }; 56 + 57 + // TODO: something a bit more robust 58 + let at_uri = format!( 59 + "at://{}/{}/{}", 60 + &*event.did, &*commit.collection, &*commit.rkey 61 + ); 62 + 63 + if commit.operation == CommitOp::Delete { 64 + cache.insert(at_uri, CachedRecord::Deleted); 65 + } else { 66 + let Some(record) = commit.record.take() else { 67 + log::warn!("consumer: commit insert or update missing record, ignoring"); 68 + continue; 69 + }; 70 + let Some(cid) = commit.cid.take() else { 71 + log::warn!("consumer: commit insert or update missing CID, ignoring"); 72 + continue; 73 + }; 74 + 75 + cache.insert(at_uri, CachedRecord::Found((cid, record).into())); 76 + } 77 + } 78 + 79 + Err(ConsumerError::JetstreamEnded) 80 + }
+93
slingshot/src/error.rs
··· 1 + use crate::ErrorResponseObject; 2 + use thiserror::Error; 3 + 4 + #[derive(Debug, Error)] 5 + pub enum ConsumerError { 6 + #[error(transparent)] 7 + JetstreamConnectionError(#[from] jetstream::error::ConnectionError), 8 + #[error(transparent)] 9 + JetstreamConfigValidationError(#[from] jetstream::error::ConfigValidationError), 10 + #[error("jetstream ended")] 11 + JetstreamEnded, 12 + #[error("delay queue output dropped")] 13 + DelayQueueOutputDropped, 14 + } 15 + 16 + #[derive(Debug, Error)] 17 + pub enum ServerError { 18 + #[error("server build error: {0}")] 19 + AcmeBuildError(std::io::Error), 20 + #[error("server exited: {0}")] 21 + ServerExited(std::io::Error), 22 + } 23 + 24 + #[derive(Debug, Error)] 25 + pub enum IdentityError { 26 + #[error("whatever: {0}")] 27 + WhateverError(String), 28 + #[error("bad DID: {0}")] 29 + BadDid(&'static str), 30 + #[error("identity types got mixed up: {0}")] 31 + IdentityValTypeMixup(String), 32 + #[error("foyer error: {0}")] 33 + FoyerError(#[from] foyer::Error), 34 + 35 + #[error("failed to resolve: {0}")] 36 + ResolutionFailed(#[from] atrium_identity::Error), 37 + // #[error("identity resolved but no handle found for user")] 38 + // NoHandle, 39 + #[error("found handle {0:?} but it appears invalid: {1}")] 40 + InvalidHandle(String, &'static str), 41 + 42 + #[error("could not convert atrium did doc to partial mini doc: {0}")] 43 + BadDidDoc(String), 44 + 45 + #[error("wrong key for clearing refresh queue: {0}")] 46 + RefreshQueueKeyError(&'static str), 47 + } 48 + 49 + #[derive(Debug, Error)] 50 + pub enum HealthCheckError { 51 + #[error("failed to send checkin: {0}")] 52 + HealthCheckError(#[from] reqwest::Error), 53 + } 54 + 55 + #[derive(Debug, Error)] 56 + pub enum MainTaskError { 57 + #[error(transparent)] 58 + ConsumerTaskError(#[from] ConsumerError), 59 + #[error(transparent)] 60 + ServerTaskError(#[from] ServerError), 61 + #[error(transparent)] 62 + IdentityTaskError(#[from] IdentityError), 63 + #[error(transparent)] 64 + HealthCheckError(#[from] HealthCheckError), 65 + #[error("firehose cache failed to close: {0}")] 66 + FirehoseCacheCloseError(foyer::Error), 67 + } 68 + 69 + #[derive(Debug, Error)] 70 + pub enum RecordError { 71 + #[error("identity error: {0}")] 72 + IdentityError(#[from] IdentityError), 73 + #[error("repo could not be validated as either a DID or an atproto handle")] 74 + BadRepo, 75 + #[error("could not get record: {0}")] 76 + NotFound(&'static str), 77 + #[error("could nto parse pds url: {0}")] 78 + UrlParseError(#[from] url::ParseError), 79 + #[error("reqwest send failed: {0}")] 80 + SendError(reqwest::Error), 81 + #[error("reqwest raised for status: {0}")] 82 + StatusError(reqwest::Error), 83 + #[error("reqwest failed to parse json: {0}")] 84 + ParseJsonError(reqwest::Error), 85 + #[error("upstream getRecord did not include a CID")] 86 + MissingUpstreamCid, 87 + #[error("upstream CID was not valid: {0}")] 88 + BadUpstreamCid(String), 89 + #[error("upstream atproto-looking bad request")] 90 + UpstreamBadRequest(ErrorResponseObject), 91 + #[error("upstream non-atproto bad request")] 92 + UpstreamBadBadNotGoodRequest(reqwest::Error), 93 + }
+22
slingshot/src/firehose_cache.rs
··· 1 + use crate::CachedRecord; 2 + use foyer::{DirectFsDeviceOptions, Engine, HybridCache, HybridCacheBuilder}; 3 + use std::path::Path; 4 + 5 + pub async fn firehose_cache( 6 + cache_dir: impl AsRef<Path>, 7 + ) -> Result<HybridCache<String, CachedRecord>, String> { 8 + let cache = HybridCacheBuilder::new() 9 + .with_name("firehose") 10 + .memory(64 * 2_usize.pow(20)) 11 + .with_weighter(|k: &String, v| k.len() + std::mem::size_of_val(v)) 12 + .storage(Engine::large()) 13 + .with_device_options( 14 + DirectFsDeviceOptions::new(cache_dir) 15 + .with_capacity(2_usize.pow(30)) // TODO: configurable (1GB to have something) 16 + .with_file_size(16 * 2_usize.pow(20)), // note: this does limit the max cached item size, warning jumbo records 17 + ) 18 + .build() 19 + .await 20 + .map_err(|e| format!("foyer setup error: {e:?}"))?; 21 + Ok(cache) 22 + }
+32
slingshot/src/healthcheck.rs
··· 1 + use crate::error::HealthCheckError; 2 + use reqwest::Client; 3 + use std::time::Duration; 4 + use tokio::time::sleep; 5 + use tokio_util::sync::CancellationToken; 6 + 7 + pub async fn healthcheck( 8 + endpoint: String, 9 + shutdown: CancellationToken, 10 + ) -> Result<(), HealthCheckError> { 11 + let client = Client::builder() 12 + .user_agent(format!( 13 + "microcosm slingshot v{} (dev: @bad-example.com)", 14 + env!("CARGO_PKG_VERSION") 15 + )) 16 + .no_proxy() 17 + .timeout(Duration::from_secs(10)) 18 + .build()?; 19 + 20 + loop { 21 + tokio::select! { 22 + res = client.get(&endpoint).send() => { 23 + let _ = res 24 + .and_then(|r| r.error_for_status()) 25 + .inspect_err(|e| log::error!("failed to send healthcheck: {e}")); 26 + }, 27 + _ = shutdown.cancelled() => break, 28 + } 29 + sleep(Duration::from_secs(51)).await; 30 + } 31 + Ok(()) 32 + }
+525
slingshot/src/identity.rs
··· 1 + use hickory_resolver::{ResolveError, TokioResolver}; 2 + use std::collections::{HashSet, VecDeque}; 3 + use std::path::Path; 4 + use std::sync::Arc; 5 + /// for now we're gonna just keep doing more cache 6 + /// 7 + /// plc.director x foyer, ttl kept with data, refresh deferred to background on fetch 8 + /// 9 + /// things we need: 10 + /// 11 + /// 1. handle -> DID resolution: getRecord must accept a handle for `repo` param 12 + /// 2. DID -> PDS resolution: so we know where to getRecord 13 + /// 3. DID -> handle resolution: for bidirectional handle validation and in case we want to offer this 14 + use std::time::Duration; 15 + use tokio::sync::Mutex; 16 + use tokio_util::sync::CancellationToken; 17 + 18 + use crate::error::IdentityError; 19 + use atrium_api::{ 20 + did_doc::DidDocument, 21 + types::string::{Did, Handle}, 22 + }; 23 + use atrium_common::resolver::Resolver; 24 + use atrium_identity::{ 25 + did::{CommonDidResolver, CommonDidResolverConfig, DEFAULT_PLC_DIRECTORY_URL}, 26 + handle::{AtprotoHandleResolver, AtprotoHandleResolverConfig, DnsTxtResolver}, 27 + }; 28 + use atrium_oauth::DefaultHttpClient; // it's probably not worth bringing all of atrium_oauth for this but 29 + use foyer::{DirectFsDeviceOptions, Engine, HybridCache, HybridCacheBuilder}; 30 + use serde::{Deserialize, Serialize}; 31 + use time::UtcDateTime; 32 + 33 + /// once we have something resolved, don't re-resolve until after this period 34 + const MIN_TTL: Duration = Duration::from_secs(4 * 3600); // probably shoudl have a max ttl 35 + const MIN_NOT_FOUND_TTL: Duration = Duration::from_secs(60); 36 + 37 + #[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)] 38 + enum IdentityKey { 39 + Handle(Handle), 40 + Did(Did), 41 + } 42 + 43 + #[derive(Debug, Serialize, Deserialize)] 44 + struct IdentityVal(UtcDateTime, IdentityData); 45 + 46 + #[derive(Debug, Serialize, Deserialize)] 47 + enum IdentityData { 48 + NotFound, 49 + Did(Did), 50 + Doc(PartialMiniDoc), 51 + } 52 + 53 + /// partial representation of a com.bad-example.identity mini atproto doc 54 + /// 55 + /// partial because the handle is not verified 56 + #[derive(Debug, Clone, Serialize, Deserialize)] 57 + pub struct PartialMiniDoc { 58 + /// an atproto handle (**unverified**) 59 + /// 60 + /// the first valid atproto handle from the did doc's aka 61 + pub unverified_handle: Handle, 62 + /// the did's atproto pds url (TODO: type this?) 63 + /// 64 + /// note: atrium *does* actually parse it into a URI, it just doesn't return 65 + /// that for some reason 66 + pub pds: String, 67 + /// for now we're just pulling this straight from the did doc 68 + /// 69 + /// would be nice to type and validate it 70 + /// 71 + /// this is the publicKeyMultibase from the did doc. 72 + /// legacy key encoding not supported. 73 + /// `id`, `type`, and `controller` must be checked, but aren't stored. 74 + pub signing_key: String, 75 + } 76 + 77 + impl TryFrom<DidDocument> for PartialMiniDoc { 78 + type Error = String; 79 + fn try_from(did_doc: DidDocument) -> Result<Self, Self::Error> { 80 + // must use the first valid handle 81 + let mut unverified_handle = None; 82 + let Some(ref doc_akas) = did_doc.also_known_as else { 83 + return Err("did doc missing `also_known_as`".to_string()); 84 + }; 85 + for aka in doc_akas { 86 + let Some(maybe_handle) = aka.strip_prefix("at://") else { 87 + continue; 88 + }; 89 + let Ok(valid_handle) = Handle::new(maybe_handle.to_string()) else { 90 + continue; 91 + }; 92 + unverified_handle = Some(valid_handle); 93 + break; 94 + } 95 + let Some(unverified_handle) = unverified_handle else { 96 + return Err("no valid atproto handles in `also_known_as`".to_string()); 97 + }; 98 + 99 + // atrium seems to get service endpoint getters 100 + let Some(pds) = did_doc.get_pds_endpoint() else { 101 + return Err("no valid pds service found".to_string()); 102 + }; 103 + 104 + // TODO can't use atrium's get_signing_key() becuase it fails to check type and controller 105 + // so if we check those and reject it, we might miss a later valid key in the array 106 + // (todo is to fix atrium) 107 + // actually: atrium might be flexible for legacy reps. for now we're rejecting legacy rep. 108 + 109 + // must use the first valid signing key 110 + let mut signing_key = None; 111 + let Some(verification_methods) = did_doc.verification_method else { 112 + return Err("no verification methods found".to_string()); 113 + }; 114 + for method in verification_methods { 115 + if method.id != format!("{}#atproto", did_doc.id) { 116 + continue; 117 + } 118 + if method.r#type != "Multikey" { 119 + continue; 120 + } 121 + if method.controller != did_doc.id { 122 + continue; 123 + } 124 + let Some(key) = method.public_key_multibase else { 125 + continue; 126 + }; 127 + signing_key = Some(key); 128 + break; 129 + } 130 + let Some(signing_key) = signing_key else { 131 + return Err("no valid atproto signing key found in verification methods".to_string()); 132 + }; 133 + 134 + Ok(PartialMiniDoc { 135 + unverified_handle, 136 + pds, 137 + signing_key, 138 + }) 139 + } 140 + } 141 + 142 + /// multi-producer *single-consumer* queue structures (wrap in arc-mutex plz) 143 + /// 144 + /// the hashset allows testing for presense of items in the queue. 145 + /// this has absolutely no support for multiple queue consumers. 146 + #[derive(Debug, Default)] 147 + struct RefreshQueue { 148 + queue: VecDeque<IdentityKey>, 149 + items: HashSet<IdentityKey>, 150 + } 151 + 152 + #[derive(Clone)] 153 + pub struct Identity { 154 + handle_resolver: Arc<AtprotoHandleResolver<HickoryDnsTxtResolver, DefaultHttpClient>>, 155 + did_resolver: Arc<CommonDidResolver<DefaultHttpClient>>, 156 + cache: HybridCache<IdentityKey, IdentityVal>, 157 + /// multi-producer *single consumer* queue 158 + refresh_queue: Arc<Mutex<RefreshQueue>>, 159 + /// just a lock to ensure only one refresher (queue consumer) is running (to be improved with a better refresher) 160 + refresher: Arc<Mutex<()>>, 161 + } 162 + 163 + impl Identity { 164 + pub async fn new(cache_dir: impl AsRef<Path>) -> Result<Self, IdentityError> { 165 + let http_client = Arc::new(DefaultHttpClient::default()); 166 + let handle_resolver = AtprotoHandleResolver::new(AtprotoHandleResolverConfig { 167 + dns_txt_resolver: HickoryDnsTxtResolver::new().unwrap(), 168 + http_client: http_client.clone(), 169 + }); 170 + let did_resolver = CommonDidResolver::new(CommonDidResolverConfig { 171 + plc_directory_url: DEFAULT_PLC_DIRECTORY_URL.to_string(), 172 + http_client: http_client.clone(), 173 + }); 174 + 175 + let cache = HybridCacheBuilder::new() 176 + .with_name("identity") 177 + .memory(16 * 2_usize.pow(20)) 178 + .with_weighter(|k, v| std::mem::size_of_val(k) + std::mem::size_of_val(v)) 179 + .storage(Engine::small()) 180 + .with_device_options( 181 + DirectFsDeviceOptions::new(cache_dir) 182 + .with_capacity(2_usize.pow(30)) // TODO: configurable (1GB to have something) 183 + .with_file_size(2_usize.pow(20)), // note: this does limit the max cached item size, warning jumbo records 184 + ) 185 + .build() 186 + .await?; 187 + 188 + Ok(Self { 189 + handle_resolver: Arc::new(handle_resolver), 190 + did_resolver: Arc::new(did_resolver), 191 + cache, 192 + refresh_queue: Default::default(), 193 + refresher: Default::default(), 194 + }) 195 + } 196 + 197 + /// Resolve (and verify!) an atproto handle to a DID 198 + /// 199 + /// The result can be stale 200 + /// 201 + /// `None` if the handle can't be found or verification fails 202 + pub async fn handle_to_did(&self, handle: Handle) -> Result<Option<Did>, IdentityError> { 203 + let Some(did) = self.handle_to_unverified_did(&handle).await? else { 204 + return Ok(None); 205 + }; 206 + let Some(doc) = self.did_to_partial_mini_doc(&did).await? else { 207 + return Ok(None); 208 + }; 209 + if doc.unverified_handle != handle { 210 + return Ok(None); 211 + } 212 + Ok(Some(did)) 213 + } 214 + 215 + /// Resolve a DID to a pds url 216 + /// 217 + /// This *also* incidentally resolves and verifies the handle, which might 218 + /// make it slower than expected 219 + pub async fn did_to_pds(&self, did: Did) -> Result<Option<String>, IdentityError> { 220 + let Some(mini_doc) = self.did_to_partial_mini_doc(&did).await? else { 221 + return Ok(None); 222 + }; 223 + Ok(Some(mini_doc.pds)) 224 + } 225 + 226 + /// Resolve (and cache but **not verify**) a handle to a DID 227 + async fn handle_to_unverified_did( 228 + &self, 229 + handle: &Handle, 230 + ) -> Result<Option<Did>, IdentityError> { 231 + let key = IdentityKey::Handle(handle.clone()); 232 + let entry = self 233 + .cache 234 + .fetch(key.clone(), { 235 + let handle = handle.clone(); 236 + let resolver = self.handle_resolver.clone(); 237 + || async move { 238 + match resolver.resolve(&handle).await { 239 + Ok(did) => Ok(IdentityVal(UtcDateTime::now(), IdentityData::Did(did))), 240 + Err(atrium_identity::Error::NotFound) => { 241 + Ok(IdentityVal(UtcDateTime::now(), IdentityData::NotFound)) 242 + } 243 + Err(other) => Err(foyer::Error::Other(Box::new({ 244 + log::debug!("other error resolving handle: {other:?}"); 245 + IdentityError::ResolutionFailed(other) 246 + }))), 247 + } 248 + } 249 + }) 250 + .await?; 251 + 252 + let now = UtcDateTime::now(); 253 + let IdentityVal(last_fetch, data) = entry.value(); 254 + match data { 255 + IdentityData::Doc(_) => { 256 + log::error!("identity value mixup: got a doc from a handle key (should be a did)"); 257 + Err(IdentityError::IdentityValTypeMixup(handle.to_string())) 258 + } 259 + IdentityData::NotFound => { 260 + if (now - *last_fetch) >= MIN_NOT_FOUND_TTL { 261 + self.queue_refresh(key).await; 262 + } 263 + Ok(None) 264 + } 265 + IdentityData::Did(did) => { 266 + if (now - *last_fetch) >= MIN_TTL { 267 + self.queue_refresh(key).await; 268 + } 269 + Ok(Some(did.clone())) 270 + } 271 + } 272 + } 273 + 274 + /// Fetch (and cache) a partial mini doc from a did 275 + pub async fn did_to_partial_mini_doc( 276 + &self, 277 + did: &Did, 278 + ) -> Result<Option<PartialMiniDoc>, IdentityError> { 279 + let key = IdentityKey::Did(did.clone()); 280 + let entry = self 281 + .cache 282 + .fetch(key.clone(), { 283 + let did = did.clone(); 284 + let resolver = self.did_resolver.clone(); 285 + || async move { 286 + match resolver.resolve(&did).await { 287 + Ok(did_doc) => { 288 + // TODO: fix in atrium: should verify id is did 289 + if did_doc.id != did.to_string() { 290 + return Err(foyer::Error::other(Box::new( 291 + IdentityError::BadDidDoc( 292 + "did doc's id did not match did".to_string(), 293 + ), 294 + ))); 295 + } 296 + let mini_doc = did_doc.try_into().map_err(|e| { 297 + foyer::Error::Other(Box::new(IdentityError::BadDidDoc(e))) 298 + })?; 299 + Ok(IdentityVal(UtcDateTime::now(), IdentityData::Doc(mini_doc))) 300 + } 301 + Err(atrium_identity::Error::NotFound) => { 302 + Ok(IdentityVal(UtcDateTime::now(), IdentityData::NotFound)) 303 + } 304 + Err(other) => Err(foyer::Error::Other(Box::new( 305 + IdentityError::ResolutionFailed(other), 306 + ))), 307 + } 308 + } 309 + }) 310 + .await?; 311 + 312 + let now = UtcDateTime::now(); 313 + let IdentityVal(last_fetch, data) = entry.value(); 314 + match data { 315 + IdentityData::Did(_) => { 316 + log::error!("identity value mixup: got a did from a did key (should be a doc)"); 317 + Err(IdentityError::IdentityValTypeMixup(did.to_string())) 318 + } 319 + IdentityData::NotFound => { 320 + if (now - *last_fetch) >= MIN_NOT_FOUND_TTL { 321 + self.queue_refresh(key).await; 322 + } 323 + Ok(None) 324 + } 325 + IdentityData::Doc(mini_did) => { 326 + if (now - *last_fetch) >= MIN_TTL { 327 + self.queue_refresh(key).await; 328 + } 329 + Ok(Some(mini_did.clone())) 330 + } 331 + } 332 + } 333 + 334 + /// put a refresh task on the queue 335 + /// 336 + /// this can be safely called from multiple concurrent tasks 337 + async fn queue_refresh(&self, key: IdentityKey) { 338 + // todo: max queue size 339 + let mut q = self.refresh_queue.lock().await; 340 + if !q.items.contains(&key) { 341 + q.items.insert(key.clone()); 342 + q.queue.push_back(key); 343 + } 344 + } 345 + 346 + /// find out what's next in the queue. concurrent consumers are not allowed. 347 + /// 348 + /// intent is to leave the item in the queue while refreshing, so that a 349 + /// producer will not re-add it if it's in progress. there's definitely 350 + /// better ways to do this, but this is ~simple for as far as a single 351 + /// consumer can take us. 352 + /// 353 + /// we could take it from the queue but leave it in the set and remove from 354 + /// set later, but splitting them apart feels more bug-prone. 355 + async fn peek_refresh(&self) -> Option<IdentityKey> { 356 + let q = self.refresh_queue.lock().await; 357 + q.queue.front().cloned() 358 + } 359 + 360 + /// call to clear the latest key from the refresh queue. concurrent consumers not allowed. 361 + /// 362 + /// must provide the last peeked refresh queue item as a small safety check 363 + async fn complete_refresh(&self, key: &IdentityKey) -> Result<(), IdentityError> { 364 + let mut q = self.refresh_queue.lock().await; 365 + 366 + let Some(queue_key) = q.queue.pop_front() else { 367 + // gone from queue + since we're in an error condition, make sure it's not stuck in items 368 + // (not toctou because we have the lock) 369 + // bolder here than below and removing from items because if the queue is *empty*, then we 370 + // know it hasn't been re-added since losing sync. 371 + if q.items.remove(key) { 372 + log::error!("identity refresh: queue de-sync: not in "); 373 + } else { 374 + log::warn!( 375 + "identity refresh: tried to complete with wrong key. are multiple queue consumers running?" 376 + ); 377 + } 378 + return Err(IdentityError::RefreshQueueKeyError("no key in queue")); 379 + }; 380 + 381 + if queue_key != *key { 382 + // extra weird case here, what's the most defensive behaviour? 383 + // we have two keys: ours should have been first but isn't. this shouldn't happen, so let's 384 + // just leave items alone for it. risks unbounded growth but we're in a bad place already. 385 + // the other key is the one we just popped. we didn't want it, so maybe we should put it 386 + // back, BUT if we somehow ended up with concurrent consumers, we have bigger problems. take 387 + // responsibility for taking it instead: remove it from items as well, and just drop it. 388 + // 389 + // hope that whoever calls us takes this error seriously. 390 + if q.items.remove(&queue_key) { 391 + log::warn!( 392 + "identity refresh: queue de-sync + dropping a bystander key without refreshing it!" 393 + ); 394 + } else { 395 + // you thought things couldn't get weirder? (i mean hopefully they can't) 396 + log::error!("identity refresh: queue de-sync + bystander key also de-sync!?"); 397 + } 398 + return Err(IdentityError::RefreshQueueKeyError( 399 + "wrong key at front of queue", 400 + )); 401 + } 402 + 403 + if q.items.remove(key) { 404 + Ok(()) 405 + } else { 406 + log::error!("identity refresh: queue de-sync: key not in items"); 407 + Err(IdentityError::RefreshQueueKeyError("key not in items")) 408 + } 409 + } 410 + 411 + /// run the refresh queue consumer 412 + pub async fn run_refresher(&self, shutdown: CancellationToken) -> Result<(), IdentityError> { 413 + let _guard = self 414 + .refresher 415 + .try_lock() 416 + .expect("there to only be one refresher running"); 417 + loop { 418 + if shutdown.is_cancelled() { 419 + log::info!("identity refresher: exiting for shutdown: closing cache..."); 420 + if let Err(e) = self.cache.close().await { 421 + log::error!("cache close errored: {e}"); 422 + } else { 423 + log::info!("identity cache closed.") 424 + } 425 + return Ok(()); 426 + } 427 + let Some(task_key) = self.peek_refresh().await else { 428 + tokio::time::sleep(tokio::time::Duration::from_millis(100)).await; 429 + continue; 430 + }; 431 + match task_key { 432 + IdentityKey::Handle(ref handle) => { 433 + log::trace!("refreshing handle {handle:?}"); 434 + match self.handle_resolver.resolve(handle).await { 435 + Ok(did) => { 436 + self.cache.insert( 437 + task_key.clone(), 438 + IdentityVal(UtcDateTime::now(), IdentityData::Did(did)), 439 + ); 440 + } 441 + Err(atrium_identity::Error::NotFound) => { 442 + self.cache.insert( 443 + task_key.clone(), 444 + IdentityVal(UtcDateTime::now(), IdentityData::NotFound), 445 + ); 446 + } 447 + Err(err) => { 448 + log::warn!( 449 + "failed to refresh handle: {err:?}. leaving stale (should we eventually do something?)" 450 + ); 451 + } 452 + } 453 + self.complete_refresh(&task_key).await?; // failures are bugs, so break loop 454 + } 455 + IdentityKey::Did(ref did) => { 456 + log::trace!("refreshing did doc: {did:?}"); 457 + 458 + match self.did_resolver.resolve(did).await { 459 + Ok(did_doc) => { 460 + // TODO: fix in atrium: should verify id is did 461 + if did_doc.id != did.to_string() { 462 + log::warn!( 463 + "refreshed did doc failed: wrong did doc id. dropping refresh." 464 + ); 465 + continue; 466 + } 467 + let mini_doc = match did_doc.try_into() { 468 + Ok(md) => md, 469 + Err(e) => { 470 + log::warn!( 471 + "converting mini doc failed: {e:?}. dropping refresh." 472 + ); 473 + continue; 474 + } 475 + }; 476 + self.cache.insert( 477 + task_key.clone(), 478 + IdentityVal(UtcDateTime::now(), IdentityData::Doc(mini_doc)), 479 + ); 480 + } 481 + Err(atrium_identity::Error::NotFound) => { 482 + self.cache.insert( 483 + task_key.clone(), 484 + IdentityVal(UtcDateTime::now(), IdentityData::NotFound), 485 + ); 486 + } 487 + Err(err) => { 488 + log::warn!( 489 + "failed to refresh did doc: {err:?}. leaving stale (should we eventually do something?)" 490 + ); 491 + } 492 + } 493 + 494 + self.complete_refresh(&task_key).await?; // failures are bugs, so break loop 495 + } 496 + } 497 + } 498 + } 499 + } 500 + 501 + pub struct HickoryDnsTxtResolver(TokioResolver); 502 + 503 + impl HickoryDnsTxtResolver { 504 + fn new() -> Result<Self, ResolveError> { 505 + Ok(Self(TokioResolver::builder_tokio()?.build())) 506 + } 507 + } 508 + 509 + impl DnsTxtResolver for HickoryDnsTxtResolver { 510 + async fn resolve( 511 + &self, 512 + query: &str, 513 + ) -> core::result::Result<Vec<String>, Box<dyn std::error::Error + Send + Sync>> { 514 + match self.0.txt_lookup(query).await { 515 + Ok(r) => { 516 + metrics::counter!("whoami_resolve_dns_txt", "success" => "true").increment(1); 517 + Ok(r.iter().map(|r| r.to_string()).collect()) 518 + } 519 + Err(e) => { 520 + metrics::counter!("whoami_resolve_dns_txt", "success" => "false").increment(1); 521 + Err(e.into()) 522 + } 523 + } 524 + } 525 + }
+14
slingshot/src/lib.rs
··· 1 + mod consumer; 2 + pub mod error; 3 + mod firehose_cache; 4 + mod healthcheck; 5 + mod identity; 6 + mod record; 7 + mod server; 8 + 9 + pub use consumer::consume; 10 + pub use firehose_cache::firehose_cache; 11 + pub use healthcheck::healthcheck; 12 + pub use identity::Identity; 13 + pub use record::{CachedRecord, ErrorResponseObject, Repo}; 14 + pub use server::serve;
+194
slingshot/src/main.rs
··· 1 + // use foyer::HybridCache; 2 + // use foyer::{Engine, DirectFsDeviceOptions, HybridCacheBuilder}; 3 + use metrics_exporter_prometheus::PrometheusBuilder; 4 + use slingshot::{ 5 + Identity, Repo, consume, error::MainTaskError, firehose_cache, healthcheck, serve, 6 + }; 7 + use std::path::PathBuf; 8 + 9 + use clap::Parser; 10 + use tokio_util::sync::CancellationToken; 11 + 12 + /// Slingshot record edge cache 13 + #[derive(Parser, Debug, Clone)] 14 + #[command(version, about, long_about = None)] 15 + struct Args { 16 + /// Jetstream server to connect to (exclusive with --fixture). Provide either a wss:// URL, or a shorhand value: 17 + /// 'us-east-1', 'us-east-2', 'us-west-1', or 'us-west-2' 18 + #[arg(long)] 19 + jetstream: String, 20 + /// don't request zstd-compressed jetstream events 21 + /// 22 + /// reduces CPU at the expense of more ingress bandwidth 23 + #[arg(long, action)] 24 + jetstream_no_zstd: bool, 25 + /// where to keep disk caches 26 + #[arg(long)] 27 + cache_dir: PathBuf, 28 + /// the domain pointing to this server 29 + /// 30 + /// if present: 31 + /// - a did:web document will be served at /.well-known/did.json 32 + /// - an HTTPS certs will be automatically configured with Acme/letsencrypt 33 + /// - TODO: a rate-limiter will be installed 34 + #[arg(long)] 35 + domain: Option<String>, 36 + /// email address for letsencrypt contact 37 + /// 38 + /// recommended in production, i guess? 39 + #[arg(long)] 40 + acme_contact: Option<String>, 41 + /// a location to cache acme https certs 42 + /// 43 + /// only used if --host is specified. omitting requires re-requesting certs 44 + /// on every restart, and letsencrypt has rate limits that are easy to hit. 45 + /// 46 + /// recommended in production, but mind the file permissions. 47 + #[arg(long)] 48 + certs: Option<PathBuf>, 49 + /// an web address to send healtcheck pings to every ~51s or so 50 + #[arg(long)] 51 + healthcheck: Option<String>, 52 + } 53 + 54 + #[tokio::main] 55 + async fn main() -> Result<(), String> { 56 + tracing_subscriber::fmt::init(); 57 + 58 + let shutdown = CancellationToken::new(); 59 + 60 + let ctrlc_shutdown = shutdown.clone(); 61 + ctrlc::set_handler(move || ctrlc_shutdown.cancel()).expect("failed to set ctrl-c handler"); 62 + 63 + let args = Args::parse(); 64 + 65 + if let Err(e) = install_metrics_server() { 66 + log::error!("failed to install metrics server: {e:?}"); 67 + } else { 68 + log::info!("metrics listening at http://0.0.0.0:8765"); 69 + } 70 + 71 + std::fs::create_dir_all(&args.cache_dir).map_err(|e| { 72 + format!( 73 + "failed to ensure cache parent dir: {e:?} (dir: {:?})", 74 + args.cache_dir 75 + ) 76 + })?; 77 + let cache_dir = args.cache_dir.canonicalize().map_err(|e| { 78 + format!( 79 + "failed to canonicalize cache_dir: {e:?} (dir: {:?})", 80 + args.cache_dir 81 + ) 82 + })?; 83 + log::info!("cache dir ready at at {cache_dir:?}."); 84 + 85 + log::info!("setting up firehose cache..."); 86 + let cache = firehose_cache(cache_dir.join("./firehose")).await?; 87 + log::info!("firehose cache ready."); 88 + 89 + let mut tasks: tokio::task::JoinSet<Result<(), MainTaskError>> = tokio::task::JoinSet::new(); 90 + 91 + log::info!("starting identity service..."); 92 + let identity = Identity::new(cache_dir.join("./identity")) 93 + .await 94 + .map_err(|e| format!("identity setup failed: {e:?}"))?; 95 + log::info!("identity service ready."); 96 + let identity_refresher = identity.clone(); 97 + let identity_shutdown = shutdown.clone(); 98 + tasks.spawn(async move { 99 + identity_refresher.run_refresher(identity_shutdown).await?; 100 + Ok(()) 101 + }); 102 + 103 + let repo = Repo::new(identity.clone()); 104 + 105 + let server_shutdown = shutdown.clone(); 106 + let server_cache_handle = cache.clone(); 107 + tasks.spawn(async move { 108 + serve( 109 + server_cache_handle, 110 + identity, 111 + repo, 112 + args.domain, 113 + args.acme_contact, 114 + args.certs, 115 + server_shutdown, 116 + ) 117 + .await?; 118 + Ok(()) 119 + }); 120 + 121 + let consumer_shutdown = shutdown.clone(); 122 + let consumer_cache = cache.clone(); 123 + tasks.spawn(async move { 124 + consume( 125 + args.jetstream, 126 + None, 127 + args.jetstream_no_zstd, 128 + consumer_shutdown, 129 + consumer_cache, 130 + ) 131 + .await?; 132 + Ok(()) 133 + }); 134 + 135 + if let Some(hc) = args.healthcheck { 136 + let healthcheck_shutdown = shutdown.clone(); 137 + tasks.spawn(async move { 138 + healthcheck(hc, healthcheck_shutdown).await?; 139 + Ok(()) 140 + }); 141 + } 142 + 143 + tokio::select! { 144 + _ = shutdown.cancelled() => log::warn!("shutdown requested"), 145 + Some(r) = tasks.join_next() => { 146 + log::warn!("a task exited, shutting down: {r:?}"); 147 + shutdown.cancel(); 148 + } 149 + } 150 + 151 + tasks.spawn(async move { 152 + cache 153 + .close() 154 + .await 155 + .map_err(MainTaskError::FirehoseCacheCloseError) 156 + }); 157 + 158 + tokio::select! { 159 + _ = async { 160 + while let Some(completed) = tasks.join_next().await { 161 + log::info!("shutdown: task completed: {completed:?}"); 162 + } 163 + } => {}, 164 + _ = tokio::time::sleep(std::time::Duration::from_secs(30)) => { 165 + log::info!("shutdown: not all tasks completed on time. aborting..."); 166 + tasks.shutdown().await; 167 + }, 168 + } 169 + 170 + log::info!("bye!"); 171 + 172 + Ok(()) 173 + } 174 + 175 + fn install_metrics_server() -> Result<(), metrics_exporter_prometheus::BuildError> { 176 + log::info!("installing metrics server..."); 177 + let host = [0, 0, 0, 0]; 178 + let port = 8765; 179 + PrometheusBuilder::new() 180 + .set_quantiles(&[0.5, 0.9, 0.99, 1.0])? 181 + .set_bucket_duration(std::time::Duration::from_secs(300))? 182 + .set_bucket_count(std::num::NonZero::new(12).unwrap()) // count * duration = 60 mins. stuff doesn't happen that fast here. 183 + .set_enable_unit_suffix(false) // this seemed buggy for constellation (sometimes wouldn't engage) 184 + .with_http_listener((host, port)) 185 + .install()?; 186 + log::info!( 187 + "metrics server installed! listening on http://{}.{}.{}.{}:{port}", 188 + host[0], 189 + host[1], 190 + host[2], 191 + host[3] 192 + ); 193 + Ok(()) 194 + }
+155
slingshot/src/record.rs
··· 1 + //! cached record storage 2 + 3 + use crate::{Identity, error::RecordError}; 4 + use atrium_api::types::string::{Cid, Did, Nsid, RecordKey}; 5 + use reqwest::{Client, StatusCode}; 6 + use serde::{Deserialize, Serialize}; 7 + use serde_json::value::RawValue; 8 + use std::str::FromStr; 9 + use std::time::Duration; 10 + use url::Url; 11 + 12 + #[derive(Debug, Serialize, Deserialize)] 13 + pub struct RawRecord { 14 + cid: Cid, 15 + record: String, 16 + } 17 + 18 + // TODO: should be able to do typed CID 19 + impl From<(Cid, Box<RawValue>)> for RawRecord { 20 + fn from((cid, rv): (Cid, Box<RawValue>)) -> Self { 21 + Self { 22 + cid, 23 + record: rv.get().to_string(), 24 + } 25 + } 26 + } 27 + 28 + /// only for use with stored (validated) values, not general strings 29 + impl From<&RawRecord> for (Cid, Box<RawValue>) { 30 + fn from(RawRecord { cid, record }: &RawRecord) -> Self { 31 + ( 32 + cid.clone(), 33 + RawValue::from_string(record.to_string()) 34 + .expect("stored string from RawValue to be valid"), 35 + ) 36 + } 37 + } 38 + 39 + #[derive(Debug, Serialize, Deserialize)] 40 + pub enum CachedRecord { 41 + Found(RawRecord), 42 + Deleted, 43 + } 44 + 45 + //////// upstream record fetching 46 + 47 + #[derive(Deserialize)] 48 + struct RecordResponseObject { 49 + #[allow(dead_code)] // expect it to be there but we ignore it 50 + uri: String, 51 + /// CID for this exact version of the record 52 + /// 53 + /// this is optional in the spec and that's potentially TODO for slingshot 54 + cid: Option<String>, 55 + /// the record itself as JSON 56 + value: Box<RawValue>, 57 + } 58 + 59 + #[derive(Debug, Deserialize)] 60 + pub struct ErrorResponseObject { 61 + pub error: String, 62 + pub message: String, 63 + } 64 + 65 + #[derive(Clone)] 66 + pub struct Repo { 67 + identity: Identity, 68 + client: Client, 69 + } 70 + 71 + impl Repo { 72 + pub fn new(identity: Identity) -> Self { 73 + let client = Client::builder() 74 + .user_agent(format!( 75 + "microcosm slingshot v{} (dev: @bad-example.com)", 76 + env!("CARGO_PKG_VERSION") 77 + )) 78 + .no_proxy() 79 + .timeout(Duration::from_secs(10)) 80 + .build() 81 + .unwrap(); 82 + Repo { identity, client } 83 + } 84 + 85 + pub async fn get_record( 86 + &self, 87 + did: &Did, 88 + collection: &Nsid, 89 + rkey: &RecordKey, 90 + cid: &Option<Cid>, 91 + ) -> Result<CachedRecord, RecordError> { 92 + let Some(pds) = self.identity.did_to_pds(did.clone()).await? else { 93 + return Err(RecordError::NotFound("could not get pds for DID")); 94 + }; 95 + 96 + // cid gets set to None for a retry, if it's Some and we got NotFound 97 + let mut cid = cid; 98 + 99 + let res = loop { 100 + // TODO: throttle outgoing requests by host probably, generally guard against outgoing requests 101 + let mut params = vec![ 102 + ("repo", did.to_string()), 103 + ("collection", collection.to_string()), 104 + ("rkey", rkey.to_string()), 105 + ]; 106 + if let Some(cid) = cid { 107 + params.push(("cid", cid.as_ref().to_string())); 108 + } 109 + let mut url = Url::parse_with_params(&pds, &params)?; 110 + url.set_path("/xrpc/com.atproto.repo.getRecord"); 111 + 112 + let res = self 113 + .client 114 + .get(url.clone()) 115 + .send() 116 + .await 117 + .map_err(RecordError::SendError)?; 118 + 119 + if res.status() == StatusCode::BAD_REQUEST { 120 + // 1. if we're not able to parse json, it's not something we can handle 121 + let err = res 122 + .json::<ErrorResponseObject>() 123 + .await 124 + .map_err(RecordError::UpstreamBadBadNotGoodRequest)?; 125 + // 2. if we are, is it a NotFound? and if so, did we try with a CID? 126 + // if so, retry with no CID (api handler will reject for mismatch but 127 + // with a nice error + warm cache) 128 + if err.error == "NotFound" && cid.is_some() { 129 + cid = &None; 130 + continue; 131 + } else { 132 + return Err(RecordError::UpstreamBadRequest(err)); 133 + } 134 + } 135 + break res; 136 + }; 137 + 138 + let data = res 139 + .error_for_status() 140 + .map_err(RecordError::StatusError)? // TODO atproto error handling (think about handling not found) 141 + .json::<RecordResponseObject>() 142 + .await 143 + .map_err(RecordError::ParseJsonError)?; // todo... 144 + 145 + let Some(cid) = data.cid else { 146 + return Err(RecordError::MissingUpstreamCid); 147 + }; 148 + let cid = Cid::from_str(&cid).map_err(|e| RecordError::BadUpstreamCid(e.to_string()))?; 149 + 150 + Ok(CachedRecord::Found(RawRecord { 151 + cid, 152 + record: data.value.to_string(), 153 + })) 154 + } 155 + }
+778
slingshot/src/server.rs
··· 1 + use crate::{ 2 + CachedRecord, ErrorResponseObject, Identity, Repo, 3 + error::{RecordError, ServerError}, 4 + }; 5 + use atrium_api::types::string::{Cid, Did, Handle, Nsid, RecordKey}; 6 + use foyer::HybridCache; 7 + use links::at_uri::parse_at_uri as normalize_at_uri; 8 + use serde::Serialize; 9 + use std::path::PathBuf; 10 + use std::str::FromStr; 11 + use std::sync::Arc; 12 + use tokio_util::sync::CancellationToken; 13 + 14 + use poem::{ 15 + Endpoint, EndpointExt, Route, Server, 16 + endpoint::{StaticFileEndpoint, make_sync}, 17 + http::Method, 18 + listener::{ 19 + Listener, TcpListener, 20 + acme::{AutoCert, LETS_ENCRYPT_PRODUCTION}, 21 + }, 22 + middleware::{CatchPanic, Cors, Tracing}, 23 + }; 24 + use poem_openapi::{ 25 + ApiResponse, ContactObject, ExternalDocumentObject, Object, OpenApi, OpenApiService, Tags, 26 + param::Query, payload::Json, types::Example, 27 + }; 28 + 29 + fn example_handle() -> String { 30 + "bad-example.com".to_string() 31 + } 32 + fn example_did() -> String { 33 + "did:plc:hdhoaan3xa3jiuq4fg4mefid".to_string() 34 + } 35 + fn example_collection() -> String { 36 + "app.bsky.feed.like".to_string() 37 + } 38 + fn example_rkey() -> String { 39 + "3lv4ouczo2b2a".to_string() 40 + } 41 + fn example_uri() -> String { 42 + format!( 43 + "at://{}/{}/{}", 44 + example_did(), 45 + example_collection(), 46 + example_rkey() 47 + ) 48 + } 49 + fn example_pds() -> String { 50 + "https://porcini.us-east.host.bsky.network".to_string() 51 + } 52 + fn example_signing_key() -> String { 53 + "zQ3shpq1g134o7HGDb86CtQFxnHqzx5pZWknrVX2Waum3fF6j".to_string() 54 + } 55 + 56 + #[derive(Object)] 57 + #[oai(example = true)] 58 + struct XrpcErrorResponseObject { 59 + /// Should correspond an error `name` in the lexicon errors array 60 + error: String, 61 + /// Human-readable description and possibly additonal context 62 + message: String, 63 + } 64 + impl Example for XrpcErrorResponseObject { 65 + fn example() -> Self { 66 + Self { 67 + error: "RecordNotFound".to_string(), 68 + message: "This record was deleted".to_string(), 69 + } 70 + } 71 + } 72 + type XrpcError = Json<XrpcErrorResponseObject>; 73 + fn xrpc_error(error: impl AsRef<str>, message: impl AsRef<str>) -> XrpcError { 74 + Json(XrpcErrorResponseObject { 75 + error: error.as_ref().to_string(), 76 + message: message.as_ref().to_string(), 77 + }) 78 + } 79 + 80 + fn bad_request_handler_get_record(err: poem::Error) -> GetRecordResponse { 81 + GetRecordResponse::BadRequest(Json(XrpcErrorResponseObject { 82 + error: "InvalidRequest".to_string(), 83 + message: format!("Bad request, here's some info that maybe should not be exposed: {err}"), 84 + })) 85 + } 86 + 87 + fn bad_request_handler_resolve_mini(err: poem::Error) -> ResolveMiniIDResponse { 88 + ResolveMiniIDResponse::BadRequest(Json(XrpcErrorResponseObject { 89 + error: "InvalidRequest".to_string(), 90 + message: format!("Bad request, here's some info that maybe should not be exposed: {err}"), 91 + })) 92 + } 93 + 94 + fn bad_request_handler_resolve_handle(err: poem::Error) -> JustDidResponse { 95 + JustDidResponse::BadRequest(Json(XrpcErrorResponseObject { 96 + error: "InvalidRequest".to_string(), 97 + message: format!("Bad request, here's some info that maybe should not be exposed: {err}"), 98 + })) 99 + } 100 + 101 + #[derive(Object)] 102 + #[oai(example = true)] 103 + struct FoundRecordResponseObject { 104 + /// at-uri for this record 105 + uri: String, 106 + /// CID for this exact version of the record 107 + /// 108 + /// Slingshot will always return the CID, despite it not being a required 109 + /// response property in the official lexicon. 110 + /// 111 + /// TODO: probably actually let it be optional, idk are some pds's weirdly 112 + /// not returning it? 113 + cid: Option<String>, 114 + /// the record itself as JSON 115 + value: serde_json::Value, 116 + } 117 + impl Example for FoundRecordResponseObject { 118 + fn example() -> Self { 119 + Self { 120 + uri: example_uri(), 121 + cid: Some("bafyreialv3mzvvxaoyrfrwoer3xmabbmdchvrbyhayd7bga47qjbycy74e".to_string()), 122 + value: serde_json::json!({ 123 + "$type": "app.bsky.feed.like", 124 + "createdAt": "2025-07-29T18:02:02.327Z", 125 + "subject": { 126 + "cid": "bafyreia2gy6eyk5qfetgahvshpq35vtbwy6negpy3gnuulcdi723mi7vxy", 127 + "uri": "at://did:plc:vwzwgnygau7ed7b7wt5ux7y2/app.bsky.feed.post/3lv4lkb4vgs2k" 128 + } 129 + }), 130 + } 131 + } 132 + } 133 + 134 + #[derive(ApiResponse)] 135 + #[oai(bad_request_handler = "bad_request_handler_get_record")] 136 + enum GetRecordResponse { 137 + /// Record found 138 + #[oai(status = 200)] 139 + Ok(Json<FoundRecordResponseObject>), 140 + /// Bad request or no record to return 141 + /// 142 + /// The only error name in the repo.getRecord lexicon is `RecordNotFound`, 143 + /// but the [canonical api docs](https://docs.bsky.app/docs/api/com-atproto-repo-get-record) 144 + /// also list `InvalidRequest`, `ExpiredToken`, and `InvalidToken`. Of 145 + /// these, slingshot will only generate `RecordNotFound` or `InvalidRequest`, 146 + /// but may return any proxied error code from the upstream repo. 147 + #[oai(status = 400)] 148 + BadRequest(XrpcError), 149 + /// Server errors 150 + #[oai(status = 500)] 151 + ServerError(XrpcError), 152 + } 153 + 154 + #[derive(Object)] 155 + #[oai(example = true)] 156 + struct MiniDocResponseObject { 157 + /// DID, bi-directionally verified if a handle was provided in the query. 158 + did: String, 159 + /// The validated handle of the account or `handle.invalid` if the handle 160 + /// did not bi-directionally match the DID document. 161 + handle: String, 162 + /// The identity's PDS URL 163 + pds: String, 164 + /// The atproto signing key publicKeyMultibase 165 + /// 166 + /// Legacy key encoding not supported. the key is returned directly; `id`, 167 + /// `type`, and `controller` are omitted. 168 + signing_key: String, 169 + } 170 + impl Example for MiniDocResponseObject { 171 + fn example() -> Self { 172 + Self { 173 + did: example_did(), 174 + handle: example_handle(), 175 + pds: example_pds(), 176 + signing_key: example_signing_key(), 177 + } 178 + } 179 + } 180 + 181 + #[derive(ApiResponse)] 182 + #[oai(bad_request_handler = "bad_request_handler_resolve_mini")] 183 + enum ResolveMiniIDResponse { 184 + /// Identity resolved 185 + #[oai(status = 200)] 186 + Ok(Json<MiniDocResponseObject>), 187 + /// Bad request or identity not resolved 188 + #[oai(status = 400)] 189 + BadRequest(XrpcError), 190 + } 191 + 192 + #[derive(Object)] 193 + #[oai(example = true)] 194 + struct FoundDidResponseObject { 195 + /// the DID, bi-directionally verified if using Slingshot 196 + did: String, 197 + } 198 + impl Example for FoundDidResponseObject { 199 + fn example() -> Self { 200 + Self { did: example_did() } 201 + } 202 + } 203 + 204 + #[derive(ApiResponse)] 205 + #[oai(bad_request_handler = "bad_request_handler_resolve_handle")] 206 + enum JustDidResponse { 207 + /// Resolution succeeded 208 + #[oai(status = 200)] 209 + Ok(Json<FoundDidResponseObject>), 210 + /// Bad request, failed to resolve, or failed to verify 211 + /// 212 + /// `error` will be one of `InvalidRequest`, `HandleNotFound`. 213 + #[oai(status = 400)] 214 + BadRequest(XrpcError), 215 + /// Something went wrong trying to complete the request 216 + #[oai(status = 500)] 217 + ServerError(XrpcError), 218 + } 219 + 220 + struct Xrpc { 221 + cache: HybridCache<String, CachedRecord>, 222 + identity: Identity, 223 + repo: Arc<Repo>, 224 + } 225 + 226 + #[derive(Tags)] 227 + enum ApiTags { 228 + /// Core ATProtocol-compatible APIs. 229 + /// 230 + /// > [!tip] 231 + /// > Upstream documentation is available at 232 + /// > https://docs.bsky.app/docs/category/http-reference 233 + /// 234 + /// These queries are usually executed directly against the PDS containing 235 + /// the data being requested. Slingshot offers a caching view of the same 236 + /// contents with better expected performance and reliability. 237 + #[oai(rename = "com.atproto.* queries")] 238 + ComAtproto, 239 + /// Additional and improved APIs. 240 + /// 241 + /// These APIs offer small tweaks to the core ATProtocol APIs, with more 242 + /// more convenient [request parameters](#tag/slingshot-specific-queries/GET/xrpc/com.bad-example.repo.getUriRecord) 243 + /// or [response formats](#tag/slingshot-specific-queries/GET/xrpc/com.bad-example.identity.resolveMiniDoc). 244 + /// 245 + /// > [!important] 246 + /// > At the moment, these are namespaced under the `com.bad-example.*` NSID 247 + /// > prefix, but as they stabilize they may be migrated to an org namespace 248 + /// > like `blue.microcosm.*`. Support for asliasing to `com.bad-example.*` 249 + /// > will be maintained as long as it's in use. 250 + #[oai(rename = "slingshot-specific queries")] 251 + Custom, 252 + } 253 + 254 + #[OpenApi] 255 + impl Xrpc { 256 + /// com.atproto.repo.getRecord 257 + /// 258 + /// Get a single record from a repository. Does not require auth. 259 + /// 260 + /// > [!tip] 261 + /// > See also the [canonical `com.atproto` XRPC documentation](https://docs.bsky.app/docs/api/com-atproto-repo-get-record) 262 + /// > that this endpoint aims to be compatible with. 263 + #[oai( 264 + path = "/com.atproto.repo.getRecord", 265 + method = "get", 266 + tag = "ApiTags::ComAtproto" 267 + )] 268 + async fn get_record( 269 + &self, 270 + /// The DID or handle of the repo 271 + #[oai(example = "example_did")] 272 + Query(repo): Query<String>, 273 + /// The NSID of the record collection 274 + #[oai(example = "example_collection")] 275 + Query(collection): Query<String>, 276 + /// The Record key 277 + #[oai(example = "example_rkey")] 278 + Query(rkey): Query<String>, 279 + /// Optional: the CID of the version of the record. 280 + /// 281 + /// If not specified, then return the most recent version. 282 + /// 283 + /// If a stale `CID` is specified and a newer version of the record 284 + /// exists, Slingshot returns a `NotFound` error. That is: Slingshot 285 + /// only retains the most recent version of a record. 286 + Query(cid): Query<Option<String>>, 287 + ) -> GetRecordResponse { 288 + self.get_record_impl(repo, collection, rkey, cid).await 289 + } 290 + 291 + /// com.bad-example.repo.getUriRecord 292 + /// 293 + /// Ergonomic complement to [`com.atproto.repo.getRecord`](https://docs.bsky.app/docs/api/com-atproto-repo-get-record) 294 + /// which accepts an `at-uri` instead of individual repo/collection/rkey params 295 + #[oai( 296 + path = "/com.bad-example.repo.getUriRecord", 297 + method = "get", 298 + tag = "ApiTags::Custom" 299 + )] 300 + async fn get_uri_record( 301 + &self, 302 + /// The at-uri of the record 303 + /// 304 + /// The identifier can be a DID or an atproto handle, and the collection 305 + /// and rkey segments must be present. 306 + #[oai(example = "example_uri")] 307 + Query(at_uri): Query<String>, 308 + /// Optional: the CID of the version of the record. 309 + /// 310 + /// If not specified, then return the most recent version. 311 + /// 312 + /// > [!tip] 313 + /// > If specified and a newer version of the record exists, returns 404 not 314 + /// > found. That is: slingshot only retains the most recent version of a 315 + /// > record. 316 + Query(cid): Query<Option<String>>, 317 + ) -> GetRecordResponse { 318 + let bad_at_uri = || { 319 + GetRecordResponse::BadRequest(xrpc_error( 320 + "InvalidRequest", 321 + "at-uri does not appear to be valid", 322 + )) 323 + }; 324 + 325 + let Some(normalized) = normalize_at_uri(&at_uri) else { 326 + return bad_at_uri(); 327 + }; 328 + 329 + // TODO: move this to links 330 + let Some(rest) = normalized.strip_prefix("at://") else { 331 + return bad_at_uri(); 332 + }; 333 + let Some((repo, rest)) = rest.split_once('/') else { 334 + return bad_at_uri(); 335 + }; 336 + let Some((collection, rest)) = rest.split_once('/') else { 337 + return bad_at_uri(); 338 + }; 339 + let rkey = if let Some((rkey, _rest)) = rest.split_once('?') { 340 + rkey 341 + } else { 342 + rest 343 + }; 344 + 345 + self.get_record_impl( 346 + repo.to_string(), 347 + collection.to_string(), 348 + rkey.to_string(), 349 + cid, 350 + ) 351 + .await 352 + } 353 + 354 + /// com.atproto.identity.resolveHandle 355 + /// 356 + /// Resolves an atproto [`handle`](https://atproto.com/guides/glossary#handle) 357 + /// (hostname) to a [`DID`](https://atproto.com/guides/glossary#did-decentralized-id). 358 + /// 359 + /// > [!tip] 360 + /// > Compatibility note: Slingshot will **always bi-directionally verify 361 + /// > against the DID document**, which is optional according to the 362 + /// > authoritative lexicon. 363 + /// 364 + /// > [!tip] 365 + /// > See the [canonical `com.atproto` XRPC documentation](https://docs.bsky.app/docs/api/com-atproto-identity-resolve-handle) 366 + /// > that this endpoint aims to be compatible with. 367 + #[oai( 368 + path = "/com.atproto.identity.resolveHandle", 369 + method = "get", 370 + tag = "ApiTags::ComAtproto" 371 + )] 372 + async fn resolve_handle( 373 + &self, 374 + /// The handle to resolve. 375 + #[oai(example = "example_handle")] 376 + Query(handle): Query<String>, 377 + ) -> JustDidResponse { 378 + let Ok(handle) = Handle::new(handle) else { 379 + return JustDidResponse::BadRequest(xrpc_error("InvalidRequest", "not a valid handle")); 380 + }; 381 + 382 + let Ok(alleged_did) = self.identity.handle_to_did(handle.clone()).await else { 383 + return JustDidResponse::ServerError(xrpc_error("Failed", "Could not resolve handle")); 384 + }; 385 + 386 + let Some(alleged_did) = alleged_did else { 387 + return JustDidResponse::BadRequest(xrpc_error( 388 + "HandleNotFound", 389 + "Could not resolve handle to a DID", 390 + )); 391 + }; 392 + 393 + let Ok(partial_doc) = self.identity.did_to_partial_mini_doc(&alleged_did).await else { 394 + return JustDidResponse::ServerError(xrpc_error("Failed", "Could not fetch DID doc")); 395 + }; 396 + 397 + let Some(partial_doc) = partial_doc else { 398 + return JustDidResponse::BadRequest(xrpc_error( 399 + "HandleNotFound", 400 + "Resolved handle but could not find DID doc for the DID", 401 + )); 402 + }; 403 + 404 + if partial_doc.unverified_handle != handle { 405 + return JustDidResponse::BadRequest(xrpc_error( 406 + "HandleNotFound", 407 + "Resolved handle failed bi-directional validation", 408 + )); 409 + } 410 + 411 + JustDidResponse::Ok(Json(FoundDidResponseObject { 412 + did: alleged_did.to_string(), 413 + })) 414 + } 415 + 416 + /// com.bad-example.identity.resolveMiniDoc 417 + /// 418 + /// Like [com.atproto.identity.resolveIdentity](https://docs.bsky.app/docs/api/com-atproto-identity-resolve-identity) 419 + /// but instead of the full `didDoc` it returns an atproto-relevant subset. 420 + #[oai( 421 + path = "/com.bad-example.identity.resolveMiniDoc", 422 + method = "get", 423 + tag = "ApiTags::Custom" 424 + )] 425 + async fn resolve_mini_id( 426 + &self, 427 + /// Handle or DID to resolve 428 + #[oai(example = "example_handle")] 429 + Query(identifier): Query<String>, 430 + ) -> ResolveMiniIDResponse { 431 + let invalid = |reason: &'static str| { 432 + ResolveMiniIDResponse::BadRequest(xrpc_error("InvalidRequest", reason)) 433 + }; 434 + 435 + let mut unverified_handle = None; 436 + let did = match Did::new(identifier.clone()) { 437 + Ok(did) => did, 438 + Err(_) => { 439 + let Ok(alleged_handle) = Handle::new(identifier) else { 440 + return invalid("identifier was not a valid DID or handle"); 441 + }; 442 + 443 + match self.identity.handle_to_did(alleged_handle.clone()).await { 444 + Ok(res) => { 445 + if let Some(did) = res { 446 + // we did it joe 447 + unverified_handle = Some(alleged_handle); 448 + did 449 + } else { 450 + return invalid("Could not resolve handle identifier to a DID"); 451 + } 452 + } 453 + Err(e) => { 454 + log::debug!("failed to resolve handle: {e}"); 455 + // TODO: ServerError not BadRequest 456 + return invalid("errored while trying to resolve handle to DID"); 457 + } 458 + } 459 + } 460 + }; 461 + let Ok(partial_doc) = self.identity.did_to_partial_mini_doc(&did).await else { 462 + return invalid("failed to get DID doc"); 463 + }; 464 + let Some(partial_doc) = partial_doc else { 465 + return invalid("failed to find DID doc"); 466 + }; 467 + 468 + // ok so here's where we're at: 469 + // ✅ we have a DID 470 + // ✅ we have a partial doc 471 + // 🔶 if we have a handle, it's from the `identifier` (user-input) 472 + // -> then we just need to compare to the partial doc to confirm 473 + // -> else we need to resolve the DID doc's to a handle and check 474 + let handle = if let Some(h) = unverified_handle { 475 + if h == partial_doc.unverified_handle { 476 + h.to_string() 477 + } else { 478 + "handle.invalid".to_string() 479 + } 480 + } else { 481 + let Ok(handle_did) = self 482 + .identity 483 + .handle_to_did(partial_doc.unverified_handle.clone()) 484 + .await 485 + else { 486 + return invalid("failed to get did doc's handle"); 487 + }; 488 + let Some(handle_did) = handle_did else { 489 + return invalid("failed to resolve did doc's handle"); 490 + }; 491 + if handle_did == did { 492 + partial_doc.unverified_handle.to_string() 493 + } else { 494 + "handle.invalid".to_string() 495 + } 496 + }; 497 + 498 + ResolveMiniIDResponse::Ok(Json(MiniDocResponseObject { 499 + did: did.to_string(), 500 + handle, 501 + pds: partial_doc.pds, 502 + signing_key: partial_doc.signing_key, 503 + })) 504 + } 505 + 506 + async fn get_record_impl( 507 + &self, 508 + repo: String, 509 + collection: String, 510 + rkey: String, 511 + cid: Option<String>, 512 + ) -> GetRecordResponse { 513 + let did = match Did::new(repo.clone()) { 514 + Ok(did) => did, 515 + Err(_) => { 516 + let Ok(handle) = Handle::new(repo) else { 517 + return GetRecordResponse::BadRequest(xrpc_error( 518 + "InvalidRequest", 519 + "repo was not a valid DID or handle", 520 + )); 521 + }; 522 + match self.identity.handle_to_did(handle).await { 523 + Ok(res) => { 524 + if let Some(did) = res { 525 + did 526 + } else { 527 + return GetRecordResponse::BadRequest(xrpc_error( 528 + "InvalidRequest", 529 + "Could not resolve handle repo to a DID", 530 + )); 531 + } 532 + } 533 + Err(e) => { 534 + log::debug!("handle resolution failed: {e}"); 535 + return GetRecordResponse::ServerError(xrpc_error( 536 + "ResolutionFailed", 537 + "errored while trying to resolve handle to DID", 538 + )); 539 + } 540 + } 541 + } 542 + }; 543 + 544 + let Ok(collection) = Nsid::new(collection) else { 545 + return GetRecordResponse::BadRequest(xrpc_error( 546 + "InvalidRequest", 547 + "invalid NSID for collection", 548 + )); 549 + }; 550 + 551 + let Ok(rkey) = RecordKey::new(rkey) else { 552 + return GetRecordResponse::BadRequest(xrpc_error("InvalidRequest", "invalid rkey")); 553 + }; 554 + 555 + let cid: Option<Cid> = if let Some(cid) = cid { 556 + let Ok(cid) = Cid::from_str(&cid) else { 557 + return GetRecordResponse::BadRequest(xrpc_error("InvalidRequest", "invalid CID")); 558 + }; 559 + Some(cid) 560 + } else { 561 + None 562 + }; 563 + 564 + let at_uri = format!("at://{}/{}/{}", &*did, &*collection, &*rkey); 565 + 566 + let fr = self 567 + .cache 568 + .fetch(at_uri.clone(), { 569 + let cid = cid.clone(); 570 + let repo_api = self.repo.clone(); 571 + || async move { 572 + repo_api 573 + .get_record(&did, &collection, &rkey, &cid) 574 + .await 575 + .map_err(|e| foyer::Error::Other(Box::new(e))) 576 + } 577 + }) 578 + .await; 579 + 580 + let entry = match fr { 581 + Ok(e) => e, 582 + Err(foyer::Error::Other(e)) => { 583 + let record_error = match e.downcast::<RecordError>() { 584 + Ok(e) => e, 585 + Err(e) => { 586 + log::error!("error (foyer other) getting cache entry, {e:?}"); 587 + return GetRecordResponse::ServerError(xrpc_error( 588 + "ServerError", 589 + "sorry, something went wrong", 590 + )); 591 + } 592 + }; 593 + let RecordError::UpstreamBadRequest(ErrorResponseObject { error, message }) = 594 + *record_error 595 + else { 596 + log::error!("RecordError getting cache entry, {record_error:?}"); 597 + return GetRecordResponse::ServerError(xrpc_error( 598 + "ServerError", 599 + "sorry, something went wrong", 600 + )); 601 + }; 602 + 603 + // all of the noise around here is so that we can ultimately reach this: 604 + // upstream BadRequest extracted from the foyer result which we can proxy back 605 + return GetRecordResponse::BadRequest(xrpc_error( 606 + error, 607 + format!("Upstream bad request: {message}"), 608 + )); 609 + } 610 + Err(e) => { 611 + log::error!("error (foyer) getting cache entry, {e:?}"); 612 + return GetRecordResponse::ServerError(xrpc_error( 613 + "ServerError", 614 + "sorry, something went wrong", 615 + )); 616 + } 617 + }; 618 + 619 + match *entry { 620 + CachedRecord::Found(ref raw) => { 621 + let (found_cid, raw_value) = raw.into(); 622 + if cid.clone().map(|c| c != found_cid).unwrap_or(false) { 623 + return GetRecordResponse::BadRequest(Json(XrpcErrorResponseObject { 624 + error: "RecordNotFound".to_string(), 625 + message: "A record was found but its CID did not match that requested" 626 + .to_string(), 627 + })); 628 + } 629 + // TODO: thank u stellz: https://gist.github.com/stella3d/51e679e55b264adff89d00a1e58d0272 630 + let value = 631 + serde_json::from_str(raw_value.get()).expect("RawValue to be valid json"); 632 + GetRecordResponse::Ok(Json(FoundRecordResponseObject { 633 + uri: at_uri, 634 + cid: Some(found_cid.as_ref().to_string()), 635 + value, 636 + })) 637 + } 638 + CachedRecord::Deleted => GetRecordResponse::BadRequest(Json(XrpcErrorResponseObject { 639 + error: "RecordNotFound".to_string(), 640 + message: "This record was deleted".to_string(), 641 + })), 642 + } 643 + } 644 + 645 + // TODO 646 + // #[oai(path = "/com.atproto.identity.resolveHandle", method = "get")] 647 + // #[oai(path = "/com.atproto.identity.resolveDid", method = "get")] 648 + // but these are both not specified to do bidirectional validation, which is what we want to offer 649 + // com.atproto.identity.resolveIdentity seems right, but requires returning the full did-doc 650 + // would be nice if there were two queries: 651 + // did -> verified handle + pds url 652 + // handle -> verified did + pds url 653 + // 654 + // we could do horrible things and implement resolveIdentity with only a stripped-down fake did doc 655 + // but this will *definitely* cause problems because eg. we're not currently storing pubkeys and 656 + // those are a little bit important 657 + } 658 + 659 + #[derive(Debug, Clone, Serialize)] 660 + #[serde(rename_all = "camelCase")] 661 + struct AppViewService { 662 + id: String, 663 + r#type: String, 664 + service_endpoint: String, 665 + } 666 + #[derive(Debug, Clone, Serialize)] 667 + struct AppViewDoc { 668 + id: String, 669 + service: [AppViewService; 1], 670 + } 671 + /// Serve a did document for did:web for this to be an xrpc appview 672 + /// 673 + /// No slingshot endpoints currently require auth, so it's not necessary to do 674 + /// service proxying, however clients may wish to: 675 + /// 676 + /// - PDS proxying offers a level of client IP anonymity from slingshot 677 + /// - slingshot *may* implement more generous per-user rate-limits for proxied requests in the future 678 + fn get_did_doc(domain: &str) -> impl Endpoint + use<> { 679 + let doc = poem::web::Json(AppViewDoc { 680 + id: format!("did:web:{domain}"), 681 + service: [AppViewService { 682 + id: "#slingshot".to_string(), 683 + r#type: "SlingshotRecordProxy".to_string(), 684 + service_endpoint: format!("https://{domain}"), 685 + }], 686 + }); 687 + make_sync(move |_| doc.clone()) 688 + } 689 + 690 + pub async fn serve( 691 + cache: HybridCache<String, CachedRecord>, 692 + identity: Identity, 693 + repo: Repo, 694 + domain: Option<String>, 695 + acme_contact: Option<String>, 696 + certs: Option<PathBuf>, 697 + shutdown: CancellationToken, 698 + ) -> Result<(), ServerError> { 699 + let repo = Arc::new(repo); 700 + let api_service = OpenApiService::new( 701 + Xrpc { 702 + cache, 703 + identity, 704 + repo, 705 + }, 706 + "Slingshot", 707 + env!("CARGO_PKG_VERSION"), 708 + ) 709 + .server(if let Some(ref h) = domain { 710 + format!("https://{h}") 711 + } else { 712 + "http://localhost:3000".to_string() 713 + }) 714 + .url_prefix("/xrpc") 715 + .contact( 716 + ContactObject::new() 717 + .name("@microcosm.blue") 718 + .url("https://bsky.app/profile/microcosm.blue"), 719 + ) 720 + .description(include_str!("../api-description.md")) 721 + .external_document(ExternalDocumentObject::new( 722 + "https://microcosm.blue/slingshot", 723 + )); 724 + 725 + let mut app = Route::new() 726 + .at("/", StaticFileEndpoint::new("./static/index.html")) 727 + .nest("/openapi", api_service.spec_endpoint()) 728 + .nest("/xrpc/", api_service); 729 + 730 + if let Some(domain) = domain { 731 + rustls::crypto::aws_lc_rs::default_provider() 732 + .install_default() 733 + .expect("alskfjalksdjf"); 734 + 735 + app = app.at("/.well-known/did.json", get_did_doc(&domain)); 736 + 737 + let mut auto_cert = AutoCert::builder() 738 + .directory_url(LETS_ENCRYPT_PRODUCTION) 739 + .domain(&domain); 740 + if let Some(contact) = acme_contact { 741 + auto_cert = auto_cert.contact(contact); 742 + } 743 + if let Some(certs) = certs { 744 + auto_cert = auto_cert.cache_path(certs); 745 + } 746 + let auto_cert = auto_cert.build().map_err(ServerError::AcmeBuildError)?; 747 + 748 + run( 749 + TcpListener::bind("0.0.0.0:443").acme(auto_cert), 750 + app, 751 + shutdown, 752 + ) 753 + .await 754 + } else { 755 + run(TcpListener::bind("127.0.0.1:3000"), app, shutdown).await 756 + } 757 + } 758 + 759 + async fn run<L>(listener: L, app: Route, shutdown: CancellationToken) -> Result<(), ServerError> 760 + where 761 + L: Listener + 'static, 762 + { 763 + let app = app 764 + .with( 765 + Cors::new() 766 + .allow_origin_regex("*") 767 + .allow_methods([Method::GET]) 768 + .allow_credentials(false), 769 + ) 770 + .with(CatchPanic::new()) 771 + .with(Tracing); 772 + Server::new(listener) 773 + .name("slingshot") 774 + .run_with_graceful_shutdown(app, shutdown.cancelled(), None) 775 + .await 776 + .map_err(ServerError::ServerExited) 777 + .inspect(|()| log::info!("server ended. goodbye.")) 778 + }
slingshot/static/favicon.ico

This is a binary file and will not be displayed.

+67
slingshot/static/index.html
··· 1 + <!doctype html> 2 + <html lang="en"> 3 + <head> 4 + <meta charset="utf-8" /> 5 + <title>Slingshot: atproto edge record cache</title> 6 + <meta name="viewport" content="width=device-width, initial-scale=1" /> 7 + <meta name="description" content="API Documentation for Slingshot, a firehose-listening atproto edge record and identity cache." /> 8 + <style> 9 + :root { 10 + --scalar-small: 13px; 11 + } 12 + .scalar-app .markdown .markdown-alert { 13 + font-size: var(--scalar-small); 14 + } 15 + .sidebar-heading-link-title { 16 + line-height: 1.2; 17 + } 18 + .custom-header { 19 + height: 42px; 20 + background-color: #221828; 21 + box-shadow: inset 0 -1px 0 var(--scalar-border-color); 22 + color: var(--scalar-color-1); 23 + font-size: var(--scalar-font-size-3); 24 + font-family: 'Iowan Old Style', 'Palatino Linotype', 'URW Palladio L', P052, serif; 25 + padding: 0 18px; 26 + justify-content: space-between; 27 + } 28 + .custom-header, 29 + .custom-header nav { 30 + display: flex; 31 + align-items: center; 32 + gap: 18px; 33 + } 34 + .custom-header a:hover { 35 + color: var(--scalar-color-2); 36 + } 37 + 38 + .light-mode .custom-header { 39 + background-color: thistle; 40 + } 41 + </style> 42 + </head> 43 + <body> 44 + <header class="custom-header scalar-app"> 45 + <p> 46 + TODO: thing 47 + </p> 48 + <nav> 49 + <b>a <a href="https://microcosm.blue">microcosm</a> project</b> 50 + <a href="https://bsky.app/profile/microcosm.blue">@microcosm.blue</a> 51 + <a href="https://github.com/at-microcosm">github</a> 52 + </nav> 53 + </header> 54 + 55 + <script id="api-reference" type="application/json" data-url="/openapi"></script> 56 + 57 + <script> 58 + var configuration = { 59 + theme: 'purple', 60 + hideModels: true, 61 + } 62 + document.getElementById('api-reference').dataset.configuration = JSON.stringify(configuration) 63 + </script> 64 + 65 + <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script> 66 + </body> 67 + </html>
+29
spacedust/Cargo.toml
··· 1 + [package] 2 + name = "spacedust" 3 + version = "0.1.0" 4 + edition = "2024" 5 + 6 + [dependencies] 7 + async-trait = "0.1.88" 8 + clap = { version = "4.5.40", features = ["derive"] } 9 + ctrlc = "3.4.7" 10 + dropshot = "0.16.2" 11 + env_logger = "0.11.8" 12 + futures = "0.3.31" 13 + http = "1.3.1" 14 + jetstream = { path = "../jetstream", features = ["metrics"] } 15 + links = { path = "../links" } 16 + log = "0.4.27" 17 + metrics = "0.24.2" 18 + metrics-exporter-prometheus = { version = "0.17.1", features = ["http-listener"] } 19 + rand = "0.9.1" 20 + schemars = "0.8.22" 21 + semver = "1.0.26" 22 + serde = { version = "1.0.219", features = ["derive"] } 23 + serde_json = "1.0.140" 24 + serde_qs = "1.0.0-rc.3" 25 + thiserror = "2.0.12" 26 + tinyjson = "2.5.1" 27 + tokio = { version = "1.45.1", features = ["full"] } 28 + tokio-tungstenite = "0.27.0" 29 + tokio-util = "0.7.15"
+116
spacedust/src/consumer.rs
··· 1 + use crate::ClientMessage; 2 + use crate::error::ConsumerError; 3 + use crate::removable_delay_queue; 4 + use jetstream::{ 5 + DefaultJetstreamEndpoints, JetstreamCompression, JetstreamConfig, JetstreamConnector, 6 + events::{CommitOp, Cursor, EventKind}, 7 + }; 8 + use links::collect_links; 9 + use std::sync::Arc; 10 + use tokio::sync::broadcast; 11 + use tokio_util::sync::CancellationToken; 12 + 13 + const MAX_LINKS_PER_EVENT: usize = 100; 14 + 15 + pub async fn consume( 16 + b: broadcast::Sender<Arc<ClientMessage>>, 17 + d: removable_delay_queue::Input<(String, usize), Arc<ClientMessage>>, 18 + jetstream_endpoint: String, 19 + cursor: Option<Cursor>, 20 + no_zstd: bool, 21 + shutdown: CancellationToken, 22 + ) -> Result<(), ConsumerError> { 23 + let endpoint = DefaultJetstreamEndpoints::endpoint_or_shortcut(&jetstream_endpoint); 24 + if endpoint == jetstream_endpoint { 25 + log::info!("consumer: connecting jetstream at {endpoint}"); 26 + } else { 27 + log::info!("consumer: connecting jetstream at {jetstream_endpoint} => {endpoint}"); 28 + } 29 + let config: JetstreamConfig = JetstreamConfig { 30 + endpoint, 31 + compression: if no_zstd { 32 + JetstreamCompression::None 33 + } else { 34 + JetstreamCompression::Zstd 35 + }, 36 + replay_on_reconnect: true, 37 + channel_size: 1024, // buffer up to ~1s of jetstream events 38 + ..Default::default() 39 + }; 40 + let mut receiver = JetstreamConnector::new(config)? 41 + .connect_cursor(cursor) 42 + .await?; 43 + 44 + log::info!("consumer: receiving messages.."); 45 + loop { 46 + if shutdown.is_cancelled() { 47 + log::info!("consumer: exiting for shutdown"); 48 + return Ok(()); 49 + } 50 + let Some(event) = receiver.recv().await else { 51 + log::error!("consumer: could not receive event, bailing"); 52 + break; 53 + }; 54 + 55 + if event.kind != EventKind::Commit { 56 + continue; 57 + } 58 + let Some(ref commit) = event.commit else { 59 + log::warn!("consumer: commit event missing commit data, ignoring"); 60 + continue; 61 + }; 62 + 63 + // TODO: something a bit more robust 64 + let at_uri = format!( 65 + "at://{}/{}/{}", 66 + &*event.did, &*commit.collection, &*commit.rkey 67 + ); 68 + 69 + // TODO: keep a buffer and remove quick deletes to debounce notifs 70 + // for now we just drop all deletes eek 71 + if commit.operation == CommitOp::Delete { 72 + d.remove_range((at_uri.clone(), 0)..=(at_uri.clone(), MAX_LINKS_PER_EVENT)) 73 + .await; 74 + continue; 75 + } 76 + let Some(ref record) = commit.record else { 77 + log::warn!("consumer: commit update/delete missing record, ignoring"); 78 + continue; 79 + }; 80 + 81 + let jv = match record.get().parse() { 82 + Ok(v) => v, 83 + Err(e) => { 84 + log::warn!("consumer: record failed to parse, ignoring: {e}"); 85 + continue; 86 + } 87 + }; 88 + 89 + for (i, link) in collect_links(&jv).into_iter().enumerate() { 90 + if i >= MAX_LINKS_PER_EVENT { 91 + // todo: indicate if the link limit was reached (-> links omitted) 92 + log::warn!("consumer: event has too many links, ignoring the rest"); 93 + metrics::counter!("consumer_dropped_links", "reason" => "too_many_links") 94 + .increment(1); 95 + break; 96 + } 97 + let client_message = match ClientMessage::new_link(link, &at_uri, commit) { 98 + Ok(m) => m, 99 + Err(e) => { 100 + // TODO indicate to clients that a link has been dropped 101 + log::warn!("consumer: failed to serialize link to json: {e:?}"); 102 + metrics::counter!("consumer_dropped_links", "reason" => "failed_to_serialize") 103 + .increment(1); 104 + continue; 105 + } 106 + }; 107 + let message = Arc::new(client_message); 108 + let _ = b.send(message.clone()); // only errors if no subscribers are connected, which is just fine. 109 + d.enqueue((at_uri.clone(), i), message) 110 + .await 111 + .map_err(|_| ConsumerError::DelayQueueOutputDropped)?; 112 + } 113 + } 114 + 115 + Err(ConsumerError::JetstreamEnded) 116 + }
+22
spacedust/src/delay.rs
··· 1 + use crate::error::DelayError; 2 + use crate::removable_delay_queue; 3 + use tokio::sync::broadcast; 4 + use tokio_util::sync::CancellationToken; 5 + 6 + pub async fn to_broadcast<T>( 7 + source: removable_delay_queue::Output<(String, usize), T>, 8 + dest: broadcast::Sender<T>, 9 + shutdown: CancellationToken, 10 + ) -> Result<(), DelayError> { 11 + loop { 12 + tokio::select! { 13 + ev = source.next() => match ev { 14 + Some(event) => { 15 + let _ = dest.send(event); // only errors of there are no listeners, but that's normal 16 + }, 17 + None => return Err(DelayError::DelayEnded), 18 + }, 19 + _ = shutdown.cancelled() => return Ok(()), 20 + } 21 + } 22 + }
+55
spacedust/src/error.rs
··· 1 + use thiserror::Error; 2 + 3 + #[derive(Debug, Error)] 4 + pub enum MainTaskError { 5 + #[error(transparent)] 6 + ConsumerTaskError(#[from] ConsumerError), 7 + #[error(transparent)] 8 + ServerTaskError(#[from] ServerError), 9 + #[error(transparent)] 10 + DelayTaskError(#[from] DelayError), 11 + } 12 + 13 + #[derive(Debug, Error)] 14 + pub enum ConsumerError { 15 + #[error(transparent)] 16 + JetstreamConnectionError(#[from] jetstream::error::ConnectionError), 17 + #[error(transparent)] 18 + JetstreamConfigValidationError(#[from] jetstream::error::ConfigValidationError), 19 + #[error("jetstream ended")] 20 + JetstreamEnded, 21 + #[error("delay queue output dropped")] 22 + DelayQueueOutputDropped, 23 + } 24 + 25 + #[derive(Debug, Error)] 26 + pub enum SubscriberUpdateError { 27 + #[error("failed to parse json for subscriber update: {0}")] 28 + FailedToParseMessage(serde_json::Error), 29 + #[error("more wantedSources were requested than allowed (max 1,000)")] 30 + TooManySourcesWanted, 31 + #[error("more wantedSubjectDids were requested than allowed (max 10,000)")] 32 + TooManyDidsWanted, 33 + #[error("more wantedSubjects were requested than allowed (max 50,000)")] 34 + TooManySubjectsWanted, 35 + } 36 + 37 + #[derive(Debug, Error)] 38 + pub enum DelayError { 39 + #[error("delay ended")] 40 + DelayEnded, 41 + } 42 + 43 + #[derive(Debug, Error)] 44 + pub enum ServerError { 45 + #[error("failed to configure server logger: {0}")] 46 + ConfigLogError(std::io::Error), 47 + #[error("failed to render json for openapi: {0}")] 48 + OpenApiJsonFail(serde_json::Error), 49 + #[error(transparent)] 50 + FailedToBuildServer(#[from] dropshot::BuildError), 51 + #[error("server exited: {0}")] 52 + ServerExited(String), 53 + #[error("server closed badly: {0}")] 54 + BadClose(String), 55 + }
+104
spacedust/src/lib.rs
··· 1 + pub mod consumer; 2 + pub mod delay; 3 + pub mod error; 4 + pub mod removable_delay_queue; 5 + pub mod server; 6 + pub mod subscriber; 7 + 8 + use jetstream::events::CommitEvent; 9 + use links::CollectedLink; 10 + use serde::{Deserialize, Serialize}; 11 + use server::MultiSubscribeQuery; 12 + use tokio_tungstenite::tungstenite::Message; 13 + 14 + #[derive(Debug)] 15 + pub struct FilterableProperties { 16 + /// Full unmodified DID, at-uri, or url 17 + pub subject: String, 18 + /// User/identity DID. 19 + /// 20 + /// Will match both bare-DIDs and DIDs extracted from at-uris. 21 + /// `None` for any URL. 22 + pub subject_did: Option<String>, 23 + /// Link source -- collection NSID joined with `:` to the record property path. 24 + pub source: String, 25 + } 26 + 27 + /// A serialized message with filterable properties attached 28 + #[derive(Debug)] 29 + pub struct ClientMessage { 30 + pub message: Message, // always Message::Text 31 + pub properties: FilterableProperties, 32 + } 33 + 34 + impl ClientMessage { 35 + pub fn new_link( 36 + link: CollectedLink, 37 + at_uri: &str, 38 + commit: &CommitEvent, 39 + ) -> Result<Self, serde_json::Error> { 40 + let subject_did = link.target.did(); 41 + 42 + let subject = link.target.into_string(); 43 + 44 + let undotted = link.path.strip_prefix('.').unwrap_or_else(|| { 45 + eprintln!("link path did not have expected '.' prefix: {}", link.path); 46 + "" 47 + }); 48 + let source = format!("{}:{undotted}", &*commit.collection); 49 + 50 + let client_link_event = ClientLinkEvent { 51 + operation: "create", 52 + source: source.clone(), 53 + source_record: at_uri.to_string(), 54 + source_rev: commit.rev.to_string(), 55 + subject: subject.clone(), 56 + }; 57 + 58 + let client_event = ClientEvent { 59 + kind: "link", 60 + origin: "live", // TODO: indicate when we're locally replaying jetstream on reconnect?? maybe not. 61 + link: client_link_event, 62 + }; 63 + 64 + let client_event_json = serde_json::to_string(&client_event)?; 65 + 66 + let message = Message::Text(client_event_json.into()); 67 + 68 + let properties = FilterableProperties { 69 + subject, 70 + subject_did, 71 + source, 72 + }; 73 + 74 + Ok(ClientMessage { 75 + message, 76 + properties, 77 + }) 78 + } 79 + } 80 + 81 + #[derive(Debug, Serialize)] 82 + #[serde(rename_all = "snake_case")] 83 + pub struct ClientEvent { 84 + kind: &'static str, // "link" 85 + origin: &'static str, // "live", "replay", "backfill" 86 + link: ClientLinkEvent, 87 + } 88 + 89 + #[derive(Debug, Serialize)] 90 + struct ClientLinkEvent { 91 + operation: &'static str, // "create", "delete" (prob no update, though maybe for rev?) 92 + source: String, 93 + source_record: String, 94 + source_rev: String, 95 + subject: String, 96 + // TODO: include the record too? would save clients a level of hydration 97 + // ^^ no, not for now. until we backfill + support broader deletes at *least*. 98 + } 99 + 100 + #[derive(Debug, Deserialize)] 101 + #[serde(tag = "type", content = "payload", rename_all = "snake_case")] 102 + pub enum SubscriberSourcedMessage { 103 + OptionsUpdate(MultiSubscribeQuery), 104 + }
+144
spacedust/src/main.rs
··· 1 + use spacedust::consumer; 2 + use spacedust::delay; 3 + use spacedust::error::MainTaskError; 4 + use spacedust::removable_delay_queue::removable_delay_queue; 5 + use spacedust::server; 6 + 7 + use clap::Parser; 8 + use metrics_exporter_prometheus::PrometheusBuilder; 9 + use std::time::Duration; 10 + use tokio::sync::broadcast; 11 + use tokio_util::sync::CancellationToken; 12 + 13 + /// Aggregate links in the at-mosphere 14 + #[derive(Parser, Debug, Clone)] 15 + #[command(version, about, long_about = None)] 16 + struct Args { 17 + /// Jetstream server to connect to (exclusive with --fixture). Provide either a wss:// URL, or a shorhand value: 18 + /// 'us-east-1', 'us-east-2', 'us-west-1', or 'us-west-2' 19 + #[arg(long)] 20 + jetstream: String, 21 + /// don't request zstd-compressed jetstream events 22 + /// 23 + /// reduces CPU at the expense of more ingress bandwidth 24 + #[arg(long, action)] 25 + jetstream_no_zstd: bool, 26 + } 27 + 28 + #[tokio::main] 29 + async fn main() -> Result<(), String> { 30 + env_logger::init(); 31 + 32 + // tokio broadcast keeps a single main output queue for all subscribers. 33 + // each subscriber clones off a copy of an individual value for each recv. 34 + // since there's no large per-client buffer, we can make this one kind of 35 + // big and accommodate more slow/bursty clients. 36 + // 37 + // in fact, we *could* even keep lagging clients alive, inserting lag- 38 + // indicating messages to their output.... but for now we'll drop them to 39 + // avoid accumulating zombies. 40 + // 41 + // events on the channel are individual links as they are discovered. a link 42 + // contains a source and a target. the target is an at-uri, so it's up to 43 + // ~1KB max; source is a collection + link path, which can be more but in 44 + // practice the whole link rarely approaches 1KB total. 45 + // 46 + // TODO: determine if a pathological case could blow this up (eg 1MB link 47 + // paths + slow subscriber -> 16GiB queue) 48 + let (b, _) = broadcast::channel(16_384); 49 + let consumer_sender = b.clone(); 50 + let (d, _) = broadcast::channel(16_384); 51 + let consumer_delayed_sender = d.clone(); 52 + 53 + let delay = Duration::from_secs(21); 54 + let (delay_queue_sender, delay_queue_receiver) = removable_delay_queue(delay); 55 + 56 + let shutdown = CancellationToken::new(); 57 + 58 + let ctrlc_shutdown = shutdown.clone(); 59 + ctrlc::set_handler(move || ctrlc_shutdown.cancel()).expect("failed to set ctrl-c handler"); 60 + 61 + let args = Args::parse(); 62 + 63 + if let Err(e) = install_metrics_server() { 64 + log::error!("failed to install metrics server: {e:?}"); 65 + }; 66 + 67 + let mut tasks: tokio::task::JoinSet<Result<(), MainTaskError>> = tokio::task::JoinSet::new(); 68 + 69 + let server_shutdown = shutdown.clone(); 70 + tasks.spawn(async move { 71 + server::serve(b, d, server_shutdown).await?; 72 + Ok(()) 73 + }); 74 + 75 + let consumer_shutdown = shutdown.clone(); 76 + tasks.spawn(async move { 77 + consumer::consume( 78 + consumer_sender, 79 + delay_queue_sender, 80 + args.jetstream, 81 + None, 82 + args.jetstream_no_zstd, 83 + consumer_shutdown, 84 + ) 85 + .await?; 86 + Ok(()) 87 + }); 88 + 89 + let delay_shutdown = shutdown.clone(); 90 + tasks.spawn(async move { 91 + delay::to_broadcast( 92 + delay_queue_receiver, 93 + consumer_delayed_sender, 94 + delay_shutdown, 95 + ) 96 + .await?; 97 + Ok(()) 98 + }); 99 + 100 + tokio::select! { 101 + _ = shutdown.cancelled() => log::warn!("shutdown requested"), 102 + Some(r) = tasks.join_next() => { 103 + log::warn!("a task exited, shutting down: {r:?}"); 104 + shutdown.cancel(); 105 + } 106 + } 107 + 108 + tokio::select! { 109 + _ = async { 110 + while let Some(completed) = tasks.join_next().await { 111 + log::info!("shutdown: task completed: {completed:?}"); 112 + } 113 + } => {}, 114 + _ = tokio::time::sleep(std::time::Duration::from_secs(3)) => { 115 + log::info!("shutdown: not all tasks completed on time. aborting..."); 116 + tasks.shutdown().await; 117 + }, 118 + } 119 + 120 + log::info!("bye!"); 121 + 122 + Ok(()) 123 + } 124 + 125 + fn install_metrics_server() -> Result<(), metrics_exporter_prometheus::BuildError> { 126 + log::info!("installing metrics server..."); 127 + let host = [0, 0, 0, 0]; 128 + let port = 8765; 129 + PrometheusBuilder::new() 130 + .set_quantiles(&[0.5, 0.9, 0.99, 1.0])? 131 + .set_bucket_duration(std::time::Duration::from_secs(300))? 132 + .set_bucket_count(std::num::NonZero::new(12).unwrap()) // count * duration = 60 mins. stuff doesn't happen that fast here. 133 + .set_enable_unit_suffix(false) // this seemed buggy for constellation (sometimes wouldn't engage) 134 + .with_http_listener((host, port)) 135 + .install()?; 136 + log::info!( 137 + "metrics server installed! listening on http://{}.{}.{}.{}:{port}", 138 + host[0], 139 + host[1], 140 + host[2], 141 + host[3] 142 + ); 143 + Ok(()) 144 + }
+125
spacedust/src/removable_delay_queue.rs
··· 1 + use std::collections::{BTreeMap, VecDeque}; 2 + use std::ops::RangeBounds; 3 + use std::sync::Arc; 4 + use std::time::{Duration, Instant}; 5 + use thiserror::Error; 6 + use tokio::sync::Mutex; 7 + 8 + #[derive(Debug, Error)] 9 + pub enum EnqueueError<T> { 10 + #[error("queue ouput dropped")] 11 + OutputDropped(T), 12 + } 13 + 14 + pub trait Key: Eq + Ord + Clone {} 15 + impl<T: Eq + Ord + Clone> Key for T {} 16 + 17 + #[derive(Debug)] 18 + struct Queue<K: Key, T> { 19 + queue: VecDeque<(Instant, K)>, 20 + items: BTreeMap<K, T>, 21 + } 22 + 23 + pub struct Input<K: Key, T> { 24 + q: Arc<Mutex<Queue<K, T>>>, 25 + } 26 + 27 + impl<K: Key, T> Input<K, T> { 28 + /// if a key is already present, its previous item will be overwritten and 29 + /// its delay time will be reset for the new item. 30 + /// 31 + /// errors if the remover has been dropped 32 + pub async fn enqueue(&self, key: K, item: T) -> Result<(), EnqueueError<T>> { 33 + if Arc::strong_count(&self.q) == 1 { 34 + return Err(EnqueueError::OutputDropped(item)); 35 + } 36 + // TODO: try to push out an old element first 37 + // for now we just hope there's a listener 38 + let now = Instant::now(); 39 + let mut q = self.q.lock().await; 40 + q.queue.push_back((now, key.clone())); 41 + q.items.insert(key, item); 42 + Ok(()) 43 + } 44 + /// remove an item from the queue, by key 45 + /// 46 + /// the item itself is removed, but the key will remain in the queue -- it 47 + /// will simply be skipped over when a new output item is requested. this 48 + /// keeps the removal cheap (=btreemap remove), for a bit of space overhead 49 + pub async fn remove_range(&self, range: impl RangeBounds<K>) { 50 + let n = { 51 + let mut q = self.q.lock().await; 52 + let keys = q 53 + .items 54 + .range(range) 55 + .map(|(k, _)| k) 56 + .cloned() 57 + .collect::<Vec<_>>(); 58 + for k in &keys { 59 + q.items.remove(k); 60 + } 61 + keys.len() 62 + }; 63 + if n == 0 { 64 + metrics::counter!("delay_queue_remove_not_found").increment(1); 65 + } else { 66 + metrics::counter!("delay_queue_remove_total_records").increment(1); 67 + metrics::counter!("delay_queue_remove_total_links").increment(n as u64); 68 + } 69 + } 70 + } 71 + 72 + pub struct Output<K: Key, T> { 73 + delay: Duration, 74 + q: Arc<Mutex<Queue<K, T>>>, 75 + } 76 + 77 + impl<K: Key, T> Output<K, T> { 78 + pub async fn next(&self) -> Option<T> { 79 + let get = || async { 80 + let mut q = self.q.lock().await; 81 + metrics::gauge!("delay_queue_queue_len").set(q.queue.len() as f64); 82 + metrics::gauge!("delay_queue_queue_capacity").set(q.queue.capacity() as f64); 83 + while let Some((t, k)) = q.queue.pop_front() { 84 + // skip over queued keys that were removed from items 85 + if let Some(item) = q.items.remove(&k) { 86 + return Some((t, item)); 87 + } 88 + } 89 + None 90 + }; 91 + loop { 92 + if let Some((t, item)) = get().await { 93 + let now = Instant::now(); 94 + let expected_release = t + self.delay; 95 + if expected_release.saturating_duration_since(now) > Duration::from_millis(1) { 96 + tokio::time::sleep_until(expected_release.into()).await; 97 + metrics::counter!("delay_queue_emit_total", "early" => "yes").increment(1); 98 + metrics::histogram!("delay_queue_emit_overshoot").record(0); 99 + } else { 100 + let overshoot = now.saturating_duration_since(expected_release); 101 + metrics::counter!("delay_queue_emit_total", "early" => "no").increment(1); 102 + metrics::histogram!("delay_queue_emit_overshoot") 103 + .record(overshoot.as_secs_f64()); 104 + } 105 + return Some(item); 106 + } else if Arc::strong_count(&self.q) == 1 { 107 + return None; 108 + } 109 + // the queue is *empty*, so we need to wait at least as long as the current delay 110 + tokio::time::sleep(self.delay).await; 111 + metrics::counter!("delay_queue_entirely_empty_total").increment(1); 112 + } 113 + } 114 + } 115 + 116 + pub fn removable_delay_queue<K: Key, T>(delay: Duration) -> (Input<K, T>, Output<K, T>) { 117 + let q: Arc<Mutex<Queue<K, T>>> = Arc::new(Mutex::new(Queue { 118 + queue: VecDeque::new(), 119 + items: BTreeMap::new(), 120 + })); 121 + 122 + let input = Input::<K, T> { q: q.clone() }; 123 + let output = Output::<K, T> { q, delay }; 124 + (input, output) 125 + }
+339
spacedust/src/server.rs
··· 1 + use crate::ClientMessage; 2 + use crate::error::ServerError; 3 + use crate::subscriber::Subscriber; 4 + use dropshot::{ 5 + ApiDescription, ApiEndpointBodyContentType, Body, ConfigDropshot, ConfigLogging, 6 + ConfigLoggingLevel, ExtractorMetadata, HttpError, HttpResponse, Query, RequestContext, 7 + ServerBuilder, ServerContext, SharedExtractor, WebsocketConnection, channel, endpoint, 8 + }; 9 + use http::{ 10 + Response, StatusCode, 11 + header::{ORIGIN, USER_AGENT}, 12 + }; 13 + use metrics::{counter, histogram}; 14 + use std::sync::Arc; 15 + 16 + use async_trait::async_trait; 17 + use schemars::JsonSchema; 18 + use serde::{Deserialize, Serialize}; 19 + use std::collections::HashSet; 20 + use tokio::sync::broadcast; 21 + use tokio::time::Instant; 22 + use tokio_tungstenite::tungstenite::protocol::{Role, WebSocketConfig}; 23 + use tokio_util::sync::CancellationToken; 24 + 25 + const INDEX_HTML: &str = include_str!("../static/index.html"); 26 + const FAVICON: &[u8] = include_bytes!("../static/favicon.ico"); 27 + 28 + pub async fn serve( 29 + b: broadcast::Sender<Arc<ClientMessage>>, 30 + d: broadcast::Sender<Arc<ClientMessage>>, 31 + shutdown: CancellationToken, 32 + ) -> Result<(), ServerError> { 33 + let config_logging = ConfigLogging::StderrTerminal { 34 + level: ConfigLoggingLevel::Info, 35 + }; 36 + 37 + let log = config_logging 38 + .to_logger("example-basic") 39 + .map_err(ServerError::ConfigLogError)?; 40 + 41 + let mut api = ApiDescription::new(); 42 + api.register(index).unwrap(); 43 + api.register(favicon).unwrap(); 44 + api.register(openapi).unwrap(); 45 + api.register(subscribe).unwrap(); 46 + 47 + // TODO: put spec in a once cell / lazy lock thing? 48 + let spec = Arc::new( 49 + api.openapi( 50 + "Spacedust", 51 + env!("CARGO_PKG_VERSION") 52 + .parse() 53 + .inspect_err(|e| { 54 + eprintln!("failed to parse cargo package version for openapi: {e:?}") 55 + }) 56 + .unwrap_or(semver::Version::new(0, 0, 1)), 57 + ) 58 + .description("A configurable ATProto notifications firehose.") 59 + .contact_name("part of @microcosm.blue") 60 + .contact_url("https://microcosm.blue") 61 + .json() 62 + .map_err(ServerError::OpenApiJsonFail)?, 63 + ); 64 + 65 + let sub_shutdown = shutdown.clone(); 66 + let ctx = Context { 67 + spec, 68 + b, 69 + d, 70 + shutdown: sub_shutdown, 71 + }; 72 + 73 + let server = ServerBuilder::new(api, ctx, log) 74 + .config(ConfigDropshot { 75 + bind_address: "0.0.0.0:9998".parse().unwrap(), 76 + ..Default::default() 77 + }) 78 + .start()?; 79 + 80 + tokio::select! { 81 + s = server.wait_for_shutdown() => { 82 + s.map_err(ServerError::ServerExited)?; 83 + log::info!("server shut down normally."); 84 + }, 85 + _ = shutdown.cancelled() => { 86 + log::info!("shutting down: closing server"); 87 + server.close().await.map_err(ServerError::BadClose)?; 88 + }, 89 + } 90 + Ok(()) 91 + } 92 + 93 + #[derive(Debug, Clone)] 94 + struct Context { 95 + pub spec: Arc<serde_json::Value>, 96 + pub b: broadcast::Sender<Arc<ClientMessage>>, 97 + pub d: broadcast::Sender<Arc<ClientMessage>>, 98 + pub shutdown: CancellationToken, 99 + } 100 + 101 + async fn instrument_handler<T, H, R>(ctx: &RequestContext<T>, handler: H) -> Result<R, HttpError> 102 + where 103 + R: HttpResponse, 104 + H: Future<Output = Result<R, HttpError>>, 105 + T: ServerContext, 106 + { 107 + let start = Instant::now(); 108 + let result = handler.await; 109 + let latency = start.elapsed(); 110 + let status_code = match &result { 111 + Ok(response) => response.status_code(), 112 + Err(e) => e.status_code.as_status(), 113 + } 114 + .as_str() // just the number (.to_string()'s Display does eg `200 OK`) 115 + .to_string(); 116 + let endpoint = ctx.endpoint.operation_id.clone(); 117 + let headers = ctx.request.headers(); 118 + let origin = headers 119 + .get(ORIGIN) 120 + .and_then(|v| v.to_str().ok()) 121 + .unwrap_or("") 122 + .to_string(); 123 + let ua = headers 124 + .get(USER_AGENT) 125 + .and_then(|v| v.to_str().ok()) 126 + .map(|ua| { 127 + if ua.starts_with("Mozilla/5.0 ") { 128 + "browser" 129 + } else { 130 + ua 131 + } 132 + }) 133 + .unwrap_or("") 134 + .to_string(); 135 + counter!("server_requests_total", 136 + "endpoint" => endpoint.clone(), 137 + "origin" => origin, 138 + "ua" => ua, 139 + "status_code" => status_code, 140 + ) 141 + .increment(1); 142 + histogram!("server_handler_latency", "endpoint" => endpoint).record(latency.as_micros() as f64); 143 + result 144 + } 145 + 146 + use dropshot::{HttpResponseHeaders, HttpResponseOk}; 147 + 148 + pub type OkCorsResponse<T> = Result<HttpResponseHeaders<HttpResponseOk<T>>, HttpError>; 149 + 150 + /// Helper for constructing Ok responses: return OkCors(T).into() 151 + /// (not happy with this yet) 152 + pub struct OkCors<T: Serialize + JsonSchema + Send + Sync>(pub T); 153 + 154 + impl<T> From<OkCors<T>> for OkCorsResponse<T> 155 + where 156 + T: Serialize + JsonSchema + Send + Sync, 157 + { 158 + fn from(ok: OkCors<T>) -> OkCorsResponse<T> { 159 + let mut res = HttpResponseHeaders::new_unnamed(HttpResponseOk(ok.0)); 160 + res.headers_mut() 161 + .insert("access-control-allow-origin", "*".parse().unwrap()); 162 + Ok(res) 163 + } 164 + } 165 + 166 + // TODO: cors for HttpError 167 + 168 + /// Serve index page as html 169 + #[endpoint { 170 + method = GET, 171 + path = "/", 172 + /* 173 + * not useful to have this in openapi 174 + */ 175 + unpublished = true, 176 + }] 177 + async fn index(ctx: RequestContext<Context>) -> Result<Response<Body>, HttpError> { 178 + instrument_handler(&ctx, async { 179 + Ok(Response::builder() 180 + .status(StatusCode::OK) 181 + .header(http::header::CONTENT_TYPE, "text/html") 182 + .body(INDEX_HTML.into())?) 183 + }) 184 + .await 185 + } 186 + 187 + /// Serve index page as html 188 + #[endpoint { 189 + method = GET, 190 + path = "/favicon.ico", 191 + /* 192 + * not useful to have this in openapi 193 + */ 194 + unpublished = true, 195 + }] 196 + async fn favicon(ctx: RequestContext<Context>) -> Result<Response<Body>, HttpError> { 197 + instrument_handler(&ctx, async { 198 + Ok(Response::builder() 199 + .status(StatusCode::OK) 200 + .header(http::header::CONTENT_TYPE, "image/x-icon") 201 + .body(FAVICON.to_vec().into())?) 202 + }) 203 + .await 204 + } 205 + 206 + /// Meta: get the openapi spec for this api 207 + #[endpoint { 208 + method = GET, 209 + path = "/openapi", 210 + /* 211 + * not useful to have this in openapi 212 + */ 213 + unpublished = true, 214 + }] 215 + async fn openapi(ctx: RequestContext<Context>) -> OkCorsResponse<serde_json::Value> { 216 + instrument_handler(&ctx, async { 217 + let spec = (*ctx.context().spec).clone(); 218 + OkCors(spec).into() 219 + }) 220 + .await 221 + } 222 + 223 + /// The real type that gets deserialized 224 + #[derive(Debug, Deserialize, JsonSchema)] 225 + #[serde(rename_all = "camelCase")] 226 + pub struct MultiSubscribeQuery { 227 + #[serde(default)] 228 + pub wanted_subjects: HashSet<String>, 229 + #[serde(default)] 230 + pub wanted_subject_dids: HashSet<String>, 231 + #[serde(default)] 232 + pub wanted_sources: HashSet<String>, 233 + } 234 + /// The fake corresponding type for docs that dropshot won't freak out about a 235 + /// vec for 236 + #[derive(Deserialize, JsonSchema)] 237 + #[allow(dead_code)] 238 + #[serde(rename_all = "camelCase")] 239 + struct MultiSubscribeQueryForDocs { 240 + /// One or more at-uris to receive links about 241 + /// 242 + /// The at-uri must be url-encoded 243 + /// 244 + /// Pass this parameter multiple times to specify multiple collections, like 245 + /// `wantedSubjects=[...]&wantedSubjects=[...]` 246 + pub wanted_subjects: String, 247 + /// One or more DIDs to receive links about 248 + /// 249 + /// Pass this parameter multiple times to specify multiple collections 250 + pub wanted_subject_dids: String, 251 + /// One or more link sources to receive links about 252 + /// 253 + /// TODO: docs about link sources 254 + /// 255 + /// eg, a bluesky like's link source: `app.bsky.feed.like:subject.uri` 256 + /// 257 + /// Pass this parameter multiple times to specify multiple sources 258 + pub wanted_sources: String, 259 + } 260 + 261 + // The `SharedExtractor` implementation for Query<QueryType> describes how to 262 + // construct an instance of `Query<QueryType>` from an HTTP request: namely, by 263 + // parsing the query string to an instance of `QueryType`. 264 + #[async_trait] 265 + impl SharedExtractor for MultiSubscribeQuery { 266 + async fn from_request<Context: ServerContext>( 267 + ctx: &RequestContext<Context>, 268 + ) -> Result<MultiSubscribeQuery, HttpError> { 269 + let raw_query = ctx.request.uri().query().unwrap_or(""); 270 + let q = serde_qs::from_str(raw_query).map_err(|e| { 271 + HttpError::for_bad_request(None, format!("unable to parse query string: {e}")) 272 + })?; 273 + Ok(q) 274 + } 275 + 276 + fn metadata(body_content_type: ApiEndpointBodyContentType) -> ExtractorMetadata { 277 + // HACK: query type switcheroo: passing MultiSubscribeQuery to 278 + // `metadata` would "helpfully" panic because dropshot believes we can 279 + // only have scalar types in a query. 280 + // 281 + // so instead we have a fake second type whose only job is to look the 282 + // same as MultiSubscribeQuery exept that it has `String` instead of 283 + // `Vec<String>`, which dropshot will accept, and generate ~close-enough 284 + // docs for. 285 + <Query<MultiSubscribeQueryForDocs> as SharedExtractor>::metadata(body_content_type) 286 + } 287 + } 288 + 289 + #[derive(Deserialize, JsonSchema)] 290 + #[serde(rename_all = "camelCase")] 291 + struct ScalarSubscribeQuery { 292 + /// Bypass the 21-sec delay buffer 293 + /// 294 + /// By default, spacedust holds all firehose links for 21 seconds before 295 + /// emitting them, to prevent quickly- undone interactions from generating 296 + /// notifications. 297 + /// 298 + /// Setting `instant` to true bypasses this buffer, allowing faster (and 299 + /// noisier) notification delivery. 300 + /// 301 + /// Typically [a little less than 1%](https://bsky.app/profile/bad-example.com/post/3ls32wctsrs2l) 302 + /// of links links get deleted within 21s of being created. 303 + #[serde(default)] 304 + pub instant: bool, 305 + } 306 + 307 + #[channel { 308 + protocol = WEBSOCKETS, 309 + path = "/subscribe", 310 + }] 311 + async fn subscribe( 312 + reqctx: RequestContext<Context>, 313 + query: MultiSubscribeQuery, 314 + scalar_query: Query<ScalarSubscribeQuery>, 315 + upgraded: WebsocketConnection, 316 + ) -> dropshot::WebsocketChannelResult { 317 + let ws = tokio_tungstenite::WebSocketStream::from_raw_socket( 318 + upgraded.into_inner(), 319 + Role::Server, 320 + Some(WebSocketConfig::default().max_message_size( 321 + Some(10 * 2_usize.pow(20)), // 10MiB, matching jetstream 322 + )), 323 + ) 324 + .await; 325 + 326 + let Context { b, d, shutdown, .. } = reqctx.context(); 327 + let sub_token = shutdown.child_token(); 328 + 329 + let q = scalar_query.into_inner(); 330 + let subscription = if q.instant { b } else { d }.subscribe(); 331 + log::info!("starting subscriber with broadcast: instant={}", q.instant); 332 + 333 + Subscriber::new(query, sub_token) 334 + .start(ws, subscription) 335 + .await 336 + .map_err(|e| format!("boo: {e:?}"))?; 337 + 338 + Ok(()) 339 + }
+164
spacedust/src/subscriber.rs
··· 1 + use crate::error::SubscriberUpdateError; 2 + use crate::server::MultiSubscribeQuery; 3 + use crate::{ClientMessage, FilterableProperties, SubscriberSourcedMessage}; 4 + use dropshot::WebsocketConnectionRaw; 5 + use futures::SinkExt; 6 + use futures::StreamExt; 7 + use std::error::Error; 8 + use std::sync::Arc; 9 + use std::time::Duration; 10 + use tokio::sync::broadcast::{self, error::RecvError}; 11 + use tokio::time::interval; 12 + use tokio_tungstenite::{WebSocketStream, tungstenite::Message}; 13 + use tokio_util::sync::CancellationToken; 14 + 15 + const PING_PERIOD: Duration = Duration::from_secs(30); 16 + 17 + pub struct Subscriber { 18 + query: MultiSubscribeQuery, 19 + shutdown: CancellationToken, 20 + } 21 + 22 + impl Subscriber { 23 + pub fn new(query: MultiSubscribeQuery, shutdown: CancellationToken) -> Self { 24 + Self { query, shutdown } 25 + } 26 + 27 + pub async fn start( 28 + mut self, 29 + ws: WebSocketStream<WebsocketConnectionRaw>, 30 + mut receiver: broadcast::Receiver<Arc<ClientMessage>>, 31 + ) -> Result<(), Box<dyn Error>> { 32 + let mut ping_state = None; 33 + let (mut ws_sender, mut ws_receiver) = ws.split(); 34 + let mut ping_interval = interval(PING_PERIOD); 35 + let _guard = self.shutdown.clone().drop_guard(); 36 + 37 + // TODO: do we need to timeout ws sends?? 38 + 39 + metrics::counter!("subscribers_connected_total").increment(1); 40 + metrics::gauge!("subscribers_connected").increment(1); 41 + 42 + loop { 43 + tokio::select! { 44 + l = receiver.recv() => match l { 45 + Ok(link) => if self.filter(&link.properties) { 46 + if let Err(e) = ws_sender.send(link.message.clone()).await { 47 + log::warn!("failed to send link, dropping subscriber: {e:?}"); 48 + break; 49 + } 50 + }, 51 + Err(RecvError::Closed) => self.shutdown.cancel(), 52 + Err(RecvError::Lagged(n)) => { 53 + log::warn!("dropping lagging subscriber (missed {n} messages already)"); 54 + self.shutdown.cancel(); 55 + } 56 + }, 57 + cm = ws_receiver.next() => match cm { 58 + Some(Ok(Message::Ping(state))) => { 59 + if let Err(e) = ws_sender.send(Message::Pong(state)).await { 60 + log::error!("failed to reply pong to subscriber: {e:?}"); 61 + break; 62 + } 63 + } 64 + Some(Ok(Message::Pong(state))) => { 65 + if let Some(expected_state) = ping_state { 66 + if *state == expected_state { 67 + ping_state = None; // good 68 + } else { 69 + log::error!("subscriber returned a pong with the wrong state, dropping"); 70 + self.shutdown.cancel(); 71 + } 72 + } else { 73 + log::error!("subscriber sent a pong when none was expected"); 74 + self.shutdown.cancel(); 75 + } 76 + } 77 + Some(Ok(Message::Text(raw))) => { 78 + if let Err(e) = self.query.update_from_raw(&raw) { 79 + log::error!("subscriber options could not be updated, dropping: {e:?}"); 80 + // TODO: send client an explanation 81 + self.shutdown.cancel(); 82 + } 83 + log::trace!("subscriber updated with opts: {:?}", self.query); 84 + }, 85 + Some(Ok(m)) => log::trace!("subscriber sent an unexpected message: {m:?}"), 86 + Some(Err(e)) => { 87 + log::error!("failed to receive subscriber message: {e:?}"); 88 + break; 89 + } 90 + None => { 91 + log::trace!("end of subscriber messages. bye!"); 92 + break; 93 + } 94 + }, 95 + _ = ping_interval.tick() => { 96 + if ping_state.is_some() { 97 + log::warn!("did not recieve pong within {PING_PERIOD:?}, dropping subscriber"); 98 + self.shutdown.cancel(); 99 + } else { 100 + let new_state: [u8; 8] = rand::random(); 101 + let ping = new_state.to_vec().into(); 102 + ping_state = Some(new_state); 103 + if let Err(e) = ws_sender.send(Message::Ping(ping)).await { 104 + log::error!("failed to send ping to subscriber, dropping: {e:?}"); 105 + self.shutdown.cancel(); 106 + } 107 + } 108 + } 109 + _ = self.shutdown.cancelled() => { 110 + log::info!("subscriber shutdown requested, bye!"); 111 + if let Err(e) = ws_sender.close().await { 112 + log::warn!("failed to close subscriber: {e:?}"); 113 + } 114 + break; 115 + }, 116 + } 117 + } 118 + log::trace!("end of subscriber. bye!"); 119 + metrics::gauge!("subscribers_connected").decrement(1); 120 + Ok(()) 121 + } 122 + 123 + fn filter(&self, properties: &FilterableProperties) -> bool { 124 + let query = &self.query; 125 + 126 + // subject + subject DIDs are logical OR 127 + if !(query.wanted_subjects.is_empty() && query.wanted_subject_dids.is_empty() 128 + || query.wanted_subjects.contains(&properties.subject) 129 + || properties 130 + .subject_did 131 + .as_ref() 132 + .map(|did| query.wanted_subject_dids.contains(did)) 133 + .unwrap_or(false)) 134 + { 135 + // wowwww ^^ fix that 136 + return false; 137 + } 138 + 139 + // subjects together with sources are logical AND 140 + if !(query.wanted_sources.is_empty() || query.wanted_sources.contains(&properties.source)) { 141 + return false; 142 + } 143 + 144 + true 145 + } 146 + } 147 + 148 + impl MultiSubscribeQuery { 149 + pub fn update_from_raw(&mut self, s: &str) -> Result<(), SubscriberUpdateError> { 150 + let SubscriberSourcedMessage::OptionsUpdate(opts) = 151 + serde_json::from_str(s).map_err(SubscriberUpdateError::FailedToParseMessage)?; 152 + if opts.wanted_sources.len() > 1_000 { 153 + return Err(SubscriberUpdateError::TooManySourcesWanted); 154 + } 155 + if opts.wanted_subject_dids.len() > 10_000 { 156 + return Err(SubscriberUpdateError::TooManyDidsWanted); 157 + } 158 + if opts.wanted_subjects.len() > 50_000 { 159 + return Err(SubscriberUpdateError::TooManySubjectsWanted); 160 + } 161 + *self = opts; 162 + Ok(()) 163 + } 164 + }
spacedust/static/favicon.ico

This is a binary file and will not be displayed.

+54
spacedust/static/index.html
··· 1 + <!doctype html> 2 + <html lang="en"> 3 + <head> 4 + <meta charset="utf-8" /> 5 + <title>Spacedust documentation</title> 6 + <meta name="viewport" content="width=device-width, initial-scale=1" /> 7 + <meta name="description" content="API Documentation for Spacedust, a configurable ATProto notifications firehose" /> 8 + <style> 9 + .custom-header { 10 + height: 42px; 11 + background-color: #221828; 12 + box-shadow: inset 0 -1px 0 var(--scalar-border-color); 13 + color: var(--scalar-color-1); 14 + font-size: var(--scalar-font-size-3); 15 + font-family: 'Iowan Old Style', 'Palatino Linotype', 'URW Palladio L', P052, serif; 16 + padding: 0 18px; 17 + justify-content: space-between; 18 + } 19 + .custom-header, 20 + .custom-header nav { 21 + display: flex; 22 + align-items: center; 23 + gap: 18px; 24 + } 25 + .custom-header a:hover { 26 + color: var(--scalar-color-2); 27 + } 28 + </style> 29 + </head> 30 + <body> 31 + <header class="custom-header scalar-app"> 32 + <p> 33 + TODO: pdsls jetstream link 34 + <a href="https://ufos.microcosm.blue">Launch 🛸 UFOs app</a>: Explore lexicons 35 + </p> 36 + <nav> 37 + <b>a <a href="https://microcosm.blue">microcosm</a> project</b> 38 + <a href="https://bsky.app/profile/microcosm.blue">@microcosm.blue</a> 39 + <a href="https://github.com/at-microcosm">github</a> 40 + </nav> 41 + </header> 42 + 43 + <script id="api-reference" type="application/json" data-url="/openapi"></script> 44 + 45 + <script> 46 + var configuration = { 47 + theme: 'purple', 48 + } 49 + document.getElementById('api-reference').dataset.configuration = JSON.stringify(configuration) 50 + </script> 51 + 52 + <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script> 53 + </body> 54 + </html>
+5 -3
ufos/Cargo.toml
··· 8 8 async-trait = "0.1.88" 9 9 base64 = "0.22.1" 10 10 bincode = { version = "2.0.1", features = ["serde"] } 11 - cardinality-estimator-safe = { version = "4.0.1", features = ["with_serde", "with_digest"] } 11 + cardinality-estimator-safe = { version = "4.0.2", features = ["with_serde", "with_digest"] } 12 12 chrono = { version = "0.4.41", features = ["serde"] } 13 13 clap = { version = "4.5.31", features = ["derive"] } 14 14 dropshot = "0.16.0" 15 15 env_logger = "0.11.7" 16 - fjall = { version = "2.8.0", features = ["lz4"] } 16 + fjall = { git = "https://github.com/fjall-rs/fjall.git", features = ["lz4"] } 17 17 getrandom = "0.3.3" 18 18 http = "1.3.1" 19 - jetstream = { path = "../jetstream" } 19 + jetstream = { path = "../jetstream", features = ["metrics"] } 20 20 log = "0.4.26" 21 21 lsm-tree = "2.6.6" 22 + metrics = "0.24.2" 23 + metrics-exporter-prometheus = { version = "0.17.0", default-features = false, features = ["http-listener"] } 22 24 schemars = { version = "0.8.22", features = ["raw_value", "chrono"] } 23 25 semver = "1.0.26" 24 26 serde = "1.0.219"
+38 -5
ufos/src/consumer.rs
··· 5 5 DefaultJetstreamEndpoints, JetstreamCompression, JetstreamConfig, JetstreamConnector, 6 6 JetstreamReceiver, 7 7 }; 8 + use metrics::{ 9 + counter, describe_counter, describe_gauge, describe_histogram, gauge, histogram, Unit, 10 + }; 8 11 use std::mem; 9 12 use std::time::Duration; 10 13 use tokio::sync::mpsc::{channel, Receiver, Sender}; ··· 79 82 batch_sender: Sender<LimitedBatch>, 80 83 sketch_secret: SketchSecretPrefix, 81 84 ) -> Self { 85 + describe_counter!( 86 + "batcher_batches_sent", 87 + Unit::Count, 88 + "how many batches of events were sent from Batcher to storage" 89 + ); 90 + describe_gauge!( 91 + "batcher_batch_age", 92 + Unit::Microseconds, 93 + "how old the last-sent batch was" 94 + ); 95 + describe_gauge!( 96 + "batcher_send_queue_capacity", 97 + Unit::Count, 98 + "how many spaces are available for batches in the send queue" 99 + ); 100 + describe_histogram!( 101 + "batcher_total_collections", 102 + Unit::Count, 103 + "how many collections are in this batch" 104 + ); 82 105 let mut rate_limit = tokio::time::interval(std::time::Duration::from_millis(3)); 83 106 rate_limit.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); 84 107 Self { ··· 188 211 // holds up all consumer progress until it can send to the channel 189 212 // use this when the current batch is too full to add more to it 190 213 async fn send_current_batch_now(&mut self, small: bool, referrer: &str) -> anyhow::Result<()> { 214 + let size_label = if small { "small" } else { "full" }; 215 + let queue_cap = self.batch_sender.capacity(); 216 + 217 + if let Some(cursor) = self.current_batch.initial_cursor { 218 + gauge!("batcher_batch_age", "size" => size_label).set(cursor.elapsed_micros_f64()); 219 + } 220 + histogram!("batcher_total_collections", "size" => size_label) 221 + .record(self.current_batch.batch.total_collections() as f64); 222 + gauge!("batcher_send_queue_capacity").set(queue_cap as f64); 223 + 191 224 let beginning = match self.current_batch.initial_cursor.map(|c| c.elapsed()) { 192 225 None => "unknown".to_string(), 193 - Some(Ok(t)) => format!("{:?}", t), 226 + Some(Ok(t)) => format!("{t:?}"), 194 227 Some(Err(e)) => format!("+{:?}", e.duration()), 195 228 }; 196 - log::info!( 197 - "sending batch now from {beginning}, {}, queue capacity: {}, referrer: {referrer}", 198 - if small { "small" } else { "full" }, 199 - self.batch_sender.capacity(), 229 + log::trace!( 230 + "sending batch now from {beginning}, {size_label}, queue capacity: {queue_cap}, referrer: {referrer}", 200 231 ); 201 232 let current = mem::take(&mut self.current_batch); 202 233 self.rate_limit.tick().await; 203 234 self.batch_sender 204 235 .send_timeout(current.batch, Duration::from_secs_f64(SEND_TIMEOUT_S)) 205 236 .await?; 237 + counter!("batcher_batches_sent", "size" => size_label, "referrer" => referrer.to_string()) 238 + .increment(1); 206 239 Ok(()) 207 240 } 208 241 }
+2 -2
ufos/src/db_types.rs
··· 427 427 ] { 428 428 let serialized = s.to_string().to_db_bytes()?; 429 429 let prefixed = String::sub_prefix(pre)?; 430 - assert_eq!(serialized.starts_with(&prefixed), is_pre, "{}", desc); 430 + assert_eq!(serialized.starts_with(&prefixed), is_pre, "{desc}"); 431 431 } 432 432 Ok(()) 433 433 } ··· 445 445 ] { 446 446 let serialized = Nsid::new(s.to_string()).unwrap().to_db_bytes()?; 447 447 let prefixed = Nsid::sub_prefix(pre)?; 448 - assert_eq!(serialized.starts_with(&prefixed), is_pre, "{}", desc); 448 + assert_eq!(serialized.starts_with(&prefixed), is_pre, "{desc}"); 449 449 } 450 450 Ok(()) 451 451 }
+6 -3
ufos/src/index_html.rs
··· 2 2 <html lang="en"> 3 3 <head> 4 4 <meta charset="utf-8" /> 5 - <title>UFOs API Documentation</title> 5 + <title>UFOs API documentation</title> 6 6 <meta name="viewport" content="width=device-width, initial-scale=1" /> 7 7 <meta name="description" content="API Documentation for UFOs: Samples and stats for all atproto lexicons." /> 8 8 <style> 9 9 .custom-header { 10 10 height: 42px; 11 - background-color: var(--scalar-background-1); 11 + background-color: #221828; 12 12 box-shadow: inset 0 -1px 0 var(--scalar-border-color); 13 13 color: var(--scalar-color-1); 14 14 font-size: var(--scalar-font-size-3); ··· 29 29 </head> 30 30 <body> 31 31 <header class="custom-header scalar-app"> 32 - <b>a <a href="https://microcosm.blue">microcosm</a> project</b> 32 + <p> 33 + <a href="https://ufos.microcosm.blue">Launch 🛸 UFOs app</a>: Explore lexicons 34 + </p> 33 35 <nav> 36 + <b>a <a href="https://microcosm.blue">microcosm</a> project</b> 34 37 <a href="https://bsky.app/profile/microcosm.blue">@microcosm.blue</a> 35 38 <a href="https://github.com/at-microcosm">github</a> 36 39 </nav>
+29 -3
ufos/src/lib.rs
··· 10 10 11 11 use crate::db_types::{EncodingError, EncodingResult}; 12 12 use crate::error::BatchInsertError; 13 - use crate::store_types::SketchSecretPrefix; 13 + use crate::store_types::{CountsValue, SketchSecretPrefix}; 14 14 use cardinality_estimator_safe::{Element, Sketch}; 15 15 use error::FirehoseEventError; 16 16 use jetstream::events::{CommitEvent, CommitOp, Cursor}; ··· 281 281 pub struct NsidCount { 282 282 nsid: String, 283 283 creates: u64, 284 - // TODO: add updates and deletes 284 + updates: u64, 285 + deletes: u64, 285 286 dids_estimate: u64, 287 + } 288 + impl NsidCount { 289 + pub fn new(nsid: &Nsid, counts: &CountsValue) -> Self { 290 + let crud = counts.counts(); 291 + Self { 292 + nsid: nsid.to_string(), 293 + creates: crud.creates, 294 + updates: crud.updates, 295 + deletes: crud.deletes, 296 + dids_estimate: counts.dids().estimate() as u64, 297 + } 298 + } 286 299 } 287 300 288 301 #[derive(Debug, PartialEq, Serialize, JsonSchema)] 289 302 pub struct PrefixCount { 290 303 prefix: String, 291 304 creates: u64, 292 - // TODO: add updates and deletes 305 + updates: u64, 306 + deletes: u64, 293 307 dids_estimate: u64, 308 + } 309 + impl PrefixCount { 310 + pub fn new(prefix: &str, counts: &CountsValue) -> Self { 311 + let crud = counts.counts(); 312 + Self { 313 + prefix: prefix.to_string(), 314 + creates: crud.creates, 315 + updates: crud.updates, 316 + deletes: crud.deletes, 317 + dids_estimate: counts.dids().estimate() as u64, 318 + } 319 + } 294 320 } 295 321 296 322 #[derive(Debug, PartialEq, Serialize, JsonSchema)]
+85 -11
ufos/src/main.rs
··· 1 1 use clap::Parser; 2 2 use jetstream::events::Cursor; 3 + use metrics::{describe_gauge, gauge, Unit}; 4 + use metrics_exporter_prometheus::PrometheusBuilder; 3 5 use std::path::PathBuf; 4 6 use std::time::{Duration, SystemTime}; 7 + use tokio::task::JoinSet; 5 8 use ufos::consumer; 6 9 use ufos::file_consumer; 7 10 use ufos::server; ··· 70 73 Ok(()) 71 74 } 72 75 73 - async fn go<B: StoreBackground>( 76 + async fn go<B: StoreBackground + 'static>( 74 77 args: Args, 75 78 read_store: impl StoreReader + 'static + Clone, 76 79 mut write_store: impl StoreWriter<B> + 'static, 77 80 cursor: Option<Cursor>, 78 81 sketch_secret: SketchSecretPrefix, 79 82 ) -> anyhow::Result<()> { 83 + let mut whatever_tasks: JoinSet<anyhow::Result<()>> = JoinSet::new(); 84 + let mut consumer_tasks: JoinSet<anyhow::Result<()>> = JoinSet::new(); 85 + 80 86 println!("starting server with storage..."); 81 87 let serving = server::serve(read_store.clone()); 88 + whatever_tasks.spawn(async move { 89 + serving.await.map_err(|e| { 90 + log::warn!("server ended: {e}"); 91 + anyhow::anyhow!(e) 92 + }) 93 + }); 82 94 83 95 if args.pause_writer { 84 96 log::info!("not starting jetstream or the write loop."); 85 - serving.await.map_err(|e| anyhow::anyhow!(e))?; 97 + for t in whatever_tasks.join_all().await { 98 + if let Err(e) = t { 99 + return Err(anyhow::anyhow!(e)); 100 + } 101 + } 86 102 return Ok(()); 87 103 } 88 104 ··· 100 116 let rolling = write_store 101 117 .background_tasks(args.reroll)? 102 118 .run(args.backfill); 103 - let consuming = write_store.receive_batches(batches); 119 + whatever_tasks.spawn(async move { 120 + rolling 121 + .await 122 + .inspect_err(|e| log::warn!("rollup ended: {e}"))?; 123 + Ok(()) 124 + }); 104 125 105 - let stating = do_update_stuff(read_store); 126 + consumer_tasks.spawn(async move { 127 + write_store 128 + .receive_batches(batches) 129 + .await 130 + .inspect_err(|e| log::warn!("consumer ended: {e}"))?; 131 + Ok(()) 132 + }); 106 133 107 - tokio::select! { 108 - z = serving => log::warn!("serve task ended: {z:?}"), 109 - z = rolling => log::warn!("rollup task ended: {z:?}"), 110 - z = consuming => log::warn!("consuming task ended: {z:?}"), 111 - z = stating => log::warn!("status task ended: {z:?}"), 112 - }; 134 + whatever_tasks.spawn(async move { 135 + do_update_stuff(read_store).await; 136 + log::warn!("status task ended"); 137 + Ok(()) 138 + }); 139 + 140 + install_metrics_server()?; 141 + 142 + for (i, t) in consumer_tasks.join_all().await.iter().enumerate() { 143 + log::warn!("task {i} done: {t:?}"); 144 + } 145 + 146 + println!("consumer tasks all completed, killing the others"); 147 + whatever_tasks.shutdown().await; 113 148 114 149 println!("bye!"); 115 150 116 151 Ok(()) 117 152 } 118 153 154 + fn install_metrics_server() -> anyhow::Result<()> { 155 + log::info!("installing metrics server..."); 156 + let host = [0, 0, 0, 0]; 157 + let port = 8765; 158 + PrometheusBuilder::new() 159 + .set_quantiles(&[0.5, 0.9, 0.99, 1.0])? 160 + .set_bucket_duration(Duration::from_secs(60))? 161 + .set_bucket_count(std::num::NonZero::new(10).unwrap()) // count * duration = 10 mins. stuff doesn't happen that fast here. 162 + .set_enable_unit_suffix(false) // this seemed buggy for constellation (sometimes wouldn't engage) 163 + .with_http_listener((host, port)) 164 + .install()?; 165 + log::info!( 166 + "metrics server installed! listening on http://{}.{}.{}.{}:{port}", 167 + host[0], 168 + host[1], 169 + host[2], 170 + host[3] 171 + ); 172 + Ok(()) 173 + } 174 + 119 175 async fn do_update_stuff(read_store: impl StoreReader) { 176 + describe_gauge!( 177 + "persisted_cursor_age", 178 + Unit::Microseconds, 179 + "microseconds between our clock and the latest persisted event's cursor" 180 + ); 181 + describe_gauge!( 182 + "rollup_cursor_age", 183 + Unit::Microseconds, 184 + "microseconds between our clock and the latest rollup cursor" 185 + ); 120 186 let started_at = std::time::SystemTime::now(); 121 187 let mut first_cursor = None; 122 188 let mut first_rollup = None; ··· 127 193 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); 128 194 loop { 129 195 interval.tick().await; 196 + read_store.update_metrics(); 130 197 match read_store.get_consumer_info().await { 131 198 Err(e) => log::warn!("failed to get jetstream consumer info: {e:?}"), 132 199 Ok(ConsumerInfo::Jetstream { ··· 170 237 started_at: SystemTime, 171 238 now: SystemTime, 172 239 ) { 240 + if let Some(cursor) = latest_cursor { 241 + gauge!("persisted_cursor_age").set(cursor.elapsed_micros_f64()); 242 + } 243 + if let Some(cursor) = rollup_cursor { 244 + gauge!("rollup_cursor_age").set(cursor.elapsed_micros_f64()); 245 + } 246 + 173 247 let nice_dt_two_maybes = |earlier: Option<Cursor>, later: Option<Cursor>| match (earlier, later) 174 248 { 175 249 (Some(earlier), Some(later)) => match later.duration_since(&earlier) { ··· 208 282 let rollup_rate = rate(rollup_cursor, last_rollup, dt_real); 209 283 let rollup_avg = rate(rollup_cursor, first_rollup, dt_real_total); 210 284 211 - log::info!( 285 + log::trace!( 212 286 "cursor: {} behind (→{}, {cursor_rate}x, {cursor_avg}x avg). rollup: {} behind (→{}, {rollup_rate}x, {rollup_avg}x avg).", 213 287 latest_cursor.map(|c| c.elapsed().map(nice_duration).unwrap_or("++".to_string())).unwrap_or("?".to_string()), 214 288 nice_dt_two_maybes(last_cursor, latest_cursor),
+1 -1
ufos/src/server/collections_query.rs
··· 53 53 ) -> Result<MultiCollectionQuery, HttpError> { 54 54 let raw_query = ctx.request.uri().query().unwrap_or(""); 55 55 let q = serde_qs::from_str(raw_query).map_err(|e| { 56 - HttpError::for_bad_request(None, format!("unable to parse query string: {}", e)) 56 + HttpError::for_bad_request(None, format!("unable to parse query string: {e}")) 57 57 })?; 58 58 Ok(q) 59 59 }
+310 -181
ufos/src/server/mod.rs
··· 19 19 use dropshot::ConfigLogging; 20 20 use dropshot::ConfigLoggingLevel; 21 21 use dropshot::HttpError; 22 + use dropshot::HttpResponse; 22 23 use dropshot::Query; 23 24 use dropshot::RequestContext; 24 25 use dropshot::ServerBuilder; 25 - 26 - use http::{Response, StatusCode}; 26 + use dropshot::ServerContext; 27 + use http::{ 28 + header::{ORIGIN, USER_AGENT}, 29 + Response, StatusCode, 30 + }; 31 + use metrics::{counter, describe_counter, describe_histogram, histogram, Unit}; 27 32 use schemars::JsonSchema; 28 33 use serde::{Deserialize, Serialize}; 29 34 use std::collections::{HashMap, HashSet}; 35 + use std::future::Future; 30 36 use std::sync::Arc; 37 + use std::time::Instant; 31 38 use std::time::{Duration, SystemTime, UNIX_EPOCH}; 32 39 40 + fn describe_metrics() { 41 + describe_counter!( 42 + "server_requests_total", 43 + Unit::Count, 44 + "total requests handled" 45 + ); 46 + describe_histogram!( 47 + "server_handler_latency", 48 + Unit::Microseconds, 49 + "time to respond to a request in microseconds, excluding dropshot overhead" 50 + ); 51 + } 52 + 53 + async fn instrument_handler<T, H, R>(ctx: &RequestContext<T>, handler: H) -> Result<R, HttpError> 54 + where 55 + R: HttpResponse, 56 + H: Future<Output = Result<R, HttpError>>, 57 + T: ServerContext, 58 + { 59 + let start = Instant::now(); 60 + let result = handler.await; 61 + let latency = start.elapsed(); 62 + let status_code = match &result { 63 + Ok(response) => response.status_code(), 64 + Err(ref e) => e.status_code.as_status(), 65 + } 66 + .as_str() // just the number (.to_string()'s Display does eg `200 OK`) 67 + .to_string(); 68 + let endpoint = ctx.endpoint.operation_id.clone(); 69 + let headers = ctx.request.headers(); 70 + let origin = headers 71 + .get(ORIGIN) 72 + .and_then(|v| v.to_str().ok()) 73 + .unwrap_or("") 74 + .to_string(); 75 + let ua = headers 76 + .get(USER_AGENT) 77 + .and_then(|v| v.to_str().ok()) 78 + .map(|ua| { 79 + if ua.starts_with("Mozilla/5.0 ") { 80 + "browser" 81 + } else { 82 + ua 83 + } 84 + }) 85 + .unwrap_or("") 86 + .to_string(); 87 + counter!("server_requests_total", 88 + "endpoint" => endpoint.clone(), 89 + "origin" => origin, 90 + "ua" => ua, 91 + "status_code" => status_code, 92 + ) 93 + .increment(1); 94 + histogram!("server_handler_latency", "endpoint" => endpoint).record(latency.as_micros() as f64); 95 + result 96 + } 97 + 33 98 struct Context { 34 99 pub spec: Arc<serde_json::Value>, 35 100 storage: Box<dyn StoreReader>, ··· 63 128 */ 64 129 unpublished = true, 65 130 }] 66 - async fn index(_ctx: RequestContext<Context>) -> Result<Response<Body>, HttpError> { 67 - Ok(Response::builder() 68 - .status(StatusCode::OK) 69 - .header(http::header::CONTENT_TYPE, "text/html") 70 - .body(INDEX_HTML.into())?) 131 + async fn index(ctx: RequestContext<Context>) -> Result<Response<Body>, HttpError> { 132 + instrument_handler(&ctx, async { 133 + Ok(Response::builder() 134 + .status(StatusCode::OK) 135 + .header(http::header::CONTENT_TYPE, "text/html") 136 + .body(INDEX_HTML.into())?) 137 + }) 138 + .await 71 139 } 72 140 73 141 /// Meta: get the openapi spec for this api ··· 80 148 unpublished = true, 81 149 }] 82 150 async fn get_openapi(ctx: RequestContext<Context>) -> OkCorsResponse<serde_json::Value> { 83 - let spec = (*ctx.context().spec).clone(); 84 - OkCors(spec).into() 151 + instrument_handler(&ctx, async { 152 + let spec = (*ctx.context().spec).clone(); 153 + OkCors(spec).into() 154 + }) 155 + .await 85 156 } 86 157 87 158 #[derive(Debug, Serialize, JsonSchema)] ··· 100 171 let failed_to_get = 101 172 |what| move |e| HttpError::for_internal_error(format!("failed to get {what}: {e:?}")); 102 173 103 - let storage_info = storage 104 - .get_storage_stats() 105 - .await 106 - .map_err(failed_to_get("storage info"))?; 174 + instrument_handler(&ctx, async { 175 + let storage_info = storage 176 + .get_storage_stats() 177 + .await 178 + .map_err(failed_to_get("storage info"))?; 107 179 108 - let consumer = storage 109 - .get_consumer_info() 110 - .await 111 - .map_err(failed_to_get("consumer info"))?; 180 + let consumer = storage 181 + .get_consumer_info() 182 + .await 183 + .map_err(failed_to_get("consumer info"))?; 112 184 113 - OkCors(MetaInfo { 114 - storage_name: storage.name(), 115 - storage: storage_info, 116 - consumer, 185 + OkCors(MetaInfo { 186 + storage_name: storage.name(), 187 + storage: storage_info, 188 + consumer, 189 + }) 190 + .into() 117 191 }) 118 - .into() 192 + .await 119 193 } 120 194 121 195 // TODO: replace with normal (🙃) multi-qs value somehow ··· 168 242 collection_query: Query<RecordsCollectionsQuery>, 169 243 ) -> OkCorsResponse<Vec<ApiRecord>> { 170 244 let Context { storage, .. } = ctx.context(); 171 - let mut limit = 42; 172 - let query = collection_query.into_inner(); 173 - let collections = if let Some(provided_collection) = query.collection { 174 - to_multiple_nsids(&provided_collection) 175 - .map_err(|reason| HttpError::for_bad_request(None, reason))? 176 - } else { 177 - limit = 12; 178 - let min_time_ago = SystemTime::now() - Duration::from_secs(86_400 * 3); // we want at least 3 days of data 179 - let since: WeekTruncatedCursor = Cursor::at(min_time_ago).into(); 180 - let (collections, _) = storage 181 - .get_collections( 182 - 1000, 183 - Default::default(), 184 - Some(since.try_as().unwrap()), 185 - None, 186 - ) 245 + instrument_handler(&ctx, async { 246 + let mut limit = 42; 247 + let query = collection_query.into_inner(); 248 + let collections = if let Some(provided_collection) = query.collection { 249 + to_multiple_nsids(&provided_collection) 250 + .map_err(|reason| HttpError::for_bad_request(None, reason))? 251 + } else { 252 + limit = 12; 253 + let min_time_ago = SystemTime::now() - Duration::from_secs(86_400 * 3); // we want at least 3 days of data 254 + let since: WeekTruncatedCursor = Cursor::at(min_time_ago).into(); 255 + let (collections, _) = storage 256 + .get_collections( 257 + 1000, 258 + Default::default(), 259 + Some(since.try_as().unwrap()), 260 + None, 261 + ) 262 + .await 263 + .map_err(|e| HttpError::for_internal_error(e.to_string()))?; 264 + collections 265 + .into_iter() 266 + .map(|c| Nsid::new(c.nsid).unwrap()) 267 + .collect() 268 + }; 269 + 270 + let records = storage 271 + .get_records_by_collections(collections, limit, true) 187 272 .await 188 - .map_err(|e| HttpError::for_internal_error(e.to_string()))?; 189 - collections 273 + .map_err(|e| HttpError::for_internal_error(e.to_string()))? 190 274 .into_iter() 191 - .map(|c| Nsid::new(c.nsid).unwrap()) 192 - .collect() 193 - }; 275 + .map(|r| r.into()) 276 + .collect(); 194 277 195 - let records = storage 196 - .get_records_by_collections(collections, limit, true) 197 - .await 198 - .map_err(|e| HttpError::for_internal_error(e.to_string()))? 199 - .into_iter() 200 - .map(|r| r.into()) 201 - .collect(); 202 - 203 - OkCors(records).into() 278 + OkCors(records).into() 279 + }) 280 + .await 204 281 } 205 282 206 283 #[derive(Debug, Deserialize, JsonSchema)] ··· 232 309 query: Query<CollectionsStatsQuery>, 233 310 ) -> OkCorsResponse<HashMap<String, JustCount>> { 234 311 let Context { storage, .. } = ctx.context(); 235 - let q = query.into_inner(); 236 - let collections: HashSet<Nsid> = collections_query.try_into()?; 312 + 313 + instrument_handler(&ctx, async { 314 + let q = query.into_inner(); 315 + let collections: HashSet<Nsid> = collections_query.try_into()?; 237 316 238 - let since = q.since.map(dt_to_cursor).transpose()?.unwrap_or_else(|| { 239 - let week_ago_secs = 7 * 86_400; 240 - let week_ago = SystemTime::now() - Duration::from_secs(week_ago_secs); 241 - Cursor::at(week_ago).into() 242 - }); 317 + let since = q.since.map(dt_to_cursor).transpose()?.unwrap_or_else(|| { 318 + let week_ago_secs = 7 * 86_400; 319 + let week_ago = SystemTime::now() - Duration::from_secs(week_ago_secs); 320 + Cursor::at(week_ago).into() 321 + }); 243 322 244 - let until = q.until.map(dt_to_cursor).transpose()?; 323 + let until = q.until.map(dt_to_cursor).transpose()?; 245 324 246 - let mut seen_by_collection = HashMap::with_capacity(collections.len()); 325 + let mut seen_by_collection = HashMap::with_capacity(collections.len()); 247 326 248 - for collection in &collections { 249 - let counts = storage 250 - .get_collection_counts(collection, since, until) 251 - .await 252 - .map_err(|e| HttpError::for_internal_error(format!("boooo: {e:?}")))?; 327 + for collection in &collections { 328 + let counts = storage 329 + .get_collection_counts(collection, since, until) 330 + .await 331 + .map_err(|e| HttpError::for_internal_error(format!("boooo: {e:?}")))?; 253 332 254 - seen_by_collection.insert(collection.to_string(), counts); 255 - } 333 + seen_by_collection.insert(collection.to_string(), counts); 334 + } 256 335 257 - OkCors(seen_by_collection).into() 336 + OkCors(seen_by_collection).into() 337 + }) 338 + .await 258 339 } 259 340 260 341 #[derive(Debug, Serialize, JsonSchema)] ··· 337 418 let Context { storage, .. } = ctx.context(); 338 419 let q = query.into_inner(); 339 420 340 - if q.cursor.is_some() && q.order.is_some() { 341 - let msg = "`cursor` is mutually exclusive with `order`. ordered results cannot be paged."; 342 - return Err(HttpError::for_bad_request(None, msg.to_string())); 343 - } 421 + instrument_handler(&ctx, async { 422 + if q.cursor.is_some() && q.order.is_some() { 423 + let msg = 424 + "`cursor` is mutually exclusive with `order`. ordered results cannot be paged."; 425 + return Err(HttpError::for_bad_request(None, msg.to_string())); 426 + } 344 427 345 - let order = if let Some(ref o) = q.order { 346 - o.into() 347 - } else { 348 - let cursor = q 349 - .cursor 350 - .and_then(|c| if c.is_empty() { None } else { Some(c) }) 351 - .map(|c| URL_SAFE_NO_PAD.decode(&c)) 352 - .transpose() 353 - .map_err(|e| HttpError::for_bad_request(None, format!("invalid cursor: {e:?}")))?; 354 - OrderCollectionsBy::Lexi { cursor } 355 - }; 428 + let order = if let Some(ref o) = q.order { 429 + o.into() 430 + } else { 431 + let cursor = q 432 + .cursor 433 + .and_then(|c| if c.is_empty() { None } else { Some(c) }) 434 + .map(|c| URL_SAFE_NO_PAD.decode(&c)) 435 + .transpose() 436 + .map_err(|e| HttpError::for_bad_request(None, format!("invalid cursor: {e:?}")))?; 437 + OrderCollectionsBy::Lexi { cursor } 438 + }; 356 439 357 - let limit = match (q.limit, q.order) { 358 - (Some(limit), _) => limit, 359 - (None, Some(_)) => 32, 360 - (None, None) => 100, 361 - }; 440 + let limit = match (q.limit, q.order) { 441 + (Some(limit), _) => limit, 442 + (None, Some(_)) => 32, 443 + (None, None) => 100, 444 + }; 362 445 363 - if !(1..=200).contains(&limit) { 364 - let msg = format!("limit not in 1..=200: {}", limit); 365 - return Err(HttpError::for_bad_request(None, msg)); 366 - } 446 + if !(1..=200).contains(&limit) { 447 + let msg = format!("limit not in 1..=200: {limit}"); 448 + return Err(HttpError::for_bad_request(None, msg)); 449 + } 367 450 368 - let since = q.since.map(dt_to_cursor).transpose()?; 369 - let until = q.until.map(dt_to_cursor).transpose()?; 451 + let since = q.since.map(dt_to_cursor).transpose()?; 452 + let until = q.until.map(dt_to_cursor).transpose()?; 370 453 371 - let (collections, next_cursor) = storage 372 - .get_collections(limit, order, since, until) 373 - .await 374 - .map_err(|e| HttpError::for_internal_error(format!("oh shoot: {e:?}")))?; 454 + let (collections, next_cursor) = storage 455 + .get_collections(limit, order, since, until) 456 + .await 457 + .map_err(|e| HttpError::for_internal_error(format!("oh shoot: {e:?}")))?; 375 458 376 - let next_cursor = next_cursor.map(|c| URL_SAFE_NO_PAD.encode(c)); 459 + let next_cursor = next_cursor.map(|c| URL_SAFE_NO_PAD.encode(c)); 377 460 378 - OkCors(CollectionsResponse { 379 - collections, 380 - cursor: next_cursor, 461 + OkCors(CollectionsResponse { 462 + collections, 463 + cursor: next_cursor, 464 + }) 465 + .into() 381 466 }) 382 - .into() 467 + .await 383 468 } 384 469 385 470 #[derive(Debug, Serialize, JsonSchema)] ··· 459 544 let Context { storage, .. } = ctx.context(); 460 545 let q = query.into_inner(); 461 546 462 - let prefix = NsidPrefix::new(&q.prefix).map_err(|e| { 463 - HttpError::for_bad_request( 464 - None, 465 - format!("{:?} was not a valid NSID prefix: {e:?}", q.prefix), 466 - ) 467 - })?; 547 + instrument_handler(&ctx, async { 548 + let prefix = NsidPrefix::new(&q.prefix).map_err(|e| { 549 + HttpError::for_bad_request( 550 + None, 551 + format!("{:?} was not a valid NSID prefix: {e:?}", q.prefix), 552 + ) 553 + })?; 468 554 469 - if q.cursor.is_some() && q.order.is_some() { 470 - let msg = "`cursor` is mutually exclusive with `order`. ordered results cannot be paged."; 471 - return Err(HttpError::for_bad_request(None, msg.to_string())); 472 - } 555 + if q.cursor.is_some() && q.order.is_some() { 556 + let msg = 557 + "`cursor` is mutually exclusive with `order`. ordered results cannot be paged."; 558 + return Err(HttpError::for_bad_request(None, msg.to_string())); 559 + } 473 560 474 - let order = if let Some(ref o) = q.order { 475 - o.into() 476 - } else { 477 - let cursor = q 478 - .cursor 479 - .and_then(|c| if c.is_empty() { None } else { Some(c) }) 480 - .map(|c| URL_SAFE_NO_PAD.decode(&c)) 481 - .transpose() 482 - .map_err(|e| HttpError::for_bad_request(None, format!("invalid cursor: {e:?}")))?; 483 - OrderCollectionsBy::Lexi { cursor } 484 - }; 561 + let order = if let Some(ref o) = q.order { 562 + o.into() 563 + } else { 564 + let cursor = q 565 + .cursor 566 + .and_then(|c| if c.is_empty() { None } else { Some(c) }) 567 + .map(|c| URL_SAFE_NO_PAD.decode(&c)) 568 + .transpose() 569 + .map_err(|e| HttpError::for_bad_request(None, format!("invalid cursor: {e:?}")))?; 570 + OrderCollectionsBy::Lexi { cursor } 571 + }; 485 572 486 - let limit = match (q.limit, q.order) { 487 - (Some(limit), _) => limit, 488 - (None, Some(_)) => 32, 489 - (None, None) => 100, 490 - }; 573 + let limit = match (q.limit, q.order) { 574 + (Some(limit), _) => limit, 575 + (None, Some(_)) => 32, 576 + (None, None) => 100, 577 + }; 491 578 492 - if !(1..=200).contains(&limit) { 493 - let msg = format!("limit not in 1..=200: {}", limit); 494 - return Err(HttpError::for_bad_request(None, msg)); 495 - } 579 + if !(1..=200).contains(&limit) { 580 + let msg = format!("limit not in 1..=200: {limit}"); 581 + return Err(HttpError::for_bad_request(None, msg)); 582 + } 496 583 497 - let since = q.since.map(dt_to_cursor).transpose()?; 498 - let until = q.until.map(dt_to_cursor).transpose()?; 584 + let since = q.since.map(dt_to_cursor).transpose()?; 585 + let until = q.until.map(dt_to_cursor).transpose()?; 499 586 500 - let (total, children, next_cursor) = storage 501 - .get_prefix(prefix, limit, order, since, until) 502 - .await 503 - .map_err(|e| HttpError::for_internal_error(format!("oh shoot: {e:?}")))?; 587 + let (total, children, next_cursor) = storage 588 + .get_prefix(prefix, limit, order, since, until) 589 + .await 590 + .map_err(|e| HttpError::for_internal_error(format!("oh shoot: {e:?}")))?; 504 591 505 - let next_cursor = next_cursor.map(|c| URL_SAFE_NO_PAD.encode(c)); 592 + let next_cursor = next_cursor.map(|c| URL_SAFE_NO_PAD.encode(c)); 506 593 507 - OkCors(PrefixResponse { 508 - total, 509 - children, 510 - cursor: next_cursor, 594 + OkCors(PrefixResponse { 595 + total, 596 + children, 597 + cursor: next_cursor, 598 + }) 599 + .into() 511 600 }) 512 - .into() 601 + .await 513 602 } 514 603 515 604 #[derive(Debug, Deserialize, JsonSchema)] ··· 549 638 let Context { storage, .. } = ctx.context(); 550 639 let q = query.into_inner(); 551 640 552 - let since = q.since.map(dt_to_cursor).transpose()?.unwrap_or_else(|| { 553 - let week_ago_secs = 7 * 86_400; 554 - let week_ago = SystemTime::now() - Duration::from_secs(week_ago_secs); 555 - Cursor::at(week_ago).into() 556 - }); 641 + instrument_handler(&ctx, async { 642 + let since = q.since.map(dt_to_cursor).transpose()?.unwrap_or_else(|| { 643 + let week_ago_secs = 7 * 86_400; 644 + let week_ago = SystemTime::now() - Duration::from_secs(week_ago_secs); 645 + Cursor::at(week_ago).into() 646 + }); 557 647 558 - let until = q.until.map(dt_to_cursor).transpose()?; 648 + let until = q.until.map(dt_to_cursor).transpose()?; 559 649 560 - let step = if let Some(secs) = q.step { 561 - if secs < 3600 { 562 - let msg = format!("step is too small: {}", secs); 563 - Err(HttpError::for_bad_request(None, msg))?; 564 - } 565 - (secs / 3600) * 3600 // trucate to hour 566 - } else { 567 - 86_400 568 - }; 650 + let step = if let Some(secs) = q.step { 651 + if secs < 3600 { 652 + let msg = format!("step is too small: {secs}"); 653 + Err(HttpError::for_bad_request(None, msg))?; 654 + } 655 + (secs / 3600) * 3600 // trucate to hour 656 + } else { 657 + 86_400 658 + }; 569 659 570 - let nsid = Nsid::new(q.collection).map_err(|e| { 571 - HttpError::for_bad_request(None, format!("collection was not a valid NSID: {:?}", e)) 572 - })?; 660 + let nsid = Nsid::new(q.collection).map_err(|e| { 661 + HttpError::for_bad_request(None, format!("collection was not a valid NSID: {e:?}")) 662 + })?; 573 663 574 - let (range_cursors, series) = storage 575 - .get_timeseries(vec![nsid], since, until, step) 576 - .await 577 - .map_err(|e| HttpError::for_internal_error(format!("oh shoot: {e:?}")))?; 664 + let (range_cursors, series) = storage 665 + .get_timeseries(vec![nsid], since, until, step) 666 + .await 667 + .map_err(|e| HttpError::for_internal_error(format!("oh shoot: {e:?}")))?; 578 668 579 - let range = range_cursors 580 - .into_iter() 581 - .map(|c| DateTime::<Utc>::from_timestamp_micros(c.to_raw_u64() as i64).unwrap()) 582 - .collect(); 669 + let range = range_cursors 670 + .into_iter() 671 + .map(|c| DateTime::<Utc>::from_timestamp_micros(c.to_raw_u64() as i64).unwrap()) 672 + .collect(); 583 673 584 - let series = series 585 - .into_iter() 586 - .map(|(k, v)| (k.to_string(), v.iter().map(Into::into).collect())) 587 - .collect(); 674 + let series = series 675 + .into_iter() 676 + .map(|(k, v)| (k.to_string(), v.iter().map(Into::into).collect())) 677 + .collect(); 678 + 679 + OkCors(CollectionTimeseriesResponse { range, series }).into() 680 + }) 681 + .await 682 + } 588 683 589 - OkCors(CollectionTimeseriesResponse { range, series }).into() 684 + #[derive(Debug, Deserialize, JsonSchema)] 685 + struct SearchQuery { 686 + /// Query 687 + /// 688 + /// at least two alphanumeric (+hyphen) characters must be present 689 + q: String, 690 + } 691 + #[derive(Debug, Serialize, JsonSchema)] 692 + struct SearchResponse { 693 + matches: Vec<NsidCount>, 694 + } 695 + /// Search lexicons 696 + #[endpoint { 697 + method = GET, 698 + path = "/search" 699 + }] 700 + async fn search_collections( 701 + ctx: RequestContext<Context>, 702 + query: Query<SearchQuery>, 703 + ) -> OkCorsResponse<SearchResponse> { 704 + let Context { storage, .. } = ctx.context(); 705 + let q = query.into_inner(); 706 + instrument_handler(&ctx, async { 707 + // TODO: query validation 708 + // TODO: also handle multi-space stuff (ufos-app tries to on client) 709 + let terms: Vec<String> = q.q.split(' ').map(Into::into).collect(); 710 + let matches = storage 711 + .search_collections(terms) 712 + .await 713 + .map_err(|e| HttpError::for_internal_error(format!("oh ugh: {e:?}")))?; 714 + OkCors(SearchResponse { matches }).into() 715 + }) 716 + .await 590 717 } 591 718 592 719 pub async fn serve(storage: impl StoreReader + 'static) -> Result<(), String> { 720 + describe_metrics(); 593 721 let log = ConfigLogging::StderrTerminal { 594 - level: ConfigLoggingLevel::Info, 722 + level: ConfigLoggingLevel::Warn, 595 723 } 596 - .to_logger("hello-ufos") 724 + .to_logger("server") 597 725 .map_err(|e| e.to_string())?; 598 726 599 727 let mut api = ApiDescription::new(); ··· 606 734 api.register(get_collections).unwrap(); 607 735 api.register(get_prefix).unwrap(); 608 736 api.register(get_timeseries).unwrap(); 737 + api.register(search_collections).unwrap(); 609 738 610 739 let context = Context { 611 740 spec: Arc::new( 612 741 api.openapi( 613 - "UFOs: Every lexicon in the ATmosphere", 742 + "UFOs API: Every lexicon in the ATmosphere", 614 743 env!("CARGO_PKG_VERSION") 615 744 .parse() 616 745 .inspect_err(|e| { ··· 633 762 ..Default::default() 634 763 }) 635 764 .start() 636 - .map_err(|error| format!("failed to start server: {}", error))? 765 + .map_err(|error| format!("failed to start server: {error}"))? 637 766 .await 638 767 }
+26 -5
ufos/src/storage.rs
··· 5 5 }; 6 6 use async_trait::async_trait; 7 7 use jetstream::exports::{Did, Nsid}; 8 + use metrics::{describe_histogram, histogram, Unit}; 8 9 use std::collections::{HashMap, HashSet}; 9 10 use std::path::Path; 10 - use std::time::{Duration, SystemTime}; 11 + use std::time::{Duration, Instant}; 11 12 use tokio::sync::mpsc::Receiver; 12 13 use tokio_util::sync::CancellationToken; 13 14 ··· 35 36 self, 36 37 mut batches: Receiver<EventBatch<LIMIT>>, 37 38 ) -> StorageResult<()> { 39 + describe_histogram!( 40 + "storage_slow_batches", 41 + Unit::Microseconds, 42 + "batches that took more than 3s to insert" 43 + ); 44 + describe_histogram!( 45 + "storage_batch_insert_time", 46 + Unit::Microseconds, 47 + "total time to insert one commit batch" 48 + ); 38 49 while let Some(event_batch) = batches.recv().await { 39 50 let token = CancellationToken::new(); 40 51 let cancelled = token.clone(); 41 52 tokio::spawn(async move { 42 - let started = SystemTime::now(); 53 + let started = Instant::now(); 43 54 let mut concerned = false; 44 55 loop { 45 56 tokio::select! { 46 - _ = tokio::time::sleep(Duration::from_secs_f64(3.)) => { 47 - log::warn!("taking a long time to insert an event batch ({:?})...", started.elapsed()); 57 + _ = tokio::time::sleep(Duration::from_secs(3)) => { 58 + if !concerned { 59 + log::warn!("taking a long time to insert an event batch..."); 60 + } 48 61 concerned = true; 49 62 } 50 63 _ = cancelled.cancelled() => { 51 64 if concerned { 52 65 log::warn!("finally inserted slow event batch (or failed) after {:?}", started.elapsed()); 66 + histogram!("storage_slow_batches").record(started.elapsed().as_micros() as f64); 53 67 } 54 68 break 55 69 } ··· 60 74 let mut me = self.clone(); 61 75 move || { 62 76 let _guard = token.drop_guard(); 63 - me.insert_batch(event_batch) 77 + let t0 = Instant::now(); 78 + let r = me.insert_batch(event_batch); 79 + histogram!("storage_batch_insert_time").record(t0.elapsed().as_micros() as f64); 80 + r 64 81 } 65 82 }) 66 83 .await??; ··· 94 111 #[async_trait] 95 112 pub trait StoreReader: Send + Sync { 96 113 fn name(&self) -> String; 114 + 115 + fn update_metrics(&self) {} 97 116 98 117 async fn get_storage_stats(&self) -> StorageResult<serde_json::Value>; 99 118 ··· 137 156 limit: usize, 138 157 expand_each_collection: bool, 139 158 ) -> StorageResult<Vec<UFOsRecord>>; 159 + 160 + async fn search_collections(&self, terms: Vec<String>) -> StorageResult<Vec<NsidCount>>; 140 161 }
+182 -54
ufos/src/storage_fjall.rs
··· 23 23 Batch as FjallBatch, Config, Keyspace, PartitionCreateOptions, PartitionHandle, Snapshot, 24 24 }; 25 25 use jetstream::events::Cursor; 26 + use lsm_tree::AbstractTree; 27 + use metrics::{ 28 + counter, describe_counter, describe_gauge, describe_histogram, gauge, histogram, Unit, 29 + }; 26 30 use std::collections::{HashMap, HashSet}; 27 31 use std::iter::Peekable; 28 32 use std::ops::Bound; ··· 39 43 /// 40 44 /// new data format, roughly: 41 45 /// 42 - /// Partion: 'global' 46 + /// Partition: 'global' 43 47 /// 44 48 /// - Global sequence counter (is the jetstream cursor -- monotonic with many gaps) 45 49 /// - key: "js_cursor" (literal) ··· 226 230 feeds: feeds.clone(), 227 231 records: records.clone(), 228 232 rollups: rollups.clone(), 233 + queues: queues.clone(), 229 234 }; 235 + reader.describe_metrics(); 230 236 let writer = FjallWriter { 231 237 bg_taken: Arc::new(AtomicBool::new(false)), 232 238 keyspace, ··· 236 242 rollups, 237 243 queues, 238 244 }; 245 + writer.describe_metrics(); 239 246 Ok((reader, writer, js_cursor, sketch_secret)) 240 247 } 241 248 } ··· 249 256 feeds: PartitionHandle, 250 257 records: PartitionHandle, 251 258 rollups: PartitionHandle, 259 + queues: PartitionHandle, 252 260 } 253 261 254 262 /// An iterator that knows how to skip over deleted/invalidated records ··· 380 388 type CollectionSerieses = HashMap<Nsid, Vec<CountsValue>>; 381 389 382 390 impl FjallReader { 391 + fn describe_metrics(&self) { 392 + describe_gauge!( 393 + "storage_fjall_l0_run_count", 394 + Unit::Count, 395 + "number of L0 runs in a partition" 396 + ); 397 + describe_gauge!( 398 + "storage_fjall_keyspace_disk_space", 399 + Unit::Bytes, 400 + "total storage used according to fjall" 401 + ); 402 + describe_gauge!( 403 + "storage_fjall_journal_count", 404 + Unit::Count, 405 + "total keyspace journals according to fjall" 406 + ); 407 + describe_gauge!( 408 + "storage_fjall_keyspace_sequence", 409 + Unit::Count, 410 + "fjall keyspace sequence" 411 + ); 412 + } 413 + 383 414 fn get_storage_stats(&self) -> StorageResult<serde_json::Value> { 384 415 let rollup_cursor = 385 416 get_static_neu::<NewRollupCursorKey, NewRollupCursorValue>(&self.global)? ··· 507 538 merged.merge(&counts); 508 539 } 509 540 } 510 - out.push(NsidCount { 511 - nsid: nsid.to_string(), 512 - creates: merged.counts().creates, 513 - dids_estimate: merged.dids().estimate() as u64, 514 - }); 541 + out.push(NsidCount::new(&nsid, &merged)); 515 542 } 516 543 517 544 let next_cursor = current_nsid.map(|s| s.to_db_bytes()).transpose()?; ··· 617 644 .into_iter() 618 645 .rev() 619 646 .take(limit) 620 - .map(|(nsid, cv)| NsidCount { 621 - nsid: nsid.to_string(), 622 - creates: cv.counts().creates, 623 - dids_estimate: cv.dids().estimate() as u64, 624 - }) 647 + .map(|(nsid, cv)| NsidCount::new(&nsid, &cv)) 625 648 .collect(); 626 649 Ok(counts) 627 650 } ··· 727 750 let mut prefix_count = CountsValue::default(); 728 751 #[derive(Debug, Clone, PartialEq)] 729 752 enum Child { 730 - FullNsid(String), 753 + FullNsid(Nsid), 731 754 ChildPrefix(String), 732 755 } 733 756 impl Child { 734 757 fn from_prefix(nsid: &Nsid, prefix: &NsidPrefix) -> Option<Self> { 735 758 if prefix.is_group_of(nsid) { 736 - return Some(Child::FullNsid(nsid.to_string())); 759 + return Some(Child::FullNsid(nsid.clone())); 737 760 } 738 761 let suffix = nsid.as_str().strip_prefix(&format!("{}.", prefix.0))?; 739 762 let (segment, _) = suffix.split_once('.').unwrap(); ··· 742 765 } 743 766 fn is_before(&self, other: &Child) -> bool { 744 767 match (self, other) { 745 - (Child::FullNsid(s), Child::ChildPrefix(o)) if s == o => true, 746 - (Child::ChildPrefix(s), Child::FullNsid(o)) if s == o => false, 747 - (Child::FullNsid(s), Child::FullNsid(o)) => s < o, 768 + (Child::FullNsid(s), Child::ChildPrefix(o)) if s.as_str() == o => true, 769 + (Child::ChildPrefix(s), Child::FullNsid(o)) if s == o.as_str() => false, 770 + (Child::FullNsid(s), Child::FullNsid(o)) => s.as_str() < o.as_str(), 748 771 (Child::ChildPrefix(s), Child::ChildPrefix(o)) => s < o, 749 - (Child::FullNsid(s), Child::ChildPrefix(o)) => s < o, 750 - (Child::ChildPrefix(s), Child::FullNsid(o)) => s < o, 772 + (Child::FullNsid(s), Child::ChildPrefix(o)) => s.to_string() < *o, 773 + (Child::ChildPrefix(s), Child::FullNsid(o)) => *s < o.to_string(), 751 774 } 752 775 } 753 776 fn into_inner(self) -> String { 754 777 match self { 755 - Child::FullNsid(s) => s, 778 + Child::FullNsid(s) => s.to_string(), 756 779 Child::ChildPrefix(s) => s, 757 780 } 758 781 } ··· 791 814 } 792 815 } 793 816 items.push(match child { 794 - Child::FullNsid(nsid) => PrefixChild::Collection(NsidCount { 795 - nsid, 796 - creates: merged.counts().creates, 797 - dids_estimate: merged.dids().estimate() as u64, 798 - }), 799 - Child::ChildPrefix(prefix) => PrefixChild::Prefix(PrefixCount { 800 - prefix, 801 - creates: merged.counts().creates, 802 - dids_estimate: merged.dids().estimate() as u64, 803 - }), 817 + Child::FullNsid(nsid) => PrefixChild::Collection(NsidCount::new(&nsid, &merged)), 818 + Child::ChildPrefix(prefix) => { 819 + PrefixChild::Prefix(PrefixCount::new(&prefix, &merged)) 820 + } 804 821 }); 805 822 } 806 823 ··· 982 999 } 983 1000 Ok(merged) 984 1001 } 1002 + 1003 + fn search_collections(&self, terms: Vec<String>) -> StorageResult<Vec<NsidCount>> { 1004 + let start = AllTimeRollupKey::start()?; 1005 + let end = AllTimeRollupKey::end()?; 1006 + let mut matches = Vec::new(); 1007 + let limit = 16; // TODO: param 1008 + for kv in self.rollups.range((start, end)) { 1009 + let (key_bytes, val_bytes) = kv?; 1010 + let key = db_complete::<AllTimeRollupKey>(&key_bytes)?; 1011 + let nsid = key.collection(); 1012 + for term in &terms { 1013 + if nsid.contains(term) { 1014 + let counts = db_complete::<CountsValue>(&val_bytes)?; 1015 + matches.push(NsidCount::new(nsid, &counts)); 1016 + break; 1017 + } 1018 + } 1019 + if matches.len() >= limit { 1020 + break; 1021 + } 1022 + } 1023 + // TODO: indicate incomplete results 1024 + Ok(matches) 1025 + } 985 1026 } 986 1027 987 1028 #[async_trait] 988 1029 impl StoreReader for FjallReader { 989 1030 fn name(&self) -> String { 990 1031 "fjall storage v2".into() 1032 + } 1033 + fn update_metrics(&self) { 1034 + gauge!("storage_fjall_l0_run_count", "partition" => "global") 1035 + .set(self.global.tree.l0_run_count() as f64); 1036 + gauge!("storage_fjall_l0_run_count", "partition" => "feeds") 1037 + .set(self.feeds.tree.l0_run_count() as f64); 1038 + gauge!("storage_fjall_l0_run_count", "partition" => "records") 1039 + .set(self.records.tree.l0_run_count() as f64); 1040 + gauge!("storage_fjall_l0_run_count", "partition" => "rollups") 1041 + .set(self.rollups.tree.l0_run_count() as f64); 1042 + gauge!("storage_fjall_l0_run_count", "partition" => "queues") 1043 + .set(self.queues.tree.l0_run_count() as f64); 1044 + gauge!("storage_fjall_keyspace_disk_space").set(self.keyspace.disk_space() as f64); 1045 + gauge!("storage_fjall_journal_count").set(self.keyspace.journal_count() as f64); 1046 + gauge!("storage_fjall_keyspace_sequence").set(self.keyspace.instant() as f64); 991 1047 } 992 1048 async fn get_storage_stats(&self) -> StorageResult<serde_json::Value> { 993 1049 let s = self.clone(); ··· 1061 1117 FjallReader::get_records_by_collections(&s, collections, limit, expand_each_collection) 1062 1118 }) 1063 1119 .await? 1120 + } 1121 + async fn search_collections(&self, terms: Vec<String>) -> StorageResult<Vec<NsidCount>> { 1122 + let s = self.clone(); 1123 + tokio::task::spawn_blocking(move || FjallReader::search_collections(&s, terms)).await? 1064 1124 } 1065 1125 } 1066 1126 ··· 1076 1136 } 1077 1137 1078 1138 impl FjallWriter { 1139 + fn describe_metrics(&self) { 1140 + describe_histogram!( 1141 + "storage_insert_batch_db_batch_items", 1142 + Unit::Count, 1143 + "how many items are in the fjall batch for batched inserts" 1144 + ); 1145 + describe_histogram!( 1146 + "storage_rollup_counts_db_batch_items", 1147 + Unit::Count, 1148 + "how many items are in the fjall batch for a timlies rollup" 1149 + ); 1150 + describe_counter!( 1151 + "storage_delete_account_partial_commits", 1152 + Unit::Count, 1153 + "fjall checkpoint commits for cleaning up accounts with too many records" 1154 + ); 1155 + describe_counter!( 1156 + "storage_delete_account_completions", 1157 + Unit::Count, 1158 + "total count of account deletes handled" 1159 + ); 1160 + describe_counter!( 1161 + "storage_delete_account_records_deleted", 1162 + Unit::Count, 1163 + "total records deleted when handling account deletes" 1164 + ); 1165 + describe_histogram!( 1166 + "storage_trim_dirty_nsids", 1167 + Unit::Count, 1168 + "number of NSIDs trimmed" 1169 + ); 1170 + describe_histogram!( 1171 + "storage_trim_duration", 1172 + Unit::Microseconds, 1173 + "how long it took to trim the dirty NSIDs" 1174 + ); 1175 + describe_counter!( 1176 + "storage_trim_removed", 1177 + Unit::Count, 1178 + "how many records were removed during trim" 1179 + ); 1180 + } 1079 1181 fn rollup_delete_account( 1080 1182 &mut self, 1081 1183 cursor: Cursor, ··· 1207 1309 AllTimeRecordsKey::new(new_creates_count.into(), &nsid).to_db_bytes()?, 1208 1310 ), 1209 1311 }; 1210 - batch.remove(&self.rollups, &old_k); // TODO: when fjall gets weak delete, this will hopefully work way better 1312 + // remove_weak is allowed here because the secondary ranking index only ever inserts once at a key 1313 + batch.remove_weak(&self.rollups, &old_k); 1211 1314 batch.insert(&self.rollups, &new_k, ""); 1212 1315 } 1213 1316 ··· 1231 1334 AllTimeDidsKey::new(new_dids_estimate.into(), &nsid).to_db_bytes()?, 1232 1335 ), 1233 1336 }; 1234 - batch.remove(&self.rollups, &old_k); // TODO: when fjall gets weak delete, this will hopefully work way better 1337 + // remove_weak is allowed here because the secondary ranking index only ever inserts once at a key 1338 + batch.remove_weak(&self.rollups, &old_k); 1235 1339 batch.insert(&self.rollups, &new_k, ""); 1236 1340 } 1237 1341 ··· 1241 1345 1242 1346 insert_batch_static_neu::<NewRollupCursorKey>(&mut batch, &self.global, last_cursor)?; 1243 1347 1348 + histogram!("storage_rollup_counts_db_batch_items").record(batch.len() as f64); 1244 1349 batch.commit()?; 1245 1350 Ok((cursors_advanced, dirty_nsids)) 1246 1351 } ··· 1249 1354 impl StoreWriter<FjallBackground> for FjallWriter { 1250 1355 fn background_tasks(&mut self, reroll: bool) -> StorageResult<FjallBackground> { 1251 1356 if self.bg_taken.swap(true, Ordering::SeqCst) { 1252 - Err(StorageError::BackgroundAlreadyStarted) 1253 - } else { 1254 - if reroll { 1255 - log::info!("reroll: resetting rollup cursor..."); 1256 - insert_static_neu::<NewRollupCursorKey>(&self.global, Cursor::from_start())?; 1257 - log::info!("reroll: clearing trim cursors..."); 1258 - let mut batch = self.keyspace.batch(); 1259 - for kv in self 1260 - .global 1261 - .prefix(TrimCollectionCursorKey::from_prefix_to_db_bytes( 1262 - &Default::default(), 1263 - )?) 1264 - { 1265 - let (k, _) = kv?; 1266 - batch.remove(&self.global, k); 1267 - } 1268 - let n = batch.len(); 1269 - batch.commit()?; 1270 - log::info!("reroll: cleared {n} trim cursors."); 1357 + return Err(StorageError::BackgroundAlreadyStarted); 1358 + } 1359 + if reroll { 1360 + log::info!("reroll: resetting rollup cursor..."); 1361 + insert_static_neu::<NewRollupCursorKey>(&self.global, Cursor::from_start())?; 1362 + log::info!("reroll: clearing trim cursors..."); 1363 + let mut batch = self.keyspace.batch(); 1364 + for kv in self 1365 + .global 1366 + .prefix(TrimCollectionCursorKey::from_prefix_to_db_bytes( 1367 + &Default::default(), 1368 + )?) 1369 + { 1370 + let (k, _) = kv?; 1371 + batch.remove(&self.global, k); 1271 1372 } 1272 - Ok(FjallBackground(self.clone())) 1373 + let n = batch.len(); 1374 + batch.commit()?; 1375 + log::info!("reroll: cleared {n} trim cursors."); 1273 1376 } 1377 + Ok(FjallBackground(self.clone())) 1274 1378 } 1275 1379 1276 1380 fn insert_batch<const LIMIT: usize>( ··· 1346 1450 latest.to_db_bytes()?, 1347 1451 ); 1348 1452 1453 + histogram!("storage_insert_batch_db_batch_items").record(batch.len() as f64); 1349 1454 batch.commit()?; 1350 1455 Ok(()) 1351 1456 } ··· 1500 1605 candidate_new_feed_lower_cursor = Some(feed_key.cursor()); 1501 1606 } 1502 1607 1503 - self.feeds.remove(&location_key_bytes)?; 1608 + self.records.remove(&location_key_bytes)?; 1504 1609 self.feeds.remove(key_bytes)?; 1505 1610 records_deleted += 1; 1506 1611 } ··· 1527 1632 batch.remove(&self.records, key_bytes); 1528 1633 records_deleted += 1; 1529 1634 if batch.len() >= MAX_BATCHED_ACCOUNT_DELETE_RECORDS { 1635 + counter!("storage_delete_account_partial_commits").increment(1); 1530 1636 batch.commit()?; 1531 1637 batch = self.keyspace.batch(); 1532 1638 } 1533 1639 } 1640 + counter!("storage_delete_account_completions").increment(1); 1641 + counter!("storage_delete_account_records_deleted").increment(records_deleted as u64); 1534 1642 batch.commit()?; 1535 1643 Ok(records_deleted) 1536 1644 } ··· 1585 1693 break; 1586 1694 } 1587 1695 } 1696 + let dt = t0.elapsed(); 1697 + log::trace!("finished trimming {n} nsids in {dt:?}: {total_danglers} dangling and {total_deleted} total removed."); 1698 + histogram!("storage_trim_dirty_nsids").record(completed.len() as f64); 1699 + histogram!("storage_trim_duration").record(dt.as_micros() as f64); 1700 + counter!("storage_trim_removed", "dangling" => "true").increment(total_danglers as u64); 1701 + if total_deleted >= total_danglers { 1702 + counter!("storage_trim_removed", "dangling" => "false").increment((total_deleted - total_danglers) as u64); 1703 + } else { 1704 + // TODO: probably think through what's happening here 1705 + log::warn!("weird trim case: more danglers than deleted? metric will be missing for dangling=false. deleted={total_deleted} danglers={total_danglers}"); 1706 + } 1588 1707 for c in completed { 1589 1708 dirty_nsids.remove(&c); 1590 1709 } 1591 - log::info!("finished trimming {n} nsids in {:?}: {total_danglers} dangling and {total_deleted} total removed.", t0.elapsed()); 1592 1710 }, 1593 1711 }; 1594 1712 } ··· 2617 2735 vec![PrefixChild::Collection(NsidCount { 2618 2736 nsid: "a.a.a".to_string(), 2619 2737 creates: 1, 2738 + updates: 0, 2739 + deletes: 0, 2620 2740 dids_estimate: 1 2621 2741 }),] 2622 2742 ); ··· 2663 2783 vec![PrefixChild::Prefix(PrefixCount { 2664 2784 prefix: "a.a.a".to_string(), 2665 2785 creates: 1, 2666 - dids_estimate: 1 2786 + updates: 0, 2787 + deletes: 0, 2788 + dids_estimate: 1, 2667 2789 }),] 2668 2790 ); 2669 2791 assert_eq!(cursor, None); ··· 2718 2840 vec![PrefixChild::Prefix(PrefixCount { 2719 2841 prefix: "a.a.a".to_string(), 2720 2842 creates: 2, 2843 + updates: 0, 2844 + deletes: 0, 2721 2845 dids_estimate: 1 2722 2846 }),] 2723 2847 ); ··· 2786 2910 PrefixChild::Collection(NsidCount { 2787 2911 nsid: "a.a.a.a".to_string(), 2788 2912 creates: 1, 2913 + updates: 0, 2914 + deletes: 0, 2789 2915 dids_estimate: 1 2790 2916 }), 2791 2917 PrefixChild::Prefix(PrefixCount { 2792 2918 prefix: "a.a.a.a".to_string(), 2793 2919 creates: 1, 2920 + updates: 0, 2921 + deletes: 0, 2794 2922 dids_estimate: 1 2795 2923 }), 2796 2924 ]
+2
who-am-i/.gitignore
··· 1 + *.pem 2 + jwks.json
+37
who-am-i/Cargo.toml
··· 1 + [package] 2 + name = "who-am-i" 3 + version = "0.1.0" 4 + edition = "2024" 5 + 6 + [dependencies] 7 + atrium-api = { version = "0.25.4", default-features = false } 8 + atrium-common = "0.1.2" 9 + atrium-identity = "0.1.5" 10 + atrium-oauth = "0.1.3" 11 + axum = "0.8.4" 12 + axum-extra = { version = "0.10.1", features = ["cookie-signed", "typed-header"] } 13 + axum-template = { version = "3.0.0", features = ["handlebars"] } 14 + clap = { version = "4.5.40", features = ["derive", "env"] } 15 + ctrlc = "3.4.7" 16 + dashmap = "6.1.0" 17 + elliptic-curve = "0.13.8" 18 + handlebars = { version = "6.3.2", features = ["dir_source"] } 19 + hickory-resolver = "0.25.2" 20 + jose-jwk = "0.1.2" 21 + jsonwebtoken = "9.3.1" 22 + metrics = "0.24.2" 23 + p256 = "0.13.2" 24 + pkcs8 = "0.10.2" 25 + rand = "0.9.1" 26 + reqwest = { version = "0.12.22", features = ["native-tls-vendored"] } 27 + serde = { version = "1.0.219", features = ["derive"] } 28 + serde_json = "1.0.140" 29 + thiserror = "2.0.12" 30 + tokio = { version = "1.45.1", features = ["full", "macros"] } 31 + tokio-util = "0.7.15" 32 + url = "2.5.4" 33 + 34 + [dependencies.metrics-exporter-prometheus] 35 + version = "0.17.2" 36 + default-features = false 37 + features = ["http-listener", "async-runtime"]
+37
who-am-i/demo/index.html
··· 1 + <!doctype html> 2 + <html> 3 + <head> 4 + <style> 5 + body { 6 + background: #333; 7 + color: #ccc; 8 + font-family: sans-serif; 9 + } 10 + </style> 11 + </head> 12 + 13 + <body> 14 + <h1>hey <span id="who"></span></h1> 15 + <p><code id="jwt"></code></p> 16 + 17 + <iframe src="http://127.0.0.1:9997/prompt" id="whoami" style="border: none" height="160" width="320"></iframe> 18 + 19 + <script type="text/javascript"> 20 + (whoami => { 21 + const handleMessage = ev => { 22 + if (ev.source !== whoami.contentWindow) { 23 + // TODO: ALSO CHECK ev.origin!!!! 24 + console.log('nah'); 25 + return; 26 + } 27 + whoami.remove(); 28 + window.removeEventListener('message', handleMessage); 29 + 30 + document.getElementById('who').textContent = ev.data.handle; 31 + document.getElementById('jwt').textContent = ev.data.token; 32 + } 33 + window.addEventListener('message', handleMessage); 34 + })(document.getElementById('whoami')); 35 + </script> 36 + </body> 37 + </html>
+4
who-am-i/demo/serve
··· 1 + #!/usr/bin/env bash 2 + 3 + echo "note: you might need to access via http://127.0.0.1:8888 (not localhost) for the iframe to get its cookies" 4 + python3 -m http.server 8888
+66
who-am-i/readme.md
··· 1 + # who am i 2 + 3 + a little auth service for microcosm demos 4 + 5 + **you probably SHOULD NOT USE THIS in any serious environment** 6 + 7 + for now the deployment is restricted to microcosm -- expanding it for wider use likely requires solving a number of challenges that oauth exists for. 8 + 9 + 10 + ## a little auth service 11 + 12 + - you drop an iframe and a short few lines of JS on your web page, and get a nice-ish atproto login prompt. 13 + - if the user has ever authorized this service before (and within some expiration), they will be presented with an in-frame one-click option to proceed. 14 + - otherwise they get bounced over to the normal atproto oauth flow (in a popup or new tab) 15 + - you get a callback containing 16 + - a verified DID and handle 17 + - a JWT containing the same that can be verified by public key 18 + - **no write permissions** or any atproto permissions at all, just a verified identity 19 + 20 + **you probably SHOULD NOT USE THIS in any serious environment** 21 + 22 + 23 + ### problems 24 + 25 + - clickjacking: if this were allowed on arbitrary domains, malicious sites could trick users into proving their atproto identity. 26 + - all the other problems oauth exists to solve: it's a little tricky to hook around the oauth flow so there are probably some annoying attacks. 27 + - auth in front of auth: it's just a bit awkward to run an auth service that acts as an intermediary for a more-real auth behind it, but that's worse, less secure, and doesn't conform to any standards. 28 + 29 + so, **you probably SHOULD NOT USE THIS in any serious environment** 30 + 31 + 32 + ## why 33 + 34 + sometimes you want to make a thing that people can use with an atproto identity, and you might not want to let them put in any else's identity. apps that operate on public data like skircle, cred.blue, and the microcosm spacedust notifications demo don't require any special permission to operate for any user, and that's sometimes fine, but sometimes creepy/stalker-y/etc. 35 + 36 + to avoid building a small torment nexus for a microcosm demo (while also not wanting to get deep into oauth or operate a demo-specific auth backend), i made this little service to just get a verified identity. 37 + 38 + note: **you probably SHOULD NOT USE THIS in any serious environment** 39 + 40 + --- 41 + 42 + since the requirements (read-only, just verifying identity) seem modest, i was hoping that a fairly simple implementation could be Good Enough, but in the time that i was willing to spend on it, the simple version without major obvious weaknesses i was hoping for didn't emerge. 43 + 44 + it's still nice to have an explicit opt-in on a per-demo basis for microcosm so it will be used for that. it's allow-listed for the microcosm domain however (so not deployed on any adversarial hosting pages), so it's simultaenously overkill and restrictive. 45 + 46 + i will get back to oauth eventually and hopefully roll out a microcosm service to make it easy for clients (and demos), but there are a few more things in the pipeline to get to first. 47 + 48 + 49 + ### todo 50 + 51 + provide a pubkey-signed JWT of the identity (just the DID as `sub` probably). (**you probably SHOULD NOT USE THIS in any serious environment**) 52 + 53 + 54 + ## building 55 + 56 + for raspi 1 model b: 57 + 58 + atrium-oauth uses reqwest with default tls config that requires openssl which `cross` doesn't have a good time getting the os deps for. 59 + 60 + fortunately, simply *enabling* a differnent tls feature for reqwest actually stops the default problematic one from causing problems, so we have a `reqwest` direct dependency with a feature enabled, even though it's never imported into actual code, 61 + 62 + it builds with 63 + 64 + ```bash 65 + cross build --release --target arm-unknown-linux-gnueabihf 66 + ```
+89
who-am-i/src/expiring_task_map.rs
··· 1 + use dashmap::DashMap; 2 + use rand::{Rng, distr::Alphanumeric}; 3 + use std::sync::Arc; 4 + use std::time::Duration; 5 + use tokio::task::{JoinHandle, spawn}; 6 + use tokio::time::sleep; 7 + use tokio_util::sync::{CancellationToken, DropGuard}; 8 + 9 + pub struct ExpiringTaskMap<T>(TaskMap<T>); 10 + 11 + /// need to manually implement clone because T is allowed to not be clone 12 + impl<T> Clone for ExpiringTaskMap<T> { 13 + fn clone(&self) -> Self { 14 + Self(self.0.clone()) 15 + } 16 + } 17 + 18 + impl<T: Send + 'static> ExpiringTaskMap<T> { 19 + pub fn new(expiration: Duration) -> Self { 20 + let map = TaskMap { 21 + map: Arc::new(DashMap::new()), 22 + expiration, 23 + }; 24 + Self(map) 25 + } 26 + 27 + pub fn dispatch<F>(&self, task: F, cancel: CancellationToken) -> String 28 + where 29 + F: Future<Output = T> + Send + 'static, 30 + { 31 + let TaskMap { 32 + ref map, 33 + expiration, 34 + } = self.0; 35 + let task_key: String = rand::rng() 36 + .sample_iter(&Alphanumeric) 37 + .take(24) 38 + .map(char::from) 39 + .collect(); 40 + 41 + // spawn a tokio task and put the join handle in the map for later retrieval 42 + map.insert(task_key.clone(), (cancel.clone().drop_guard(), spawn(task))); 43 + 44 + // spawn a second task to clean up the map in case it doesn't get claimed 45 + let k = task_key.clone(); 46 + let map = map.clone(); 47 + spawn(async move { 48 + if cancel 49 + .run_until_cancelled(sleep(expiration)) 50 + .await 51 + .is_some() 52 + // the (sleep) task completed first 53 + { 54 + map.remove(&k); 55 + cancel.cancel(); 56 + metrics::counter!("whoami_task_map_completions", "result" => "expired") 57 + .increment(1); 58 + } 59 + }); 60 + 61 + task_key 62 + } 63 + 64 + pub fn take(&self, key: &str) -> Option<JoinHandle<T>> { 65 + if let Some((_key, (_guard, handle))) = self.0.map.remove(key) { 66 + // when the _guard drops, it cancels the token for us 67 + metrics::counter!("whoami_task_map_completions", "result" => "retrieved").increment(1); 68 + Some(handle) 69 + } else { 70 + metrics::counter!("whoami_task_map_gones").increment(1); 71 + None 72 + } 73 + } 74 + } 75 + 76 + struct TaskMap<T> { 77 + map: Arc<DashMap<String, (DropGuard, JoinHandle<T>)>>, 78 + expiration: Duration, 79 + } 80 + 81 + /// need to manually implement clone because T is allowed to not be clone 82 + impl<T> Clone for TaskMap<T> { 83 + fn clone(&self) -> Self { 84 + Self { 85 + map: self.map.clone(), 86 + expiration: self.expiration, 87 + } 88 + } 89 + }
+93
who-am-i/src/jwt.rs
··· 1 + use elliptic_curve::SecretKey; 2 + use jose_jwk::{Class, Jwk, Key, Parameters}; 3 + use jsonwebtoken::{Algorithm, EncodingKey, Header, encode, errors::Error as JWTError}; 4 + use pkcs8::DecodePrivateKey; 5 + use serde::Serialize; 6 + use std::fs; 7 + use std::io::Error as IOError; 8 + use std::path::Path; 9 + use std::string::FromUtf8Error; 10 + use std::time::{Duration, SystemTime, UNIX_EPOCH}; 11 + use thiserror::Error; 12 + 13 + #[derive(Debug, Error)] 14 + pub enum TokensSetupError { 15 + #[error("failed to read private key")] 16 + ReadPrivateKey(IOError), 17 + #[error("failed to retrieve private key: {0}")] 18 + PrivateKey(JWTError), 19 + #[error("failed to read private key")] 20 + ReadJwks(IOError), 21 + #[error("failed to retrieve jwks: {0}")] 22 + DecodeJwks(FromUtf8Error), 23 + } 24 + 25 + #[derive(Debug, Error)] 26 + pub enum TokenMintingError { 27 + #[error("failed to mint: {0}")] 28 + EncodingError(#[from] JWTError), 29 + } 30 + 31 + pub struct Tokens { 32 + encoding_key: EncodingKey, 33 + jwk: Jwk, 34 + } 35 + 36 + impl Tokens { 37 + pub fn from_files(priv_f: impl AsRef<Path>) -> Result<Self, TokensSetupError> { 38 + let private_key_data: Vec<u8> = 39 + fs::read(priv_f).map_err(TokensSetupError::ReadPrivateKey)?; 40 + let encoding_key = 41 + EncodingKey::from_ec_pem(&private_key_data).map_err(TokensSetupError::PrivateKey)?; 42 + 43 + let jwk_key_string = String::from_utf8(private_key_data).unwrap(); 44 + let mut jwk = SecretKey::<p256::NistP256>::from_pkcs8_pem(&jwk_key_string) 45 + .map(|secret_key| Jwk { 46 + key: Key::from(&secret_key.into()), 47 + prm: Parameters { 48 + kid: Some("who-am-i-00".to_string()), 49 + cls: Some(Class::Signing), 50 + ..Default::default() 51 + }, 52 + }) 53 + .expect("to get private key"); 54 + 55 + // CRITICAL: this is what turns the private jwk into a public one: the 56 + // `d` parameter is the secret for an EC key; a pubkey just has no `d`. 57 + // 58 + // this feels baaaadd but hey we're just copying atrium 59 + // https://github.com/atrium-rs/atrium/blob/b48810f84d83d037ee89b79b8566df9e0f2a6dae/atrium-oauth/src/keyset.rs#L41 60 + let Key::Ec(ref mut ec) = jwk.key else { 61 + unimplemented!() 62 + }; 63 + ec.d = None; // CRITICAL 64 + 65 + Ok(Self { encoding_key, jwk }) 66 + } 67 + 68 + pub fn mint(&self, t: impl ToString) -> Result<String, TokenMintingError> { 69 + let sub = t.to_string(); 70 + 71 + let dt_now = SystemTime::now() 72 + .duration_since(UNIX_EPOCH) 73 + .expect("unix epoch is in the past"); 74 + let dt_exp = dt_now + Duration::from_secs(30 * 86_400); 75 + let exp = dt_exp.as_secs(); 76 + 77 + let mut header = Header::new(Algorithm::ES256); 78 + header.kid = Some("who-am-i-00".to_string()); 79 + // todo: consider setting jku? 80 + 81 + Ok(encode(&header, &Claims { sub, exp }, &self.encoding_key)?) 82 + } 83 + 84 + pub fn jwk(&self) -> Jwk { 85 + self.jwk.clone() 86 + } 87 + } 88 + 89 + #[derive(Debug, Serialize)] 90 + struct Claims { 91 + sub: String, 92 + exp: u64, 93 + }
+9
who-am-i/src/lib.rs
··· 1 + mod expiring_task_map; 2 + mod jwt; 3 + mod oauth; 4 + mod server; 5 + 6 + pub use expiring_task_map::ExpiringTaskMap; 7 + pub use jwt::Tokens; 8 + pub use oauth::{OAuth, OAuthCallbackParams, OAuthCompleteError, ResolveHandleError}; 9 + pub use server::serve;
+120
who-am-i/src/main.rs
··· 1 + use clap::{ArgAction, Parser}; 2 + use metrics_exporter_prometheus::{BuildError as PromBuildError, PrometheusBuilder}; 3 + use std::path::PathBuf; 4 + use tokio_util::sync::CancellationToken; 5 + use who_am_i::{Tokens, serve}; 6 + 7 + /// Aggregate links in the at-mosphere 8 + #[derive(Parser, Debug, Clone)] 9 + #[command(version, about, long_about = None)] 10 + struct Args { 11 + /// secret key from which the cookie-signing key is derived 12 + /// 13 + /// must have at least 512 bits (64 bytes) of randomness 14 + /// 15 + /// eg: `cat /dev/urandom | head -c 64 | base64` 16 + #[arg(long, env)] 17 + app_secret: String, 18 + /// path to at-oauth private key (PEM pk8 format) 19 + /// 20 + /// generate with: 21 + /// 22 + /// openssl ecparam -genkey -noout -name prime256v1 \ 23 + /// | openssl pkcs8 -topk8 -nocrypt -out <PATH-TO-PRIV-KEY>.pem 24 + #[arg(long, env)] 25 + oauth_private_key: Option<PathBuf>, 26 + /// path to jwt private key (PEM pk8 format) 27 + /// 28 + /// generate with: 29 + /// 30 + /// openssl ecparam -genkey -noout -name prime256v1 \ 31 + /// | openssl pkcs8 -topk8 -nocrypt -out <PATH-TO-PRIV-KEY>.pem 32 + #[arg(long)] 33 + jwt_private_key: PathBuf, 34 + /// this server's client-reachable base url, for oauth redirect + jwt check 35 + /// 36 + /// required unless running in localhost mode with --dev 37 + #[arg(long, env)] 38 + base_url: Option<String>, 39 + /// host:port to bind to on startup 40 + #[arg(long, env, default_value = "127.0.0.1:9997")] 41 + bind: String, 42 + /// Enable dev mode 43 + /// 44 + /// enables automatic template reloading, uses localhost oauth config, etc 45 + #[arg(long, action)] 46 + dev: bool, 47 + /// Hosts who are allowed to one-click auth 48 + /// 49 + /// Pass this argument multiple times to allow multiple hosts 50 + #[arg(long = "allow_host", short = 'a', action = ArgAction::Append)] 51 + allowed_hosts: Vec<String>, 52 + } 53 + 54 + #[tokio::main(flavor = "current_thread")] 55 + async fn main() { 56 + let shutdown = CancellationToken::new(); 57 + 58 + let ctrlc_shutdown = shutdown.clone(); 59 + ctrlc::set_handler(move || ctrlc_shutdown.cancel()).expect("failed to set ctrl-c handler"); 60 + 61 + let args = Args::parse(); 62 + 63 + // let bind = args.bind.to_socket_addrs().expect("--bind must be ToSocketAddrs"); 64 + 65 + let base = args.base_url.unwrap_or_else(|| { 66 + if args.dev { 67 + format!("http://{}", args.bind) 68 + } else { 69 + panic!("not in --dev mode so --base-url is required") 70 + } 71 + }); 72 + 73 + if !args.dev && args.oauth_private_key.is_none() { 74 + panic!("--at-oauth-key is required except in --dev"); 75 + } else if args.dev && args.oauth_private_key.is_some() { 76 + eprintln!("warn: --at-oauth-key is ignored in dev (localhost config)"); 77 + } 78 + 79 + if args.allowed_hosts.is_empty() { 80 + panic!("at least one --allowed-host host must be set"); 81 + } 82 + 83 + println!("starting with allowed_hosts hosts:"); 84 + for host in &args.allowed_hosts { 85 + println!(" - {host}"); 86 + } 87 + 88 + let tokens = Tokens::from_files(args.jwt_private_key).unwrap(); 89 + 90 + if let Err(e) = install_metrics_server() { 91 + eprintln!("failed to install metrics server: {e:?}"); 92 + }; 93 + 94 + serve( 95 + shutdown, 96 + args.app_secret, 97 + args.oauth_private_key, 98 + tokens, 99 + base, 100 + args.bind, 101 + args.allowed_hosts, 102 + args.dev, 103 + ) 104 + .await; 105 + } 106 + 107 + fn install_metrics_server() -> Result<(), PromBuildError> { 108 + println!("installing metrics server..."); 109 + let host = [0, 0, 0, 0]; 110 + let port = 8765; 111 + PrometheusBuilder::new() 112 + .set_enable_unit_suffix(false) 113 + .with_http_listener((host, port)) 114 + .install()?; 115 + println!( 116 + "metrics server installed! listening on http://{}.{}.{}.{}:{port}", 117 + host[0], host[1], host[2], host[3] 118 + ); 119 + Ok(()) 120 + }
+268
who-am-i/src/oauth.rs
··· 1 + use jose_jwk::Class; 2 + use jose_jwk::Jwk; 3 + use jose_jwk::Key; 4 + use jose_jwk::Parameters; 5 + use std::fs; 6 + use std::path::PathBuf; 7 + // use p256::SecretKey; 8 + use atrium_api::{agent::SessionManager, types::string::Did}; 9 + use atrium_common::resolver::Resolver; 10 + use atrium_identity::{ 11 + did::{CommonDidResolver, CommonDidResolverConfig, DEFAULT_PLC_DIRECTORY_URL}, 12 + handle::{AtprotoHandleResolver, AtprotoHandleResolverConfig, DnsTxtResolver}, 13 + }; 14 + use atrium_oauth::{ 15 + AtprotoClientMetadata, AtprotoLocalhostClientMetadata, AuthMethod, AuthorizeOptions, 16 + CallbackParams, DefaultHttpClient, GrantType, KnownScope, OAuthClient, OAuthClientConfig, 17 + OAuthClientMetadata, OAuthResolverConfig, Scope, 18 + store::{session::MemorySessionStore, state::MemoryStateStore}, 19 + }; 20 + use elliptic_curve::SecretKey; 21 + use hickory_resolver::{ResolveError, TokioResolver}; 22 + use jose_jwk::JwkSet; 23 + use pkcs8::DecodePrivateKey; 24 + use serde::Deserialize; 25 + use std::sync::Arc; 26 + use thiserror::Error; 27 + 28 + const READONLY_SCOPE: [Scope; 1] = [Scope::Known(KnownScope::Atproto)]; 29 + 30 + #[derive(Debug, Deserialize)] 31 + pub struct CallbackErrorParams { 32 + error: String, 33 + error_description: Option<String>, 34 + #[allow(dead_code)] 35 + state: Option<String>, // TODO: we _should_ use state to associate the auth request but how to do that with atrium is unclear 36 + iss: Option<String>, 37 + } 38 + 39 + #[derive(Debug, Deserialize)] 40 + #[serde(untagged)] 41 + pub enum OAuthCallbackParams { 42 + Granted(CallbackParams), 43 + Failed(CallbackErrorParams), 44 + } 45 + 46 + type Client = OAuthClient< 47 + MemoryStateStore, 48 + MemorySessionStore, 49 + CommonDidResolver<DefaultHttpClient>, 50 + AtprotoHandleResolver<HickoryDnsTxtResolver, DefaultHttpClient>, 51 + >; 52 + 53 + #[derive(Clone)] 54 + pub struct OAuth { 55 + client: Arc<Client>, 56 + did_resolver: Arc<CommonDidResolver<DefaultHttpClient>>, 57 + } 58 + 59 + #[derive(Debug, Error)] 60 + pub enum AuthSetupError { 61 + #[error("failed to intiialize atrium client: {0}")] 62 + AtriumClientError(atrium_oauth::Error), 63 + #[error("failed to initialize hickory dns resolver: {0}")] 64 + HickoryResolverError(ResolveError), 65 + } 66 + 67 + #[derive(Debug, Error)] 68 + pub enum OAuthCompleteError { 69 + #[error("the user denied request: {description:?} (from {issuer:?})")] 70 + Denied { 71 + description: Option<String>, 72 + issuer: Option<String>, 73 + }, 74 + #[error("the request failed: {error}: {description:?} (from {issuer:?})")] 75 + Failed { 76 + error: String, 77 + description: Option<String>, 78 + issuer: Option<String>, 79 + }, 80 + #[error("failed to complete oauth callback: {0}")] 81 + CallbackFailed(atrium_oauth::Error), 82 + #[error("the authorized session did not contain a DID")] 83 + NoDid, 84 + } 85 + 86 + #[derive(Debug, Error)] 87 + pub enum ResolveHandleError { 88 + #[error("failed to resolve: {0}")] 89 + ResolutionFailed(#[from] atrium_identity::Error), 90 + #[error("identity resolved but no handle found for user")] 91 + NoHandle, 92 + #[error("found handle {0:?} but it appears invalid: {1}")] 93 + InvalidHandle(String, &'static str), 94 + } 95 + 96 + impl OAuth { 97 + pub fn new(oauth_private_key: Option<PathBuf>, base: String) -> Result<Self, AuthSetupError> { 98 + let http_client = Arc::new(DefaultHttpClient::default()); 99 + let did_resolver = || { 100 + CommonDidResolver::new(CommonDidResolverConfig { 101 + plc_directory_url: DEFAULT_PLC_DIRECTORY_URL.to_string(), 102 + http_client: http_client.clone(), 103 + }) 104 + }; 105 + let dns_txt_resolver = 106 + HickoryDnsTxtResolver::new().map_err(AuthSetupError::HickoryResolverError)?; 107 + 108 + let resolver = OAuthResolverConfig { 109 + did_resolver: did_resolver(), 110 + handle_resolver: AtprotoHandleResolver::new(AtprotoHandleResolverConfig { 111 + dns_txt_resolver, 112 + http_client: Arc::clone(&http_client), 113 + }), 114 + authorization_server_metadata: Default::default(), 115 + protected_resource_metadata: Default::default(), 116 + }; 117 + 118 + let state_store = MemoryStateStore::default(); 119 + let session_store = MemorySessionStore::default(); 120 + 121 + let client = if let Some(path) = oauth_private_key { 122 + let key_contents: Vec<u8> = fs::read(path).unwrap(); 123 + let key_string = String::from_utf8(key_contents).unwrap(); 124 + let key = SecretKey::<p256::NistP256>::from_pkcs8_pem(&key_string) 125 + .map(|secret_key| Jwk { 126 + key: Key::from(&secret_key.into()), 127 + prm: Parameters { 128 + kid: Some("at-oauth-00".to_string()), 129 + cls: Some(Class::Signing), 130 + ..Default::default() 131 + }, 132 + }) 133 + .expect("to get private key"); 134 + OAuthClient::new(OAuthClientConfig { 135 + client_metadata: AtprotoClientMetadata { 136 + client_id: format!("{base}/client-metadata.json"), 137 + client_uri: Some(base.clone()), 138 + redirect_uris: vec![format!("{base}/authorized")], 139 + token_endpoint_auth_method: AuthMethod::PrivateKeyJwt, 140 + grant_types: vec![GrantType::AuthorizationCode, GrantType::RefreshToken], 141 + scopes: READONLY_SCOPE.to_vec(), 142 + jwks_uri: Some(format!("{base}/.well-known/jwks.json")), 143 + token_endpoint_auth_signing_alg: Some(String::from("ES256")), 144 + }, 145 + keys: Some(vec![key]), 146 + resolver, 147 + state_store, 148 + session_store, 149 + }) 150 + .map_err(AuthSetupError::AtriumClientError)? 151 + } else { 152 + OAuthClient::new(OAuthClientConfig { 153 + client_metadata: AtprotoLocalhostClientMetadata { 154 + redirect_uris: Some(vec![String::from("http://127.0.0.1:9997/authorized")]), 155 + scopes: Some(READONLY_SCOPE.to_vec()), 156 + }, 157 + keys: None, 158 + resolver, 159 + state_store, 160 + session_store, 161 + }) 162 + .map_err(AuthSetupError::AtriumClientError)? 163 + }; 164 + 165 + Ok(Self { 166 + client: Arc::new(client), 167 + did_resolver: Arc::new(did_resolver()), 168 + }) 169 + } 170 + 171 + pub fn client_metadata(&self) -> OAuthClientMetadata { 172 + self.client.client_metadata.clone() 173 + } 174 + 175 + pub fn jwks(&self) -> JwkSet { 176 + self.client.jwks() 177 + } 178 + 179 + pub async fn begin(&self, handle: &str) -> Result<String, atrium_oauth::Error> { 180 + let auth_opts = AuthorizeOptions { 181 + scopes: READONLY_SCOPE.to_vec(), 182 + ..Default::default() 183 + }; 184 + self.client.authorize(handle, auth_opts).await 185 + } 186 + 187 + /// Finally, resolve the oauth flow to a verified DID 188 + pub async fn complete(&self, params: OAuthCallbackParams) -> Result<Did, OAuthCompleteError> { 189 + let params = match params { 190 + OAuthCallbackParams::Granted(params) => params, 191 + OAuthCallbackParams::Failed(p) if p.error == "access_denied" => { 192 + return Err(OAuthCompleteError::Denied { 193 + description: p.error_description.clone(), 194 + issuer: p.iss.clone(), 195 + }); 196 + } 197 + OAuthCallbackParams::Failed(p) => { 198 + return Err(OAuthCompleteError::Failed { 199 + error: p.error.clone(), 200 + description: p.error_description.clone(), 201 + issuer: p.iss.clone(), 202 + }); 203 + } 204 + }; 205 + let (session, _) = self 206 + .client 207 + .callback(params) 208 + .await 209 + .map_err(OAuthCompleteError::CallbackFailed)?; 210 + let Some(did) = session.did().await else { 211 + return Err(OAuthCompleteError::NoDid); 212 + }; 213 + Ok(did) 214 + } 215 + 216 + pub async fn resolve_handle(&self, did: Did) -> Result<String, ResolveHandleError> { 217 + // TODO: this is only half the resolution? or is atrium checking dns? 218 + let doc = self.did_resolver.resolve(&did).await?; 219 + let Some(aka) = doc.also_known_as else { 220 + return Err(ResolveHandleError::NoHandle); 221 + }; 222 + let Some(at_uri_handle) = aka.first() else { 223 + return Err(ResolveHandleError::NoHandle); 224 + }; 225 + if aka.len() > 1 { 226 + eprintln!("more than one handle found for {did:?}"); 227 + } 228 + let Some(bare_handle) = at_uri_handle.strip_prefix("at://") else { 229 + return Err(ResolveHandleError::InvalidHandle( 230 + at_uri_handle.to_string(), 231 + "did not start with 'at://'", 232 + )); 233 + }; 234 + if bare_handle.is_empty() { 235 + return Err(ResolveHandleError::InvalidHandle( 236 + at_uri_handle.to_string(), 237 + "empty handle", 238 + )); 239 + } 240 + Ok(bare_handle.to_string()) 241 + } 242 + } 243 + 244 + pub struct HickoryDnsTxtResolver(TokioResolver); 245 + 246 + impl HickoryDnsTxtResolver { 247 + fn new() -> Result<Self, ResolveError> { 248 + Ok(Self(TokioResolver::builder_tokio()?.build())) 249 + } 250 + } 251 + 252 + impl DnsTxtResolver for HickoryDnsTxtResolver { 253 + async fn resolve( 254 + &self, 255 + query: &str, 256 + ) -> core::result::Result<Vec<String>, Box<dyn std::error::Error + Send + Sync>> { 257 + match self.0.txt_lookup(query).await { 258 + Ok(r) => { 259 + metrics::counter!("whoami_resolve_dns_txt", "success" => "true").increment(1); 260 + Ok(r.iter().map(|r| r.to_string()).collect()) 261 + } 262 + Err(e) => { 263 + metrics::counter!("whoami_resolve_dns_txt", "success" => "false").increment(1); 264 + Err(e.into()) 265 + } 266 + } 267 + } 268 + }
+525
who-am-i/src/server.rs
··· 1 + use atrium_api::types::string::Did; 2 + use atrium_oauth::OAuthClientMetadata; 3 + use axum::{ 4 + Router, 5 + extract::{FromRef, Json as ExtractJson, Query, State}, 6 + http::{ 7 + StatusCode, 8 + header::{CONTENT_SECURITY_POLICY, CONTENT_TYPE, HeaderMap, ORIGIN, REFERER}, 9 + }, 10 + response::{IntoResponse, Json, Redirect, Response}, 11 + routing::{get, post}, 12 + }; 13 + use axum_extra::extract::cookie::{Cookie, Expiration, Key, SameSite, SignedCookieJar}; 14 + use axum_template::{RenderHtml, engine::Engine}; 15 + use handlebars::{Handlebars, handlebars_helper}; 16 + use jose_jwk::JwkSet; 17 + use std::path::PathBuf; 18 + 19 + use serde::Deserialize; 20 + use serde_json::{Value, json}; 21 + use std::collections::HashSet; 22 + use std::sync::Arc; 23 + use std::time::{Duration, SystemTime}; 24 + use tokio::net::TcpListener; 25 + use tokio_util::sync::CancellationToken; 26 + use url::Url; 27 + 28 + use crate::{ 29 + ExpiringTaskMap, OAuth, OAuthCallbackParams, OAuthCompleteError, ResolveHandleError, Tokens, 30 + }; 31 + 32 + const FAVICON: &[u8] = include_bytes!("../static/favicon.ico"); 33 + const STYLE_CSS: &str = include_str!("../static/style.css"); 34 + 35 + const HELLO_COOKIE_KEY: &str = "hello-who-am-i"; 36 + const DID_COOKIE_KEY: &str = "did"; 37 + 38 + const COOKIE_EXPIRATION: Duration = Duration::from_secs(30 * 86_400); 39 + 40 + type AppEngine = Engine<Handlebars<'static>>; 41 + 42 + #[derive(Clone)] 43 + struct AppState { 44 + pub key: Key, 45 + pub allowed_hosts: Arc<HashSet<String>>, 46 + pub engine: AppEngine, 47 + pub oauth: Arc<OAuth>, 48 + pub resolve_handles: ExpiringTaskMap<Result<String, ResolveHandleError>>, 49 + pub shutdown: CancellationToken, 50 + pub tokens: Arc<Tokens>, 51 + } 52 + 53 + impl FromRef<AppState> for Key { 54 + fn from_ref(state: &AppState) -> Self { 55 + state.key.clone() 56 + } 57 + } 58 + 59 + #[allow(clippy::too_many_arguments)] 60 + pub async fn serve( 61 + shutdown: CancellationToken, 62 + app_secret: String, 63 + oauth_private_key: Option<PathBuf>, 64 + tokens: Tokens, 65 + base: String, 66 + bind: String, 67 + allowed_hosts: Vec<String>, 68 + dev: bool, 69 + ) { 70 + let mut hbs = Handlebars::new(); 71 + hbs.set_dev_mode(dev); 72 + hbs.register_templates_directory("templates", Default::default()) 73 + .unwrap(); 74 + 75 + handlebars_helper!(json: |v: Value| serde_json::to_string(&v).unwrap()); 76 + hbs.register_helper("json", Box::new(json)); 77 + 78 + // clients have to pick up their identity-resolving tasks within this period 79 + let task_pickup_expiration = Duration::from_secs(15); 80 + 81 + let oauth = OAuth::new(oauth_private_key, base).unwrap(); 82 + 83 + let state = AppState { 84 + engine: Engine::new(hbs), 85 + key: Key::from(app_secret.as_bytes()), // TODO: via config 86 + allowed_hosts: Arc::new(HashSet::from_iter(allowed_hosts)), 87 + oauth: Arc::new(oauth), 88 + resolve_handles: ExpiringTaskMap::new(task_pickup_expiration), 89 + shutdown: shutdown.clone(), 90 + tokens: Arc::new(tokens), 91 + }; 92 + 93 + let app = Router::new() 94 + .route("/", get(hello)) 95 + .route("/favicon.ico", get(favicon)) // todo MIME 96 + .route("/style.css", get(css)) 97 + .route("/prompt", get(prompt)) 98 + .route("/user-info", post(user_info)) 99 + .route("/client-metadata.json", get(client_metadata)) 100 + .route("/auth", get(start_oauth)) 101 + .route("/authorized", get(complete_oauth)) 102 + .route("/disconnect", post(disconnect)) 103 + .route("/.well-known/jwks.json", get(jwks)) 104 + .with_state(state); 105 + 106 + eprintln!("starting server at http://{bind}"); 107 + let listener = TcpListener::bind(bind) 108 + .await 109 + .expect("listener binding to work"); 110 + 111 + axum::serve(listener, app) 112 + .with_graceful_shutdown(async move { shutdown.cancelled().await }) 113 + .await 114 + .unwrap(); 115 + } 116 + 117 + #[derive(Debug, Deserialize)] 118 + struct HelloQuery { 119 + auth_reload: Option<String>, 120 + auth_failed: Option<String>, 121 + } 122 + async fn hello( 123 + State(AppState { 124 + engine, 125 + resolve_handles, 126 + shutdown, 127 + oauth, 128 + .. 129 + }): State<AppState>, 130 + Query(params): Query<HelloQuery>, 131 + mut jar: SignedCookieJar, 132 + ) -> Response { 133 + let is_auth_reload = params.auth_reload.is_some(); 134 + let auth_failed = params.auth_failed.is_some(); 135 + let no_cookie = jar.get(HELLO_COOKIE_KEY).is_none(); 136 + jar = jar.add(hello_cookie()); 137 + 138 + let info = if let Some(did) = jar.get(DID_COOKIE_KEY) { 139 + if let Ok(did) = Did::new(did.value_trimmed().to_string()) { 140 + // push cookie expiry 141 + jar = jar.add(cookie(&did)); 142 + let fetch_key = resolve_handles.dispatch( 143 + { 144 + let oauth = oauth.clone(); 145 + let did = did.clone(); 146 + async move { oauth.resolve_handle(did.clone()).await } 147 + }, 148 + shutdown.child_token(), 149 + ); 150 + json!({ 151 + "did": did, 152 + "fetch_key": fetch_key, 153 + "is_auth_reload": is_auth_reload, 154 + "auth_failed": auth_failed, 155 + "no_cookie": no_cookie, 156 + }) 157 + } else { 158 + jar = jar.remove(DID_COOKIE_KEY); 159 + json!({ 160 + "is_auth_reload": is_auth_reload, 161 + "auth_failed": auth_failed, 162 + "no_cookie": no_cookie, 163 + }) 164 + } 165 + } else { 166 + json!({ 167 + "is_auth_reload": is_auth_reload, 168 + "auth_failed": auth_failed, 169 + "no_cookie": no_cookie, 170 + }) 171 + }; 172 + let frame_headers = [(CONTENT_SECURITY_POLICY, "frame-ancestors 'none'")]; 173 + (frame_headers, jar, RenderHtml("hello", engine, info)).into_response() 174 + } 175 + 176 + async fn css() -> impl IntoResponse { 177 + let headers = [ 178 + (CONTENT_TYPE, "text/css"), 179 + // (CACHE_CONTROL, "") // TODO 180 + ]; 181 + (headers, STYLE_CSS) 182 + } 183 + 184 + async fn favicon() -> impl IntoResponse { 185 + ([(CONTENT_TYPE, "image/x-icon")], FAVICON) 186 + } 187 + 188 + fn hello_cookie() -> Cookie<'static> { 189 + Cookie::build((HELLO_COOKIE_KEY, "hiiii")) 190 + .http_only(true) 191 + .secure(true) 192 + .same_site(SameSite::None) 193 + .expires(Expiration::DateTime( 194 + (SystemTime::now() + COOKIE_EXPIRATION).into(), 195 + )) // wtf safari needs this to not be a session cookie?? 196 + .max_age(COOKIE_EXPIRATION.try_into().unwrap()) 197 + .path("/") 198 + .into() 199 + } 200 + 201 + fn cookie(did: &Did) -> Cookie<'static> { 202 + Cookie::build((DID_COOKIE_KEY, did.to_string())) 203 + .http_only(true) 204 + .secure(true) 205 + .same_site(SameSite::None) 206 + .expires(Expiration::DateTime( 207 + (SystemTime::now() + COOKIE_EXPIRATION).into(), 208 + )) // wtf safari needs this to not be a session cookie?? 209 + .max_age(COOKIE_EXPIRATION.try_into().unwrap()) 210 + .path("/") 211 + .into() 212 + } 213 + 214 + #[derive(Debug, Deserialize)] 215 + struct PromptQuery { 216 + // this must *ONLY* be used for the postmessage target origin 217 + app: Option<String>, 218 + } 219 + async fn prompt( 220 + State(AppState { 221 + allowed_hosts, 222 + engine, 223 + oauth, 224 + resolve_handles, 225 + shutdown, 226 + tokens, 227 + .. 228 + }): State<AppState>, 229 + Query(params): Query<PromptQuery>, 230 + jar: SignedCookieJar, 231 + headers: HeaderMap, 232 + ) -> impl IntoResponse { 233 + let err = |reason, check_frame, detail| { 234 + metrics::counter!("whoami_auth_prompt", "ok" => "false", "reason" => reason).increment(1); 235 + let info = json!({ 236 + "reason": reason, 237 + "check_frame": check_frame, 238 + "detail": detail, 239 + }); 240 + let html = RenderHtml("prompt-error", engine.clone(), info); 241 + (StatusCode::BAD_REQUEST, html).into_response() 242 + }; 243 + 244 + let Some(parent) = headers.get(ORIGIN).or_else(|| { 245 + eprintln!("referrer fallback"); 246 + // TODO: referer should only be used for localhost?? 247 + headers.get(REFERER) 248 + }) else { 249 + return err("Missing origin and no referrer for fallback", true, None); 250 + }; 251 + let Ok(parent) = parent.to_str() else { 252 + return err("Unreadable origin or referrer", true, None); 253 + }; 254 + eprintln!( 255 + "rolling with parent: {parent:?} (from origin? {})", 256 + headers.get(ORIGIN).is_some() 257 + ); 258 + let Ok(url) = Url::parse(parent) else { 259 + return err("Bad origin or referrer", true, None); 260 + }; 261 + let Some(parent_host) = url.host_str() else { 262 + return err("Origin or referrer missing host", true, None); 263 + }; 264 + if !allowed_hosts.contains(parent_host) { 265 + return err( 266 + "Login is not allowed on this page", 267 + false, 268 + Some(parent_host), 269 + ); 270 + } 271 + if let Some(ref app) = params.app { 272 + if !allowed_hosts.contains(app) { 273 + return err("Login is not allowed for this app", false, Some(app)); 274 + } 275 + } 276 + let parent_origin = url.origin().ascii_serialization(); 277 + if parent_origin == "null" { 278 + return err("Origin or referrer header value is opaque", true, None); 279 + } 280 + 281 + let all_allowed = allowed_hosts 282 + .iter() 283 + .map(|h| format!("https://{h}")) 284 + .collect::<Vec<_>>() 285 + .join(" "); 286 + let csp = format!("frame-ancestors 'self' {parent_origin} {all_allowed}"); 287 + let frame_headers = [(CONTENT_SECURITY_POLICY, &csp)]; 288 + 289 + if let Some(did) = jar.get(DID_COOKIE_KEY) { 290 + let Ok(did) = Did::new(did.value_trimmed().to_string()) else { 291 + return err("Bad cookie", false, None); 292 + }; 293 + 294 + // push cookie expiry 295 + let jar = jar.add(cookie(&did)); 296 + 297 + let token = match tokens.mint(&*did) { 298 + Ok(t) => t, 299 + Err(e) => { 300 + eprintln!("failed to create JWT: {e:?}"); 301 + return err("failed to create JWT", false, None); 302 + } 303 + }; 304 + 305 + let fetch_key = resolve_handles.dispatch( 306 + { 307 + let oauth = oauth.clone(); 308 + let did = did.clone(); 309 + async move { oauth.resolve_handle(did.clone()).await } 310 + }, 311 + shutdown.child_token(), 312 + ); 313 + 314 + metrics::counter!("whoami_auth_prompt", "ok" => "true", "known" => "true").increment(1); 315 + let info = json!({ 316 + "did": did, 317 + "token": token, 318 + "fetch_key": fetch_key, 319 + "parent_host": parent_host, 320 + "parent_origin": parent_origin, 321 + "parent_target": params.app.map(|h| format!("https://{h}")), 322 + }); 323 + (frame_headers, jar, RenderHtml("prompt", engine, info)).into_response() 324 + } else { 325 + metrics::counter!("whoami_auth_prompt", "ok" => "true", "known" => "false").increment(1); 326 + let info = json!({ 327 + "parent_host": parent_host, 328 + "parent_origin": parent_origin, 329 + }); 330 + (frame_headers, RenderHtml("prompt", engine, info)).into_response() 331 + } 332 + } 333 + 334 + #[derive(Debug, Deserialize)] 335 + struct UserInfoParams { 336 + fetch_key: String, 337 + } 338 + async fn user_info( 339 + State(AppState { 340 + resolve_handles, .. 341 + }): State<AppState>, 342 + ExtractJson(params): ExtractJson<UserInfoParams>, 343 + ) -> impl IntoResponse { 344 + let err = |status, reason: &str| { 345 + metrics::counter!("whoami_user_info", "found" => "false", "reason" => reason.to_string()) 346 + .increment(1); 347 + (status, Json(json!({ "reason": reason }))).into_response() 348 + }; 349 + 350 + let Some(task_handle) = resolve_handles.take(&params.fetch_key) else { 351 + return err(StatusCode::NOT_FOUND, "fetch key does not exist or expired"); 352 + }; 353 + 354 + match task_handle.await { 355 + Err(task_err) => { 356 + eprintln!("task join error? {task_err:?}"); 357 + err(StatusCode::INTERNAL_SERVER_ERROR, "server errored") 358 + } 359 + Ok(Err(ResolveHandleError::ResolutionFailed(atrium_identity::Error::NotFound))) => { 360 + err(StatusCode::NOT_FOUND, "handle not found") 361 + } 362 + Ok(Err(ResolveHandleError::ResolutionFailed(e))) => { 363 + eprintln!("handle resolution failed: {e:?}"); 364 + err( 365 + StatusCode::INTERNAL_SERVER_ERROR, 366 + "handle resolution failed", 367 + ) 368 + } 369 + Ok(Err(ResolveHandleError::NoHandle)) => err( 370 + StatusCode::INTERNAL_SERVER_ERROR, 371 + "resolved identity but did not find a handle", 372 + ), 373 + Ok(Err(ResolveHandleError::InvalidHandle(_h, reason))) => err( 374 + StatusCode::INTERNAL_SERVER_ERROR, 375 + &format!("handle appears invalid: {reason}"), 376 + ), 377 + Ok(Ok(handle)) => { 378 + metrics::counter!("whoami_user_info", "found" => "true").increment(1); 379 + Json(json!({ "handle": handle })).into_response() 380 + } 381 + } 382 + } 383 + 384 + async fn client_metadata( 385 + State(AppState { oauth, .. }): State<AppState>, 386 + ) -> Json<OAuthClientMetadata> { 387 + Json(oauth.client_metadata()) 388 + } 389 + 390 + #[derive(Debug, Deserialize)] 391 + struct BeginOauthParams { 392 + handle: String, 393 + } 394 + async fn start_oauth( 395 + State(AppState { oauth, engine, .. }): State<AppState>, 396 + Query(params): Query<BeginOauthParams>, 397 + jar: SignedCookieJar, 398 + ) -> Response { 399 + // if any existing session was active, clear it first 400 + // ...this might help a confusion attack w multiple sign-in flows or smth 401 + let jar = jar.remove(DID_COOKIE_KEY); 402 + 403 + use atrium_identity::Error as IdError; 404 + use atrium_oauth::Error as OAuthError; 405 + 406 + let err = |code, reason: &str| { 407 + metrics::counter!("whoami_auth_start", "ok" => "false", "reason" => reason.to_string()) 408 + .increment(1); 409 + let info = json!({ 410 + "result": "fail", 411 + "reason": reason, 412 + }); 413 + (code, RenderHtml("auth-fail", engine.clone(), info)).into_response() 414 + }; 415 + 416 + match oauth.begin(&params.handle).await { 417 + Err(OAuthError::Identity( 418 + IdError::NotFound | IdError::HttpStatus(StatusCode::NOT_FOUND), 419 + )) => err(StatusCode::NOT_FOUND, "handle not found"), 420 + Err(OAuthError::Identity(IdError::AtIdentifier(r))) => err(StatusCode::BAD_REQUEST, &r), 421 + Err(e) => { 422 + eprintln!("begin auth failed: {e:?}"); 423 + err(StatusCode::INTERNAL_SERVER_ERROR, "unknown") 424 + } 425 + Ok(auth_url) => { 426 + metrics::counter!("whoami_auth_start", "ok" => "true").increment(1); 427 + (jar, Redirect::to(&auth_url)).into_response() 428 + } 429 + } 430 + } 431 + 432 + async fn complete_oauth( 433 + State(AppState { 434 + engine, 435 + resolve_handles, 436 + oauth, 437 + shutdown, 438 + tokens, 439 + .. 440 + }): State<AppState>, 441 + Query(params): Query<OAuthCallbackParams>, 442 + jar: SignedCookieJar, 443 + ) -> Response { 444 + let err = |code, result, reason: &str| { 445 + metrics::counter!("whoami_auth_complete", "ok" => "false", "reason" => reason.to_string()) 446 + .increment(1); 447 + let info = json!({ 448 + "result": result, 449 + "reason": reason, 450 + }); 451 + (code, RenderHtml("auth-fail", engine.clone(), info)).into_response() 452 + }; 453 + 454 + let did = match oauth.complete(params).await { 455 + Ok(did) => did, 456 + Err(e) => { 457 + return match e { 458 + OAuthCompleteError::Denied { description, .. } => { 459 + let desc = description.unwrap_or("permission to share was denied".to_string()); 460 + err(StatusCode::FORBIDDEN, "deny", desc.as_str()) 461 + } 462 + OAuthCompleteError::Failed { .. } => { 463 + eprintln!("auth completion failed: {e:?}"); 464 + err( 465 + StatusCode::INTERNAL_SERVER_ERROR, 466 + "fail", 467 + "failed to complete", 468 + ) 469 + } 470 + OAuthCompleteError::CallbackFailed(e) => { 471 + eprintln!("auth callback failed: {e:?}"); 472 + err( 473 + StatusCode::INTERNAL_SERVER_ERROR, 474 + "fail", 475 + "failed to complete callback", 476 + ) 477 + } 478 + OAuthCompleteError::NoDid => err(StatusCode::BAD_REQUEST, "fail", "no DID found"), 479 + }; 480 + } 481 + }; 482 + 483 + let jar = jar.add(cookie(&did)); 484 + 485 + let token = match tokens.mint(&*did) { 486 + Ok(t) => t, 487 + Err(e) => { 488 + eprintln!("failed to create JWT: {e:?}"); 489 + return err( 490 + StatusCode::INTERNAL_SERVER_ERROR, 491 + "fail", 492 + "failed to create JWT", 493 + ); 494 + } 495 + }; 496 + 497 + let fetch_key = resolve_handles.dispatch( 498 + { 499 + let oauth = oauth.clone(); 500 + let did = did.clone(); 501 + async move { oauth.resolve_handle(did.clone()).await } 502 + }, 503 + shutdown.child_token(), 504 + ); 505 + 506 + metrics::counter!("whoami_auth_complete", "ok" => "true").increment(1); 507 + let info = json!({ 508 + "did": did, 509 + "token": token, 510 + "fetch_key": fetch_key, 511 + }); 512 + (jar, RenderHtml("authorized", engine, info)).into_response() 513 + } 514 + 515 + async fn disconnect(jar: SignedCookieJar) -> impl IntoResponse { 516 + metrics::counter!("whoami_disconnect").increment(1); 517 + let jar = jar.remove(DID_COOKIE_KEY); 518 + (jar, Json(json!({ "ok": true }))) 519 + } 520 + 521 + async fn jwks(State(AppState { oauth, tokens, .. }): State<AppState>) -> Json<JwkSet> { 522 + let mut jwks = oauth.jwks(); 523 + jwks.keys.push(tokens.jwk()); 524 + Json(jwks) 525 + }
who-am-i/static/favicon.ico

This is a binary file and will not be displayed.

+195
who-am-i/static/style.css
··· 1 + body { 2 + color: #434; 3 + font-family: 'Iowan Old Style', 'Palatino Linotype', 'URW Palladio L', P052, serif; 4 + margin: 0; 5 + min-height: 100vh; 6 + padding: 0; 7 + } 8 + .wrap { 9 + border: 2px solid #221828; 10 + border-radius: 0.5rem; 11 + box-sizing: border-box; 12 + overflow: hidden; 13 + display: flex; 14 + flex-direction: column; 15 + min-height: 100vh; 16 + } 17 + .wrap.unframed { 18 + border-radius: 0; 19 + border-width: 0.4rem; 20 + } 21 + header { 22 + background: #221828; 23 + display: flex; 24 + justify-content: space-between; 25 + padding: 0 0.25rem; 26 + color: #c9b; 27 + display: flex; 28 + gap: 0.5rem; 29 + align-items: baseline; 30 + } 31 + header > * { 32 + flex-basis: 33%; 33 + } 34 + header > .empty { 35 + font-size: 0.8rem; 36 + opacity: 0.5; 37 + } 38 + header > .title { 39 + text-align: center; 40 + } 41 + header > a.micro { 42 + text-decoration: none; 43 + font-size: 0.8rem; 44 + text-align: right; 45 + opacity: 0.5; 46 + } 47 + header > a.micro:hover { 48 + opacity: 1; 49 + } 50 + main { 51 + background: #ccc; 52 + display: flex; 53 + flex-direction: column; 54 + flex-grow: 1; 55 + padding: 0.25rem 0.5rem; 56 + } 57 + .mini-content { 58 + margin: 1rem auto 0; 59 + padding: 1rem 0.5rem; 60 + max-width: 21rem; 61 + } 62 + 63 + .explain { 64 + border-bottom: 1px dashed #888; 65 + margin-bottom: 1rem; 66 + padding-bottom: 2rem; 67 + } 68 + .explain p { 69 + text-align: left; 70 + } 71 + 72 + #error-message { 73 + font-size: 0.8rem; 74 + color: #a31; 75 + } 76 + 77 + #error-message:not(.hidden) + #prompt { 78 + display: none !important; 79 + } 80 + 81 + #error-message, 82 + p { 83 + margin: 1rem 0 0; 84 + text-align: center; 85 + } 86 + p.detail { 87 + font-size: 0.8rem; 88 + } 89 + p.detail.no { 90 + font-style: italic; 91 + } 92 + .parent-host { 93 + font-weight: bold; 94 + color: #48c; 95 + display: inline-block; 96 + padding: 0 0.125rem; 97 + border-radius: 0.25rem; 98 + border: 1px solid #aaa; 99 + font-size: 0.8rem; 100 + } 101 + 102 + #loader { 103 + display: flex; 104 + flex-grow: 1; 105 + justify-content: center; 106 + align-items: center; 107 + } 108 + .spinner { 109 + animation: rotation 1.618s ease-in-out infinite; 110 + border-radius: 50%; 111 + border: 3px dashed #434; 112 + box-sizing: border-box; 113 + display: inline-block; 114 + height: 1.5em; 115 + width: 1.5em; 116 + } 117 + @keyframes rotation { 118 + 0% { transform: rotate(0deg) } 119 + 100% { transform: rotate(360deg) } 120 + } 121 + /* loader visibility is mutually exclusive with its immediate sibling */ 122 + #loader:not(.hidden) + * { 123 + display: none !important; 124 + } 125 + 126 + #user-info { 127 + flex-grow: 1; 128 + display: flex; 129 + flex-direction: column; 130 + justify-content: center; 131 + } 132 + .action { 133 + background: #eee; 134 + display: flex; 135 + justify-content: space-between; 136 + padding: 0.5rem 0.25rem 0.5rem 0.5rem; 137 + font-size: 0.8rem; 138 + align-items: baseline; 139 + border-radius: 0.5rem; 140 + border: 1px solid #bbb; 141 + cursor: pointer; 142 + } 143 + .action:hover { 144 + background: #fff; 145 + } 146 + #form-action:not(.hidden) + .action { 147 + display: none !important; 148 + } 149 + 150 + #connect, 151 + #allow, 152 + #revoke { 153 + background: transparent; 154 + border: none; 155 + border-left: 1px solid #bbb; 156 + padding: 0 0.5rem; 157 + color: #375; 158 + font: inherit; 159 + cursor: pointer; 160 + } 161 + #revoke { 162 + color: #a31; 163 + } 164 + #action:hover #allow { 165 + color: #285; 166 + } 167 + 168 + #need-storage { 169 + font-size: 0.8rem; 170 + } 171 + .problem { 172 + color: #a31; 173 + } 174 + 175 + #or { 176 + font-size: 0.8rem; 177 + text-align: center; 178 + } 179 + #or p { 180 + margin: 0 0 1rem; 181 + } 182 + 183 + input.handle { 184 + border: none; 185 + border-bottom: 1px dashed #aaa; 186 + background: transparent; 187 + } 188 + 189 + .hidden { 190 + display: none !important; 191 + } 192 + 193 + .hello-connect-plz { 194 + margin: 1.667rem 0 0.667rem; 195 + }
+20
who-am-i/templates/auth-fail.hbs
··· 1 + {{#*inline "main"}} 2 + <p> 3 + Auth failed: {{ reason }} 4 + </p> 5 + 6 + <div id="user-info"> 7 + auth failed. 8 + </div> 9 + 10 + <script> 11 + localStorage.setItem("who-am-i", JSON.stringify({ 12 + result: {{{json result}}}, 13 + reason: {{{json reason}}}, 14 + })); 15 + 16 + window.close(); 17 + </script> 18 + {{/inline}} 19 + 20 + {{#> base-framed}}{{/base-framed}}
+19
who-am-i/templates/authorized.hbs
··· 1 + <!doctype html> 2 + <meta charset="utf-8" /> 3 + <title>great job!</title> 4 + 5 + <h1>oauth success!</h1> 6 + <p>this window should automatically close itself (probably a bug if it hasn't)</p> 7 + 8 + <script> 9 + // TODO: tie this back to its source........... 10 + 11 + localStorage.setItem("who-am-i", JSON.stringify({ 12 + result: "success", 13 + did: {{{json did}}}, 14 + token: {{{json token}}}, 15 + fetch_key: {{{json fetch_key}}}, 16 + })); 17 + // TODO: probably also wait for a reply from the frame and show an error if not 18 + window.close(); 19 + </script>
+17
who-am-i/templates/base-base.hbs
··· 1 + <!doctype html> 2 + <html lang="en"> 3 + <head> 4 + <meta charset="utf-8" /> 5 + <title>who-am-i</title> 6 + <meta name="description" content="{{> description }}"> 7 + <meta property="og:type" content="website"> 8 + <meta property="og:description" content="{{> description}}"> 9 + <!-- <meta property="og:image" content=""> --> 10 + 11 + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> 12 + <link href="/style.css" rel="stylesheet" type="text/css" /> 13 + </head> 14 + <body> 15 + {{> body}} 16 + </body> 17 + </html>
+28
who-am-i/templates/base-framed.hbs
··· 1 + {{#*inline "description"}}{{/inline}} 2 + 3 + {{#*inline "body"}} 4 + <div class="wrap"> 5 + <header> 6 + <div class="empty">🔒</div> 7 + <code class="title" style="font-family: monospace;" 8 + >who-am-i</code> 9 + <a href="https://microcosm.blue" target="_blank" class="micro" 10 + ><span style="color: #f396a9">m</span 11 + ><span style="color: #f49c5c">i</span 12 + ><span style="color: #c7b04c">c</span 13 + ><span style="color: #92be4c">r</span 14 + ><span style="color: #4ec688">o</span 15 + ><span style="color: #51c2b6">c</span 16 + ><span style="color: #54bed7">o</span 17 + ><span style="color: #8fb1f1">s</span 18 + ><span style="color: #ce9df1">m</span 19 + ></a> 20 + </header> 21 + 22 + <main> 23 + {{> main}} 24 + </main> 25 + </div> 26 + {{/inline}} 27 + 28 + {{#> base-base}}{{/base-base}}
+26
who-am-i/templates/base-full.hbs
··· 1 + {{#*inline "body"}} 2 + <div class="wrap unframed"> 3 + <header> 4 + <div class="empty">🔒</div> 5 + <code class="title" style="font-family: monospace;" 6 + >who-am-i</code> 7 + <a href="https://microcosm.blue" target="_blank" class="micro" 8 + ><span style="color: #f396a9">m</span 9 + ><span style="color: #f49c5c">i</span 10 + ><span style="color: #c7b04c">c</span 11 + ><span style="color: #92be4c">r</span 12 + ><span style="color: #4ec688">o</span 13 + ><span style="color: #51c2b6">c</span 14 + ><span style="color: #54bed7">o</span 15 + ><span style="color: #8fb1f1">s</span 16 + ><span style="color: #ce9df1">m</span 17 + ></a> 18 + </header> 19 + 20 + <main> 21 + {{> main}} 22 + </main> 23 + </div> 24 + {{/inline}} 25 + 26 + {{#> base-base}}{{/base-base}}
+122
who-am-i/templates/hello.hbs
··· 1 + {{#*inline "description"}}A little identity-verifying auth service for microcosm demos{{/inline}} 2 + 3 + {{#*inline "main"}} 4 + <div class="mini-content"> 5 + <div class="explain"> 6 + <p>This is a little identity-verifying service for microcosm demos.</p> 7 + <p>Only <strong>read access to your public data</strong> is required to connect: connecting does not grant any ability to modify your account or data.</p> 8 + </div> 9 + 10 + {{#if did}} 11 + <p id="error-message" class="hidden"></p> 12 + 13 + <p id="prompt" class="detail"> 14 + Connected identity: 15 + </p> 16 + 17 + <div id="loader"> 18 + <span class="spinner"></span> 19 + </div> 20 + 21 + <div id="user-info"> 22 + <div id="handle-action" class="action"> 23 + <span id="handle-view" class="handle"></span> 24 + <button id="revoke">disconnect</button> 25 + </div> 26 + </div> 27 + <script> 28 + const errorEl = document.getElementById('error-message'); 29 + const loaderEl = document.getElementById('loader'); 30 + const handleViewEl = document.getElementById('handle-view'); 31 + const revokeEl = document.getElementById('revoke'); // for known-did 32 + 33 + function err(e, msg) { 34 + loaderEl.classList.add('hidden'); 35 + errorEl.classList.remove('hidden'); 36 + errorEl.textContent = msg || e; 37 + throw new Error(e); 38 + } 39 + 40 + // already-known user 41 + ({{{json did}}}) && (async () => { 42 + 43 + const handle = await lookUp({{{json fetch_key}}}); 44 + 45 + loaderEl.classList.add('hidden'); 46 + handleViewEl.textContent = `@${handle}`; 47 + revokeEl.addEventListener('click', async () => { 48 + try { 49 + let res = await fetch('/disconnect', { method: 'POST', credentials: 'include' }); 50 + if (!res.ok) throw res; 51 + } catch (e) { 52 + err(e, 'failed to clear session, sorry'); 53 + } 54 + window.location.replace(location.pathname); 55 + window.location.reload(); // backup, in case there is no query? 56 + }); 57 + })(); 58 + 59 + async function lookUp(fetch_key) { 60 + let info; 61 + try { 62 + const resp = await fetch('/user-info', { 63 + method: 'POST', 64 + headers: {'Content-Type': 'application/json'}, 65 + body: JSON.stringify({ fetch_key }), 66 + }); 67 + if (!resp.ok) throw resp; 68 + info = await resp.json(); 69 + } catch (e) { 70 + err(e, 'failed to resolve handle from DID') 71 + } 72 + return info.handle; 73 + } 74 + </script> 75 + {{else}} 76 + 77 + <p class="hello-connect-plz">Connect your handle</p> 78 + 79 + {{#if is_auth_reload}} 80 + {{#if no_cookie}} 81 + <p id="prompt" class="detail no"> 82 + No identity connected. Your browser may be blocking access for connecting. 83 + </p> 84 + {{else}} 85 + {{#if auth_failed}} 86 + <p id="prompt" class="detail no"> 87 + No identity connected. Connecting failed or was denied. 88 + </p> 89 + {{else}} 90 + <p id="prompt" class="detail no"> 91 + No identity connected. 92 + </p> 93 + {{/if}} 94 + {{/if}} 95 + {{/if}} 96 + 97 + <div id="user-info"> 98 + <form id="form-action" action="/auth" target="_blank" method="GET" class="action {{#if did}}hidden{{/if}}"> 99 + <label> 100 + @<input id="handle-input" class="handle" name="handle" placeholder="example.bsky.social" /> 101 + </label> 102 + <button id="connect" type="submit">connect</button> 103 + </form> 104 + </div> 105 + {{/if}} 106 + 107 + </div> 108 + <script> 109 + window.addEventListener('storage', e => { 110 + console.log('eyyy got storage', e); 111 + if (e.key !== 'who-am-i') return; 112 + if (!e.newValue) return; 113 + if (e.newValue.result === 'success') { 114 + window.location = '/?auth_reload=1'; 115 + } else { 116 + window.location = '/?auth_reload=1&auth_failed=1'; 117 + } 118 + }); 119 + </script> 120 + {{/inline}} 121 + 122 + {{#> base-full}}{{/base-full}}
+18
who-am-i/templates/prompt-error.hbs
··· 1 + {{#*inline "main"}} 2 + <div class="prompt-error"> 3 + <p class="went-wrong">Something went wrong :(</p> 4 + <p class="reason">{{ reason }}</p> 5 + <p class="reason detail">{{ detail }}</p> 6 + <p id="maybe-not-in-iframe" class="hidden"> 7 + Possibly related: this prompt is meant to be shown in an iframe, but it seems like it's not. 8 + </p> 9 + </div> 10 + 11 + <script> 12 + if ({{{json check_frame}}} && window.self === window.top) { 13 + document.getElementById('maybe-not-in-iframe').classList.remove('hidden'); 14 + } 15 + </script> 16 + {{/inline}} 17 + 18 + {{#> base-framed}}{{/base-framed}}
+187
who-am-i/templates/prompt.hbs
··· 1 + {{#*inline "main"}} 2 + <p> 3 + Connect in the ATmosphere 4 + </p> 5 + 6 + <p id="error-message" class="hidden"></p> 7 + 8 + <p id="prompt" class="detail"> 9 + <span class="parent-host">{{ parent_host }}</span> wants to confirm your handle 10 + </p> 11 + 12 + <div id="loader" {{#unless did}}class="hidden"{{/unless}}> 13 + <span class="spinner"></span> 14 + </div> 15 + 16 + <div id="user-info"> 17 + <form id="form-action" action="/auth" method="GET" target="_blank" class="action {{#if did}}hidden{{/if}}"> 18 + <label> 19 + @<input id="handle-input" class="handle" name="handle" placeholder="example.bsky.social" /> 20 + </label> 21 + <button id="connect" type="submit">connect</button> 22 + </form> 23 + 24 + <div id="handle-action" class="action"> 25 + <span id="handle-view" class="handle"></span> 26 + <button id="allow">Allow</button> 27 + </div> 28 + </div> 29 + 30 + <div id="need-storage" class="hidden"> 31 + <p class="problem">Sorry, your browser is blocking access.</p> 32 + <p> 33 + Try <a href="/" target="_blank">connecting directly</a> first (but no promises). 34 + Clicking <button id="desperation">this button</button> might also help. 35 + </p> 36 + </div> 37 + 38 + 39 + 40 + <script> 41 + const errorEl = document.getElementById('error-message'); 42 + const promptEl = document.getElementById('prompt'); 43 + const loaderEl = document.getElementById('loader'); 44 + const infoEl = document.getElementById('user-info'); 45 + const handleInputEl = document.getElementById('handle-input'); 46 + const handleViewEl = document.getElementById('handle-view'); 47 + const formEl = document.getElementById('form-action'); // for anon 48 + const allowEl = document.getElementById('handle-action'); // for known-did 49 + const connectEl = document.getElementById('connect'); // for anon 50 + const needStorageEl = document.getElementById('need-storage'); // for safari/frame isolation 51 + const desperationEl = document.getElementById('desperation'); 52 + 53 + function err(e, msg) { 54 + loaderEl.classList.add('hidden'); 55 + errorEl.classList.remove('hidden'); 56 + errorEl.textContent = msg || e; 57 + throw new Error(e); 58 + } 59 + 60 + // already-known user 61 + ({{{json did}}}) && (async () => { 62 + const handle = await lookUp({{{json fetch_key}}}); 63 + loaderEl.classList.add('hidden'); 64 + handleViewEl.textContent = `@${handle}`; 65 + allowEl.addEventListener('click', () => shareAllow(handle, {{{json token}}})); 66 + })(); 67 + 68 + // anon user 69 + formEl.onsubmit = e => { 70 + e.preventDefault(); 71 + loaderEl.classList.remove('hidden'); 72 + // TODO: include expected referer! (..this system is probably bad) 73 + // maybe a random localstorage key that we specifically listen for? 74 + const url = new URL('/auth', window.location); 75 + url.searchParams.set('handle', handleInputEl.value); 76 + window.open(url, '_blank'); 77 + }; 78 + 79 + // check if we may be partitioned, preventing access after auth completion 80 + // this should only happen if on a browser that implements storage access api 81 + if ('hasStorageAccess' in document) { 82 + document.hasStorageAccess().then((hasAccess) => { 83 + if (!hasAccess) { 84 + promptEl.classList.add('hidden'); 85 + infoEl.classList.add('hidden'); 86 + needStorageEl.classList.remove('hidden'); 87 + desperation.addEventListener('click', () => { 88 + document.requestStorageAccess({ 89 + cookies: true, 90 + localStorage: true, 91 + }).then( 92 + () => { 93 + desperation.textContent = "(maybe helped?)"; 94 + setTimeout(() => location.reload(), 350); 95 + }, 96 + () => desperation.textContent = "(doubtful)", 97 + ); 98 + }) 99 + } 100 + }); 101 + } 102 + 103 + window.addEventListener('storage', async e => { 104 + // here's a fun minor vuln: we can't tell which flow triggers the storage event. 105 + // so if you have two flows going, it grants for both (or the first responder?) if you grant for either. 106 + // (letting this slide while parent pages are allowlisted to microcosm only) 107 + 108 + if (e.key !== 'who-am-i') return; 109 + if (e.newValue === null) return; 110 + 111 + const details = e.newValue; 112 + if (!details) { 113 + console.error("hmm, heard from localstorage but did not get DID", details, e); 114 + err('sorry, something went wrong getting your details'); 115 + } 116 + 117 + let parsed; 118 + try { 119 + parsed = JSON.parse(details); 120 + } catch (e) { 121 + err(e, "something went wrong getting the details back"); 122 + } 123 + 124 + const fail = (e, msg) => { 125 + loaderEl.classList.add('hidden'); 126 + formEl.classList.remove('hidden'); 127 + handleInputEl.focus(); 128 + handleInputEl.select(); 129 + err(e, msg); 130 + } 131 + 132 + if (parsed.result === "fail") { 133 + fail(`uh oh: ${parsed.reason}`); 134 + } 135 + 136 + if (parsed.result === "deny") { 137 + fail(parsed.reason); 138 + } 139 + 140 + infoEl.classList.add('hidden'); 141 + 142 + const handle = await lookUp(parsed.fetch_key); 143 + 144 + shareAllow(handle, parsed.token); 145 + }); 146 + 147 + async function lookUp(fetch_key) { 148 + let info; 149 + try { 150 + const resp = await fetch('/user-info', { 151 + method: 'POST', 152 + headers: { 'Content-Type': 'application/json' }, 153 + body: JSON.stringify({ fetch_key }), 154 + }); 155 + if (!resp.ok) throw resp; 156 + info = await resp.json(); 157 + } catch (e) { 158 + err(e, `failed to resolve handle from DID with ${fetch_key}`); 159 + } 160 + return info.handle; 161 + } 162 + 163 + const parentTarget = {{{json parent_target}}} ?? {{{json parent_origin}}}; 164 + 165 + const shareAllow = (handle, token) => { 166 + try { 167 + top.postMessage( 168 + { action: "allow", handle, token }, 169 + parentTarget, 170 + ); 171 + } catch (e) { 172 + err(e, 'Identity verified but failed to connect with app'); 173 + }; 174 + promptEl.textContent = '✔️ shared'; 175 + } 176 + 177 + const shareDeny = reason => { 178 + top.postMessage( 179 + { action: "deny", reason }, 180 + parentTarget, 181 + ); 182 + } 183 + </script> 184 + 185 + {{/inline}} 186 + 187 + {{#> base-framed}}{{/base-framed}}