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

Merge branch 'main' into constellation/filtering

+15
.github/FUNDING.yml
···
+
# These are supported funding model platforms
+
+
github: uniphil
+
patreon: # Replace with a single Patreon username
+
open_collective: # Replace with a single Open Collective username
+
ko_fi: # Replace with a single Ko-fi username
+
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
+
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
+
liberapay: # Replace with a single Liberapay username
+
issuehunt: # Replace with a single IssueHunt username
+
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
+
polar: # Replace with a single Polar username
+
buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
+
thanks_dev: # Replace with a single thanks.dev username
+
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
+21
.github/workflows/build.yml
···
+
name: Build
+
+
on:
+
push:
+
tags:
+
- "reflector-v*.*.*"
+
+
jobs:
+
build:
+
runs-on: ubuntu-latest
+
permissions:
+
contents: write
+
+
steps:
+
- uses: actions/checkout@v4
+
- name: build reflector
+
run: cargo build --bin reflector --release && mv target/release/reflector target/release/reflector_amd64
+
- name: release
+
uses: softprops/action-gh-release@v2
+
with:
+
files: target/release/reflector_amd64
+4 -2
.github/workflows/checks.yml
···
- uses: actions/checkout@v4
- name: Build lib
run: cargo build --verbose
+
- name: Check (default features)
+
run: cargo check
- name: Run tests
-
run: cargo test --verbose
+
run: cargo test --all-features --verbose
style:
runs-on: ubuntu-24.04
···
- name: get nightly toolchain for jetstream fmt
run: rustup toolchain install nightly --allow-downgrade -c rustfmt
- name: fmt
-
run: cargo fmt --package links --package constellation --package ufos -- --check
+
run: cargo fmt --package links --package constellation --package ufos --package spacedust --package who-am-i --package slingshot --package pocket -- --check
- name: fmt jetstream (nightly)
run: cargo +nightly fmt --package jetstream -- --check
- name: clippy
+2580 -184
Cargo.lock
···
checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011"
dependencies = [
"cfg-if",
+
"getrandom 0.2.15",
"once_cell",
"version_check",
"zerocopy 0.7.35",
···
checksum = "dde20b3d026af13f561bdd0f15edf01fc734f0dafcedbaf42bba506a9517f223"
[[package]]
+
name = "arc-swap"
+
version = "1.7.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "69f7f8c3906b62b754cd5326047894316021dcfe5a194c8ea52bdd94934a3457"
+
+
[[package]]
name = "arrayvec"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
"proc-macro2",
"quote",
"serde",
-
"syn",
+
"syn 2.0.103",
]
[[package]]
···
]
[[package]]
+
name = "asn1-rs"
+
version = "0.7.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "56624a96882bb8c26d61312ae18cb45868e5a9992ea73c58e45c3101e56a1e60"
+
dependencies = [
+
"asn1-rs-derive",
+
"asn1-rs-impl",
+
"displaydoc",
+
"nom",
+
"num-traits",
+
"rusticata-macros",
+
"thiserror 2.0.16",
+
"time",
+
]
+
+
[[package]]
+
name = "asn1-rs-derive"
+
version = "0.6.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c"
+
dependencies = [
+
"proc-macro2",
+
"quote",
+
"syn 2.0.103",
+
"synstructure",
+
]
+
+
[[package]]
+
name = "asn1-rs-impl"
+
version = "0.2.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7"
+
dependencies = [
+
"proc-macro2",
+
"quote",
+
"syn 2.0.103",
+
]
+
+
[[package]]
+
name = "async-channel"
+
version = "2.5.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"
+
dependencies = [
+
"concurrent-queue",
+
"event-listener-strategy",
+
"futures-core",
+
"pin-project-lite",
+
]
+
+
[[package]]
+
name = "async-compression"
+
version = "0.4.25"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "40f6024f3f856663b45fd0c9b6f2024034a702f453549449e0d84a305900dad4"
+
dependencies = [
+
"flate2",
+
"futures-core",
+
"memchr",
+
"pin-project-lite",
+
"tokio",
+
]
+
+
[[package]]
name = "async-lock"
version = "3.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
]
[[package]]
+
name = "async-task"
+
version = "4.7.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"
+
+
[[package]]
name = "async-trait"
version = "0.1.88"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
]
[[package]]
···
[[package]]
name = "atrium-api"
-
version = "0.25.3"
-
source = "git+https://github.com/uniphil/atrium?branch=fix%2Fnsid-allow-nonleading-name-digits#c4364f318d337bbc3e3e3aaf97c9f971e95f5f7e"
+
version = "0.25.4"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "46355d3245edc7b3160b2a45fe55d09a6963ebd3eee0252feb6b72fb0eb71463"
+
dependencies = [
+
"atrium-common 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
+
"atrium-xrpc 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)",
+
"chrono",
+
"http",
+
"ipld-core",
+
"langtag",
+
"regex",
+
"serde",
+
"serde_bytes",
+
"serde_json",
+
"thiserror 1.0.69",
+
"tokio",
+
"trait-variant",
+
]
+
+
[[package]]
+
name = "atrium-api"
+
version = "0.25.4"
+
source = "git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace#80a355991ac9b48ba3f559d12aac74f071fc638c"
dependencies = [
-
"atrium-common",
-
"atrium-xrpc",
+
"atrium-common 0.1.2 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)",
+
"atrium-xrpc 0.12.3 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)",
"chrono",
"http",
"ipld-core",
···
"serde_bytes",
"serde_json",
"thiserror 1.0.69",
+
"tokio",
"trait-variant",
]
[[package]]
name = "atrium-common"
version = "0.1.2"
-
source = "git+https://github.com/uniphil/atrium?branch=fix%2Fnsid-allow-nonleading-name-digits#c4364f318d337bbc3e3e3aaf97c9f971e95f5f7e"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "9ed5610654043faa396a5a15afac0ac646d76aebe45aebd7cef4f8b96b0ab7f4"
+
dependencies = [
+
"dashmap",
+
"lru",
+
"moka",
+
"thiserror 1.0.69",
+
"tokio",
+
"trait-variant",
+
"web-time",
+
]
+
+
[[package]]
+
name = "atrium-common"
+
version = "0.1.2"
+
source = "git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace#80a355991ac9b48ba3f559d12aac74f071fc638c"
dependencies = [
"dashmap",
"lru",
···
]
[[package]]
+
name = "atrium-crypto"
+
version = "0.1.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "73a3da430c71dd9006d61072c20771f264e5c498420a49c32305ceab8bd71955"
+
dependencies = [
+
"ecdsa",
+
"k256",
+
"multibase",
+
"p256",
+
"thiserror 1.0.69",
+
]
+
+
[[package]]
+
name = "atrium-identity"
+
version = "0.1.5"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "c9e2d42bb4dbea038f4f5f45e3af2a89d61a9894a75f06aa550b74a60d2be380"
+
dependencies = [
+
"atrium-api 0.25.4 (registry+https://github.com/rust-lang/crates.io-index)",
+
"atrium-common 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
+
"atrium-xrpc 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)",
+
"serde",
+
"serde_html_form",
+
"serde_json",
+
"thiserror 1.0.69",
+
"trait-variant",
+
]
+
+
[[package]]
+
name = "atrium-identity"
+
version = "0.1.5"
+
source = "git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace#80a355991ac9b48ba3f559d12aac74f071fc638c"
+
dependencies = [
+
"atrium-api 0.25.4 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)",
+
"atrium-common 0.1.2 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)",
+
"atrium-xrpc 0.12.3 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)",
+
"serde",
+
"serde_html_form",
+
"serde_json",
+
"thiserror 1.0.69",
+
"trait-variant",
+
]
+
+
[[package]]
+
name = "atrium-oauth"
+
version = "0.1.3"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "ca22dc4eaf77fd9bf050b21192ac58cd654a437d28e000ec114ebd93a51d36f5"
+
dependencies = [
+
"atrium-api 0.25.4 (registry+https://github.com/rust-lang/crates.io-index)",
+
"atrium-common 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
+
"atrium-identity 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
+
"atrium-xrpc 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)",
+
"base64 0.22.1",
+
"chrono",
+
"dashmap",
+
"ecdsa",
+
"elliptic-curve",
+
"jose-jwa",
+
"jose-jwk",
+
"p256",
+
"rand 0.8.5",
+
"reqwest",
+
"serde",
+
"serde_html_form",
+
"serde_json",
+
"sha2",
+
"thiserror 1.0.69",
+
"tokio",
+
"trait-variant",
+
]
+
+
[[package]]
+
name = "atrium-oauth"
+
version = "0.1.3"
+
source = "git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace#80a355991ac9b48ba3f559d12aac74f071fc638c"
+
dependencies = [
+
"atrium-api 0.25.4 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)",
+
"atrium-common 0.1.2 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)",
+
"atrium-identity 0.1.5 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)",
+
"atrium-xrpc 0.12.3 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)",
+
"base64 0.22.1",
+
"chrono",
+
"dashmap",
+
"ecdsa",
+
"elliptic-curve",
+
"jose-jwa",
+
"jose-jwk",
+
"p256",
+
"rand 0.8.5",
+
"reqwest",
+
"serde",
+
"serde_html_form",
+
"serde_json",
+
"sha2",
+
"thiserror 1.0.69",
+
"tokio",
+
"trait-variant",
+
]
+
+
[[package]]
name = "atrium-xrpc"
version = "0.12.3"
-
source = "git+https://github.com/uniphil/atrium?branch=fix%2Fnsid-allow-nonleading-name-digits#c4364f318d337bbc3e3e3aaf97c9f971e95f5f7e"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "0216ad50ce34e9ff982e171c3659e65dedaa2ed5ac2994524debdc9a9647ffa8"
+
dependencies = [
+
"http",
+
"serde",
+
"serde_html_form",
+
"serde_json",
+
"thiserror 1.0.69",
+
"trait-variant",
+
]
+
+
[[package]]
+
name = "atrium-xrpc"
+
version = "0.12.3"
+
source = "git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace#80a355991ac9b48ba3f559d12aac74f071fc638c"
dependencies = [
"http",
"serde",
···
]
[[package]]
+
name = "auto_enums"
+
version = "0.8.7"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "9c170965892137a3a9aeb000b4524aa3cc022a310e709d848b6e1cdce4ab4781"
+
dependencies = [
+
"derive_utils",
+
"proc-macro2",
+
"quote",
+
"syn 2.0.103",
+
]
+
+
[[package]]
name = "autocfg"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
[[package]]
+
name = "aws-lc-rs"
+
version = "1.13.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "93fcc8f365936c834db5514fc45aee5b1202d677e6b40e48468aaaa8183ca8c7"
+
dependencies = [
+
"aws-lc-sys",
+
"zeroize",
+
]
+
+
[[package]]
+
name = "aws-lc-sys"
+
version = "0.29.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "61b1d86e7705efe1be1b569bab41d4fa1e14e220b60a160f78de2db687add079"
+
dependencies = [
+
"bindgen 0.69.5",
+
"cc",
+
"cmake",
+
"dunce",
+
"fs_extra",
+
]
+
+
[[package]]
name = "axum"
-
version = "0.8.3"
+
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "de45108900e1f9b9242f7f2e254aa3e2c029c921c258fe9e6b4217eeebd54288"
+
checksum = "021e862c184ae977658b36c4500f7feac3221ca5da43e3f25bd04ab6c79a29b5"
dependencies = [
"axum-core",
"bytes",
···
"axum",
"axum-core",
"bytes",
+
"cookie",
"futures-util",
"headers",
"http",
···
]
[[package]]
+
name = "axum-template"
+
version = "3.0.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "3df50f7d669bfc3a8c348f08f536fe37e7acfbeded3cfdffd2ad3d76725fc40c"
+
dependencies = [
+
"axum",
+
"handlebars",
+
"serde",
+
"thiserror 2.0.16",
+
]
+
+
[[package]]
name = "backtrace"
version = "0.3.74"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
"miniz_oxide",
"object",
"rustc-demangle",
-
"windows-targets",
+
"windows-targets 0.52.6",
]
[[package]]
···
checksum = "4cbbc9d0964165b47557570cce6c952866c2678457aca742aafc9fb771d30270"
[[package]]
+
name = "base16ct"
+
version = "0.2.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf"
+
+
[[package]]
name = "base64"
version = "0.21.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+
+
[[package]]
+
name = "base64ct"
+
version = "1.8.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "55248b47b0caf0546f7988906588779981c43bb1bc9d0c44087278f80cdb44ba"
[[package]]
name = "basic-toml"
···
"itertools 0.12.1",
"lazy_static",
"lazycell",
+
"log",
+
"prettyplease",
"proc-macro2",
"quote",
"regex",
"rustc-hash 1.1.0",
"shlex",
-
"syn",
+
"syn 2.0.103",
+
"which",
]
[[package]]
···
"regex",
"rustc-hash 1.1.0",
"shlex",
-
"syn",
+
"syn 2.0.103",
]
[[package]]
···
"regex",
"rustc-hash 2.1.1",
"shlex",
-
"syn",
+
"syn 2.0.103",
+
]
+
+
[[package]]
+
name = "bitcoin-io"
+
version = "0.1.3"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "0b47c4ab7a93edb0c7198c5535ed9b52b63095f4e9b45279c6736cec4b856baf"
+
+
[[package]]
+
name = "bitcoin_hashes"
+
version = "0.14.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "bb18c03d0db0247e147a21a6faafd5a7eb851c743db062de72018b6b7e8e4d16"
+
dependencies = [
+
"bitcoin-io",
+
"hex-conservative",
]
[[package]]
···
[[package]]
name = "cardinality-estimator-safe"
-
version = "4.0.1"
+
version = "4.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "b41ec0cd313b46ba3b508377544b25aa1d56d05ce9e657e77dfb001d5e726e53"
+
checksum = "dc9887b4092040ea9a416fc3de9769ee7783e3cd5c168c941e6a8de69723b971"
dependencies = [
"digest",
"enum_dispatch",
···
]
[[package]]
+
name = "ciborium"
+
version = "0.2.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e"
+
dependencies = [
+
"ciborium-io",
+
"ciborium-ll",
+
"serde",
+
]
+
+
[[package]]
+
name = "ciborium-io"
+
version = "0.2.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757"
+
+
[[package]]
+
name = "ciborium-ll"
+
version = "0.2.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9"
+
dependencies = [
+
"ciborium-io",
+
"half",
+
]
+
+
[[package]]
name = "cid"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
[[package]]
name = "clap"
-
version = "4.5.35"
+
version = "4.5.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "d8aa86934b44c19c50f87cc2790e19f54f7a67aedb64101c2e1a2e5ecfb73944"
+
checksum = "7eac00902d9d136acd712710d71823fb8ac8004ca445a89e73a41d45aa712931"
dependencies = [
"clap_builder",
"clap_derive",
···
[[package]]
name = "clap_builder"
-
version = "4.5.35"
+
version = "4.5.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "2414dbb2dd0695280da6ea9261e327479e9d37b0630f6b53ba2a11c60c679fd9"
+
checksum = "2ad9bbf750e73b5884fb8a211a9424a1906c1e156724260fdae972f31d70e1d6"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
-
"strsim",
+
"strsim 0.11.1",
]
[[package]]
name = "clap_derive"
-
version = "4.5.32"
+
version = "4.5.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "09176aae279615badda0765c0c0b3f6ed53f4709118af73cf4655d85d1530cd7"
+
checksum = "bbfd7eae0b0f1a6e63d4b13c9c478de77c2eb546fba158ad50b4203dc24b9f9c"
dependencies = [
"heck",
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
]
[[package]]
···
]
[[package]]
+
name = "cmake"
+
version = "0.1.54"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "e7caa3f9de89ddbe2c607f4101924c5abec803763ae9534e4f4d7d8f84aa81f0"
+
dependencies = [
+
"cc",
+
]
+
+
[[package]]
+
name = "cmsketch"
+
version = "0.2.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "553c840ee51da812c6cd621f9f7e07dfb00a49f91283a8e6380c78cba4f61aba"
+
dependencies = [
+
"paste",
+
]
+
+
[[package]]
name = "colorchoice"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
]
[[package]]
+
name = "const-oid"
+
version = "0.9.6"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
+
+
[[package]]
name = "constellation"
version = "0.1.0"
dependencies = [
···
"clap",
"ctrlc",
"flume",
-
"fs4",
+
"fs4 0.12.0",
"headers-accept",
"links",
"mediatype",
"metrics",
-
"metrics-exporter-prometheus",
+
"metrics-exporter-prometheus 0.16.2",
"metrics-process",
"num-format",
"ratelimit",
···
"tokio",
"tokio-util",
"tower-http",
-
"tungstenite",
+
"tungstenite 0.26.2",
"zstd",
]
[[package]]
+
name = "cookie"
+
version = "0.18.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747"
+
dependencies = [
+
"base64 0.22.1",
+
"hmac",
+
"percent-encoding",
+
"rand 0.8.5",
+
"sha2",
+
"subtle",
+
"time",
+
"version_check",
+
]
+
+
[[package]]
name = "core-foundation"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
]
[[package]]
+
name = "core-foundation"
+
version = "0.10.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
+
dependencies = [
+
"core-foundation-sys",
+
"libc",
+
]
+
+
[[package]]
name = "core-foundation-sys"
version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
]
[[package]]
+
name = "crc32fast"
+
version = "1.4.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3"
+
dependencies = [
+
"cfg-if",
+
]
+
+
[[package]]
+
name = "critical-section"
+
version = "1.2.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b"
+
+
[[package]]
name = "crossbeam-channel"
version = "0.5.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
[[package]]
+
name = "crunchy"
+
version = "0.2.4"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
+
+
[[package]]
+
name = "crypto-bigint"
+
version = "0.5.5"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76"
+
dependencies = [
+
"generic-array",
+
"rand_core 0.6.4",
+
"subtle",
+
"zeroize",
+
]
+
+
[[package]]
name = "crypto-common"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
[[package]]
name = "ctrlc"
-
version = "3.4.6"
+
version = "3.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "697b5419f348fd5ae2478e8018cb016c00a5881c7f46c717de98ffd135a5651c"
+
checksum = "46f93780a459b7d656ef7f071fe699c4d3d2cb201c4b24d085b6ddc505276e73"
dependencies = [
"nix",
"windows-sys 0.59.0",
···
[[package]]
name = "darling"
+
version = "0.14.4"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "7b750cb3417fd1b327431a470f388520309479ab0bf5e323505daf0290cd3850"
+
dependencies = [
+
"darling_core 0.14.4",
+
"darling_macro 0.14.4",
+
]
+
+
[[package]]
+
name = "darling"
version = "0.20.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee"
dependencies = [
-
"darling_core",
-
"darling_macro",
+
"darling_core 0.20.11",
+
"darling_macro 0.20.11",
+
]
+
+
[[package]]
+
name = "darling_core"
+
version = "0.14.4"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "109c1ca6e6b7f82cc233a97004ea8ed7ca123a9af07a8230878fcfda9b158bf0"
+
dependencies = [
+
"fnv",
+
"ident_case",
+
"proc-macro2",
+
"quote",
+
"strsim 0.10.0",
+
"syn 1.0.109",
]
[[package]]
···
"ident_case",
"proc-macro2",
"quote",
-
"strsim",
-
"syn",
+
"strsim 0.11.1",
+
"syn 2.0.103",
+
]
+
+
[[package]]
+
name = "darling_macro"
+
version = "0.14.4"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "a4aab4dbc9f7611d8b55048a3a16d2d010c2c8334e46304b40ac1cc14bf3b48e"
+
dependencies = [
+
"darling_core 0.14.4",
+
"quote",
+
"syn 1.0.109",
]
[[package]]
···
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead"
dependencies = [
-
"darling_core",
+
"darling_core 0.20.11",
"quote",
-
"syn",
+
"syn 2.0.103",
]
[[package]]
···
checksum = "18e4fdb82bd54a12e42fb58a800dcae6b9e13982238ce2296dc3570b92148e1f"
dependencies = [
"data-encoding",
-
"syn",
+
"syn 2.0.103",
]
[[package]]
···
checksum = "ffe7ed1d93f4553003e20b629abe9085e1e81b1429520f897f8f8860bc6dfc21"
[[package]]
+
name = "der"
+
version = "0.7.10"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
+
dependencies = [
+
"const-oid",
+
"pem-rfc7468",
+
"zeroize",
+
]
+
+
[[package]]
+
name = "der-parser"
+
version = "10.0.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6"
+
dependencies = [
+
"asn1-rs",
+
"displaydoc",
+
"nom",
+
"num-bigint",
+
"num-traits",
+
"rusticata-macros",
+
]
+
+
[[package]]
name = "deranged"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
]
[[package]]
+
name = "derive_builder"
+
version = "0.20.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947"
+
dependencies = [
+
"derive_builder_macro",
+
]
+
+
[[package]]
+
name = "derive_builder_core"
+
version = "0.20.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8"
+
dependencies = [
+
"darling 0.20.11",
+
"proc-macro2",
+
"quote",
+
"syn 2.0.103",
+
]
+
+
[[package]]
+
name = "derive_builder_macro"
+
version = "0.20.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c"
+
dependencies = [
+
"derive_builder_core",
+
"syn 2.0.103",
+
]
+
+
[[package]]
+
name = "derive_more"
+
version = "2.0.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "093242cf7570c207c83073cf82f79706fe7b8317e98620a47d5be7c3d8497678"
+
dependencies = [
+
"derive_more-impl",
+
]
+
+
[[package]]
+
name = "derive_more-impl"
+
version = "2.0.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3"
+
dependencies = [
+
"proc-macro2",
+
"quote",
+
"syn 2.0.103",
+
"unicode-xid",
+
]
+
+
[[package]]
+
name = "derive_utils"
+
version = "0.15.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "ccfae181bab5ab6c5478b2ccb69e4c68a02f8c3ec72f6616bfec9dbc599d2ee0"
+
dependencies = [
+
"proc-macro2",
+
"quote",
+
"syn 2.0.103",
+
]
+
+
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
+
"const-oid",
"crypto-common",
+
"subtle",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
]
[[package]]
···
checksum = "c0d05e1c0dbad51b52c38bda7adceef61b9efc2baf04acfe8726a8c4630a6f57"
[[package]]
+
name = "downcast-rs"
+
version = "1.2.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
+
+
[[package]]
name = "dropshot"
-
version = "0.16.0"
+
version = "0.16.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "a37c505dad56e0c1fa5ed47e29fab1a1ab2d1a9d93e952024bb47168969705f6"
+
checksum = "50e8fed669e35e757646ad10f97c4d26dd22cce3da689b307954f7000d2719d0"
dependencies = [
"async-stream",
"async-trait",
···
"openapiv3",
"paste",
"percent-encoding",
-
"rustls",
+
"rustls 0.22.4",
"rustls-pemfile",
"schemars",
"scopeguard",
···
"slog-bunyan",
"slog-json",
"slog-term",
-
"thiserror 2.0.12",
+
"thiserror 2.0.16",
"tokio",
-
"tokio-rustls",
+
"tokio-rustls 0.25.0",
"toml",
"uuid",
"version_check",
···
[[package]]
name = "dropshot_endpoint"
-
version = "0.16.0"
+
version = "0.16.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "8b1a6db3728f0195e3ad62807649913aaba06d45421e883416e555e51464ef67"
+
checksum = "acebb687581abdeaa2c89fa448818a5f803b0e68e5d7e7a1cf585a8f3c5c57ac"
dependencies = [
"heck",
"proc-macro2",
···
"semver",
"serde",
"serde_tokenstream",
-
"syn",
+
"syn 2.0.103",
[[package]]
+
name = "dunce"
+
version = "1.0.5"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
+
+
[[package]]
name = "dyn-clone"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c7a8fb8a9fbf66c1f703fe16184d10ca0ee9d23be5b4436400408ba54a95005"
[[package]]
+
name = "ecdsa"
+
version = "0.16.9"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca"
+
dependencies = [
+
"der",
+
"digest",
+
"elliptic-curve",
+
"rfc6979",
+
"signature",
+
"spki",
+
]
+
+
[[package]]
name = "either"
version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
[[package]]
+
name = "elliptic-curve"
+
version = "0.13.8"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47"
+
dependencies = [
+
"base16ct",
+
"crypto-bigint",
+
"digest",
+
"ff",
+
"generic-array",
+
"group",
+
"pem-rfc7468",
+
"pkcs8",
+
"rand_core 0.6.4",
+
"sec1",
+
"subtle",
+
"zeroize",
+
]
+
+
[[package]]
name = "encoding_rs"
version = "0.8.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
[[package]]
+
name = "enum-as-inner"
+
version = "0.6.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc"
+
dependencies = [
+
"heck",
+
"proc-macro2",
+
"quote",
+
"syn 2.0.103",
+
]
+
+
[[package]]
name = "enum_dispatch"
version = "0.3.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
"once_cell",
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
[[package]]
···
[[package]]
+
name = "fallible-iterator"
+
version = "0.3.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
+
+
[[package]]
+
name = "fallible-streaming-iterator"
+
version = "0.1.9"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
+
+
[[package]]
name = "fastrand"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
[[package]]
+
name = "ff"
+
version = "0.13.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393"
+
dependencies = [
+
"rand_core 0.6.4",
+
"subtle",
+
]
+
+
[[package]]
name = "fjall"
-
version = "2.8.0"
+
version = "2.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "26b2ced3483989a62b3533c9f99054d73b527c6c0045cf22b00fe87956f1a46f"
+
checksum = "0b25ad44cd4360a0448a9b5a0a6f1c7a621101cca4578706d43c9a821418aebc"
+
dependencies = [
+
"byteorder",
+
"byteview",
+
"dashmap",
+
"log",
+
"lsm-tree",
+
"path-absolutize",
+
"std-semaphore",
+
"tempfile",
+
"xxhash-rust",
+
]
+
+
[[package]]
+
name = "fjall"
+
version = "2.11.2"
+
source = "git+https://github.com/fjall-rs/fjall.git#42d811f7c8cc9004407d520d37d2a1d8d246c03d"
dependencies = [
"byteorder",
"byteview",
···
[[package]]
+
name = "flate2"
+
version = "1.1.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "4a3d7db9596fecd151c5f638c0ee5d5bd487b6e0ea232e5dc96d5250f6f94b1d"
+
dependencies = [
+
"crc32fast",
+
"miniz_oxide",
+
]
+
+
[[package]]
name = "fluent-uri"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095"
dependencies = [
+
"futures-core",
+
"futures-sink",
+
"nanorand",
"spin",
···
[[package]]
+
name = "foyer"
+
version = "0.18.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "0b4d8e96374206ff1b4265f2e2e6e1f80bc3048957b2a1e7fdeef929d68f318f"
+
dependencies = [
+
"equivalent",
+
"foyer-common",
+
"foyer-memory",
+
"foyer-storage",
+
"madsim-tokio",
+
"mixtrics",
+
"pin-project",
+
"serde",
+
"thiserror 2.0.16",
+
"tokio",
+
"tracing",
+
]
+
+
[[package]]
+
name = "foyer-common"
+
version = "0.18.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "911b8e3f23d5fe55b0b240f75af1d2fa5cb7261d3f9b38ef1c57bbc9f0449317"
+
dependencies = [
+
"bincode 1.3.3",
+
"bytes",
+
"cfg-if",
+
"itertools 0.14.0",
+
"madsim-tokio",
+
"mixtrics",
+
"parking_lot",
+
"pin-project",
+
"serde",
+
"thiserror 2.0.16",
+
"tokio",
+
"twox-hash",
+
]
+
+
[[package]]
+
name = "foyer-intrusive-collections"
+
version = "0.10.0-dev"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "6e4fee46bea69e0596130e3210e65d3424e0ac1e6df3bde6636304bdf1ca4a3b"
+
dependencies = [
+
"memoffset",
+
]
+
+
[[package]]
+
name = "foyer-memory"
+
version = "0.18.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "506883d5a8500dea1b1662f7180f3534bdcbfa718d3253db7179552ef83612fa"
+
dependencies = [
+
"arc-swap",
+
"bitflags",
+
"cmsketch",
+
"equivalent",
+
"foyer-common",
+
"foyer-intrusive-collections",
+
"hashbrown 0.15.2",
+
"itertools 0.14.0",
+
"madsim-tokio",
+
"mixtrics",
+
"parking_lot",
+
"pin-project",
+
"serde",
+
"thiserror 2.0.16",
+
"tokio",
+
"tracing",
+
]
+
+
[[package]]
+
name = "foyer-storage"
+
version = "0.18.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "1ba8403a54a2f2032fb647e49c442e5feeb33f3989f7024f1b178341a016f06d"
+
dependencies = [
+
"allocator-api2",
+
"anyhow",
+
"auto_enums",
+
"bytes",
+
"equivalent",
+
"flume",
+
"foyer-common",
+
"foyer-memory",
+
"fs4 0.13.1",
+
"futures-core",
+
"futures-util",
+
"itertools 0.14.0",
+
"libc",
+
"lz4",
+
"madsim-tokio",
+
"ordered_hash_map",
+
"parking_lot",
+
"paste",
+
"pin-project",
+
"rand 0.9.1",
+
"serde",
+
"thiserror 2.0.16",
+
"tokio",
+
"tracing",
+
"twox-hash",
+
"zstd",
+
]
+
+
[[package]]
name = "fs4"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
[[package]]
+
name = "fs4"
+
version = "0.13.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "8640e34b88f7652208ce9e88b1a37a2ae95227d84abec377ccd3c5cfeb141ed4"
+
dependencies = [
+
"rustix 1.0.5",
+
"windows-sys 0.59.0",
+
]
+
+
[[package]]
+
name = "fs_extra"
+
version = "1.3.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
+
+
[[package]]
name = "futures"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
[[package]]
···
dependencies = [
"typenum",
"version_check",
+
"zeroize",
[[package]]
···
checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7"
dependencies = [
"cfg-if",
+
"js-sys",
"libc",
"wasi 0.11.0+wasi-snapshot-preview1",
+
"wasm-bindgen",
[[package]]
···
checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4"
dependencies = [
"cfg-if",
+
"js-sys",
"libc",
"r-efi",
"wasi 0.14.2+wasi-0.2.4",
+
"wasm-bindgen",
[[package]]
···
checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2"
[[package]]
+
name = "group"
+
version = "0.13.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63"
+
dependencies = [
+
"ff",
+
"rand_core 0.6.4",
+
"subtle",
+
]
+
+
[[package]]
name = "guardian"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
[[package]]
+
name = "half"
+
version = "2.6.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "459196ed295495a68f7d7fe1d84f6c4b7ff0e21fe3017b2f283c6fac3ad803c9"
+
dependencies = [
+
"cfg-if",
+
"crunchy",
+
]
+
+
[[package]]
+
name = "handlebars"
+
version = "6.3.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "759e2d5aea3287cb1190c8ec394f42866cb5bf74fcbf213f354e3c856ea26098"
+
dependencies = [
+
"derive_builder",
+
"log",
+
"num-order",
+
"pest",
+
"pest_derive",
+
"serde",
+
"serde_json",
+
"thiserror 2.0.16",
+
"walkdir",
+
]
+
+
[[package]]
name = "hashbrown"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
[[package]]
name = "hashbrown"
+
version = "0.13.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e"
+
dependencies = [
+
"ahash",
+
]
+
+
[[package]]
+
name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
···
[[package]]
+
name = "hashlink"
+
version = "0.10.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1"
+
dependencies = [
+
"hashbrown 0.15.2",
+
]
+
+
[[package]]
name = "headers"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
+
name = "hex-conservative"
+
version = "0.2.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "5313b072ce3c597065a808dbf612c4c8e8590bdbf8b579508bf7a762c5eae6cd"
+
dependencies = [
+
"arrayvec",
+
]
+
+
[[package]]
+
name = "hickory-proto"
+
version = "0.25.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "f8a6fe56c0038198998a6f217ca4e7ef3a5e51f46163bd6dd60b5c71ca6c6502"
+
dependencies = [
+
"async-trait",
+
"cfg-if",
+
"data-encoding",
+
"enum-as-inner",
+
"futures-channel",
+
"futures-io",
+
"futures-util",
+
"idna",
+
"ipnet",
+
"once_cell",
+
"rand 0.9.1",
+
"ring",
+
"thiserror 2.0.16",
+
"tinyvec",
+
"tokio",
+
"tracing",
+
"url",
+
]
+
+
[[package]]
+
name = "hickory-resolver"
+
version = "0.25.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "dc62a9a99b0bfb44d2ab95a7208ac952d31060efc16241c87eaf36406fecf87a"
+
dependencies = [
+
"cfg-if",
+
"futures-util",
+
"hickory-proto",
+
"ipconfig",
+
"moka",
+
"once_cell",
+
"parking_lot",
+
"rand 0.9.1",
+
"resolv-conf",
+
"smallvec",
+
"thiserror 2.0.16",
+
"tokio",
+
"tracing",
+
]
+
+
[[package]]
+
name = "hmac"
+
version = "0.12.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
+
dependencies = [
+
"digest",
+
]
+
+
[[package]]
+
name = "home"
+
version = "0.5.11"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "589533453244b0995c858700322199b2becb13b627df2851f64a2775d024abcf"
+
dependencies = [
+
"windows-sys 0.59.0",
+
]
+
+
[[package]]
name = "hostname"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
[[package]]
+
name = "hyper-rustls"
+
version = "0.27.7"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58"
+
dependencies = [
+
"http",
+
"hyper",
+
"hyper-util",
+
"rustls 0.23.31",
+
"rustls-native-certs",
+
"rustls-pki-types",
+
"tokio",
+
"tokio-rustls 0.26.2",
+
"tower-service",
+
]
+
+
[[package]]
+
name = "hyper-tls"
+
version = "0.6.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0"
+
dependencies = [
+
"bytes",
+
"http-body-util",
+
"hyper",
+
"hyper-util",
+
"native-tls",
+
"tokio",
+
"tokio-native-tls",
+
"tower-service",
+
]
+
+
[[package]]
name = "hyper-util"
-
version = "0.1.11"
+
version = "0.1.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "497bbc33a26fdd4af9ed9c70d63f61cf56a938375fbb32df34db9b1cd6d643f2"
+
checksum = "8d9b05277c7e8da2c93a568989bb6207bef0112e8d17df7a6eda4a3cf143bc5e"
dependencies = [
+
"base64 0.22.1",
"bytes",
"futures-channel",
+
"futures-core",
"futures-util",
"http",
"http-body",
"hyper",
+
"ipnet",
"libc",
+
"percent-encoding",
"pin-project-lite",
-
"socket2",
+
"socket2 0.6.0",
+
"system-configuration",
"tokio",
"tower-service",
"tracing",
+
"windows-registry",
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
[[package]]
···
[[package]]
+
name = "io-uring"
+
version = "0.7.9"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "d93587f37623a1a17d94ef2bc9ada592f5465fe7732084ab7beefabe5c77c0c4"
+
dependencies = [
+
"bitflags",
+
"cfg-if",
+
"libc",
+
]
+
+
[[package]]
+
name = "ipconfig"
+
version = "0.3.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "b58db92f96b720de98181bbbe63c831e87005ab460c1bf306eb2622b4707997f"
+
dependencies = [
+
"socket2 0.5.9",
+
"widestring",
+
"windows-sys 0.48.0",
+
"winreg",
+
]
+
+
[[package]]
name = "ipld-core"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130"
[[package]]
+
name = "iri-string"
+
version = "0.7.8"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "dbc5ebe9c3a1a7a5127f920a418f7585e9e758e911d0466ed004f393b0e380b2"
+
dependencies = [
+
"memchr",
+
"serde",
+
]
+
+
[[package]]
name = "is-terminal"
version = "0.4.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
[[package]]
+
name = "itertools"
+
version = "0.14.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
+
dependencies = [
+
"either",
+
]
+
+
[[package]]
name = "itoa"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
dependencies = [
"anyhow",
"async-trait",
-
"atrium-api",
+
"atrium-api 0.25.4 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)",
"chrono",
"clap",
"futures-util",
"log",
+
"metrics",
"serde",
"serde_json",
-
"thiserror 2.0.12",
+
"thiserror 2.0.16",
"tokio",
-
"tokio-tungstenite",
+
"tokio-tungstenite 0.26.2",
"url",
"zstd",
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
[[package]]
···
[[package]]
+
name = "jose-b64"
+
version = "0.1.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "bec69375368709666b21c76965ce67549f2d2db7605f1f8707d17c9656801b56"
+
dependencies = [
+
"base64ct",
+
"serde",
+
"subtle",
+
"zeroize",
+
]
+
+
[[package]]
+
name = "jose-jwa"
+
version = "0.1.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "9ab78e053fe886a351d67cf0d194c000f9d0dcb92906eb34d853d7e758a4b3a7"
+
dependencies = [
+
"serde",
+
]
+
+
[[package]]
+
name = "jose-jwk"
+
version = "0.1.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "280fa263807fe0782ecb6f2baadc28dffc04e00558a58e33bfdb801d11fd58e7"
+
dependencies = [
+
"jose-b64",
+
"jose-jwa",
+
"p256",
+
"p384",
+
"rsa",
+
"serde",
+
"zeroize",
+
]
+
+
[[package]]
name = "js-sys"
version = "0.3.77"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
[[package]]
+
name = "jsonwebtoken"
+
version = "9.3.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde"
+
dependencies = [
+
"base64 0.22.1",
+
"js-sys",
+
"pem",
+
"ring",
+
"serde",
+
"serde_json",
+
"simple_asn1",
+
]
+
+
[[package]]
+
name = "jwt-compact"
+
version = "0.9.0-beta.1"
+
source = "git+https://github.com/fatfingers23/jwt-compact.git#aed088b8ff5ad44ef2785c453f6a4b7916728b1c"
+
dependencies = [
+
"anyhow",
+
"base64ct",
+
"chrono",
+
"ciborium",
+
"hmac",
+
"lazy_static",
+
"rand_core 0.6.4",
+
"secp256k1",
+
"serde",
+
"serde_json",
+
"sha2",
+
"smallvec",
+
"subtle",
+
"zeroize",
+
]
+
+
[[package]]
+
name = "k256"
+
version = "0.13.4"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "f6e3919bbaa2945715f0bb6d3934a173d1e9a59ac23767fbaaef277265a7411b"
+
dependencies = [
+
"cfg-if",
+
"ecdsa",
+
"elliptic-curve",
+
"sha2",
+
]
+
+
[[package]]
name = "langtag"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
+
dependencies = [
+
"spin",
+
]
[[package]]
name = "lazycell"
···
[[package]]
name = "libc"
-
version = "0.2.171"
+
version = "0.2.174"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "c19937216e9d3aa9956d9bb8dfc0b0c8beb6058fc4f7a4dc4d850edf86a237d6"
+
checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776"
[[package]]
name = "libfuzzer-sys"
···
checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34"
dependencies = [
"cfg-if",
-
"windows-targets",
+
"windows-targets 0.52.6",
[[package]]
···
[[package]]
+
name = "libsqlite3-sys"
+
version = "0.35.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "133c182a6a2c87864fe97778797e46c7e999672690dc9fa3ee8e241aa4a9c13f"
+
dependencies = [
+
"pkg-config",
+
"vcpkg",
+
]
+
+
[[package]]
name = "libz-sys"
version = "1.1.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
"anyhow",
"fluent-uri",
"nom",
-
"thiserror 2.0.12",
+
"thiserror 2.0.16",
"tinyjson",
···
[[package]]
name = "log"
-
version = "0.4.27"
+
version = "0.4.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94"
+
checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432"
[[package]]
name = "loom"
···
dependencies = [
"hashbrown 0.15.2",
+
+
[[package]]
+
name = "lru-slab"
+
version = "0.1.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
[[package]]
name = "lsm-tree"
-
version = "2.8.0"
+
version = "2.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "d0a63a5e98a38b51765274137d8aedfbd848da5f4d016867e186b673fcc06a8c"
+
checksum = "55b6d7475a8dd22e749186968daacf8e2a77932b061b1bd263157987bbfc0c6c"
dependencies = [
"byteorder",
"crossbeam-skiplist",
···
[[package]]
+
name = "lz4"
+
version = "1.28.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "a20b523e860d03443e98350ceaac5e71c6ba89aea7d960769ec3ce37f4de5af4"
+
dependencies = [
+
"lz4-sys",
+
]
+
+
[[package]]
name = "lz4-sys"
version = "1.11.1+lz4-1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
[[package]]
+
name = "madsim"
+
version = "0.2.32"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "db6694555643da293dfb89e33c2880a13b62711d64b6588bc7df6ce4110b27f1"
+
dependencies = [
+
"ahash",
+
"async-channel",
+
"async-stream",
+
"async-task",
+
"bincode 1.3.3",
+
"bytes",
+
"downcast-rs",
+
"futures-util",
+
"lazy_static",
+
"libc",
+
"madsim-macros",
+
"naive-timer",
+
"panic-message",
+
"rand 0.8.5",
+
"rand_xoshiro 0.6.0",
+
"rustversion",
+
"serde",
+
"spin",
+
"tokio",
+
"tokio-util",
+
"toml",
+
"tracing",
+
"tracing-subscriber",
+
]
+
+
[[package]]
+
name = "madsim-macros"
+
version = "0.2.12"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "f3d248e97b1a48826a12c3828d921e8548e714394bf17274dd0a93910dc946e1"
+
dependencies = [
+
"darling 0.14.4",
+
"proc-macro2",
+
"quote",
+
"syn 1.0.109",
+
]
+
+
[[package]]
+
name = "madsim-tokio"
+
version = "0.2.30"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "7d3eb2acc57c82d21d699119b859e2df70a91dbdb84734885a1e72be83bdecb5"
+
dependencies = [
+
"madsim",
+
"spin",
+
"tokio",
+
]
+
+
[[package]]
name = "match_cfg"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
[[package]]
name = "matchers"
-
version = "0.1.0"
+
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558"
+
checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
dependencies = [
-
"regex-automata 0.1.10",
+
"regex-automata",
[[package]]
···
checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
[[package]]
+
name = "memoffset"
+
version = "0.9.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
+
dependencies = [
+
"autocfg",
+
]
+
+
[[package]]
name = "metrics"
-
version = "0.24.1"
+
version = "0.24.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "7a7deb012b3b2767169ff203fadb4c6b0b82b947512e5eb9e0b78c2e186ad9e3"
+
checksum = "25dea7ac8057892855ec285c440160265225438c3c45072613c25a4b26e98ef5"
dependencies = [
"ahash",
"portable-atomic",
···
"indexmap 2.9.0",
"ipnet",
"metrics",
-
"metrics-util",
+
"metrics-util 0.19.0",
"quanta",
"thiserror 1.0.69",
"tokio",
···
[[package]]
+
name = "metrics-exporter-prometheus"
+
version = "0.17.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "2b166dea96003ee2531cf14833efedced545751d800f03535801d833313f8c15"
+
dependencies = [
+
"base64 0.22.1",
+
"http-body-util",
+
"hyper",
+
"hyper-rustls",
+
"hyper-util",
+
"indexmap 2.9.0",
+
"ipnet",
+
"metrics",
+
"metrics-util 0.20.0",
+
"quanta",
+
"thiserror 2.0.16",
+
"tokio",
+
"tracing",
+
]
+
+
[[package]]
name = "metrics-process"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
"metrics",
"quanta",
"rand 0.8.5",
-
"rand_xoshiro",
+
"rand_xoshiro 0.6.0",
+
"sketches-ddsketch",
+
]
+
+
[[package]]
+
name = "metrics-util"
+
version = "0.20.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "fe8db7a05415d0f919ffb905afa37784f71901c9a773188876984b4f769ab986"
+
dependencies = [
+
"crossbeam-epoch",
+
"crossbeam-utils",
+
"hashbrown 0.15.2",
+
"metrics",
+
"quanta",
+
"rand 0.9.1",
+
"rand_xoshiro 0.7.0",
"sketches-ddsketch",
···
[[package]]
+
name = "mixtrics"
+
version = "0.2.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "adbcddf5a90b959eea97ae505e0391f5c6dd411fbf546d43b9c59ad1c3bd4391"
+
dependencies = [
+
"itertools 0.14.0",
+
"parking_lot",
+
]
+
+
[[package]]
name = "moka"
version = "0.12.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
"memchr",
"mime",
"spin",
+
"tokio",
"version_check",
···
[[package]]
+
name = "naive-timer"
+
version = "0.2.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "034a0ad7deebf0c2abcf2435950a6666c3c15ea9d8fad0c0f48efa8a7f843fed"
+
+
[[package]]
+
name = "nanorand"
+
version = "0.7.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "6a51313c5820b0b02bd422f4b44776fbf47961755c74ce64afc73bfad10226c3"
+
dependencies = [
+
"getrandom 0.2.15",
+
]
+
+
[[package]]
name = "native-tls"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
"openssl-probe",
"openssl-sys",
"schannel",
-
"security-framework",
+
"security-framework 2.11.1",
"security-framework-sys",
"tempfile",
[[package]]
name = "nix"
-
version = "0.29.0"
+
version = "0.30.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"
+
checksum = "74523f3a35e05aba87a1d978330aef40f67b0304ac79c1c00b294c9830543db6"
dependencies = [
"bitflags",
"cfg-if",
···
[[package]]
name = "nu-ansi-term"
-
version = "0.46.0"
+
version = "0.50.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84"
+
checksum = "d4a28e057d01f97e61255210fcff094d74ed0466038633e95017f5beb68e4399"
dependencies = [
-
"overload",
-
"winapi",
+
"windows-sys 0.52.0",
+
]
+
+
[[package]]
+
name = "num-bigint"
+
version = "0.4.6"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9"
+
dependencies = [
+
"num-integer",
+
"num-traits",
+
]
+
+
[[package]]
+
name = "num-bigint-dig"
+
version = "0.8.4"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "dc84195820f291c7697304f3cbdadd1cb7199c0efc917ff5eafd71225c136151"
+
dependencies = [
+
"byteorder",
+
"lazy_static",
+
"libm",
+
"num-integer",
+
"num-iter",
+
"num-traits",
+
"rand 0.8.5",
+
"smallvec",
+
"zeroize",
[[package]]
···
[[package]]
+
name = "num-integer"
+
version = "0.1.46"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
+
dependencies = [
+
"num-traits",
+
]
+
+
[[package]]
+
name = "num-iter"
+
version = "0.1.45"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf"
+
dependencies = [
+
"autocfg",
+
"num-integer",
+
"num-traits",
+
]
+
+
[[package]]
+
name = "num-modular"
+
version = "0.6.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "17bb261bf36fa7d83f4c294f834e91256769097b3cb505d44831e0a179ac647f"
+
+
[[package]]
+
name = "num-order"
+
version = "1.2.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "537b596b97c40fcf8056d153049eb22f481c17ebce72a513ec9286e4986d1bb6"
+
dependencies = [
+
"num-modular",
+
]
+
+
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
+
"libm",
[[package]]
···
checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87"
dependencies = [
"memchr",
+
]
+
+
[[package]]
+
name = "oid-registry"
+
version = "0.8.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7"
+
dependencies = [
+
"asn1-rs",
[[package]]
···
version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
+
dependencies = [
+
"critical-section",
+
"portable-atomic",
+
]
[[package]]
name = "openapiv3"
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
[[package]]
···
[[package]]
-
name = "overload"
-
version = "0.1.1"
+
name = "ordered_hash_map"
+
version = "0.4.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "ab0e5f22bf6dd04abd854a8874247813a8fa2c8c1260eba6fbb150270ce7c176"
+
dependencies = [
+
"hashbrown 0.13.2",
+
]
+
+
[[package]]
+
name = "p256"
+
version = "0.13.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b"
+
dependencies = [
+
"ecdsa",
+
"elliptic-curve",
+
"primeorder",
+
"sha2",
+
]
+
+
[[package]]
+
name = "p384"
+
version = "0.13.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6"
+
dependencies = [
+
"elliptic-curve",
+
"primeorder",
+
]
+
+
[[package]]
+
name = "panic-message"
+
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"
+
checksum = "384e52fd8fbd4cbe3c317e8216260c21a0f9134de108cea8a4dd4e7e152c472d"
[[package]]
name = "parking"
···
"libc",
"redox_syscall",
"smallvec",
-
"windows-targets",
+
"windows-targets 0.52.6",
[[package]]
···
[[package]]
+
name = "pem"
+
version = "3.0.5"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "38af38e8470ac9dee3ce1bae1af9c1671fffc44ddfd8bd1d0a3445bf349a8ef3"
+
dependencies = [
+
"base64 0.22.1",
+
"serde",
+
]
+
+
[[package]]
+
name = "pem-rfc7468"
+
version = "0.7.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412"
+
dependencies = [
+
"base64ct",
+
]
+
+
[[package]]
name = "percent-encoding"
version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e"
[[package]]
+
name = "pest"
+
version = "2.8.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "1db05f56d34358a8b1066f67cbb203ee3e7ed2ba674a6263a1d5ec6db2204323"
+
dependencies = [
+
"memchr",
+
"thiserror 2.0.16",
+
"ucd-trie",
+
]
+
+
[[package]]
+
name = "pest_derive"
+
version = "2.8.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "bb056d9e8ea77922845ec74a1c4e8fb17e7c218cc4fc11a15c5d25e189aa40bc"
+
dependencies = [
+
"pest",
+
"pest_generator",
+
]
+
+
[[package]]
+
name = "pest_generator"
+
version = "2.8.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "87e404e638f781eb3202dc82db6760c8ae8a1eeef7fb3fa8264b2ef280504966"
+
dependencies = [
+
"pest",
+
"pest_meta",
+
"proc-macro2",
+
"quote",
+
"syn 2.0.103",
+
]
+
+
[[package]]
+
name = "pest_meta"
+
version = "2.8.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "edd1101f170f5903fde0914f899bb503d9ff5271d7ba76bbb70bea63690cc0d5"
+
dependencies = [
+
"pest",
+
"sha2",
+
]
+
+
[[package]]
+
name = "pin-project"
+
version = "1.1.10"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "677f1add503faace112b9f1373e43e9e054bfdd22ff1a63c1bc485eaec6a6a8a"
+
dependencies = [
+
"pin-project-internal",
+
]
+
+
[[package]]
+
name = "pin-project-internal"
+
version = "1.1.10"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "6e918e4ff8c4549eb882f14b3a4bc8c8bc93de829416eacf579f1207a8fbf861"
+
dependencies = [
+
"proc-macro2",
+
"quote",
+
"syn 2.0.103",
+
]
+
+
[[package]]
name = "pin-project-lite"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
[[package]]
+
name = "pkcs1"
+
version = "0.7.5"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"
+
dependencies = [
+
"der",
+
"pkcs8",
+
"spki",
+
]
+
+
[[package]]
+
name = "pkcs8"
+
version = "0.10.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
+
dependencies = [
+
"der",
+
"spki",
+
]
+
+
[[package]]
name = "pkg-config"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
[[package]]
+
name = "pocket"
+
version = "0.1.0"
+
dependencies = [
+
"atrium-crypto",
+
"clap",
+
"jwt-compact",
+
"log",
+
"poem",
+
"poem-openapi",
+
"reqwest",
+
"rusqlite",
+
"serde",
+
"serde_json",
+
"thiserror 2.0.16",
+
"tokio",
+
"tracing-subscriber",
+
]
+
+
[[package]]
+
name = "poem"
+
version = "3.1.12"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "9f977080932c87287147dca052951c3e2696f8759863f6b4e4c0c9ffe7a4cc8b"
+
dependencies = [
+
"base64 0.22.1",
+
"bytes",
+
"chrono",
+
"futures-util",
+
"headers",
+
"http",
+
"http-body-util",
+
"httpdate",
+
"hyper",
+
"hyper-util",
+
"mime",
+
"mime_guess",
+
"multer",
+
"nix",
+
"parking_lot",
+
"percent-encoding",
+
"pin-project-lite",
+
"poem-derive",
+
"quick-xml",
+
"rcgen",
+
"regex",
+
"reqwest",
+
"rfc7239",
+
"ring",
+
"rustls-pemfile",
+
"serde",
+
"serde_json",
+
"serde_urlencoded",
+
"serde_yaml",
+
"smallvec",
+
"sync_wrapper",
+
"tempfile",
+
"thiserror 2.0.16",
+
"tokio",
+
"tokio-rustls 0.26.2",
+
"tokio-stream",
+
"tokio-util",
+
"tracing",
+
"wildmatch",
+
"x509-parser",
+
]
+
+
[[package]]
+
name = "poem-derive"
+
version = "3.1.12"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "056e2fea6de1cb240ffe23cfc4fc370b629f8be83b5f27e16b7acd5231a72de4"
+
dependencies = [
+
"proc-macro-crate",
+
"proc-macro2",
+
"quote",
+
"syn 2.0.103",
+
]
+
+
[[package]]
+
name = "poem-openapi"
+
version = "5.1.16"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "1ccbcc395bf4dd03df1da32da351b6b6732e4074ce27ddec315650e52a2be44c"
+
dependencies = [
+
"base64 0.22.1",
+
"bytes",
+
"derive_more",
+
"futures-util",
+
"indexmap 2.9.0",
+
"itertools 0.14.0",
+
"mime",
+
"num-traits",
+
"poem",
+
"poem-openapi-derive",
+
"quick-xml",
+
"regex",
+
"serde",
+
"serde_json",
+
"serde_urlencoded",
+
"serde_yaml",
+
"thiserror 2.0.16",
+
"tokio",
+
]
+
+
[[package]]
+
name = "poem-openapi-derive"
+
version = "5.1.16"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "41273b691a3d467a8c44d05506afba9f7b6bd56c9cdf80123de13fe52d7ec587"
+
dependencies = [
+
"darling 0.20.11",
+
"http",
+
"indexmap 2.9.0",
+
"mime",
+
"proc-macro-crate",
+
"proc-macro2",
+
"quote",
+
"regex",
+
"syn 2.0.103",
+
"thiserror 2.0.16",
+
]
+
+
[[package]]
name = "portable-atomic"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
[[package]]
+
name = "prettyplease"
+
version = "0.2.34"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "6837b9e10d61f45f987d50808f83d1ee3d206c66acf650c3e4ae2e1f6ddedf55"
+
dependencies = [
+
"proc-macro2",
+
"syn 2.0.103",
+
]
+
+
[[package]]
+
name = "primeorder"
+
version = "0.13.6"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6"
+
dependencies = [
+
"elliptic-curve",
+
]
+
+
[[package]]
+
name = "proc-macro-crate"
+
version = "3.3.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "edce586971a4dfaa28950c6f18ed55e0406c1ab88bbce2c6f6293a7aaba73d35"
+
dependencies = [
+
"toml_edit",
+
]
+
+
[[package]]
name = "proc-macro2"
version = "1.0.94"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
[[package]]
+
name = "quasar"
+
version = "0.1.0"
+
dependencies = [
+
"clap",
+
"fjall 2.11.2 (registry+https://github.com/rust-lang/crates.io-index)",
+
]
+
+
[[package]]
+
name = "quick-xml"
+
version = "0.36.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "f7649a7b4df05aed9ea7ec6f628c67c9953a43869b8bc50929569b2999d443fe"
+
dependencies = [
+
"memchr",
+
"serde",
+
]
+
+
[[package]]
name = "quick_cache"
version = "0.6.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
[[package]]
+
name = "quinn"
+
version = "0.11.8"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "626214629cda6781b6dc1d316ba307189c85ba657213ce642d9c77670f8202c8"
+
dependencies = [
+
"bytes",
+
"cfg_aliases",
+
"pin-project-lite",
+
"quinn-proto",
+
"quinn-udp",
+
"rustc-hash 2.1.1",
+
"rustls 0.23.31",
+
"socket2 0.5.9",
+
"thiserror 2.0.16",
+
"tokio",
+
"tracing",
+
"web-time",
+
]
+
+
[[package]]
+
name = "quinn-proto"
+
version = "0.11.12"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "49df843a9161c85bb8aae55f101bc0bac8bcafd637a620d9122fd7e0b2f7422e"
+
dependencies = [
+
"bytes",
+
"getrandom 0.3.3",
+
"lru-slab",
+
"rand 0.9.1",
+
"ring",
+
"rustc-hash 2.1.1",
+
"rustls 0.23.31",
+
"rustls-pki-types",
+
"slab",
+
"thiserror 2.0.16",
+
"tinyvec",
+
"tracing",
+
"web-time",
+
]
+
+
[[package]]
+
name = "quinn-udp"
+
version = "0.5.13"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "fcebb1209ee276352ef14ff8732e24cc2b02bbac986cd74a4c81bcb2f9881970"
+
dependencies = [
+
"cfg_aliases",
+
"libc",
+
"once_cell",
+
"socket2 0.5.9",
+
"tracing",
+
"windows-sys 0.59.0",
+
]
+
+
[[package]]
name = "quote"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
[[package]]
+
name = "rand_xoshiro"
+
version = "0.7.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "f703f4665700daf5512dcca5f43afa6af89f09db47fb56be587f80636bda2d41"
+
dependencies = [
+
"rand_core 0.9.3",
+
]
+
+
[[package]]
name = "ratelimit"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
[[package]]
+
name = "rcgen"
+
version = "0.12.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "48406db8ac1f3cbc7dcdb56ec355343817958a356ff430259bb07baf7607e1e1"
+
dependencies = [
+
"pem",
+
"ring",
+
"time",
+
"yasna",
+
]
+
+
[[package]]
name = "redox_syscall"
version = "0.5.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
+
]
+
+
[[package]]
+
name = "reflector"
+
version = "0.1.0"
+
dependencies = [
+
"clap",
+
"log",
+
"poem",
+
"serde",
+
"tokio",
+
"tracing-subscriber",
[[package]]
···
dependencies = [
"aho-corasick",
"memchr",
-
"regex-automata 0.4.9",
-
"regex-syntax 0.8.5",
+
"regex-automata",
+
"regex-syntax",
[[package]]
name = "regex-automata"
-
version = "0.1.10"
+
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132"
+
checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908"
dependencies = [
-
"regex-syntax 0.6.29",
+
"aho-corasick",
+
"memchr",
+
"regex-syntax",
[[package]]
-
name = "regex-automata"
-
version = "0.4.9"
+
name = "regex-syntax"
+
version = "0.8.5"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
+
+
[[package]]
+
name = "reqwest"
+
version = "0.12.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908"
+
checksum = "cbc931937e6ca3a06e3b6c0aa7841849b160a90351d6ab467a8b9b9959767531"
dependencies = [
-
"aho-corasick",
-
"memchr",
-
"regex-syntax 0.8.5",
+
"async-compression",
+
"base64 0.22.1",
+
"bytes",
+
"encoding_rs",
+
"futures-core",
+
"futures-util",
+
"h2",
+
"http",
+
"http-body",
+
"http-body-util",
+
"hyper",
+
"hyper-rustls",
+
"hyper-tls",
+
"hyper-util",
+
"js-sys",
+
"log",
+
"mime",
+
"native-tls",
+
"percent-encoding",
+
"pin-project-lite",
+
"quinn",
+
"rustls 0.23.31",
+
"rustls-native-certs",
+
"rustls-pki-types",
+
"serde",
+
"serde_json",
+
"serde_urlencoded",
+
"sync_wrapper",
+
"tokio",
+
"tokio-native-tls",
+
"tokio-rustls 0.26.2",
+
"tokio-util",
+
"tower",
+
"tower-http",
+
"tower-service",
+
"url",
+
"wasm-bindgen",
+
"wasm-bindgen-futures",
+
"web-sys",
[[package]]
-
name = "regex-syntax"
-
version = "0.6.29"
+
name = "resolv-conf"
+
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1"
+
checksum = "95325155c684b1c89f7765e30bc1c42e4a6da51ca513615660cb8a62ef9a88e3"
[[package]]
-
name = "regex-syntax"
-
version = "0.8.5"
+
name = "rfc6979"
+
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
+
checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2"
+
dependencies = [
+
"hmac",
+
"subtle",
+
]
+
+
[[package]]
+
name = "rfc7239"
+
version = "0.1.3"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "4a82f1d1e38e9a85bb58ffcfadf22ed6f2c94e8cd8581ec2b0f80a2a6858350f"
+
dependencies = [
+
"uncased",
+
]
[[package]]
name = "ring"
···
[[package]]
+
name = "rsa"
+
version = "0.9.8"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "78928ac1ed176a5ca1d17e578a1825f3d81ca54cf41053a592584b020cfd691b"
+
dependencies = [
+
"const-oid",
+
"digest",
+
"num-bigint-dig",
+
"num-integer",
+
"num-traits",
+
"pkcs1",
+
"pkcs8",
+
"rand_core 0.6.4",
+
"signature",
+
"spki",
+
"subtle",
+
"zeroize",
+
]
+
+
[[package]]
+
name = "rusqlite"
+
version = "0.37.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "165ca6e57b20e1351573e3729b958bc62f0e48025386970b6e4d29e7a7e71f3f"
+
dependencies = [
+
"bitflags",
+
"fallible-iterator",
+
"fallible-streaming-iterator",
+
"hashlink",
+
"libsqlite3-sys",
+
"smallvec",
+
]
+
+
[[package]]
name = "rustc-demangle"
version = "0.1.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
[[package]]
+
name = "rusticata-macros"
+
version = "4.1.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632"
+
dependencies = [
+
"nom",
+
]
+
+
[[package]]
name = "rustix"
version = "0.38.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
"log",
"ring",
"rustls-pki-types",
-
"rustls-webpki",
+
"rustls-webpki 0.102.8",
+
"subtle",
+
"zeroize",
+
]
+
+
[[package]]
+
name = "rustls"
+
version = "0.23.31"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "c0ebcbd2f03de0fc1122ad9bb24b127a5a6cd51d72604a3f3c50ac459762b6cc"
+
dependencies = [
+
"aws-lc-rs",
+
"log",
+
"once_cell",
+
"ring",
+
"rustls-pki-types",
+
"rustls-webpki 0.103.4",
"subtle",
"zeroize",
[[package]]
+
name = "rustls-native-certs"
+
version = "0.8.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "7fcff2dd52b58a8d98a70243663a0d234c4e2b79235637849d15913394a247d3"
+
dependencies = [
+
"openssl-probe",
+
"rustls-pki-types",
+
"schannel",
+
"security-framework 3.2.0",
+
]
+
+
[[package]]
name = "rustls-pemfile"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
[[package]]
name = "rustls-pki-types"
-
version = "1.11.0"
+
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "917ce264624a4b4db1c364dcc35bfca9ded014d0a958cd47ad3e960e988ea51c"
+
checksum = "229a4a4c221013e7e1f1a043678c5cc39fe5171437c88fb47151a21e6f5b5c79"
+
dependencies = [
+
"web-time",
+
"zeroize",
+
]
[[package]]
name = "rustls-webpki"
···
[[package]]
+
name = "rustls-webpki"
+
version = "0.103.4"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "0a17884ae0c1b773f1ccd2bd4a8c72f16da897310a98b0e84bf349ad5ead92fc"
+
dependencies = [
+
"aws-lc-rs",
+
"ring",
+
"rustls-pki-types",
+
"untrusted",
+
]
+
+
[[package]]
name = "rustversion"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f"
[[package]]
+
name = "same-file"
+
version = "1.0.6"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
+
dependencies = [
+
"winapi-util",
+
]
+
+
[[package]]
name = "schannel"
version = "0.1.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
"proc-macro2",
"quote",
"serde_derive_internals",
-
"syn",
+
"syn 2.0.103",
[[package]]
···
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
+
name = "sec1"
+
version = "0.7.3"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc"
+
dependencies = [
+
"base16ct",
+
"der",
+
"generic-array",
+
"pkcs8",
+
"subtle",
+
"zeroize",
+
]
+
+
[[package]]
+
name = "secp256k1"
+
version = "0.30.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "b50c5943d326858130af85e049f2661ba3c78b26589b8ab98e65e80ae44a1252"
+
dependencies = [
+
"bitcoin_hashes",
+
"rand 0.8.5",
+
"secp256k1-sys",
+
]
+
+
[[package]]
+
name = "secp256k1-sys"
+
version = "0.10.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "d4387882333d3aa8cb20530a17c69a3752e97837832f34f6dccc760e715001d9"
+
dependencies = [
+
"cc",
+
]
+
+
[[package]]
name = "security-framework"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"
dependencies = [
"bitflags",
-
"core-foundation",
+
"core-foundation 0.9.4",
+
"core-foundation-sys",
+
"libc",
+
"security-framework-sys",
+
]
+
+
[[package]]
+
name = "security-framework"
+
version = "3.2.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "271720403f46ca04f7ba6f55d438f8bd878d6b8ca0a1046e8228c4145bcbb316"
+
dependencies = [
+
"bitflags",
+
"core-foundation 0.10.1",
"core-foundation-sys",
"libc",
"security-framework-sys",
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
[[package]]
···
[[package]]
name = "serde_json"
-
version = "1.0.140"
+
version = "1.0.141"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373"
+
checksum = "30b9eff21ebe718216c6ec64e1d9ac57087aad11efc64e32002bce4a0d4c03d3"
dependencies = [
"itoa",
"memchr",
···
"percent-encoding",
"ryu",
"serde",
-
"thiserror 2.0.12",
+
"thiserror 2.0.16",
[[package]]
name = "serde_spanned"
-
version = "0.6.8"
+
version = "0.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "87607cb1398ed59d48732e575a4c28a7a8ebf2454b964fe3f224f2afc07909e1"
+
checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"
dependencies = [
"serde",
···
"proc-macro2",
"quote",
"serde",
-
"syn",
+
"syn 2.0.103",
[[package]]
···
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d00caa5193a3c8362ac2b73be6b9e768aa5a4b2f721d8f4b339600c3cb51f8e"
dependencies = [
-
"darling",
+
"darling 0.20.11",
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
+
]
+
+
[[package]]
+
name = "serde_yaml"
+
version = "0.9.34+deprecated"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"
+
dependencies = [
+
"indexmap 2.9.0",
+
"itoa",
+
"ryu",
+
"serde",
+
"unsafe-libyaml",
[[package]]
···
[[package]]
+
name = "signature"
+
version = "2.2.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
+
dependencies = [
+
"digest",
+
"rand_core 0.6.4",
+
]
+
+
[[package]]
+
name = "simple_asn1"
+
version = "0.6.3"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "297f631f50729c8c99b84667867963997ec0b50f32b2a7dbcab828ef0541e8bb"
+
dependencies = [
+
"num-bigint",
+
"num-traits",
+
"thiserror 2.0.16",
+
"time",
+
]
+
+
[[package]]
name = "sketches-ddsketch"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67"
dependencies = [
"autocfg",
+
]
+
+
[[package]]
+
name = "slingshot"
+
version = "0.1.0"
+
dependencies = [
+
"atrium-api 0.25.4 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)",
+
"atrium-common 0.1.2 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)",
+
"atrium-identity 0.1.5 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)",
+
"atrium-oauth 0.1.3 (git+https://github.com/uniphil/atrium.git?branch=fix%2Fresolve-handle-https-accept-whitespace)",
+
"clap",
+
"ctrlc",
+
"foyer",
+
"hickory-resolver",
+
"jetstream",
+
"links",
+
"log",
+
"metrics",
+
"metrics-exporter-prometheus 0.17.2",
+
"poem",
+
"poem-openapi",
+
"reqwest",
+
"rustls 0.23.31",
+
"serde",
+
"serde_json",
+
"thiserror 2.0.16",
+
"time",
+
"tokio",
+
"tokio-util",
+
"tracing-subscriber",
+
"url",
[[package]]
···
[[package]]
+
name = "socket2"
+
version = "0.6.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "233504af464074f9d066d7b5416c5f9b894a5862a6506e306f7b816cdd6f1807"
+
dependencies = [
+
"libc",
+
"windows-sys 0.59.0",
+
]
+
+
[[package]]
+
name = "spacedust"
+
version = "0.1.0"
+
dependencies = [
+
"async-trait",
+
"clap",
+
"ctrlc",
+
"dropshot",
+
"env_logger",
+
"futures",
+
"http",
+
"jetstream",
+
"links",
+
"log",
+
"metrics",
+
"metrics-exporter-prometheus 0.17.2",
+
"rand 0.9.1",
+
"schemars",
+
"semver",
+
"serde",
+
"serde_json",
+
"serde_qs",
+
"thiserror 2.0.16",
+
"tinyjson",
+
"tokio",
+
"tokio-tungstenite 0.27.0",
+
"tokio-util",
+
]
+
+
[[package]]
name = "spin"
version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
dependencies = [
"lock_api",
+
]
+
+
[[package]]
+
name = "spki"
+
version = "0.7.3"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
+
dependencies = [
+
"base64ct",
+
"der",
[[package]]
···
[[package]]
name = "strsim"
+
version = "0.10.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
+
+
[[package]]
+
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
···
[[package]]
name = "syn"
-
version = "2.0.100"
+
version = "1.0.109"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0"
+
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
+
dependencies = [
+
"proc-macro2",
+
"quote",
+
"unicode-ident",
+
]
+
+
[[package]]
+
name = "syn"
+
version = "2.0.103"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "e4307e30089d6fd6aff212f2da3a1f9e32f3223b1f010fb09b7c95f90f3ca1e8"
dependencies = [
"proc-macro2",
"quote",
···
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
+
dependencies = [
+
"futures-core",
+
]
[[package]]
name = "synstructure"
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
+
]
+
+
[[package]]
+
name = "system-configuration"
+
version = "0.6.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b"
+
dependencies = [
+
"bitflags",
+
"core-foundation 0.9.4",
+
"system-configuration-sys",
+
]
+
+
[[package]]
+
name = "system-configuration-sys"
+
version = "0.6.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4"
+
dependencies = [
+
"core-foundation-sys",
+
"libc",
[[package]]
···
[[package]]
name = "thiserror"
-
version = "2.0.12"
+
version = "2.0.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "567b8a2dae586314f7be2a752ec7474332959c6460e02bde30d702a66d488708"
+
checksum = "3467d614147380f2e4e374161426ff399c91084acd2363eaf549172b3d5e60c0"
dependencies = [
-
"thiserror-impl 2.0.12",
+
"thiserror-impl 2.0.16",
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
[[package]]
name = "thiserror-impl"
-
version = "2.0.12"
+
version = "2.0.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "7f7cf42b4507d8ea322120659672cf1b9dbb93f8f2d4ecfd6e51350ff5b17a1d"
+
checksum = "6c5e1be1c48b9172ee610da68fd9cd2770e7a4056cb3fc98710ee6906f0c7960"
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
[[package]]
···
[[package]]
+
name = "tinyvec"
+
version = "1.9.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "09b3661f17e86524eccd4371ab0429194e0d7c008abb45f7a7495b1719463c71"
+
dependencies = [
+
"tinyvec_macros",
+
]
+
+
[[package]]
+
name = "tinyvec_macros"
+
version = "0.1.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
+
+
[[package]]
name = "tokio"
-
version = "1.44.2"
+
version = "1.47.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "e6b88822cbe49de4185e3a4cbf8321dd487cf5fe0c5c65695fef6346371e9c48"
+
checksum = "89e49afdadebb872d3145a5638b59eb0691ea23e46ca484037cfab3b76b95038"
dependencies = [
"backtrace",
"bytes",
+
"io-uring",
"libc",
"mio",
"parking_lot",
"pin-project-lite",
"signal-hook-registry",
-
"socket2",
+
"slab",
+
"socket2 0.6.0",
"tokio-macros",
-
"windows-sys 0.52.0",
+
"windows-sys 0.59.0",
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
[[package]]
···
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "775e0c0f0adb3a2f22a00c4745d728b479985fc15ee7ca6a2608388c5569860f"
dependencies = [
-
"rustls",
+
"rustls 0.22.4",
"rustls-pki-types",
"tokio",
[[package]]
+
name = "tokio-rustls"
+
version = "0.26.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "8e727b36a1a0e8b74c376ac2211e40c2c8af09fb4013c60d910495810f008e9b"
+
dependencies = [
+
"rustls 0.23.31",
+
"tokio",
+
]
+
+
[[package]]
+
name = "tokio-stream"
+
version = "0.1.17"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "eca58d7bba4a75707817a2c44174253f9236b2d5fbd055602e9d5c07c139a047"
+
dependencies = [
+
"futures-core",
+
"pin-project-lite",
+
"tokio",
+
]
+
+
[[package]]
name = "tokio-tungstenite"
version = "0.26.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
"native-tls",
"tokio",
"tokio-native-tls",
-
"tungstenite",
+
"tungstenite 0.26.2",
+
]
+
+
[[package]]
+
name = "tokio-tungstenite"
+
version = "0.27.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "489a59b6730eda1b0171fcfda8b121f4bee2b35cba8645ca35c5f7ba3eb736c1"
+
dependencies = [
+
"futures-util",
+
"log",
+
"tokio",
+
"tungstenite 0.27.0",
[[package]]
···
[[package]]
name = "toml"
-
version = "0.8.20"
+
version = "0.8.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "cd87a5cdd6ffab733b2f74bc4fd7ee5fff6634124999ac278c35fc78c6120148"
+
checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"
dependencies = [
"serde",
"serde_spanned",
···
[[package]]
name = "toml_datetime"
-
version = "0.6.8"
+
version = "0.6.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "0dd7358ecb8fc2f8d014bf86f6f638ce72ba252a2c3a2572f2a795f1d23efb41"
+
checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c"
dependencies = [
"serde",
[[package]]
name = "toml_edit"
-
version = "0.22.24"
+
version = "0.22.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "17b4795ff5edd201c7cd6dca065ae59972ce77d1b80fa0a84d94950ece7d1474"
+
checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
dependencies = [
"indexmap 2.9.0",
"serde",
"serde_spanned",
"toml_datetime",
+
"toml_write",
"winnow",
[[package]]
+
name = "toml_write"
+
version = "0.1.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
+
+
[[package]]
name = "tower"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
[[package]]
name = "tower-http"
-
version = "0.6.2"
+
version = "0.6.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "403fa3b783d4b626a8ad51d766ab03cb6d2dbfc46b1c5d4448395e6628dc9697"
+
checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2"
dependencies = [
"bitflags",
"bytes",
+
"futures-util",
"http",
+
"http-body",
+
"iri-string",
"pin-project-lite",
+
"tower",
"tower-layer",
"tower-service",
···
dependencies = [
"log",
"pin-project-lite",
+
"tracing-attributes",
"tracing-core",
[[package]]
+
name = "tracing-attributes"
+
version = "0.1.30"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "81383ab64e72a7a8b8e13130c49e3dab29def6d0c7d76a03087b3cf71c5c6903"
+
dependencies = [
+
"proc-macro2",
+
"quote",
+
"syn 2.0.103",
+
]
+
+
[[package]]
name = "tracing-core"
version = "0.1.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
[[package]]
name = "tracing-subscriber"
-
version = "0.3.19"
+
version = "0.3.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "e8189decb5ac0fa7bc8b96b7cb9b2701d60d48805aca84a238004d665fcc4008"
+
checksum = "2054a14f5307d601f88daf0553e1cbf472acc4f2c51afab632431cdcd72124d5"
dependencies = [
"matchers",
"nu-ansi-term",
"once_cell",
-
"regex",
+
"regex-automata",
"sharded-slab",
"smallvec",
"thread_local",
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
[[package]]
···
"native-tls",
"rand 0.9.1",
"sha1",
-
"thiserror 2.0.12",
+
"thiserror 2.0.16",
"url",
"utf-8",
[[package]]
+
name = "tungstenite"
+
version = "0.27.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "eadc29d668c91fcc564941132e17b28a7ceb2f3ebf0b9dae3e03fd7a6748eb0d"
+
dependencies = [
+
"bytes",
+
"data-encoding",
+
"http",
+
"httparse",
+
"log",
+
"rand 0.9.1",
+
"sha1",
+
"thiserror 2.0.16",
+
"utf-8",
+
]
+
+
[[package]]
+
name = "twox-hash"
+
version = "2.1.1"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "8b907da542cbced5261bd3256de1b3a1bf340a3d37f93425a07362a1d687de56"
+
dependencies = [
+
"rand 0.9.1",
+
]
+
+
[[package]]
name = "typenum"
version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f"
+
+
[[package]]
+
name = "ucd-trie"
+
version = "0.1.7"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971"
[[package]]
name = "ufos"
···
"clap",
"dropshot",
"env_logger",
-
"fjall",
+
"fjall 2.11.2 (git+https://github.com/fjall-rs/fjall.git)",
"getrandom 0.3.3",
"http",
"jetstream",
"log",
"lsm-tree",
+
"metrics",
+
"metrics-exporter-prometheus 0.17.2",
"schemars",
"semver",
"serde",
···
"serde_qs",
"sha2",
"tempfile",
-
"thiserror 2.0.12",
+
"thiserror 2.0.16",
"tikv-jemallocator",
"tokio",
"tokio-util",
···
[[package]]
+
name = "uncased"
+
version = "0.9.10"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "e1b88fcfe09e89d3866a5c11019378088af2d24c3fbd4f0543f96b479ec90697"
+
dependencies = [
+
"version_check",
+
]
+
+
[[package]]
name = "unicase"
version = "2.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
[[package]]
+
name = "unicode-xid"
+
version = "0.2.6"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
+
+
[[package]]
+
name = "unsafe-libyaml"
+
version = "0.2.11"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861"
+
+
[[package]]
name = "unsigned-varint"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
[[package]]
name = "value-log"
-
version = "1.8.0"
+
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "fd29b17c041f94e0885179637289815cd038f0c9fc19c4549d5a97017404fb7d"
+
checksum = "62fc7c4ce161f049607ecea654dca3f2d727da5371ae85e2e4f14ce2b98ed67c"
dependencies = [
"byteorder",
"byteview",
···
[[package]]
+
name = "walkdir"
+
version = "2.5.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
+
dependencies = [
+
"same-file",
+
"winapi-util",
+
]
+
+
[[package]]
name = "want"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
"log",
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
"wasm-bindgen-shared",
[[package]]
+
name = "wasm-bindgen-futures"
+
version = "0.4.50"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "555d470ec0bc3bb57890405e5d4322cc9ea83cebb085523ced7be4144dac1e61"
+
dependencies = [
+
"cfg-if",
+
"js-sys",
+
"once_cell",
+
"wasm-bindgen",
+
"web-sys",
+
]
+
+
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
···
[[package]]
+
name = "which"
+
version = "4.4.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7"
+
dependencies = [
+
"either",
+
"home",
+
"once_cell",
+
"rustix 0.38.44",
+
]
+
+
[[package]]
+
name = "who-am-i"
+
version = "0.1.0"
+
dependencies = [
+
"atrium-api 0.25.4 (registry+https://github.com/rust-lang/crates.io-index)",
+
"atrium-common 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
+
"atrium-identity 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
+
"atrium-oauth 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
+
"axum",
+
"axum-extra",
+
"axum-template",
+
"clap",
+
"ctrlc",
+
"dashmap",
+
"elliptic-curve",
+
"handlebars",
+
"hickory-resolver",
+
"jose-jwk",
+
"jsonwebtoken",
+
"metrics",
+
"metrics-exporter-prometheus 0.17.2",
+
"p256",
+
"pkcs8",
+
"rand 0.9.1",
+
"reqwest",
+
"serde",
+
"serde_json",
+
"thiserror 2.0.16",
+
"tokio",
+
"tokio-util",
+
"url",
+
]
+
+
[[package]]
+
name = "widestring"
+
version = "1.2.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "dd7cf3379ca1aac9eea11fba24fd7e315d621f8dfe35c8d7d2be8b793726e07d"
+
+
[[package]]
+
name = "wildmatch"
+
version = "2.4.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "68ce1ab1f8c62655ebe1350f589c61e505cf94d385bc6a12899442d9081e71fd"
+
+
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
+
name = "winapi-util"
+
version = "0.1.9"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb"
+
dependencies = [
+
"windows-sys 0.59.0",
+
]
+
+
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6"
dependencies = [
"windows-core 0.58.0",
-
"windows-targets",
+
"windows-targets 0.52.6",
[[package]]
···
"windows-interface 0.58.0",
"windows-result 0.2.0",
"windows-strings 0.1.0",
-
"windows-targets",
+
"windows-targets 0.52.6",
[[package]]
···
"windows-implement 0.60.0",
"windows-interface 0.59.1",
"windows-link",
-
"windows-result 0.3.2",
-
"windows-strings 0.4.0",
+
"windows-result 0.3.4",
+
"windows-strings 0.4.2",
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
[[package]]
···
checksum = "76840935b766e1b0a05c0066835fb9ec80071d4c09a16f6bd5f7e655e3c14c38"
[[package]]
+
name = "windows-registry"
+
version = "0.5.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "b3bab093bdd303a1240bb99b8aba8ea8a69ee19d34c9e2ef9594e708a4878820"
+
dependencies = [
+
"windows-link",
+
"windows-result 0.3.4",
+
"windows-strings 0.4.2",
+
]
+
+
[[package]]
name = "windows-result"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e"
dependencies = [
-
"windows-targets",
+
"windows-targets 0.52.6",
[[package]]
name = "windows-result"
-
version = "0.3.2"
+
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "c64fd11a4fd95df68efcfee5f44a294fe71b8bc6a91993e2791938abcc712252"
+
checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6"
dependencies = [
"windows-link",
···
checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10"
dependencies = [
"windows-result 0.2.0",
-
"windows-targets",
+
"windows-targets 0.52.6",
[[package]]
name = "windows-strings"
-
version = "0.4.0"
+
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "7a2ba9642430ee452d5a7aa78d72907ebe8cfda358e8cb7918a2050581322f97"
+
checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57"
dependencies = [
"windows-link",
[[package]]
name = "windows-sys"
+
version = "0.48.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
+
dependencies = [
+
"windows-targets 0.48.5",
+
]
+
+
[[package]]
+
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
-
"windows-targets",
+
"windows-targets 0.52.6",
[[package]]
···
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
-
"windows-targets",
+
"windows-targets 0.52.6",
+
]
+
+
[[package]]
+
name = "windows-targets"
+
version = "0.48.5"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
+
dependencies = [
+
"windows_aarch64_gnullvm 0.48.5",
+
"windows_aarch64_msvc 0.48.5",
+
"windows_i686_gnu 0.48.5",
+
"windows_i686_msvc 0.48.5",
+
"windows_x86_64_gnu 0.48.5",
+
"windows_x86_64_gnullvm 0.48.5",
+
"windows_x86_64_msvc 0.48.5",
[[package]]
···
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
-
"windows_aarch64_gnullvm",
-
"windows_aarch64_msvc",
-
"windows_i686_gnu",
+
"windows_aarch64_gnullvm 0.52.6",
+
"windows_aarch64_msvc 0.52.6",
+
"windows_i686_gnu 0.52.6",
"windows_i686_gnullvm",
-
"windows_i686_msvc",
-
"windows_x86_64_gnu",
-
"windows_x86_64_gnullvm",
-
"windows_x86_64_msvc",
+
"windows_i686_msvc 0.52.6",
+
"windows_x86_64_gnu 0.52.6",
+
"windows_x86_64_gnullvm 0.52.6",
+
"windows_x86_64_msvc 0.52.6",
[[package]]
name = "windows_aarch64_gnullvm"
+
version = "0.48.5"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
+
+
[[package]]
+
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
+
version = "0.48.5"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
+
+
[[package]]
+
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+
+
[[package]]
+
name = "windows_i686_gnu"
+
version = "0.48.5"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
[[package]]
name = "windows_i686_gnu"
···
[[package]]
name = "windows_i686_msvc"
+
version = "0.48.5"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
+
+
[[package]]
+
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
+
version = "0.48.5"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
+
+
[[package]]
+
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
+
version = "0.48.5"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
+
+
[[package]]
+
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
+
version = "0.48.5"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
+
+
[[package]]
+
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "winnow"
-
version = "0.7.6"
+
version = "0.7.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "63d3fcd9bba44b03821e7d699eeee959f3126dcc4aa8e4ae18ec617c2a5cea10"
+
checksum = "74c7b26e3480b707944fc872477815d29a8e429d2f93a1ce000f5fa84a15cbcd"
dependencies = [
"memchr",
+
]
+
+
[[package]]
+
name = "winreg"
+
version = "0.50.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "524e57b2c537c0f9b1e69f1965311ec12182b4122e45035b1508cd24d2adadb1"
+
dependencies = [
+
"cfg-if",
+
"windows-sys 0.48.0",
[[package]]
···
[[package]]
+
name = "x509-parser"
+
version = "0.17.0"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "4569f339c0c402346d4a75a9e39cf8dad310e287eef1ff56d4c68e5067f53460"
+
dependencies = [
+
"asn1-rs",
+
"data-encoding",
+
"der-parser",
+
"lazy_static",
+
"nom",
+
"oid-registry",
+
"rusticata-macros",
+
"thiserror 2.0.16",
+
"time",
+
]
+
+
[[package]]
name = "xxhash-rust"
version = "0.8.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fdd20c5420375476fbd4394763288da7eb0cc0b8c11deed431a91562af7335d3"
[[package]]
+
name = "yasna"
+
version = "0.5.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "e17bb3549cc1321ae1296b9cdc2698e2b6cb1992adfa19a8c72e5b7a738f44cd"
+
dependencies = [
+
"time",
+
]
+
+
[[package]]
name = "yoke"
version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
"synstructure",
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
"synstructure",
···
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde"
+
dependencies = [
+
"serde",
+
"zeroize_derive",
+
]
+
+
[[package]]
+
name = "zeroize_derive"
+
version = "1.4.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69"
+
dependencies = [
+
"proc-macro2",
+
"quote",
+
"syn 2.0.103",
+
]
[[package]]
name = "zerovec"
···
dependencies = [
"proc-macro2",
"quote",
-
"syn",
+
"syn 2.0.103",
[[package]]
+6
Cargo.toml
···
"jetstream",
"ufos",
"ufos/fuzz",
+
"spacedust",
+
"who-am-i",
+
"slingshot",
+
"quasar",
+
"pocket",
+
"reflector",
]
+9 -2
Makefile
···
all: check
test:
-
cargo test
+
cargo test --all-features
fmt:
-
cargo fmt --package links --package constellation --package ufos
+
cargo fmt --package links \
+
--package constellation \
+
--package ufos \
+
--package spacedust \
+
--package who-am-i \
+
--package slingshot \
+
--package pocket \
+
--package reflector
cargo +nightly fmt --package jetstream
clippy:
+1 -1
cozy-setup (move to another repo).md legacy/cozy-setup (move to another repo).md
···
- systemd unit for running: `sudo nano /etc/systemd/system/constellation.service`
-
```toml
+
```ini
[Unit]
Description=Constellation backlinks index
After=network.target
+6 -1
jetstream/Cargo.toml
···
[dependencies]
async-trait = "0.1.83"
-
atrium-api = { git = "https://github.com/uniphil/atrium", branch = "fix/nsid-allow-nonleading-name-digits", default-features = false, features = [
+
atrium-api = { git = "https://github.com/uniphil/atrium.git", branch = "fix/resolve-handle-https-accept-whitespace", default-features = false, features = [
"namespace-appbsky",
] }
tokio = { version = "1.44.2", features = ["full", "sync", "time"] }
···
"url",
] }
futures-util = "0.3.31"
+
metrics = { version = "0.24.2", optional = true }
url = "2.5.4"
serde = { version = "1.0.215", features = ["derive"] }
serde_json = { version = "1.0.140", features = ["raw_value"] }
···
[dev-dependencies]
anyhow = "1.0.93"
clap = { version = "4.5.20", features = ["derive"] }
+
+
[features]
+
default = []
+
metrics = ["dep:metrics"]
+2 -6
jetstream/src/error.rs
···
/// See [websocket_task](crate::websocket_task).
#[derive(Error, Debug)]
pub enum JetstreamEventError {
-
#[error("received websocket message that could not be deserialized as JSON: {0}")]
-
ReceivedMalformedJSON(#[from] serde_json::Error),
#[error("failed to load built-in zstd dictionary for decoding: {0}")]
CompressionDictionaryError(io::Error),
-
#[error("failed to decode zstd-compressed message: {0}")]
-
CompressionDecoderError(io::Error),
-
#[error("all receivers were dropped but the websocket connection failed to close cleanly")]
-
WebSocketCloseFailure,
#[error("failed to send ping or pong: {0}")]
PingPongError(#[from] tokio_tungstenite::tungstenite::Error),
+
#[error("no messages received within ttl")]
+
NoMessagesReceived,
#[error("jetstream event receiver closed")]
ReceiverClosedError,
}
+11
jetstream/src/events.rs
···
let t: SystemTime = self.into();
t.elapsed()
}
+
/// Compute the age of the cursor vs the local clock
+
///
+
/// Converts the resulting duration into an f64, which can be negative!
+
///
+
/// Warning: this exploits the internal implementation detail of jetstream cursors
+
pub fn elapsed_micros_f64(&self) -> f64 {
+
match self.elapsed() {
+
Ok(d) => d.as_micros() as f64,
+
Err(e) => -(e.duration().as_micros() as f64),
+
}
+
}
/// Get the immediate next cursor value
///
/// This is possible for the implementation of jetstream cursors
+128 -8
jetstream/src/lib.rs
···
stream::StreamExt,
SinkExt,
};
+
#[cfg(feature = "metrics")]
+
use metrics::{
+
counter,
+
describe_counter,
+
Unit,
+
};
use tokio::{
net::TcpStream,
sync::mpsc::{
···
Receiver,
Sender,
},
+
time::timeout,
};
use tokio_tungstenite::{
connect_async,
···
/// can help prevent that if your consumer sometimes pauses, at a cost of higher memory
/// usage while events are buffered.
pub channel_size: usize,
+
/// How long since the last jetstream message before we consider the connection dead
+
///
+
/// Default: 15s
+
pub liveliness_ttl: Duration,
}
impl Default for JetstreamConfig {
···
omit_user_agent_jetstream_info: false,
replay_on_reconnect: false,
channel_size: 4096, // a few seconds of firehose buffer
+
liveliness_ttl: Duration::from_secs(15),
}
}
}
···
}
}
+
#[cfg(feature = "metrics")]
+
fn describe_metrics() {
+
describe_counter!(
+
"jetstream_connects",
+
Unit::Count,
+
"how many times we've tried to connect"
+
);
+
describe_counter!(
+
"jetstream_disconnects",
+
Unit::Count,
+
"how many times we've been disconnected"
+
);
+
describe_counter!(
+
"jetstream_total_events_received",
+
Unit::Count,
+
"total number of events received"
+
);
+
describe_counter!(
+
"jetstream_total_bytes_received",
+
Unit::Count,
+
"total uncompressed bytes received, not including websocket overhead"
+
);
+
describe_counter!(
+
"jetstream_total_event_errors",
+
Unit::Count,
+
"total errors when handling events"
+
);
+
describe_counter!(
+
"jetstream_total_events_sent",
+
Unit::Count,
+
"total events sent to the consumer"
+
);
+
}
+
impl JetstreamConnector {
/// Create a Jetstream connector with a valid [JetstreamConfig].
///
/// After creation, you can call [connect] to connect to the provided Jetstream instance.
pub fn new(config: JetstreamConfig) -> Result<Self, ConfigValidationError> {
+
#[cfg(feature = "metrics")]
+
describe_metrics();
+
// We validate the configuration here so any issues are caught early.
config.validate()?;
Ok(JetstreamConnector { config })
···
let (send_channel, receive_channel) = channel(self.config.channel_size);
let replay_on_reconnect = self.config.replay_on_reconnect;
+
let liveliness_ttl = self.config.liveliness_ttl;
let build_request = self.config.get_request_builder();
tokio::task::spawn(async move {
···
}
};
+
#[cfg(feature = "metrics")]
+
if let Some(host) = req.uri().host() {
+
let retry = if retry_attempt > 0 { "yes" } else { "no" };
+
counter!("jetstream_connects", "host" => host.to_string(), "retry" => retry)
+
.increment(1);
+
}
+
let mut last_cursor = connect_cursor;
retry_attempt += 1;
if let Ok((ws_stream, _)) = connect_async(req).await {
let t_connected = Instant::now();
log::info!("jetstream connected. starting websocket task...");
-
if let Err(e) =
-
websocket_task(dict, ws_stream, send_channel.clone(), &mut last_cursor)
-
.await
+
if let Err(e) = websocket_task(
+
dict,
+
ws_stream,
+
send_channel.clone(),
+
&mut last_cursor,
+
liveliness_ttl,
+
)
+
.await
{
-
if let JetstreamEventError::ReceiverClosedError = e {
-
log::error!("Jetstream receiver channel closed. Exiting consumer.");
-
return;
+
match e {
+
JetstreamEventError::ReceiverClosedError => {
+
#[cfg(feature="metrics")]
+
counter!("jetstream_disconnects", "reason" => "channel", "fatal" => "yes").increment(1);
+
log::error!("Jetstream receiver channel closed. Exiting consumer.");
+
return;
+
}
+
JetstreamEventError::CompressionDictionaryError(_) => {
+
#[cfg(feature="metrics")]
+
counter!("jetstream_disconnects", "reason" => "zstd", "fatal" => "no").increment(1);
+
}
+
JetstreamEventError::NoMessagesReceived => {
+
#[cfg(feature="metrics")]
+
counter!("jetstream_disconnects", "reason" => "ttl", "fatal" => "no").increment(1);
+
}
+
JetstreamEventError::PingPongError(_) => {
+
#[cfg(feature="metrics")]
+
counter!("jetstream_disconnects", "reason" => "pingpong", "fatal" => "no").increment(1);
+
}
}
-
log::error!("Jetstream closed after encountering error: {e:?}");
+
log::warn!("Jetstream closed after encountering error: {e:?}");
} else {
+
#[cfg(feature = "metrics")]
+
counter!("jetstream_disconnects", "reason" => "close", "fatal" => "no")
+
.increment(1);
log::warn!("Jetstream connection closed cleanly");
}
if t_connected.elapsed() > Duration::from_secs(success_threshold_s) {
···
ws: WebSocketStream<MaybeTlsStream<TcpStream>>,
send_channel: JetstreamSender,
last_cursor: &mut Option<Cursor>,
+
liveliness_ttl: Duration,
) -> Result<(), JetstreamEventError> {
// TODO: Use the write half to allow the user to change configuration settings on the fly.
let (mut socket_write, mut socket_read) = ws.split();
let mut closing_connection = false;
loop {
-
match socket_read.next().await {
+
let next = match timeout(liveliness_ttl, socket_read.next()).await {
+
Ok(n) => n,
+
Err(_) => {
+
log::warn!("jetstream no events for {liveliness_ttl:?}, closing");
+
_ = socket_write.close().await;
+
return Err(JetstreamEventError::NoMessagesReceived);
+
}
+
};
+
match next {
Some(Ok(message)) => match message {
Message::Text(json) => {
+
#[cfg(feature = "metrics")]
+
{
+
counter!("jetstream_total_events_received", "compressed" => "false")
+
.increment(1);
+
counter!("jetstream_total_bytes_received", "compressed" => "false")
+
.increment(json.len() as u64);
+
}
let event: JetstreamEvent = match serde_json::from_str(&json) {
Ok(ev) => ev,
Err(e) => {
+
#[cfg(feature = "metrics")]
+
counter!("jetstream_total_event_errors", "reason" => "deserialize")
+
.increment(1);
log::warn!(
"failed to parse json: {e:?} (from {})",
json.get(..24).unwrap_or(&json)
···
if let Some(last) = last_cursor {
if event_cursor <= *last {
+
#[cfg(feature = "metrics")]
+
counter!("jetstream_total_event_errors", "reason" => "old")
+
.increment(1);
log::warn!("event cursor {event_cursor:?} was not newer than the last one: {last:?}. dropping event.");
continue;
}
···
} else if let Some(last) = last_cursor.as_mut() {
*last = event_cursor;
}
+
#[cfg(feature = "metrics")]
+
counter!("jetstream_total_events_sent").increment(1);
}
Message::Binary(zstd_json) => {
+
#[cfg(feature = "metrics")]
+
{
+
counter!("jetstream_total_events_received", "compressed" => "true")
+
.increment(1);
+
counter!("jetstream_total_bytes_received", "compressed" => "true")
+
.increment(zstd_json.len() as u64);
+
}
let mut cursor = IoCursor::new(zstd_json);
let decoder =
zstd::stream::Decoder::with_prepared_dictionary(&mut cursor, &dictionary)
···
let event: JetstreamEvent = match serde_json::from_reader(decoder) {
Ok(ev) => ev,
Err(e) => {
+
#[cfg(feature = "metrics")]
+
counter!("jetstream_total_event_errors", "reason" => "deserialize")
+
.increment(1);
log::warn!("failed to parse json: {e:?}");
continue;
}
···
if let Some(last) = last_cursor {
if event_cursor <= *last {
+
#[cfg(feature = "metrics")]
+
counter!("jetstream_total_event_errors", "reason" => "old")
+
.increment(1);
log::warn!("event cursor {event_cursor:?} was not newer than the last one: {last:?}. dropping event.");
continue;
}
···
} else if let Some(last) = last_cursor.as_mut() {
*last = event_cursor;
}
+
#[cfg(feature = "metrics")]
+
counter!("jetstream_total_events_sent").increment(1);
}
Message::Ping(vec) => {
log::trace!("Ping recieved, responding");
+35
legacy/old-readme-details.md
···
+
[Constellation](./constellation/)
+
--------------------------------------------
+
+
A global atproto backlink index ✨
+
+
- Self hostable: handles the full write throughput of the global atproto firehose on a raspberry pi 4b + single SSD
+
- Storage efficient: less than 2GB/day disk consumption indexing all references in all lexicons and all non-atproto URLs
+
- Handles record deletion, account de/re-activation, and account deletion, ensuring accurate link counts and respecting users data choices
+
- Simple JSON API
+
+
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.
+
+
- **status**: works! api is unstable and likely to change, and no known instances have a full network backfill yet.
+
- source: [./constellation/](./constellation/)
+
- public instance: [constellation.microcosm.blue](https://constellation.microcosm.blue/)
+
+
_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._
+
+
+
App: Spacedust
+
--------------
+
+
A notification subscription service 💫
+
+
using the same "link source" concept as [constellation](./constellation/), offer webhook notifications for new references created to records
+
+
- **status**: in design
+
+
+
Library: [links](./links/)
+
------------------------------------
+
+
A rust crate (not published on crates.io yet) for optimistically parsing links out of arbitrary atproto PDS records, and potentially canonicalizing them
+
+
- **status**: unstable, might remain an internal lib for constellation (and spacedust, soon)
+123
legacy/original-notes.md
···
+
---
+
+
+
old notes follow, ignore
+
------------------------
+
+
+
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.
+
+
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.
+
+
+
why
+
---
+
+
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.
+
+
- bluesky posts (firesky, deletions, )
+
- blueksy post stats (emojis, )
+
- trending keywords ()
+
+
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?_
+
+
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.
+
+
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!
+
+
**so, why**
+
+
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.
+
+
everything is links:
+
+
- likes
+
- follows
+
- blocks
+
- reposts
+
- quotes
+
+
some low-level things you could make from links:
+
+
- notification streams (part of ucosm)
+
- a global reverse index (part of ucosm)
+
+
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.
+
+
+
extracting links
+
---------------
+
+
+
- low-level: pass a &str of a field value and get a parsed link back
+
+
- 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?)
+
+
- high-ish level: pass the json record and maybe apply some pre-loaded rules based on known lexicons to get the best result.
+
+
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.
+
+
+
resolving / canonicalizing links
+
--------------------------------
+
+
+
### at-uris
+
+
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):
+
+
- `at://did:plc:44ybard66vv44zksje25o7dz/app.bsky.feed.post/3jwdwj2ctlk26`
+
- `at://bnewbold.bsky.team/app.bsky.feed.post/3jwdwj2ctlk26`
+
+
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?
+
+
hopefully atrium will make it easy to resolve at-uris.
+
+
+
### urls
+
+
canonicalizing URLs is more annoying but also a bit more established. lots of details.
+
+
- do we have to deal with punycode?
+
- follow redirects (todo: only permanent ones, or all?)
+
- check for rel=canonical http header and possibly follow it
+
- check link rel=canonical meta tag and possibly follow it
+
- do we need to check site maps??
+
- do we have to care at all about AMP?
+
- do we want anything to do with url shorteners??
+
- how do multilingual sites affect this?
+
- do we have to care about `script type="application/ld+json"` ???
+
+
ugh. is there a crate for this.
+
+
+
### relative uris?
+
+
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)
+
+
+
### canonicalizing
+
+
there should be a few async functions available to canonicalize already-parsed links.
+
+
- what happens if a link can't be resolved?
+
+
+
---
+
+
- using `tinyjson` because it's nice -- maybe should switch to serde_json to share deps with atrium?
+
+
- 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?
+
+
- rsky-syntax has an aturi
+
- adenosyne also
+
- might come back to these
+
+
+
-------
+
+
rocks
+
+
```bash
+
ROCKSDB_LIB_DIR=/nix/store/z2chn0hsik0clridr8mlprx1cngh1g3c-rocksdb-9.7.3/lib/ cargo build
+
```
+196
legacy/ufos ops (move to micro-ops).md
···
+
ufos ops
+
+
btrfs snapshots: snapper
+
+
```bash
+
sudo apt install snapper
+
sudo snapper -c ufos-db create-config /mnt/ufos-db
+
+
# edit /etc/snapper/configs/ufos-db
+
# change
+
TIMELINE_MIN_AGE="1800"
+
TIMELINE_LIMIT_HOURLY="10"
+
TIMELINE_LIMIT_DAILY="10"
+
TIMELINE_LIMIT_WEEKLY="0"
+
TIMELINE_LIMIT_MONTHLY="10"
+
TIMELINE_LIMIT_YEARLY="10"
+
# to
+
TIMELINE_MIN_AGE="1800"
+
TIMELINE_LIMIT_HOURLY="22"
+
TIMELINE_LIMIT_DAILY="4"
+
TIMELINE_LIMIT_WEEKLY="0"
+
TIMELINE_LIMIT_MONTHLY="0"
+
TIMELINE_LIMIT_YEARLY="0"
+
```
+
+
this should be enough?
+
+
list snapshots:
+
+
```bash
+
sudo snapper -c ufos-db list
+
```
+
+
systemd
+
+
create file: `/etc/systemd/system/ufos.service`
+
+
```ini
+
[Unit]
+
Description=UFOs-API
+
After=network.target
+
+
[Service]
+
User=pi
+
WorkingDirectory=/home/pi/
+
ExecStart=/home/pi/ufos --jetstream us-west-2 --data /mnt/ufos-db/
+
Environment="RUST_LOG=info"
+
LimitNOFILE=16384
+
Restart=always
+
+
[Install]
+
WantedBy=multi-user.target
+
```
+
+
then
+
+
```bash
+
sudo systemctl daemon-reload
+
sudo systemctl enable ufos
+
sudo systemctl start ufos
+
```
+
+
monitor with
+
+
```bash
+
journalctl -u ufos -f
+
```
+
+
make sure a backup dir exists
+
+
```bash
+
mkdir /home/pi/backup
+
```
+
+
mount the NAS
+
+
```bash
+
sudo mount.cifs "//truenas.local/folks data" /home/pi/backup -o user=phil,uid=pi
+
```
+
+
manual rsync
+
+
```bash
+
sudo rsync -ahP --delete /mnt/ufos-db/.snapshots/1/snapshot/ backup/ufos/
+
```
+
+
backup script sketch
+
+
```bash
+
NUM=$(sudo snapper --csvout -c ufos-db list --type single --columns number | tail -n1)
+
sudo rsync -ahP --delete "/mnt/ufos-db/.snapshots/${NUM}/snapshot/" backup/ufos/
+
```
+
+
just crontab it?
+
+
`sudo crontab -e`
+
```bash
+
0 1/6 * * * rsync -ahP --delete "/mnt/ufos-db/.snapshots/$(sudo snapper --csvout -c ufos-db list --columns number | tail -n1)/snapshot/" backup/ufos/
+
```
+
+
^^ try once initial backup is done
+
+
+
--columns subvolume,number
+
+
subvolume
+
number
+
+
+
+
+
gateway: follow constellation for nginx->prom thing
+
+
config at `/etc/prometheus-nginxlog-exporter.hcl`
+
+
before: `/etc/prometheus-nginxlog-exporter.hcl`
+
+
```hcl
+
listen {
+
port = 4044
+
}
+
+
namespace "nginx" {
+
source = {
+
files = [
+
"/var/log/nginx/constellation-access.log"
+
]
+
}
+
+
format = "$remote_addr - $remote_user [$time_local] \"$request\" $status $upstream_cache_status $body_bytes_sent \"$http_referer\" \"$http_user_agent\" \"$http_x_forwarded_for\""
+
+
labels {
+
app = "constellation"
+
}
+
+
relabel "cache_status" {
+
from = "upstream_cache_status"
+
}
+
}
+
```
+
+
after:
+
+
```hcl
+
listen {
+
port = 4044
+
}
+
+
namespace "constellation" {
+
source = {
+
files = [
+
"/var/log/nginx/constellation-access.log"
+
]
+
}
+
+
format = "$remote_addr - $remote_user [$time_local] \"$request\" $status $upstream_cache_status $body_bytes_sent \"$http_referer\" \"$http_user_agent\" \"$http_x_forwarded_for\""
+
+
labels {
+
app = "constellation"
+
}
+
+
relabel "cache_status" {
+
from = "upstream_cache_status"
+
}
+
+
namespace_label = "vhost"
+
metrics_override = { prefix = "nginx" }
+
}
+
+
namespace "ufos" {
+
source = {
+
files = [
+
"/var/log/nginx/ufos-access.log"
+
]
+
}
+
+
format = "$remote_addr - $remote_user [$time_local] \"$request\" $status $upstream_cache_status $body_bytes_sent \"$http_referer\" \"$http_user_agent\" \"$http_x_forwarded_for\""
+
+
labels {
+
app = "ufos"
+
}
+
+
relabel "cache_status" {
+
from = "upstream_cache_status"
+
}
+
+
namespace_label = "vhost"
+
metrics_override = { prefix = "nginx" }
+
}
+
```
+
+
+
```bash
+
systemctl start prometheus-nginxlog-exporter.service
+
```
+
+15
links/src/lib.rs
···
None
}
}
+
pub fn did(&self) -> Option<String> {
+
let did = match self {
+
Link::AtUri(s) => {
+
let rest = s.strip_prefix("at://")?; // todo: this might be safe to unwrap?
+
if let Some((did, _)) = rest.split_once("/") {
+
did
+
} else {
+
rest
+
}
+
}
+
Link::Uri(_) => return None,
+
Link::Did(did) => did,
+
};
+
Some(did.to_string())
+
}
}
#[derive(Debug, PartialEq)]
+1
pocket/.gitignore
···
+
prefs.sqlite3*
+19
pocket/Cargo.toml
···
+
[package]
+
name = "pocket"
+
version = "0.1.0"
+
edition = "2024"
+
+
[dependencies]
+
atrium-crypto = "0.1.2"
+
clap = { version = "4.5.41", features = ["derive"] }
+
jwt-compact = { git = "https://github.com/fatfingers23/jwt-compact.git", features = ["es256k"] }
+
log = "0.4.27"
+
poem = { version = "3.1.12", features = ["acme", "static-files"] }
+
poem-openapi = { version = "5.1.16", features = ["scalar"] }
+
reqwest = { version = "0.12.22", features = ["json"] }
+
rusqlite = "0.37.0"
+
serde = { version = "1.0.219", features = ["derive"] }
+
serde_json = { version = "1.0.141" }
+
thiserror = "2.0.16"
+
tokio = { version = "1.47.0", features = ["full"] }
+
tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }
+17
pocket/api-description.md
···
+
_A pocket dimension to stash a bit of non-public user data._
+
+
+
# Pocket: user preference storage
+
+
This API leverages atproto service proxying to offer a bit of per-user per-app non-public data storage.
+
Perfect for things like application preferences that might be better left out of the public PDS data.
+
+
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.
+
+
+
### Current status
+
+
> [!important]
+
> 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.
+
+
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
···
+
mod server;
+
mod storage;
+
mod token;
+
+
pub use server::serve;
+
pub use storage::Storage;
+
pub use token::TokenVerifier;
+34
pocket/src/main.rs
···
+
use clap::Parser;
+
use pocket::{Storage, serve};
+
use std::path::PathBuf;
+
+
/// Slingshot record edge cache
+
#[derive(Parser, Debug, Clone)]
+
#[command(version, about, long_about = None)]
+
struct Args {
+
/// path to the sqlite db file
+
#[arg(long)]
+
db: Option<PathBuf>,
+
/// just initialize the db and exit
+
#[arg(long, action)]
+
init_db: bool,
+
/// the domain for serving a did doc (unused if running behind reflector)
+
#[arg(long)]
+
domain: Option<String>,
+
}
+
+
#[tokio::main]
+
async fn main() {
+
tracing_subscriber::fmt::init();
+
log::info!("👖 hi");
+
let args = Args::parse();
+
let domain = args.domain.unwrap_or("bad-example.com".into());
+
let db_path = args.db.unwrap_or("prefs.sqlite3".into());
+
if args.init_db {
+
Storage::init(&db_path).unwrap();
+
log::info!("👖 initialized db at {db_path:?}. bye")
+
} else {
+
let storage = Storage::connect(db_path).unwrap();
+
serve(&domain, storage).await
+
}
+
}
+265
pocket/src/server.rs
···
+
use crate::{Storage, TokenVerifier};
+
use poem::{
+
Endpoint, EndpointExt, Route, Server,
+
endpoint::{StaticFileEndpoint, make_sync},
+
http::Method,
+
listener::TcpListener,
+
middleware::{CatchPanic, Cors, Tracing},
+
};
+
use poem_openapi::{
+
ApiResponse, ContactObject, ExternalDocumentObject, Object, OpenApi, OpenApiService,
+
SecurityScheme, Tags,
+
auth::Bearer,
+
payload::{Json, PlainText},
+
types::Example,
+
};
+
use serde::Serialize;
+
use serde_json::{Value, json};
+
use std::sync::{Arc, Mutex};
+
+
#[derive(Debug, SecurityScheme)]
+
#[oai(ty = "bearer")]
+
struct XrpcAuth(Bearer);
+
+
#[derive(Tags)]
+
enum ApiTags {
+
/// Custom pocket APIs
+
#[oai(rename = "Pocket APIs")]
+
Pocket,
+
}
+
+
#[derive(Object)]
+
#[oai(example = true)]
+
struct XrpcErrorResponseObject {
+
/// Should correspond an error `name` in the lexicon errors array
+
error: String,
+
/// Human-readable description and possibly additonal context
+
message: String,
+
}
+
impl Example for XrpcErrorResponseObject {
+
fn example() -> Self {
+
Self {
+
error: "PreferencesNotFound".to_string(),
+
message: "No preferences were found for this user".to_string(),
+
}
+
}
+
}
+
type XrpcError = Json<XrpcErrorResponseObject>;
+
fn xrpc_error(error: impl AsRef<str>, message: impl AsRef<str>) -> XrpcError {
+
Json(XrpcErrorResponseObject {
+
error: error.as_ref().to_string(),
+
message: message.as_ref().to_string(),
+
})
+
}
+
+
#[derive(Debug, Object)]
+
#[oai(example = true)]
+
struct BskyPrefsObject {
+
/// at-uri for this record
+
preferences: Value,
+
}
+
impl Example for BskyPrefsObject {
+
fn example() -> Self {
+
Self {
+
preferences: json!({
+
"hello": "world",
+
}),
+
}
+
}
+
}
+
+
#[derive(ApiResponse)]
+
enum GetBskyPrefsResponse {
+
/// Record found
+
#[oai(status = 200)]
+
Ok(Json<BskyPrefsObject>),
+
/// Bad request or no preferences to return
+
#[oai(status = 400)]
+
BadRequest(XrpcError),
+
}
+
+
#[derive(ApiResponse)]
+
enum PutBskyPrefsResponse {
+
/// Record found
+
#[oai(status = 200)]
+
Ok(PlainText<String>),
+
/// Bad request or no preferences to return
+
#[oai(status = 400)]
+
BadRequest(XrpcError),
+
// /// Server errors
+
// #[oai(status = 500)]
+
// ServerError(XrpcError),
+
}
+
+
struct Xrpc {
+
verifier: TokenVerifier,
+
storage: Arc<Mutex<Storage>>,
+
}
+
+
#[OpenApi]
+
impl Xrpc {
+
/// com.bad-example.pocket.getPreferences
+
///
+
/// get stored preferencess
+
#[oai(
+
path = "/com.bad-example.pocket.getPreferences",
+
method = "get",
+
tag = "ApiTags::Pocket"
+
)]
+
async fn pocket_get_prefs(&self, XrpcAuth(auth): XrpcAuth) -> GetBskyPrefsResponse {
+
let (did, aud) = match self
+
.verifier
+
.verify("com.bad-example.pocket.getPreferences", &auth.token)
+
.await
+
{
+
Ok(d) => d,
+
Err(e) => return GetBskyPrefsResponse::BadRequest(xrpc_error("boooo", e.to_string())),
+
};
+
log::info!("verified did: {did}/{aud}");
+
+
let storage = self.storage.clone();
+
+
let Ok(Ok(res)) = tokio::task::spawn_blocking(move || {
+
storage
+
.lock()
+
.unwrap()
+
.get(&did, &aud)
+
.inspect_err(|e| log::error!("failed to get prefs: {e}"))
+
})
+
.await
+
else {
+
return GetBskyPrefsResponse::BadRequest(xrpc_error("boooo", "failed to get from db"));
+
};
+
+
let Some(serialized) = res else {
+
return GetBskyPrefsResponse::BadRequest(xrpc_error(
+
"NotFound",
+
"could not find prefs for u",
+
));
+
};
+
+
let preferences = match serde_json::from_str(&serialized) {
+
Ok(v) => v,
+
Err(e) => {
+
log::error!("failed to deserialize prefs: {e}");
+
return GetBskyPrefsResponse::BadRequest(xrpc_error(
+
"boooo",
+
"failed to deserialize prefs",
+
));
+
}
+
};
+
+
GetBskyPrefsResponse::Ok(Json(BskyPrefsObject { preferences }))
+
}
+
+
/// com.bad-example.pocket.putPreferences
+
///
+
/// store bluesky prefs
+
#[oai(
+
path = "/com.bad-example.pocket.putPreferences",
+
method = "post",
+
tag = "ApiTags::Pocket"
+
)]
+
async fn pocket_put_prefs(
+
&self,
+
XrpcAuth(auth): XrpcAuth,
+
Json(prefs): Json<BskyPrefsObject>,
+
) -> PutBskyPrefsResponse {
+
let (did, aud) = match self
+
.verifier
+
.verify("com.bad-example.pocket.putPreferences", &auth.token)
+
.await
+
{
+
Ok(d) => d,
+
Err(e) => return PutBskyPrefsResponse::BadRequest(xrpc_error("boooo", e.to_string())),
+
};
+
log::info!("verified did: {did}/{aud}");
+
log::warn!("received prefs: {prefs:?}");
+
+
let storage = self.storage.clone();
+
let serialized = prefs.preferences.to_string();
+
+
let Ok(Ok(())) = tokio::task::spawn_blocking(move || {
+
storage
+
.lock()
+
.unwrap()
+
.put(&did, &aud, &serialized)
+
.inspect_err(|e| log::error!("failed to insert prefs: {e}"))
+
})
+
.await
+
else {
+
return PutBskyPrefsResponse::BadRequest(xrpc_error("boooo", "failed to put to db"));
+
};
+
+
PutBskyPrefsResponse::Ok(PlainText("saved.".to_string()))
+
}
+
}
+
+
#[derive(Debug, Clone, Serialize)]
+
#[serde(rename_all = "camelCase")]
+
struct AppViewService {
+
id: String,
+
r#type: String,
+
service_endpoint: String,
+
}
+
#[derive(Debug, Clone, Serialize)]
+
struct AppViewDoc {
+
id: String,
+
service: [AppViewService; 2],
+
}
+
/// Serve a did document for did:web for this to be an xrpc appview
+
fn get_did_doc(domain: &str) -> impl Endpoint + use<> {
+
let doc = poem::web::Json(AppViewDoc {
+
id: format!("did:web:{domain}"),
+
service: [
+
AppViewService {
+
id: "#pocket_prefs".to_string(),
+
r#type: "PocketPreferences".to_string(),
+
service_endpoint: format!("https://{domain}"),
+
},
+
AppViewService {
+
id: "#bsky_appview".to_string(),
+
r#type: "BlueskyAppview".to_string(),
+
service_endpoint: format!("https://{domain}"),
+
},
+
],
+
});
+
make_sync(move |_| doc.clone())
+
}
+
+
pub async fn serve(domain: &str, storage: Storage) -> () {
+
let verifier = TokenVerifier::default();
+
let api_service = OpenApiService::new(
+
Xrpc {
+
verifier,
+
storage: Arc::new(Mutex::new(storage)),
+
},
+
"Pocket",
+
env!("CARGO_PKG_VERSION"),
+
)
+
.server(domain)
+
.url_prefix("/xrpc")
+
.contact(
+
ContactObject::new()
+
.name("@microcosm.blue")
+
.url("https://bsky.app/profile/microcosm.blue"),
+
)
+
.description(include_str!("../api-description.md"))
+
.external_document(ExternalDocumentObject::new("https://microcosm.blue/pocket"));
+
+
let app = Route::new()
+
.nest("/openapi", api_service.spec_endpoint())
+
.nest("/xrpc/", api_service)
+
.at("/.well-known/did.json", get_did_doc(domain))
+
.at("/", StaticFileEndpoint::new("./static/index.html"))
+
.with(
+
Cors::new()
+
.allow_method(Method::GET)
+
.allow_method(Method::POST),
+
)
+
.with(CatchPanic::new())
+
.with(Tracing);
+
+
let listener = TcpListener::bind("127.0.0.1:3000");
+
Server::new(listener).name("pocket").run(app).await.unwrap();
+
}
+50
pocket/src/storage.rs
···
+
use rusqlite::{Connection, OptionalExtension, Result};
+
use std::path::Path;
+
+
pub struct Storage {
+
con: Connection,
+
}
+
+
impl Storage {
+
pub fn connect(path: impl AsRef<Path>) -> Result<Self> {
+
let con = Connection::open(path)?;
+
con.pragma_update(None, "journal_mode", "WAL")?;
+
con.pragma_update(None, "synchronous", "NORMAL")?;
+
con.pragma_update(None, "busy_timeout", "100")?;
+
con.pragma_update(None, "foreign_keys", "ON")?;
+
Ok(Self { con })
+
}
+
pub fn init(path: impl AsRef<Path>) -> Result<Self> {
+
let me = Self::connect(path)?;
+
me.con.execute(
+
r#"
+
create table prefs (
+
actor text not null,
+
aud text not null,
+
pref text not null,
+
primary key (actor, aud)
+
) strict"#,
+
(),
+
)?;
+
Ok(me)
+
}
+
pub fn put(&self, actor: &str, aud: &str, pref: &str) -> Result<()> {
+
self.con.execute(
+
r#"insert into prefs (actor, aud, pref)
+
values (?1, ?2, ?3)
+
on conflict do update set pref = excluded.pref"#,
+
[actor, aud, pref],
+
)?;
+
Ok(())
+
}
+
pub fn get(&self, actor: &str, aud: &str) -> Result<Option<String>> {
+
self.con
+
.query_one(
+
r#"select pref from prefs
+
where actor = ?1 and aud = ?2"#,
+
[actor, aud],
+
|row| row.get(0),
+
)
+
.optional()
+
}
+
}
+143
pocket/src/token.rs
···
+
use atrium_crypto::did::parse_multikey;
+
use atrium_crypto::verify::Verifier;
+
use jwt_compact::UntrustedToken;
+
use serde::Deserialize;
+
use std::collections::HashMap;
+
use std::time::Duration;
+
use thiserror::Error;
+
+
#[derive(Debug, Deserialize)]
+
struct MiniDoc {
+
signing_key: String,
+
did: String,
+
}
+
+
#[derive(Error, Debug)]
+
pub enum VerifyError {
+
#[error("The cross-service authorization token failed verification: {0}")]
+
VerificationFailed(&'static str),
+
#[error("Error trying to resolve the DID to a signing key, retry in a moment: {0}")]
+
ResolutionFailed(&'static str),
+
}
+
+
pub struct TokenVerifier {
+
client: reqwest::Client,
+
}
+
+
impl TokenVerifier {
+
pub fn new() -> Self {
+
let client = reqwest::Client::builder()
+
.user_agent(format!(
+
"microcosm pocket v{} (dev: @bad-example.com)",
+
env!("CARGO_PKG_VERSION")
+
))
+
.no_proxy()
+
.timeout(Duration::from_secs(12)) // slingshot timeout is 10s
+
.build()
+
.unwrap();
+
Self { client }
+
}
+
+
pub async fn verify(
+
&self,
+
expected_lxm: &str,
+
token: &str,
+
) -> Result<(String, String), VerifyError> {
+
let untrusted = UntrustedToken::new(token).unwrap();
+
+
// danger! unfortunately we need to decode the DID from the jwt body before we have a public key to verify the jwt with
+
let Ok(untrusted_claims) =
+
untrusted.deserialize_claims_unchecked::<HashMap<String, String>>()
+
else {
+
return Err(VerifyError::VerificationFailed(
+
"could not deserialize jtw claims",
+
));
+
};
+
+
// get the (untrusted!) claimed DID
+
let Some(untrusted_did) = untrusted_claims.custom.get("iss") else {
+
return Err(VerifyError::VerificationFailed(
+
"jwt must include the user's did in `iss`",
+
));
+
};
+
+
// bail if it's not even a user-ish did
+
if !untrusted_did.starts_with("did:") {
+
return Err(VerifyError::VerificationFailed("iss should be a did"));
+
}
+
if untrusted_did.contains("#") {
+
return Err(VerifyError::VerificationFailed(
+
"iss should be a user did without a service identifier",
+
));
+
}
+
+
let endpoint =
+
"https://slingshot.microcosm.blue/xrpc/com.bad-example.identity.resolveMiniDoc";
+
let doc: MiniDoc = self
+
.client
+
.get(format!("{endpoint}?identifier={untrusted_did}"))
+
.send()
+
.await
+
.map_err(|_| VerifyError::ResolutionFailed("failed to fetch minidoc"))?
+
.error_for_status()
+
.map_err(|_| VerifyError::ResolutionFailed("non-ok response for minidoc"))?
+
.json()
+
.await
+
.map_err(|_| VerifyError::ResolutionFailed("failed to parse json to minidoc"))?;
+
+
// sanity check before we go ahead with this signing key
+
if doc.did != *untrusted_did {
+
return Err(VerifyError::VerificationFailed(
+
"wtf, resolveMiniDoc returned a doc for a different DID, slingshot bug",
+
));
+
}
+
+
let Ok((alg, public_key)) = parse_multikey(&doc.signing_key) else {
+
return Err(VerifyError::VerificationFailed(
+
"could not parse signing key form minidoc",
+
));
+
};
+
+
// i _guess_ we've successfully bootstrapped the verification of the jwt unless this fails
+
if let Err(e) = Verifier::default().verify(
+
alg,
+
&public_key,
+
&untrusted.signed_data,
+
untrusted.signature_bytes(),
+
) {
+
log::warn!("jwt verification failed: {e}");
+
return Err(VerifyError::VerificationFailed(
+
"jwt signature verification failed",
+
));
+
}
+
+
// past this point we're should have established trust. crossing ts and dotting is.
+
let did = &untrusted_did;
+
let claims = &untrusted_claims;
+
+
let Some(aud) = claims.custom.get("aud") else {
+
return Err(VerifyError::VerificationFailed("missing aud"));
+
};
+
let Some(mut aud) = aud.strip_prefix("did:web:") else {
+
return Err(VerifyError::VerificationFailed("expected a did:web aud"));
+
};
+
if let Some((aud_without_hash, _)) = aud.split_once("#") {
+
log::warn!("aud claim is missing service id fragment: {aud:?}");
+
aud = aud_without_hash;
+
}
+
let Some(lxm) = claims.custom.get("lxm") else {
+
return Err(VerifyError::VerificationFailed("missing lxm"));
+
};
+
if lxm != expected_lxm {
+
return Err(VerifyError::VerificationFailed("wrong lxm"));
+
}
+
+
Ok((did.to_string(), aud.to_string()))
+
}
+
}
+
+
impl Default for TokenVerifier {
+
fn default() -> Self {
+
Self::new()
+
}
+
}
+67
pocket/static/index.html
···
+
<!doctype html>
+
<html lang="en">
+
<head>
+
<meta charset="utf-8" />
+
<title>Pocket: atproto user preference storage</title>
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
+
<meta name="description" content="API Documentation for Pocket, a simple user-preference storage system for atproto" />
+
<style>
+
:root {
+
--scalar-small: 13px;
+
}
+
.scalar-app .markdown .markdown-alert {
+
font-size: var(--scalar-small);
+
}
+
.sidebar-heading-link-title {
+
line-height: 1.2;
+
}
+
.custom-header {
+
height: 42px;
+
background-color: #221828;
+
box-shadow: inset 0 -1px 0 var(--scalar-border-color);
+
color: var(--scalar-color-1);
+
font-size: var(--scalar-font-size-3);
+
font-family: 'Iowan Old Style', 'Palatino Linotype', 'URW Palladio L', P052, serif;
+
padding: 0 18px;
+
justify-content: space-between;
+
}
+
.custom-header,
+
.custom-header nav {
+
display: flex;
+
align-items: center;
+
gap: 18px;
+
}
+
.custom-header a:hover {
+
color: var(--scalar-color-2);
+
}
+
+
.light-mode .custom-header {
+
background-color: thistle;
+
}
+
</style>
+
</head>
+
<body>
+
<header class="custom-header scalar-app">
+
<p>
+
TODO: thing
+
</p>
+
<nav>
+
<b>a <a href="https://microcosm.blue">microcosm</a> project</b>
+
<a href="https://bsky.app/profile/microcosm.blue">@microcosm.blue</a>
+
<a href="https://github.com/at-microcosm">github</a>
+
</nav>
+
</header>
+
+
<script id="api-reference" type="application/json" data-url="/openapi"></script>
+
+
<script>
+
var configuration = {
+
theme: 'purple',
+
hideModels: true,
+
}
+
document.getElementById('api-reference').dataset.configuration = JSON.stringify(configuration)
+
</script>
+
+
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
+
</body>
+
</html>
+8
quasar/Cargo.toml
···
+
[package]
+
name = "quasar"
+
version = "0.1.0"
+
edition = "2024"
+
+
[dependencies]
+
clap = { version = "4.5.46", features = ["derive"] }
+
fjall = "2.11.2"
+3
quasar/readme.md
···
+
# quasar
+
+
indexed replay and fan-out for event stream services (wip)
+3
quasar/src/lib.rs
···
+
mod storage;
+
+
pub use storage::Storage;
+3
quasar/src/main.rs
···
+
fn main() {
+
println!("Hello, world!");
+
}
+4
quasar/src/storage.rs
···
+
+
pub trait Storage {
+
+
}
+57 -129
readme.md
···
-
microcosm: links
-
================
-
-
this repo contains libraries and apps for working with cross-record references in at-protocol.
-
+
microcosm HTTP APIs + rust crates
+
=================================
+
[![@microcosm.blue: bluesky](https://img.shields.io/badge/@microcosm.blue-bluesky-blue)](https://bsky.app/profile/microcosm.blue)
+
[![microcosm discord: join](https://img.shields.io/badge/microcosm_discord-join-purple)](https://discord.gg/tcDfe4PGVB)
+
[![github sponsors: support](https://img.shields.io/badge/github_sponsors-support-pink)](https://github.com/sponsors/uniphil/)
+
[![ko-fi: support](https://img.shields.io/badge/ko--fi-support-pink)](https://ko-fi.com/bad_example)
-
App: [Constellation](./constellation/)
-
--------------------------------------------
+
Welcome! Documentation is under active development. If you like reading API docs, you'll probably hit the ground running!
-
A global atproto backlink index ✨
+
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.
-
- Self hostable: handles the full write throughput of the global atproto firehose on a raspberry pi 4b + single SSD
-
- Storage efficient: less than 2GB/day disk consumption indexing all references in all lexicons and all non-atproto URLs
-
- Handles record deletion, account de/re-activation, and account deletion, ensuring accurate link counts and respecting users data choices
-
- Simple JSON API
+
> [!tip]
+
> 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!
-
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.
-
- **status**: works! api is unstable and likely to change, and no known instances have a full network backfill yet.
-
- source: [./constellation/](./constellation/)
-
- public instance: [constellation.microcosm.blue](https://constellation.microcosm.blue/)
-
-
_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._
-
-
-
App: Spacedust
-
--------------
-
-
A notification subscription service 💫
-
-
using the same "link source" concept as [constellation](./constellation/), offer webhook notifications for new references created to records
-
-
- **status**: in design
-
-
-
Library: [links](./links/)
+
🌌 [Constellation](./constellation/)
------------------------------------
-
A rust crate (not published on crates.io yet) for optimistically parsing links out of arbitrary atproto PDS records, and potentially canonicalizing them
-
-
- **status**: unstable, might remain an internal lib for constellation (and spacedust, soon)
-
-
-
-
---
-
-
-
old notes follow, ignore
-
------------------------
-
-
-
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.
-
-
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.
-
-
-
why
-
---
-
-
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.
-
-
- bluesky posts (firesky, deletions, )
-
- blueksy post stats (emojis, )
-
- trending keywords ()
-
-
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?_
-
-
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.
-
-
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!
-
-
**so, why**
-
-
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.
-
-
everything is links:
-
-
- likes
-
- follows
-
- blocks
-
- reposts
-
- quotes
-
-
some low-level things you could make from links:
-
-
- notification streams (part of ucosm)
-
- a global reverse index (part of ucosm)
-
-
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.
+
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.
+
- Source: [./constellation/](./constellation/)
+
- [Public instance/API docs](https://constellation.microcosm.blue/)
+
- Status: used in production. APIs will change but backwards compatibility will be maintained as long as needed.
-
extracting links
-
---------------
+
🎇 [Spacedust](./spacedust/)
+
----------------------------
-
- low-level: pass a &str of a field value and get a parsed link back
+
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).
-
- 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?)
+
- Source: [./spacedust/](./spacedust/)
+
- [Public instance/API docs](https://spacedust.microcosm.blue/)
+
- Status: v0: the basics work and the APIs are in place! missing cursor replay, forward link storage, and delete event link hydration.
-
- high-ish level: pass the json record and maybe apply some pre-loaded rules based on known lexicons to get the best result.
+
### Demos:
-
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.
+
- [Spacedust notifications](https://notifications.microcosm.blue/): web push notifications for _every_ atproto app
+
- [Zero-Bluesky real-time interaction-updating post embed](https://bsky.bad-example.com/zero-bluesky-realtime-embed/)
-
resolving / canonicalizing links
-
--------------------------------
+
🛰️ [Slingshot](./slingshot)
+
---------------------------
+
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.
-
### at-uris
+
- Source: [./slingshot/](./slingshot/)
+
- [Public instance/API docs](https://slingshot.microcosm.blue/)
+
- Status: v0: most XRPC APIs are working. cache storage is being reworked.
-
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):
-
- `at://did:plc:44ybard66vv44zksje25o7dz/app.bsky.feed.post/3jwdwj2ctlk26`
-
- `at://bnewbold.bsky.team/app.bsky.feed.post/3jwdwj2ctlk26`
+
🛸 [UFOs API](./ufos)
+
---------------------
-
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?
+
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.
-
hopefully atrium will make it easy to resolve at-uris.
+
- Source: [./ufos/](./ufos/)
+
- [Public instance/API docs](https://ufos-api.microcosm.blue/)
+
- 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.
+
> [!tip]
+
> See also: [UFOs atproto explorer](https://ufos.microcosm.blue/) built on UFOs API. ([source](github.com/at-microcosm/spacedust-utils))
-
### urls
-
canonicalizing URLs is more annoying but also a bit more established. lots of details.
+
💫 [Links](./links)
+
-------------------
-
- do we have to deal with punycode?
-
- follow redirects (todo: only permanent ones, or all?)
-
- check for rel=canonical http header and possibly follow it
-
- check link rel=canonical meta tag and possibly follow it
-
- do we need to check site maps??
-
- do we have to care at all about AMP?
-
- do we want anything to do with url shorteners??
-
- how do multilingual sites affect this?
-
- do we have to care about `script type="application/ld+json"` ???
+
Rust library for parsing and extracting links (at-uris, DIDs, and URLs) from atproto records.
-
ugh. is there a crate for this.
+
- Source: [./links/](./links/)
+
- Status: not yet published to crates.io; needs some rework
-
### relative uris?
-
-
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)
-
-
-
### canonicalizing
-
-
there should be a few async functions available to canonicalize already-parsed links.
-
-
- what happens if a link can't be resolved?
+
🛩️ [Jetstream](./jetstream)
+
---------------------------
+
A low-overhead jetstream client with cursor handling and automatic reconnect.
-
---
+
- Source: [./links/](./links/)
+
- Status: used in multiple apps in production, but not yet published to crates.io; some rework planned
-
- using `tinyjson` because it's nice -- maybe should switch to serde_json to share deps with atrium?
+
> [!tip]
+
> 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.
-
- 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?
-
- rsky-syntax has an aturi
-
- adenosyne also
-
- might come back to these
+
🔭 Deprecated: [Who am I](./who-am-i)
+
-------------------------------------
-
-------
+
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.
-
rocks
+
- Source: [./who-am-i/](./who-am-i/)
+
- Status: ready for retirement.
-
```bash
-
ROCKSDB_LIB_DIR=/nix/store/z2chn0hsik0clridr8mlprx1cngh1g3c-rocksdb-9.7.3/lib/ cargo build
-
```
+
> [!warning]
+
> `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
···
+
[package]
+
name = "reflector"
+
version = "0.1.0"
+
edition = "2024"
+
+
[dependencies]
+
clap = { version = "4.5.47", features = ["derive"] }
+
log = "0.4.28"
+
poem = "3.1.12"
+
serde = { version = "1.0.219", features = ["derive"] }
+
tokio = "1.47.1"
+
tracing-subscriber = { version = "0.3.20", features = ["env-filter"] }
+9
reflector/readme.md
···
+
# reflector
+
+
a tiny did:web service server that maps subdomains to a single service endpoint
+
+
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).
+
+
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.
+
+
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
···
+
use clap::Parser;
+
use poem::{
+
EndpointExt, Response, Route, Server, get, handler,
+
http::StatusCode,
+
listener::TcpListener,
+
middleware::{AddData, Tracing},
+
web::{Data, Json, Query, TypedHeader, headers::Host},
+
};
+
use serde::{Deserialize, Serialize};
+
+
#[handler]
+
fn hello() -> String {
+
"ɹoʇɔǝʅⅎǝɹ".to_string()
+
}
+
+
#[derive(Debug, Serialize)]
+
struct DidDoc {
+
id: String,
+
service: [DidService; 1],
+
}
+
+
#[derive(Debug, Clone, Serialize)]
+
#[serde(rename_all = "camelCase")]
+
struct DidService {
+
id: String,
+
r#type: String,
+
service_endpoint: String,
+
}
+
+
#[handler]
+
fn did_doc(TypedHeader(host): TypedHeader<Host>, service: Data<&DidService>) -> Json<DidDoc> {
+
Json(DidDoc {
+
id: format!("did:web:{}", host.hostname()),
+
service: [service.clone()],
+
})
+
}
+
+
#[derive(Deserialize)]
+
struct AskQuery {
+
domain: String,
+
}
+
#[handler]
+
fn ask_caddy(
+
Data(parent): Data<&Option<String>>,
+
Query(AskQuery { domain }): Query<AskQuery>,
+
) -> Response {
+
if let Some(parent) = parent {
+
if let Some(prefix) = domain.strip_suffix(&format!(".{parent}")) {
+
if !prefix.contains('.') {
+
// no sub-sub-domains allowed
+
return Response::builder().body("ok");
+
}
+
}
+
};
+
Response::builder()
+
.status(StatusCode::FORBIDDEN)
+
.body("nope")
+
}
+
+
/// Slingshot record edge cache
+
#[derive(Parser, Debug, Clone)]
+
#[command(version, about, long_about = None)]
+
struct Args {
+
/// The DID document service ID to serve
+
///
+
/// must start with a '#', like `#bsky_appview'
+
#[arg(long)]
+
id: String,
+
/// Service type
+
///
+
/// Not sure exactly what its requirements are. 'BlueskyAppview' for example
+
#[arg(long)]
+
r#type: String,
+
/// The HTTPS endpoint for the service
+
#[arg(long)]
+
service_endpoint: String,
+
/// The parent domain; requests should come from subdomains of this
+
#[arg(long)]
+
domain: Option<String>,
+
}
+
+
impl From<Args> for DidService {
+
fn from(a: Args) -> Self {
+
Self {
+
id: a.id,
+
r#type: a.r#type,
+
service_endpoint: a.service_endpoint,
+
}
+
}
+
}
+
+
#[tokio::main(flavor = "current_thread")]
+
async fn main() {
+
tracing_subscriber::fmt::init();
+
log::info!("ɹoʇɔǝʅⅎǝɹ");
+
+
let args = Args::parse();
+
let domain = args.domain.clone();
+
let service: DidService = args.into();
+
+
Server::new(TcpListener::bind("0.0.0.0:3001"))
+
.run(
+
Route::new()
+
.at("/", get(hello))
+
.at("/.well-known/did.json", get(did_doc))
+
.at("/ask", get(ask_caddy))
+
.with(AddData::new(service))
+
.with(AddData::new(domain))
+
.with(Tracing),
+
)
+
.await
+
.unwrap()
+
}
+1
slingshot/.gitignore
···
+
foyer
+31
slingshot/Cargo.toml
···
+
[package]
+
name = "slingshot"
+
version = "0.1.0"
+
edition = "2024"
+
+
[dependencies]
+
atrium-api = { git = "https://github.com/uniphil/atrium.git", branch = "fix/resolve-handle-https-accept-whitespace", default-features = false }
+
atrium-common = { git = "https://github.com/uniphil/atrium.git", branch = "fix/resolve-handle-https-accept-whitespace" }
+
atrium-identity = { git = "https://github.com/uniphil/atrium.git", branch = "fix/resolve-handle-https-accept-whitespace" }
+
atrium-oauth = { git = "https://github.com/uniphil/atrium.git", branch = "fix/resolve-handle-https-accept-whitespace" }
+
clap = { version = "4.5.41", features = ["derive"] }
+
ctrlc = "3.4.7"
+
foyer = { version = "0.18.0", features = ["serde"] }
+
hickory-resolver = "0.25.2"
+
jetstream = { path = "../jetstream", features = ["metrics"] }
+
links = { path = "../links" }
+
log = "0.4.27"
+
metrics = "0.24.2"
+
metrics-exporter-prometheus = { version = "0.17.1", features = ["http-listener"] }
+
poem = { version = "3.1.12", features = ["acme", "static-files"] }
+
poem-openapi = { version = "5.1.16", features = ["scalar"] }
+
reqwest = { version = "0.12.22", features = ["json"] }
+
rustls = "0.23.31"
+
serde = { version = "1.0.219", features = ["derive"] }
+
serde_json = { version = "1.0.141", features = ["raw_value"] }
+
thiserror = "2.0.12"
+
time = { version = "0.3.41", features = ["serde"] }
+
tokio = { version = "1.47.0", features = ["full"] }
+
tokio-util = "0.7.15"
+
tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }
+
url = "2.5.4"
+93
slingshot/api-description.md
···
+
_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._
+
+
+
# Slingshot: edge record cache
+
+
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:
+
+
- A PDS might be far away with long network latency
+
- or may be on an unreliable connection
+
- or overloaded when you need it, or offline, or…
+
+
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.
+
+
**Slingshot is a fast, eager, production-grade cache of data in the [ATmosphere](https://atproto.com/)**, offering performance and reliability without custom infrastructure.
+
+
+
### Current status
+
+
> [!important]
+
> 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.
+
+
The core APIs will not change, since they are standard third-party `com.atproto` query APIs from ATProtocol.
+
+
+
## Eager caching
+
+
In many cases, Slingshot can cache the data you need *before* first request!
+
+
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)_
+
+
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.
+
+
+
## Precise invalidation
+
+
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)_
+
+
+
## Low-trust
+
+
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.
+
+
Two core standard query APIs are supported to balance convenience and trust. They both fetch [records](https://atproto.com/guides/glossary#record):
+
+
### [`com.atproto.repo.getRecord`](#tag/comatproto-queries/get/xrpc/com.atproto.repo.getRecord)
+
+
- convenient `JSON` response format
+
- cannot be proven authentic
+
+
### [`com.atproto.sync.getRecord`](#tag/comatproto-queries/get/xrpc/com.atproto.sync.getRecord)
+
+
- [`DAG-CBOR`](https://atproto.com/specs/data-model)-encoded response requires extra libraries to decode, but
+
- includes a cryptographic proof of authenticity!
+
+
_(work on this endpoint is in progress)_
+
+
+
## Service proxying
+
+
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.
+
+
Service-proxied requests can specify a Slingshot instance via the `atproto-proxy` header:
+
+
```http
+
GET /xrpc/com.bad-example.identity.resolveMiniDoc?identifier=bad-example.com
+
Host: <your pds>
+
atproto-proxy: did:web:<slingshot domain>#slingshot
+
```
+
+
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.
+
+
> [!tip]
+
> 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_)
+
+
+
## Ergonomic APIs
+
+
- 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.
+
+
- 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.
+
+
+
## Part of microcosm
+
+
[Microcosm](https://www.microcosm.blue/) is a collection of services and independent community-run infrastructure for ATProtocol.
+
+
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!
+
+
- [🌌 Constellation](https://constellation.microcosm.blue/), a global backlink index (all social interactions in atproto are links!)
+
- [🎇 Spacedust](https://spacedust.microcosm.blue/), a firehose of all social interactions
+
+
> [!success]
+
> 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
···
+
# slingshot: atproto record edge cache
+
+
local dev running:
+
+
```bash
+
RUST_LOG=info,slingshot=trace ulimit -n 4096 && RUST_LOG=info cargo run -- --jetstream us-east-1 --cache-dir ./foyer
+
```
+80
slingshot/src/consumer.rs
···
+
use crate::CachedRecord;
+
use crate::error::ConsumerError;
+
use foyer::HybridCache;
+
use jetstream::{
+
DefaultJetstreamEndpoints, JetstreamCompression, JetstreamConfig, JetstreamConnector,
+
events::{CommitOp, Cursor, EventKind},
+
};
+
use tokio_util::sync::CancellationToken;
+
+
pub async fn consume(
+
jetstream_endpoint: String,
+
cursor: Option<Cursor>,
+
no_zstd: bool,
+
shutdown: CancellationToken,
+
cache: HybridCache<String, CachedRecord>,
+
) -> Result<(), ConsumerError> {
+
let endpoint = DefaultJetstreamEndpoints::endpoint_or_shortcut(&jetstream_endpoint);
+
if endpoint == jetstream_endpoint {
+
log::info!("consumer: connecting jetstream at {endpoint}");
+
} else {
+
log::info!("consumer: connecting jetstream at {jetstream_endpoint} => {endpoint}");
+
}
+
let config: JetstreamConfig = JetstreamConfig {
+
endpoint,
+
compression: if no_zstd {
+
JetstreamCompression::None
+
} else {
+
JetstreamCompression::Zstd
+
},
+
replay_on_reconnect: true,
+
channel_size: 1024, // buffer up to ~1s of jetstream events
+
..Default::default()
+
};
+
let mut receiver = JetstreamConnector::new(config)?
+
.connect_cursor(cursor)
+
.await?;
+
+
log::info!("consumer: receiving messages..");
+
loop {
+
if shutdown.is_cancelled() {
+
log::info!("consumer: exiting for shutdown");
+
return Ok(());
+
}
+
let Some(mut event) = receiver.recv().await else {
+
log::error!("consumer: could not receive event, bailing");
+
break;
+
};
+
+
if event.kind != EventKind::Commit {
+
continue;
+
}
+
let Some(ref mut commit) = event.commit else {
+
log::warn!("consumer: commit event missing commit data, ignoring");
+
continue;
+
};
+
+
// TODO: something a bit more robust
+
let at_uri = format!(
+
"at://{}/{}/{}",
+
&*event.did, &*commit.collection, &*commit.rkey
+
);
+
+
if commit.operation == CommitOp::Delete {
+
cache.insert(at_uri, CachedRecord::Deleted);
+
} else {
+
let Some(record) = commit.record.take() else {
+
log::warn!("consumer: commit insert or update missing record, ignoring");
+
continue;
+
};
+
let Some(cid) = commit.cid.take() else {
+
log::warn!("consumer: commit insert or update missing CID, ignoring");
+
continue;
+
};
+
+
cache.insert(at_uri, CachedRecord::Found((cid, record).into()));
+
}
+
}
+
+
Err(ConsumerError::JetstreamEnded)
+
}
+93
slingshot/src/error.rs
···
+
use crate::ErrorResponseObject;
+
use thiserror::Error;
+
+
#[derive(Debug, Error)]
+
pub enum ConsumerError {
+
#[error(transparent)]
+
JetstreamConnectionError(#[from] jetstream::error::ConnectionError),
+
#[error(transparent)]
+
JetstreamConfigValidationError(#[from] jetstream::error::ConfigValidationError),
+
#[error("jetstream ended")]
+
JetstreamEnded,
+
#[error("delay queue output dropped")]
+
DelayQueueOutputDropped,
+
}
+
+
#[derive(Debug, Error)]
+
pub enum ServerError {
+
#[error("server build error: {0}")]
+
AcmeBuildError(std::io::Error),
+
#[error("server exited: {0}")]
+
ServerExited(std::io::Error),
+
}
+
+
#[derive(Debug, Error)]
+
pub enum IdentityError {
+
#[error("whatever: {0}")]
+
WhateverError(String),
+
#[error("bad DID: {0}")]
+
BadDid(&'static str),
+
#[error("identity types got mixed up: {0}")]
+
IdentityValTypeMixup(String),
+
#[error("foyer error: {0}")]
+
FoyerError(#[from] foyer::Error),
+
+
#[error("failed to resolve: {0}")]
+
ResolutionFailed(#[from] atrium_identity::Error),
+
// #[error("identity resolved but no handle found for user")]
+
// NoHandle,
+
#[error("found handle {0:?} but it appears invalid: {1}")]
+
InvalidHandle(String, &'static str),
+
+
#[error("could not convert atrium did doc to partial mini doc: {0}")]
+
BadDidDoc(String),
+
+
#[error("wrong key for clearing refresh queue: {0}")]
+
RefreshQueueKeyError(&'static str),
+
}
+
+
#[derive(Debug, Error)]
+
pub enum HealthCheckError {
+
#[error("failed to send checkin: {0}")]
+
HealthCheckError(#[from] reqwest::Error),
+
}
+
+
#[derive(Debug, Error)]
+
pub enum MainTaskError {
+
#[error(transparent)]
+
ConsumerTaskError(#[from] ConsumerError),
+
#[error(transparent)]
+
ServerTaskError(#[from] ServerError),
+
#[error(transparent)]
+
IdentityTaskError(#[from] IdentityError),
+
#[error(transparent)]
+
HealthCheckError(#[from] HealthCheckError),
+
#[error("firehose cache failed to close: {0}")]
+
FirehoseCacheCloseError(foyer::Error),
+
}
+
+
#[derive(Debug, Error)]
+
pub enum RecordError {
+
#[error("identity error: {0}")]
+
IdentityError(#[from] IdentityError),
+
#[error("repo could not be validated as either a DID or an atproto handle")]
+
BadRepo,
+
#[error("could not get record: {0}")]
+
NotFound(&'static str),
+
#[error("could nto parse pds url: {0}")]
+
UrlParseError(#[from] url::ParseError),
+
#[error("reqwest send failed: {0}")]
+
SendError(reqwest::Error),
+
#[error("reqwest raised for status: {0}")]
+
StatusError(reqwest::Error),
+
#[error("reqwest failed to parse json: {0}")]
+
ParseJsonError(reqwest::Error),
+
#[error("upstream getRecord did not include a CID")]
+
MissingUpstreamCid,
+
#[error("upstream CID was not valid: {0}")]
+
BadUpstreamCid(String),
+
#[error("upstream atproto-looking bad request")]
+
UpstreamBadRequest(ErrorResponseObject),
+
#[error("upstream non-atproto bad request")]
+
UpstreamBadBadNotGoodRequest(reqwest::Error),
+
}
+22
slingshot/src/firehose_cache.rs
···
+
use crate::CachedRecord;
+
use foyer::{DirectFsDeviceOptions, Engine, HybridCache, HybridCacheBuilder};
+
use std::path::Path;
+
+
pub async fn firehose_cache(
+
cache_dir: impl AsRef<Path>,
+
) -> Result<HybridCache<String, CachedRecord>, String> {
+
let cache = HybridCacheBuilder::new()
+
.with_name("firehose")
+
.memory(64 * 2_usize.pow(20))
+
.with_weighter(|k: &String, v| k.len() + std::mem::size_of_val(v))
+
.storage(Engine::large())
+
.with_device_options(
+
DirectFsDeviceOptions::new(cache_dir)
+
.with_capacity(2_usize.pow(30)) // TODO: configurable (1GB to have something)
+
.with_file_size(16 * 2_usize.pow(20)), // note: this does limit the max cached item size, warning jumbo records
+
)
+
.build()
+
.await
+
.map_err(|e| format!("foyer setup error: {e:?}"))?;
+
Ok(cache)
+
}
+32
slingshot/src/healthcheck.rs
···
+
use crate::error::HealthCheckError;
+
use reqwest::Client;
+
use std::time::Duration;
+
use tokio::time::sleep;
+
use tokio_util::sync::CancellationToken;
+
+
pub async fn healthcheck(
+
endpoint: String,
+
shutdown: CancellationToken,
+
) -> Result<(), HealthCheckError> {
+
let client = Client::builder()
+
.user_agent(format!(
+
"microcosm slingshot v{} (dev: @bad-example.com)",
+
env!("CARGO_PKG_VERSION")
+
))
+
.no_proxy()
+
.timeout(Duration::from_secs(10))
+
.build()?;
+
+
loop {
+
tokio::select! {
+
res = client.get(&endpoint).send() => {
+
let _ = res
+
.and_then(|r| r.error_for_status())
+
.inspect_err(|e| log::error!("failed to send healthcheck: {e}"));
+
},
+
_ = shutdown.cancelled() => break,
+
}
+
sleep(Duration::from_secs(51)).await;
+
}
+
Ok(())
+
}
+525
slingshot/src/identity.rs
···
+
use hickory_resolver::{ResolveError, TokioResolver};
+
use std::collections::{HashSet, VecDeque};
+
use std::path::Path;
+
use std::sync::Arc;
+
/// for now we're gonna just keep doing more cache
+
///
+
/// plc.director x foyer, ttl kept with data, refresh deferred to background on fetch
+
///
+
/// things we need:
+
///
+
/// 1. handle -> DID resolution: getRecord must accept a handle for `repo` param
+
/// 2. DID -> PDS resolution: so we know where to getRecord
+
/// 3. DID -> handle resolution: for bidirectional handle validation and in case we want to offer this
+
use std::time::Duration;
+
use tokio::sync::Mutex;
+
use tokio_util::sync::CancellationToken;
+
+
use crate::error::IdentityError;
+
use atrium_api::{
+
did_doc::DidDocument,
+
types::string::{Did, Handle},
+
};
+
use atrium_common::resolver::Resolver;
+
use atrium_identity::{
+
did::{CommonDidResolver, CommonDidResolverConfig, DEFAULT_PLC_DIRECTORY_URL},
+
handle::{AtprotoHandleResolver, AtprotoHandleResolverConfig, DnsTxtResolver},
+
};
+
use atrium_oauth::DefaultHttpClient; // it's probably not worth bringing all of atrium_oauth for this but
+
use foyer::{DirectFsDeviceOptions, Engine, HybridCache, HybridCacheBuilder};
+
use serde::{Deserialize, Serialize};
+
use time::UtcDateTime;
+
+
/// once we have something resolved, don't re-resolve until after this period
+
const MIN_TTL: Duration = Duration::from_secs(4 * 3600); // probably shoudl have a max ttl
+
const MIN_NOT_FOUND_TTL: Duration = Duration::from_secs(60);
+
+
#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
+
enum IdentityKey {
+
Handle(Handle),
+
Did(Did),
+
}
+
+
#[derive(Debug, Serialize, Deserialize)]
+
struct IdentityVal(UtcDateTime, IdentityData);
+
+
#[derive(Debug, Serialize, Deserialize)]
+
enum IdentityData {
+
NotFound,
+
Did(Did),
+
Doc(PartialMiniDoc),
+
}
+
+
/// partial representation of a com.bad-example.identity mini atproto doc
+
///
+
/// partial because the handle is not verified
+
#[derive(Debug, Clone, Serialize, Deserialize)]
+
pub struct PartialMiniDoc {
+
/// an atproto handle (**unverified**)
+
///
+
/// the first valid atproto handle from the did doc's aka
+
pub unverified_handle: Handle,
+
/// the did's atproto pds url (TODO: type this?)
+
///
+
/// note: atrium *does* actually parse it into a URI, it just doesn't return
+
/// that for some reason
+
pub pds: String,
+
/// for now we're just pulling this straight from the did doc
+
///
+
/// would be nice to type and validate it
+
///
+
/// this is the publicKeyMultibase from the did doc.
+
/// legacy key encoding not supported.
+
/// `id`, `type`, and `controller` must be checked, but aren't stored.
+
pub signing_key: String,
+
}
+
+
impl TryFrom<DidDocument> for PartialMiniDoc {
+
type Error = String;
+
fn try_from(did_doc: DidDocument) -> Result<Self, Self::Error> {
+
// must use the first valid handle
+
let mut unverified_handle = None;
+
let Some(ref doc_akas) = did_doc.also_known_as else {
+
return Err("did doc missing `also_known_as`".to_string());
+
};
+
for aka in doc_akas {
+
let Some(maybe_handle) = aka.strip_prefix("at://") else {
+
continue;
+
};
+
let Ok(valid_handle) = Handle::new(maybe_handle.to_string()) else {
+
continue;
+
};
+
unverified_handle = Some(valid_handle);
+
break;
+
}
+
let Some(unverified_handle) = unverified_handle else {
+
return Err("no valid atproto handles in `also_known_as`".to_string());
+
};
+
+
// atrium seems to get service endpoint getters
+
let Some(pds) = did_doc.get_pds_endpoint() else {
+
return Err("no valid pds service found".to_string());
+
};
+
+
// TODO can't use atrium's get_signing_key() becuase it fails to check type and controller
+
// so if we check those and reject it, we might miss a later valid key in the array
+
// (todo is to fix atrium)
+
// actually: atrium might be flexible for legacy reps. for now we're rejecting legacy rep.
+
+
// must use the first valid signing key
+
let mut signing_key = None;
+
let Some(verification_methods) = did_doc.verification_method else {
+
return Err("no verification methods found".to_string());
+
};
+
for method in verification_methods {
+
if method.id != format!("{}#atproto", did_doc.id) {
+
continue;
+
}
+
if method.r#type != "Multikey" {
+
continue;
+
}
+
if method.controller != did_doc.id {
+
continue;
+
}
+
let Some(key) = method.public_key_multibase else {
+
continue;
+
};
+
signing_key = Some(key);
+
break;
+
}
+
let Some(signing_key) = signing_key else {
+
return Err("no valid atproto signing key found in verification methods".to_string());
+
};
+
+
Ok(PartialMiniDoc {
+
unverified_handle,
+
pds,
+
signing_key,
+
})
+
}
+
}
+
+
/// multi-producer *single-consumer* queue structures (wrap in arc-mutex plz)
+
///
+
/// the hashset allows testing for presense of items in the queue.
+
/// this has absolutely no support for multiple queue consumers.
+
#[derive(Debug, Default)]
+
struct RefreshQueue {
+
queue: VecDeque<IdentityKey>,
+
items: HashSet<IdentityKey>,
+
}
+
+
#[derive(Clone)]
+
pub struct Identity {
+
handle_resolver: Arc<AtprotoHandleResolver<HickoryDnsTxtResolver, DefaultHttpClient>>,
+
did_resolver: Arc<CommonDidResolver<DefaultHttpClient>>,
+
cache: HybridCache<IdentityKey, IdentityVal>,
+
/// multi-producer *single consumer* queue
+
refresh_queue: Arc<Mutex<RefreshQueue>>,
+
/// just a lock to ensure only one refresher (queue consumer) is running (to be improved with a better refresher)
+
refresher: Arc<Mutex<()>>,
+
}
+
+
impl Identity {
+
pub async fn new(cache_dir: impl AsRef<Path>) -> Result<Self, IdentityError> {
+
let http_client = Arc::new(DefaultHttpClient::default());
+
let handle_resolver = AtprotoHandleResolver::new(AtprotoHandleResolverConfig {
+
dns_txt_resolver: HickoryDnsTxtResolver::new().unwrap(),
+
http_client: http_client.clone(),
+
});
+
let did_resolver = CommonDidResolver::new(CommonDidResolverConfig {
+
plc_directory_url: DEFAULT_PLC_DIRECTORY_URL.to_string(),
+
http_client: http_client.clone(),
+
});
+
+
let cache = HybridCacheBuilder::new()
+
.with_name("identity")
+
.memory(16 * 2_usize.pow(20))
+
.with_weighter(|k, v| std::mem::size_of_val(k) + std::mem::size_of_val(v))
+
.storage(Engine::small())
+
.with_device_options(
+
DirectFsDeviceOptions::new(cache_dir)
+
.with_capacity(2_usize.pow(30)) // TODO: configurable (1GB to have something)
+
.with_file_size(2_usize.pow(20)), // note: this does limit the max cached item size, warning jumbo records
+
)
+
.build()
+
.await?;
+
+
Ok(Self {
+
handle_resolver: Arc::new(handle_resolver),
+
did_resolver: Arc::new(did_resolver),
+
cache,
+
refresh_queue: Default::default(),
+
refresher: Default::default(),
+
})
+
}
+
+
/// Resolve (and verify!) an atproto handle to a DID
+
///
+
/// The result can be stale
+
///
+
/// `None` if the handle can't be found or verification fails
+
pub async fn handle_to_did(&self, handle: Handle) -> Result<Option<Did>, IdentityError> {
+
let Some(did) = self.handle_to_unverified_did(&handle).await? else {
+
return Ok(None);
+
};
+
let Some(doc) = self.did_to_partial_mini_doc(&did).await? else {
+
return Ok(None);
+
};
+
if doc.unverified_handle != handle {
+
return Ok(None);
+
}
+
Ok(Some(did))
+
}
+
+
/// Resolve a DID to a pds url
+
///
+
/// This *also* incidentally resolves and verifies the handle, which might
+
/// make it slower than expected
+
pub async fn did_to_pds(&self, did: Did) -> Result<Option<String>, IdentityError> {
+
let Some(mini_doc) = self.did_to_partial_mini_doc(&did).await? else {
+
return Ok(None);
+
};
+
Ok(Some(mini_doc.pds))
+
}
+
+
/// Resolve (and cache but **not verify**) a handle to a DID
+
async fn handle_to_unverified_did(
+
&self,
+
handle: &Handle,
+
) -> Result<Option<Did>, IdentityError> {
+
let key = IdentityKey::Handle(handle.clone());
+
let entry = self
+
.cache
+
.fetch(key.clone(), {
+
let handle = handle.clone();
+
let resolver = self.handle_resolver.clone();
+
|| async move {
+
match resolver.resolve(&handle).await {
+
Ok(did) => Ok(IdentityVal(UtcDateTime::now(), IdentityData::Did(did))),
+
Err(atrium_identity::Error::NotFound) => {
+
Ok(IdentityVal(UtcDateTime::now(), IdentityData::NotFound))
+
}
+
Err(other) => Err(foyer::Error::Other(Box::new({
+
log::debug!("other error resolving handle: {other:?}");
+
IdentityError::ResolutionFailed(other)
+
}))),
+
}
+
}
+
})
+
.await?;
+
+
let now = UtcDateTime::now();
+
let IdentityVal(last_fetch, data) = entry.value();
+
match data {
+
IdentityData::Doc(_) => {
+
log::error!("identity value mixup: got a doc from a handle key (should be a did)");
+
Err(IdentityError::IdentityValTypeMixup(handle.to_string()))
+
}
+
IdentityData::NotFound => {
+
if (now - *last_fetch) >= MIN_NOT_FOUND_TTL {
+
self.queue_refresh(key).await;
+
}
+
Ok(None)
+
}
+
IdentityData::Did(did) => {
+
if (now - *last_fetch) >= MIN_TTL {
+
self.queue_refresh(key).await;
+
}
+
Ok(Some(did.clone()))
+
}
+
}
+
}
+
+
/// Fetch (and cache) a partial mini doc from a did
+
pub async fn did_to_partial_mini_doc(
+
&self,
+
did: &Did,
+
) -> Result<Option<PartialMiniDoc>, IdentityError> {
+
let key = IdentityKey::Did(did.clone());
+
let entry = self
+
.cache
+
.fetch(key.clone(), {
+
let did = did.clone();
+
let resolver = self.did_resolver.clone();
+
|| async move {
+
match resolver.resolve(&did).await {
+
Ok(did_doc) => {
+
// TODO: fix in atrium: should verify id is did
+
if did_doc.id != did.to_string() {
+
return Err(foyer::Error::other(Box::new(
+
IdentityError::BadDidDoc(
+
"did doc's id did not match did".to_string(),
+
),
+
)));
+
}
+
let mini_doc = did_doc.try_into().map_err(|e| {
+
foyer::Error::Other(Box::new(IdentityError::BadDidDoc(e)))
+
})?;
+
Ok(IdentityVal(UtcDateTime::now(), IdentityData::Doc(mini_doc)))
+
}
+
Err(atrium_identity::Error::NotFound) => {
+
Ok(IdentityVal(UtcDateTime::now(), IdentityData::NotFound))
+
}
+
Err(other) => Err(foyer::Error::Other(Box::new(
+
IdentityError::ResolutionFailed(other),
+
))),
+
}
+
}
+
})
+
.await?;
+
+
let now = UtcDateTime::now();
+
let IdentityVal(last_fetch, data) = entry.value();
+
match data {
+
IdentityData::Did(_) => {
+
log::error!("identity value mixup: got a did from a did key (should be a doc)");
+
Err(IdentityError::IdentityValTypeMixup(did.to_string()))
+
}
+
IdentityData::NotFound => {
+
if (now - *last_fetch) >= MIN_NOT_FOUND_TTL {
+
self.queue_refresh(key).await;
+
}
+
Ok(None)
+
}
+
IdentityData::Doc(mini_did) => {
+
if (now - *last_fetch) >= MIN_TTL {
+
self.queue_refresh(key).await;
+
}
+
Ok(Some(mini_did.clone()))
+
}
+
}
+
}
+
+
/// put a refresh task on the queue
+
///
+
/// this can be safely called from multiple concurrent tasks
+
async fn queue_refresh(&self, key: IdentityKey) {
+
// todo: max queue size
+
let mut q = self.refresh_queue.lock().await;
+
if !q.items.contains(&key) {
+
q.items.insert(key.clone());
+
q.queue.push_back(key);
+
}
+
}
+
+
/// find out what's next in the queue. concurrent consumers are not allowed.
+
///
+
/// intent is to leave the item in the queue while refreshing, so that a
+
/// producer will not re-add it if it's in progress. there's definitely
+
/// better ways to do this, but this is ~simple for as far as a single
+
/// consumer can take us.
+
///
+
/// we could take it from the queue but leave it in the set and remove from
+
/// set later, but splitting them apart feels more bug-prone.
+
async fn peek_refresh(&self) -> Option<IdentityKey> {
+
let q = self.refresh_queue.lock().await;
+
q.queue.front().cloned()
+
}
+
+
/// call to clear the latest key from the refresh queue. concurrent consumers not allowed.
+
///
+
/// must provide the last peeked refresh queue item as a small safety check
+
async fn complete_refresh(&self, key: &IdentityKey) -> Result<(), IdentityError> {
+
let mut q = self.refresh_queue.lock().await;
+
+
let Some(queue_key) = q.queue.pop_front() else {
+
// gone from queue + since we're in an error condition, make sure it's not stuck in items
+
// (not toctou because we have the lock)
+
// bolder here than below and removing from items because if the queue is *empty*, then we
+
// know it hasn't been re-added since losing sync.
+
if q.items.remove(key) {
+
log::error!("identity refresh: queue de-sync: not in ");
+
} else {
+
log::warn!(
+
"identity refresh: tried to complete with wrong key. are multiple queue consumers running?"
+
);
+
}
+
return Err(IdentityError::RefreshQueueKeyError("no key in queue"));
+
};
+
+
if queue_key != *key {
+
// extra weird case here, what's the most defensive behaviour?
+
// we have two keys: ours should have been first but isn't. this shouldn't happen, so let's
+
// just leave items alone for it. risks unbounded growth but we're in a bad place already.
+
// the other key is the one we just popped. we didn't want it, so maybe we should put it
+
// back, BUT if we somehow ended up with concurrent consumers, we have bigger problems. take
+
// responsibility for taking it instead: remove it from items as well, and just drop it.
+
//
+
// hope that whoever calls us takes this error seriously.
+
if q.items.remove(&queue_key) {
+
log::warn!(
+
"identity refresh: queue de-sync + dropping a bystander key without refreshing it!"
+
);
+
} else {
+
// you thought things couldn't get weirder? (i mean hopefully they can't)
+
log::error!("identity refresh: queue de-sync + bystander key also de-sync!?");
+
}
+
return Err(IdentityError::RefreshQueueKeyError(
+
"wrong key at front of queue",
+
));
+
}
+
+
if q.items.remove(key) {
+
Ok(())
+
} else {
+
log::error!("identity refresh: queue de-sync: key not in items");
+
Err(IdentityError::RefreshQueueKeyError("key not in items"))
+
}
+
}
+
+
/// run the refresh queue consumer
+
pub async fn run_refresher(&self, shutdown: CancellationToken) -> Result<(), IdentityError> {
+
let _guard = self
+
.refresher
+
.try_lock()
+
.expect("there to only be one refresher running");
+
loop {
+
if shutdown.is_cancelled() {
+
log::info!("identity refresher: exiting for shutdown: closing cache...");
+
if let Err(e) = self.cache.close().await {
+
log::error!("cache close errored: {e}");
+
} else {
+
log::info!("identity cache closed.")
+
}
+
return Ok(());
+
}
+
let Some(task_key) = self.peek_refresh().await else {
+
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
+
continue;
+
};
+
match task_key {
+
IdentityKey::Handle(ref handle) => {
+
log::trace!("refreshing handle {handle:?}");
+
match self.handle_resolver.resolve(handle).await {
+
Ok(did) => {
+
self.cache.insert(
+
task_key.clone(),
+
IdentityVal(UtcDateTime::now(), IdentityData::Did(did)),
+
);
+
}
+
Err(atrium_identity::Error::NotFound) => {
+
self.cache.insert(
+
task_key.clone(),
+
IdentityVal(UtcDateTime::now(), IdentityData::NotFound),
+
);
+
}
+
Err(err) => {
+
log::warn!(
+
"failed to refresh handle: {err:?}. leaving stale (should we eventually do something?)"
+
);
+
}
+
}
+
self.complete_refresh(&task_key).await?; // failures are bugs, so break loop
+
}
+
IdentityKey::Did(ref did) => {
+
log::trace!("refreshing did doc: {did:?}");
+
+
match self.did_resolver.resolve(did).await {
+
Ok(did_doc) => {
+
// TODO: fix in atrium: should verify id is did
+
if did_doc.id != did.to_string() {
+
log::warn!(
+
"refreshed did doc failed: wrong did doc id. dropping refresh."
+
);
+
continue;
+
}
+
let mini_doc = match did_doc.try_into() {
+
Ok(md) => md,
+
Err(e) => {
+
log::warn!(
+
"converting mini doc failed: {e:?}. dropping refresh."
+
);
+
continue;
+
}
+
};
+
self.cache.insert(
+
task_key.clone(),
+
IdentityVal(UtcDateTime::now(), IdentityData::Doc(mini_doc)),
+
);
+
}
+
Err(atrium_identity::Error::NotFound) => {
+
self.cache.insert(
+
task_key.clone(),
+
IdentityVal(UtcDateTime::now(), IdentityData::NotFound),
+
);
+
}
+
Err(err) => {
+
log::warn!(
+
"failed to refresh did doc: {err:?}. leaving stale (should we eventually do something?)"
+
);
+
}
+
}
+
+
self.complete_refresh(&task_key).await?; // failures are bugs, so break loop
+
}
+
}
+
}
+
}
+
}
+
+
pub struct HickoryDnsTxtResolver(TokioResolver);
+
+
impl HickoryDnsTxtResolver {
+
fn new() -> Result<Self, ResolveError> {
+
Ok(Self(TokioResolver::builder_tokio()?.build()))
+
}
+
}
+
+
impl DnsTxtResolver for HickoryDnsTxtResolver {
+
async fn resolve(
+
&self,
+
query: &str,
+
) -> core::result::Result<Vec<String>, Box<dyn std::error::Error + Send + Sync>> {
+
match self.0.txt_lookup(query).await {
+
Ok(r) => {
+
metrics::counter!("whoami_resolve_dns_txt", "success" => "true").increment(1);
+
Ok(r.iter().map(|r| r.to_string()).collect())
+
}
+
Err(e) => {
+
metrics::counter!("whoami_resolve_dns_txt", "success" => "false").increment(1);
+
Err(e.into())
+
}
+
}
+
}
+
}
+14
slingshot/src/lib.rs
···
+
mod consumer;
+
pub mod error;
+
mod firehose_cache;
+
mod healthcheck;
+
mod identity;
+
mod record;
+
mod server;
+
+
pub use consumer::consume;
+
pub use firehose_cache::firehose_cache;
+
pub use healthcheck::healthcheck;
+
pub use identity::Identity;
+
pub use record::{CachedRecord, ErrorResponseObject, Repo};
+
pub use server::serve;
+194
slingshot/src/main.rs
···
+
// use foyer::HybridCache;
+
// use foyer::{Engine, DirectFsDeviceOptions, HybridCacheBuilder};
+
use metrics_exporter_prometheus::PrometheusBuilder;
+
use slingshot::{
+
Identity, Repo, consume, error::MainTaskError, firehose_cache, healthcheck, serve,
+
};
+
use std::path::PathBuf;
+
+
use clap::Parser;
+
use tokio_util::sync::CancellationToken;
+
+
/// Slingshot record edge cache
+
#[derive(Parser, Debug, Clone)]
+
#[command(version, about, long_about = None)]
+
struct Args {
+
/// Jetstream server to connect to (exclusive with --fixture). Provide either a wss:// URL, or a shorhand value:
+
/// 'us-east-1', 'us-east-2', 'us-west-1', or 'us-west-2'
+
#[arg(long)]
+
jetstream: String,
+
/// don't request zstd-compressed jetstream events
+
///
+
/// reduces CPU at the expense of more ingress bandwidth
+
#[arg(long, action)]
+
jetstream_no_zstd: bool,
+
/// where to keep disk caches
+
#[arg(long)]
+
cache_dir: PathBuf,
+
/// the domain pointing to this server
+
///
+
/// if present:
+
/// - a did:web document will be served at /.well-known/did.json
+
/// - an HTTPS certs will be automatically configured with Acme/letsencrypt
+
/// - TODO: a rate-limiter will be installed
+
#[arg(long)]
+
domain: Option<String>,
+
/// email address for letsencrypt contact
+
///
+
/// recommended in production, i guess?
+
#[arg(long)]
+
acme_contact: Option<String>,
+
/// a location to cache acme https certs
+
///
+
/// only used if --host is specified. omitting requires re-requesting certs
+
/// on every restart, and letsencrypt has rate limits that are easy to hit.
+
///
+
/// recommended in production, but mind the file permissions.
+
#[arg(long)]
+
certs: Option<PathBuf>,
+
/// an web address to send healtcheck pings to every ~51s or so
+
#[arg(long)]
+
healthcheck: Option<String>,
+
}
+
+
#[tokio::main]
+
async fn main() -> Result<(), String> {
+
tracing_subscriber::fmt::init();
+
+
let shutdown = CancellationToken::new();
+
+
let ctrlc_shutdown = shutdown.clone();
+
ctrlc::set_handler(move || ctrlc_shutdown.cancel()).expect("failed to set ctrl-c handler");
+
+
let args = Args::parse();
+
+
if let Err(e) = install_metrics_server() {
+
log::error!("failed to install metrics server: {e:?}");
+
} else {
+
log::info!("metrics listening at http://0.0.0.0:8765");
+
}
+
+
std::fs::create_dir_all(&args.cache_dir).map_err(|e| {
+
format!(
+
"failed to ensure cache parent dir: {e:?} (dir: {:?})",
+
args.cache_dir
+
)
+
})?;
+
let cache_dir = args.cache_dir.canonicalize().map_err(|e| {
+
format!(
+
"failed to canonicalize cache_dir: {e:?} (dir: {:?})",
+
args.cache_dir
+
)
+
})?;
+
log::info!("cache dir ready at at {cache_dir:?}.");
+
+
log::info!("setting up firehose cache...");
+
let cache = firehose_cache(cache_dir.join("./firehose")).await?;
+
log::info!("firehose cache ready.");
+
+
let mut tasks: tokio::task::JoinSet<Result<(), MainTaskError>> = tokio::task::JoinSet::new();
+
+
log::info!("starting identity service...");
+
let identity = Identity::new(cache_dir.join("./identity"))
+
.await
+
.map_err(|e| format!("identity setup failed: {e:?}"))?;
+
log::info!("identity service ready.");
+
let identity_refresher = identity.clone();
+
let identity_shutdown = shutdown.clone();
+
tasks.spawn(async move {
+
identity_refresher.run_refresher(identity_shutdown).await?;
+
Ok(())
+
});
+
+
let repo = Repo::new(identity.clone());
+
+
let server_shutdown = shutdown.clone();
+
let server_cache_handle = cache.clone();
+
tasks.spawn(async move {
+
serve(
+
server_cache_handle,
+
identity,
+
repo,
+
args.domain,
+
args.acme_contact,
+
args.certs,
+
server_shutdown,
+
)
+
.await?;
+
Ok(())
+
});
+
+
let consumer_shutdown = shutdown.clone();
+
let consumer_cache = cache.clone();
+
tasks.spawn(async move {
+
consume(
+
args.jetstream,
+
None,
+
args.jetstream_no_zstd,
+
consumer_shutdown,
+
consumer_cache,
+
)
+
.await?;
+
Ok(())
+
});
+
+
if let Some(hc) = args.healthcheck {
+
let healthcheck_shutdown = shutdown.clone();
+
tasks.spawn(async move {
+
healthcheck(hc, healthcheck_shutdown).await?;
+
Ok(())
+
});
+
}
+
+
tokio::select! {
+
_ = shutdown.cancelled() => log::warn!("shutdown requested"),
+
Some(r) = tasks.join_next() => {
+
log::warn!("a task exited, shutting down: {r:?}");
+
shutdown.cancel();
+
}
+
}
+
+
tasks.spawn(async move {
+
cache
+
.close()
+
.await
+
.map_err(MainTaskError::FirehoseCacheCloseError)
+
});
+
+
tokio::select! {
+
_ = async {
+
while let Some(completed) = tasks.join_next().await {
+
log::info!("shutdown: task completed: {completed:?}");
+
}
+
} => {},
+
_ = tokio::time::sleep(std::time::Duration::from_secs(30)) => {
+
log::info!("shutdown: not all tasks completed on time. aborting...");
+
tasks.shutdown().await;
+
},
+
}
+
+
log::info!("bye!");
+
+
Ok(())
+
}
+
+
fn install_metrics_server() -> Result<(), metrics_exporter_prometheus::BuildError> {
+
log::info!("installing metrics server...");
+
let host = [0, 0, 0, 0];
+
let port = 8765;
+
PrometheusBuilder::new()
+
.set_quantiles(&[0.5, 0.9, 0.99, 1.0])?
+
.set_bucket_duration(std::time::Duration::from_secs(300))?
+
.set_bucket_count(std::num::NonZero::new(12).unwrap()) // count * duration = 60 mins. stuff doesn't happen that fast here.
+
.set_enable_unit_suffix(false) // this seemed buggy for constellation (sometimes wouldn't engage)
+
.with_http_listener((host, port))
+
.install()?;
+
log::info!(
+
"metrics server installed! listening on http://{}.{}.{}.{}:{port}",
+
host[0],
+
host[1],
+
host[2],
+
host[3]
+
);
+
Ok(())
+
}
+155
slingshot/src/record.rs
···
+
//! cached record storage
+
+
use crate::{Identity, error::RecordError};
+
use atrium_api::types::string::{Cid, Did, Nsid, RecordKey};
+
use reqwest::{Client, StatusCode};
+
use serde::{Deserialize, Serialize};
+
use serde_json::value::RawValue;
+
use std::str::FromStr;
+
use std::time::Duration;
+
use url::Url;
+
+
#[derive(Debug, Serialize, Deserialize)]
+
pub struct RawRecord {
+
cid: Cid,
+
record: String,
+
}
+
+
// TODO: should be able to do typed CID
+
impl From<(Cid, Box<RawValue>)> for RawRecord {
+
fn from((cid, rv): (Cid, Box<RawValue>)) -> Self {
+
Self {
+
cid,
+
record: rv.get().to_string(),
+
}
+
}
+
}
+
+
/// only for use with stored (validated) values, not general strings
+
impl From<&RawRecord> for (Cid, Box<RawValue>) {
+
fn from(RawRecord { cid, record }: &RawRecord) -> Self {
+
(
+
cid.clone(),
+
RawValue::from_string(record.to_string())
+
.expect("stored string from RawValue to be valid"),
+
)
+
}
+
}
+
+
#[derive(Debug, Serialize, Deserialize)]
+
pub enum CachedRecord {
+
Found(RawRecord),
+
Deleted,
+
}
+
+
//////// upstream record fetching
+
+
#[derive(Deserialize)]
+
struct RecordResponseObject {
+
#[allow(dead_code)] // expect it to be there but we ignore it
+
uri: String,
+
/// CID for this exact version of the record
+
///
+
/// this is optional in the spec and that's potentially TODO for slingshot
+
cid: Option<String>,
+
/// the record itself as JSON
+
value: Box<RawValue>,
+
}
+
+
#[derive(Debug, Deserialize)]
+
pub struct ErrorResponseObject {
+
pub error: String,
+
pub message: String,
+
}
+
+
#[derive(Clone)]
+
pub struct Repo {
+
identity: Identity,
+
client: Client,
+
}
+
+
impl Repo {
+
pub fn new(identity: Identity) -> Self {
+
let client = Client::builder()
+
.user_agent(format!(
+
"microcosm slingshot v{} (dev: @bad-example.com)",
+
env!("CARGO_PKG_VERSION")
+
))
+
.no_proxy()
+
.timeout(Duration::from_secs(10))
+
.build()
+
.unwrap();
+
Repo { identity, client }
+
}
+
+
pub async fn get_record(
+
&self,
+
did: &Did,
+
collection: &Nsid,
+
rkey: &RecordKey,
+
cid: &Option<Cid>,
+
) -> Result<CachedRecord, RecordError> {
+
let Some(pds) = self.identity.did_to_pds(did.clone()).await? else {
+
return Err(RecordError::NotFound("could not get pds for DID"));
+
};
+
+
// cid gets set to None for a retry, if it's Some and we got NotFound
+
let mut cid = cid;
+
+
let res = loop {
+
// TODO: throttle outgoing requests by host probably, generally guard against outgoing requests
+
let mut params = vec![
+
("repo", did.to_string()),
+
("collection", collection.to_string()),
+
("rkey", rkey.to_string()),
+
];
+
if let Some(cid) = cid {
+
params.push(("cid", cid.as_ref().to_string()));
+
}
+
let mut url = Url::parse_with_params(&pds, &params)?;
+
url.set_path("/xrpc/com.atproto.repo.getRecord");
+
+
let res = self
+
.client
+
.get(url.clone())
+
.send()
+
.await
+
.map_err(RecordError::SendError)?;
+
+
if res.status() == StatusCode::BAD_REQUEST {
+
// 1. if we're not able to parse json, it's not something we can handle
+
let err = res
+
.json::<ErrorResponseObject>()
+
.await
+
.map_err(RecordError::UpstreamBadBadNotGoodRequest)?;
+
// 2. if we are, is it a NotFound? and if so, did we try with a CID?
+
// if so, retry with no CID (api handler will reject for mismatch but
+
// with a nice error + warm cache)
+
if err.error == "NotFound" && cid.is_some() {
+
cid = &None;
+
continue;
+
} else {
+
return Err(RecordError::UpstreamBadRequest(err));
+
}
+
}
+
break res;
+
};
+
+
let data = res
+
.error_for_status()
+
.map_err(RecordError::StatusError)? // TODO atproto error handling (think about handling not found)
+
.json::<RecordResponseObject>()
+
.await
+
.map_err(RecordError::ParseJsonError)?; // todo...
+
+
let Some(cid) = data.cid else {
+
return Err(RecordError::MissingUpstreamCid);
+
};
+
let cid = Cid::from_str(&cid).map_err(|e| RecordError::BadUpstreamCid(e.to_string()))?;
+
+
Ok(CachedRecord::Found(RawRecord {
+
cid,
+
record: data.value.to_string(),
+
}))
+
}
+
}
+778
slingshot/src/server.rs
···
+
use crate::{
+
CachedRecord, ErrorResponseObject, Identity, Repo,
+
error::{RecordError, ServerError},
+
};
+
use atrium_api::types::string::{Cid, Did, Handle, Nsid, RecordKey};
+
use foyer::HybridCache;
+
use links::at_uri::parse_at_uri as normalize_at_uri;
+
use serde::Serialize;
+
use std::path::PathBuf;
+
use std::str::FromStr;
+
use std::sync::Arc;
+
use tokio_util::sync::CancellationToken;
+
+
use poem::{
+
Endpoint, EndpointExt, Route, Server,
+
endpoint::{StaticFileEndpoint, make_sync},
+
http::Method,
+
listener::{
+
Listener, TcpListener,
+
acme::{AutoCert, LETS_ENCRYPT_PRODUCTION},
+
},
+
middleware::{CatchPanic, Cors, Tracing},
+
};
+
use poem_openapi::{
+
ApiResponse, ContactObject, ExternalDocumentObject, Object, OpenApi, OpenApiService, Tags,
+
param::Query, payload::Json, types::Example,
+
};
+
+
fn example_handle() -> String {
+
"bad-example.com".to_string()
+
}
+
fn example_did() -> String {
+
"did:plc:hdhoaan3xa3jiuq4fg4mefid".to_string()
+
}
+
fn example_collection() -> String {
+
"app.bsky.feed.like".to_string()
+
}
+
fn example_rkey() -> String {
+
"3lv4ouczo2b2a".to_string()
+
}
+
fn example_uri() -> String {
+
format!(
+
"at://{}/{}/{}",
+
example_did(),
+
example_collection(),
+
example_rkey()
+
)
+
}
+
fn example_pds() -> String {
+
"https://porcini.us-east.host.bsky.network".to_string()
+
}
+
fn example_signing_key() -> String {
+
"zQ3shpq1g134o7HGDb86CtQFxnHqzx5pZWknrVX2Waum3fF6j".to_string()
+
}
+
+
#[derive(Object)]
+
#[oai(example = true)]
+
struct XrpcErrorResponseObject {
+
/// Should correspond an error `name` in the lexicon errors array
+
error: String,
+
/// Human-readable description and possibly additonal context
+
message: String,
+
}
+
impl Example for XrpcErrorResponseObject {
+
fn example() -> Self {
+
Self {
+
error: "RecordNotFound".to_string(),
+
message: "This record was deleted".to_string(),
+
}
+
}
+
}
+
type XrpcError = Json<XrpcErrorResponseObject>;
+
fn xrpc_error(error: impl AsRef<str>, message: impl AsRef<str>) -> XrpcError {
+
Json(XrpcErrorResponseObject {
+
error: error.as_ref().to_string(),
+
message: message.as_ref().to_string(),
+
})
+
}
+
+
fn bad_request_handler_get_record(err: poem::Error) -> GetRecordResponse {
+
GetRecordResponse::BadRequest(Json(XrpcErrorResponseObject {
+
error: "InvalidRequest".to_string(),
+
message: format!("Bad request, here's some info that maybe should not be exposed: {err}"),
+
}))
+
}
+
+
fn bad_request_handler_resolve_mini(err: poem::Error) -> ResolveMiniIDResponse {
+
ResolveMiniIDResponse::BadRequest(Json(XrpcErrorResponseObject {
+
error: "InvalidRequest".to_string(),
+
message: format!("Bad request, here's some info that maybe should not be exposed: {err}"),
+
}))
+
}
+
+
fn bad_request_handler_resolve_handle(err: poem::Error) -> JustDidResponse {
+
JustDidResponse::BadRequest(Json(XrpcErrorResponseObject {
+
error: "InvalidRequest".to_string(),
+
message: format!("Bad request, here's some info that maybe should not be exposed: {err}"),
+
}))
+
}
+
+
#[derive(Object)]
+
#[oai(example = true)]
+
struct FoundRecordResponseObject {
+
/// at-uri for this record
+
uri: String,
+
/// CID for this exact version of the record
+
///
+
/// Slingshot will always return the CID, despite it not being a required
+
/// response property in the official lexicon.
+
///
+
/// TODO: probably actually let it be optional, idk are some pds's weirdly
+
/// not returning it?
+
cid: Option<String>,
+
/// the record itself as JSON
+
value: serde_json::Value,
+
}
+
impl Example for FoundRecordResponseObject {
+
fn example() -> Self {
+
Self {
+
uri: example_uri(),
+
cid: Some("bafyreialv3mzvvxaoyrfrwoer3xmabbmdchvrbyhayd7bga47qjbycy74e".to_string()),
+
value: serde_json::json!({
+
"$type": "app.bsky.feed.like",
+
"createdAt": "2025-07-29T18:02:02.327Z",
+
"subject": {
+
"cid": "bafyreia2gy6eyk5qfetgahvshpq35vtbwy6negpy3gnuulcdi723mi7vxy",
+
"uri": "at://did:plc:vwzwgnygau7ed7b7wt5ux7y2/app.bsky.feed.post/3lv4lkb4vgs2k"
+
}
+
}),
+
}
+
}
+
}
+
+
#[derive(ApiResponse)]
+
#[oai(bad_request_handler = "bad_request_handler_get_record")]
+
enum GetRecordResponse {
+
/// Record found
+
#[oai(status = 200)]
+
Ok(Json<FoundRecordResponseObject>),
+
/// Bad request or no record to return
+
///
+
/// The only error name in the repo.getRecord lexicon is `RecordNotFound`,
+
/// but the [canonical api docs](https://docs.bsky.app/docs/api/com-atproto-repo-get-record)
+
/// also list `InvalidRequest`, `ExpiredToken`, and `InvalidToken`. Of
+
/// these, slingshot will only generate `RecordNotFound` or `InvalidRequest`,
+
/// but may return any proxied error code from the upstream repo.
+
#[oai(status = 400)]
+
BadRequest(XrpcError),
+
/// Server errors
+
#[oai(status = 500)]
+
ServerError(XrpcError),
+
}
+
+
#[derive(Object)]
+
#[oai(example = true)]
+
struct MiniDocResponseObject {
+
/// DID, bi-directionally verified if a handle was provided in the query.
+
did: String,
+
/// The validated handle of the account or `handle.invalid` if the handle
+
/// did not bi-directionally match the DID document.
+
handle: String,
+
/// The identity's PDS URL
+
pds: String,
+
/// The atproto signing key publicKeyMultibase
+
///
+
/// Legacy key encoding not supported. the key is returned directly; `id`,
+
/// `type`, and `controller` are omitted.
+
signing_key: String,
+
}
+
impl Example for MiniDocResponseObject {
+
fn example() -> Self {
+
Self {
+
did: example_did(),
+
handle: example_handle(),
+
pds: example_pds(),
+
signing_key: example_signing_key(),
+
}
+
}
+
}
+
+
#[derive(ApiResponse)]
+
#[oai(bad_request_handler = "bad_request_handler_resolve_mini")]
+
enum ResolveMiniIDResponse {
+
/// Identity resolved
+
#[oai(status = 200)]
+
Ok(Json<MiniDocResponseObject>),
+
/// Bad request or identity not resolved
+
#[oai(status = 400)]
+
BadRequest(XrpcError),
+
}
+
+
#[derive(Object)]
+
#[oai(example = true)]
+
struct FoundDidResponseObject {
+
/// the DID, bi-directionally verified if using Slingshot
+
did: String,
+
}
+
impl Example for FoundDidResponseObject {
+
fn example() -> Self {
+
Self { did: example_did() }
+
}
+
}
+
+
#[derive(ApiResponse)]
+
#[oai(bad_request_handler = "bad_request_handler_resolve_handle")]
+
enum JustDidResponse {
+
/// Resolution succeeded
+
#[oai(status = 200)]
+
Ok(Json<FoundDidResponseObject>),
+
/// Bad request, failed to resolve, or failed to verify
+
///
+
/// `error` will be one of `InvalidRequest`, `HandleNotFound`.
+
#[oai(status = 400)]
+
BadRequest(XrpcError),
+
/// Something went wrong trying to complete the request
+
#[oai(status = 500)]
+
ServerError(XrpcError),
+
}
+
+
struct Xrpc {
+
cache: HybridCache<String, CachedRecord>,
+
identity: Identity,
+
repo: Arc<Repo>,
+
}
+
+
#[derive(Tags)]
+
enum ApiTags {
+
/// Core ATProtocol-compatible APIs.
+
///
+
/// > [!tip]
+
/// > Upstream documentation is available at
+
/// > https://docs.bsky.app/docs/category/http-reference
+
///
+
/// These queries are usually executed directly against the PDS containing
+
/// the data being requested. Slingshot offers a caching view of the same
+
/// contents with better expected performance and reliability.
+
#[oai(rename = "com.atproto.* queries")]
+
ComAtproto,
+
/// Additional and improved APIs.
+
///
+
/// These APIs offer small tweaks to the core ATProtocol APIs, with more
+
/// more convenient [request parameters](#tag/slingshot-specific-queries/GET/xrpc/com.bad-example.repo.getUriRecord)
+
/// or [response formats](#tag/slingshot-specific-queries/GET/xrpc/com.bad-example.identity.resolveMiniDoc).
+
///
+
/// > [!important]
+
/// > At the moment, these are namespaced under the `com.bad-example.*` NSID
+
/// > prefix, but as they stabilize they may be migrated to an org namespace
+
/// > like `blue.microcosm.*`. Support for asliasing to `com.bad-example.*`
+
/// > will be maintained as long as it's in use.
+
#[oai(rename = "slingshot-specific queries")]
+
Custom,
+
}
+
+
#[OpenApi]
+
impl Xrpc {
+
/// com.atproto.repo.getRecord
+
///
+
/// Get a single record from a repository. Does not require auth.
+
///
+
/// > [!tip]
+
/// > See also the [canonical `com.atproto` XRPC documentation](https://docs.bsky.app/docs/api/com-atproto-repo-get-record)
+
/// > that this endpoint aims to be compatible with.
+
#[oai(
+
path = "/com.atproto.repo.getRecord",
+
method = "get",
+
tag = "ApiTags::ComAtproto"
+
)]
+
async fn get_record(
+
&self,
+
/// The DID or handle of the repo
+
#[oai(example = "example_did")]
+
Query(repo): Query<String>,
+
/// The NSID of the record collection
+
#[oai(example = "example_collection")]
+
Query(collection): Query<String>,
+
/// The Record key
+
#[oai(example = "example_rkey")]
+
Query(rkey): Query<String>,
+
/// Optional: the CID of the version of the record.
+
///
+
/// If not specified, then return the most recent version.
+
///
+
/// If a stale `CID` is specified and a newer version of the record
+
/// exists, Slingshot returns a `NotFound` error. That is: Slingshot
+
/// only retains the most recent version of a record.
+
Query(cid): Query<Option<String>>,
+
) -> GetRecordResponse {
+
self.get_record_impl(repo, collection, rkey, cid).await
+
}
+
+
/// com.bad-example.repo.getUriRecord
+
///
+
/// Ergonomic complement to [`com.atproto.repo.getRecord`](https://docs.bsky.app/docs/api/com-atproto-repo-get-record)
+
/// which accepts an `at-uri` instead of individual repo/collection/rkey params
+
#[oai(
+
path = "/com.bad-example.repo.getUriRecord",
+
method = "get",
+
tag = "ApiTags::Custom"
+
)]
+
async fn get_uri_record(
+
&self,
+
/// The at-uri of the record
+
///
+
/// The identifier can be a DID or an atproto handle, and the collection
+
/// and rkey segments must be present.
+
#[oai(example = "example_uri")]
+
Query(at_uri): Query<String>,
+
/// Optional: the CID of the version of the record.
+
///
+
/// If not specified, then return the most recent version.
+
///
+
/// > [!tip]
+
/// > If specified and a newer version of the record exists, returns 404 not
+
/// > found. That is: slingshot only retains the most recent version of a
+
/// > record.
+
Query(cid): Query<Option<String>>,
+
) -> GetRecordResponse {
+
let bad_at_uri = || {
+
GetRecordResponse::BadRequest(xrpc_error(
+
"InvalidRequest",
+
"at-uri does not appear to be valid",
+
))
+
};
+
+
let Some(normalized) = normalize_at_uri(&at_uri) else {
+
return bad_at_uri();
+
};
+
+
// TODO: move this to links
+
let Some(rest) = normalized.strip_prefix("at://") else {
+
return bad_at_uri();
+
};
+
let Some((repo, rest)) = rest.split_once('/') else {
+
return bad_at_uri();
+
};
+
let Some((collection, rest)) = rest.split_once('/') else {
+
return bad_at_uri();
+
};
+
let rkey = if let Some((rkey, _rest)) = rest.split_once('?') {
+
rkey
+
} else {
+
rest
+
};
+
+
self.get_record_impl(
+
repo.to_string(),
+
collection.to_string(),
+
rkey.to_string(),
+
cid,
+
)
+
.await
+
}
+
+
/// com.atproto.identity.resolveHandle
+
///
+
/// Resolves an atproto [`handle`](https://atproto.com/guides/glossary#handle)
+
/// (hostname) to a [`DID`](https://atproto.com/guides/glossary#did-decentralized-id).
+
///
+
/// > [!tip]
+
/// > Compatibility note: Slingshot will **always bi-directionally verify
+
/// > against the DID document**, which is optional according to the
+
/// > authoritative lexicon.
+
///
+
/// > [!tip]
+
/// > See the [canonical `com.atproto` XRPC documentation](https://docs.bsky.app/docs/api/com-atproto-identity-resolve-handle)
+
/// > that this endpoint aims to be compatible with.
+
#[oai(
+
path = "/com.atproto.identity.resolveHandle",
+
method = "get",
+
tag = "ApiTags::ComAtproto"
+
)]
+
async fn resolve_handle(
+
&self,
+
/// The handle to resolve.
+
#[oai(example = "example_handle")]
+
Query(handle): Query<String>,
+
) -> JustDidResponse {
+
let Ok(handle) = Handle::new(handle) else {
+
return JustDidResponse::BadRequest(xrpc_error("InvalidRequest", "not a valid handle"));
+
};
+
+
let Ok(alleged_did) = self.identity.handle_to_did(handle.clone()).await else {
+
return JustDidResponse::ServerError(xrpc_error("Failed", "Could not resolve handle"));
+
};
+
+
let Some(alleged_did) = alleged_did else {
+
return JustDidResponse::BadRequest(xrpc_error(
+
"HandleNotFound",
+
"Could not resolve handle to a DID",
+
));
+
};
+
+
let Ok(partial_doc) = self.identity.did_to_partial_mini_doc(&alleged_did).await else {
+
return JustDidResponse::ServerError(xrpc_error("Failed", "Could not fetch DID doc"));
+
};
+
+
let Some(partial_doc) = partial_doc else {
+
return JustDidResponse::BadRequest(xrpc_error(
+
"HandleNotFound",
+
"Resolved handle but could not find DID doc for the DID",
+
));
+
};
+
+
if partial_doc.unverified_handle != handle {
+
return JustDidResponse::BadRequest(xrpc_error(
+
"HandleNotFound",
+
"Resolved handle failed bi-directional validation",
+
));
+
}
+
+
JustDidResponse::Ok(Json(FoundDidResponseObject {
+
did: alleged_did.to_string(),
+
}))
+
}
+
+
/// com.bad-example.identity.resolveMiniDoc
+
///
+
/// Like [com.atproto.identity.resolveIdentity](https://docs.bsky.app/docs/api/com-atproto-identity-resolve-identity)
+
/// but instead of the full `didDoc` it returns an atproto-relevant subset.
+
#[oai(
+
path = "/com.bad-example.identity.resolveMiniDoc",
+
method = "get",
+
tag = "ApiTags::Custom"
+
)]
+
async fn resolve_mini_id(
+
&self,
+
/// Handle or DID to resolve
+
#[oai(example = "example_handle")]
+
Query(identifier): Query<String>,
+
) -> ResolveMiniIDResponse {
+
let invalid = |reason: &'static str| {
+
ResolveMiniIDResponse::BadRequest(xrpc_error("InvalidRequest", reason))
+
};
+
+
let mut unverified_handle = None;
+
let did = match Did::new(identifier.clone()) {
+
Ok(did) => did,
+
Err(_) => {
+
let Ok(alleged_handle) = Handle::new(identifier) else {
+
return invalid("identifier was not a valid DID or handle");
+
};
+
+
match self.identity.handle_to_did(alleged_handle.clone()).await {
+
Ok(res) => {
+
if let Some(did) = res {
+
// we did it joe
+
unverified_handle = Some(alleged_handle);
+
did
+
} else {
+
return invalid("Could not resolve handle identifier to a DID");
+
}
+
}
+
Err(e) => {
+
log::debug!("failed to resolve handle: {e}");
+
// TODO: ServerError not BadRequest
+
return invalid("errored while trying to resolve handle to DID");
+
}
+
}
+
}
+
};
+
let Ok(partial_doc) = self.identity.did_to_partial_mini_doc(&did).await else {
+
return invalid("failed to get DID doc");
+
};
+
let Some(partial_doc) = partial_doc else {
+
return invalid("failed to find DID doc");
+
};
+
+
// ok so here's where we're at:
+
// ✅ we have a DID
+
// ✅ we have a partial doc
+
// 🔶 if we have a handle, it's from the `identifier` (user-input)
+
// -> then we just need to compare to the partial doc to confirm
+
// -> else we need to resolve the DID doc's to a handle and check
+
let handle = if let Some(h) = unverified_handle {
+
if h == partial_doc.unverified_handle {
+
h.to_string()
+
} else {
+
"handle.invalid".to_string()
+
}
+
} else {
+
let Ok(handle_did) = self
+
.identity
+
.handle_to_did(partial_doc.unverified_handle.clone())
+
.await
+
else {
+
return invalid("failed to get did doc's handle");
+
};
+
let Some(handle_did) = handle_did else {
+
return invalid("failed to resolve did doc's handle");
+
};
+
if handle_did == did {
+
partial_doc.unverified_handle.to_string()
+
} else {
+
"handle.invalid".to_string()
+
}
+
};
+
+
ResolveMiniIDResponse::Ok(Json(MiniDocResponseObject {
+
did: did.to_string(),
+
handle,
+
pds: partial_doc.pds,
+
signing_key: partial_doc.signing_key,
+
}))
+
}
+
+
async fn get_record_impl(
+
&self,
+
repo: String,
+
collection: String,
+
rkey: String,
+
cid: Option<String>,
+
) -> GetRecordResponse {
+
let did = match Did::new(repo.clone()) {
+
Ok(did) => did,
+
Err(_) => {
+
let Ok(handle) = Handle::new(repo) else {
+
return GetRecordResponse::BadRequest(xrpc_error(
+
"InvalidRequest",
+
"repo was not a valid DID or handle",
+
));
+
};
+
match self.identity.handle_to_did(handle).await {
+
Ok(res) => {
+
if let Some(did) = res {
+
did
+
} else {
+
return GetRecordResponse::BadRequest(xrpc_error(
+
"InvalidRequest",
+
"Could not resolve handle repo to a DID",
+
));
+
}
+
}
+
Err(e) => {
+
log::debug!("handle resolution failed: {e}");
+
return GetRecordResponse::ServerError(xrpc_error(
+
"ResolutionFailed",
+
"errored while trying to resolve handle to DID",
+
));
+
}
+
}
+
}
+
};
+
+
let Ok(collection) = Nsid::new(collection) else {
+
return GetRecordResponse::BadRequest(xrpc_error(
+
"InvalidRequest",
+
"invalid NSID for collection",
+
));
+
};
+
+
let Ok(rkey) = RecordKey::new(rkey) else {
+
return GetRecordResponse::BadRequest(xrpc_error("InvalidRequest", "invalid rkey"));
+
};
+
+
let cid: Option<Cid> = if let Some(cid) = cid {
+
let Ok(cid) = Cid::from_str(&cid) else {
+
return GetRecordResponse::BadRequest(xrpc_error("InvalidRequest", "invalid CID"));
+
};
+
Some(cid)
+
} else {
+
None
+
};
+
+
let at_uri = format!("at://{}/{}/{}", &*did, &*collection, &*rkey);
+
+
let fr = self
+
.cache
+
.fetch(at_uri.clone(), {
+
let cid = cid.clone();
+
let repo_api = self.repo.clone();
+
|| async move {
+
repo_api
+
.get_record(&did, &collection, &rkey, &cid)
+
.await
+
.map_err(|e| foyer::Error::Other(Box::new(e)))
+
}
+
})
+
.await;
+
+
let entry = match fr {
+
Ok(e) => e,
+
Err(foyer::Error::Other(e)) => {
+
let record_error = match e.downcast::<RecordError>() {
+
Ok(e) => e,
+
Err(e) => {
+
log::error!("error (foyer other) getting cache entry, {e:?}");
+
return GetRecordResponse::ServerError(xrpc_error(
+
"ServerError",
+
"sorry, something went wrong",
+
));
+
}
+
};
+
let RecordError::UpstreamBadRequest(ErrorResponseObject { error, message }) =
+
*record_error
+
else {
+
log::error!("RecordError getting cache entry, {record_error:?}");
+
return GetRecordResponse::ServerError(xrpc_error(
+
"ServerError",
+
"sorry, something went wrong",
+
));
+
};
+
+
// all of the noise around here is so that we can ultimately reach this:
+
// upstream BadRequest extracted from the foyer result which we can proxy back
+
return GetRecordResponse::BadRequest(xrpc_error(
+
error,
+
format!("Upstream bad request: {message}"),
+
));
+
}
+
Err(e) => {
+
log::error!("error (foyer) getting cache entry, {e:?}");
+
return GetRecordResponse::ServerError(xrpc_error(
+
"ServerError",
+
"sorry, something went wrong",
+
));
+
}
+
};
+
+
match *entry {
+
CachedRecord::Found(ref raw) => {
+
let (found_cid, raw_value) = raw.into();
+
if cid.clone().map(|c| c != found_cid).unwrap_or(false) {
+
return GetRecordResponse::BadRequest(Json(XrpcErrorResponseObject {
+
error: "RecordNotFound".to_string(),
+
message: "A record was found but its CID did not match that requested"
+
.to_string(),
+
}));
+
}
+
// TODO: thank u stellz: https://gist.github.com/stella3d/51e679e55b264adff89d00a1e58d0272
+
let value =
+
serde_json::from_str(raw_value.get()).expect("RawValue to be valid json");
+
GetRecordResponse::Ok(Json(FoundRecordResponseObject {
+
uri: at_uri,
+
cid: Some(found_cid.as_ref().to_string()),
+
value,
+
}))
+
}
+
CachedRecord::Deleted => GetRecordResponse::BadRequest(Json(XrpcErrorResponseObject {
+
error: "RecordNotFound".to_string(),
+
message: "This record was deleted".to_string(),
+
})),
+
}
+
}
+
+
// TODO
+
// #[oai(path = "/com.atproto.identity.resolveHandle", method = "get")]
+
// #[oai(path = "/com.atproto.identity.resolveDid", method = "get")]
+
// but these are both not specified to do bidirectional validation, which is what we want to offer
+
// com.atproto.identity.resolveIdentity seems right, but requires returning the full did-doc
+
// would be nice if there were two queries:
+
// did -> verified handle + pds url
+
// handle -> verified did + pds url
+
//
+
// we could do horrible things and implement resolveIdentity with only a stripped-down fake did doc
+
// but this will *definitely* cause problems because eg. we're not currently storing pubkeys and
+
// those are a little bit important
+
}
+
+
#[derive(Debug, Clone, Serialize)]
+
#[serde(rename_all = "camelCase")]
+
struct AppViewService {
+
id: String,
+
r#type: String,
+
service_endpoint: String,
+
}
+
#[derive(Debug, Clone, Serialize)]
+
struct AppViewDoc {
+
id: String,
+
service: [AppViewService; 1],
+
}
+
/// Serve a did document for did:web for this to be an xrpc appview
+
///
+
/// No slingshot endpoints currently require auth, so it's not necessary to do
+
/// service proxying, however clients may wish to:
+
///
+
/// - PDS proxying offers a level of client IP anonymity from slingshot
+
/// - slingshot *may* implement more generous per-user rate-limits for proxied requests in the future
+
fn get_did_doc(domain: &str) -> impl Endpoint + use<> {
+
let doc = poem::web::Json(AppViewDoc {
+
id: format!("did:web:{domain}"),
+
service: [AppViewService {
+
id: "#slingshot".to_string(),
+
r#type: "SlingshotRecordProxy".to_string(),
+
service_endpoint: format!("https://{domain}"),
+
}],
+
});
+
make_sync(move |_| doc.clone())
+
}
+
+
pub async fn serve(
+
cache: HybridCache<String, CachedRecord>,
+
identity: Identity,
+
repo: Repo,
+
domain: Option<String>,
+
acme_contact: Option<String>,
+
certs: Option<PathBuf>,
+
shutdown: CancellationToken,
+
) -> Result<(), ServerError> {
+
let repo = Arc::new(repo);
+
let api_service = OpenApiService::new(
+
Xrpc {
+
cache,
+
identity,
+
repo,
+
},
+
"Slingshot",
+
env!("CARGO_PKG_VERSION"),
+
)
+
.server(if let Some(ref h) = domain {
+
format!("https://{h}")
+
} else {
+
"http://localhost:3000".to_string()
+
})
+
.url_prefix("/xrpc")
+
.contact(
+
ContactObject::new()
+
.name("@microcosm.blue")
+
.url("https://bsky.app/profile/microcosm.blue"),
+
)
+
.description(include_str!("../api-description.md"))
+
.external_document(ExternalDocumentObject::new(
+
"https://microcosm.blue/slingshot",
+
));
+
+
let mut app = Route::new()
+
.at("/", StaticFileEndpoint::new("./static/index.html"))
+
.nest("/openapi", api_service.spec_endpoint())
+
.nest("/xrpc/", api_service);
+
+
if let Some(domain) = domain {
+
rustls::crypto::aws_lc_rs::default_provider()
+
.install_default()
+
.expect("alskfjalksdjf");
+
+
app = app.at("/.well-known/did.json", get_did_doc(&domain));
+
+
let mut auto_cert = AutoCert::builder()
+
.directory_url(LETS_ENCRYPT_PRODUCTION)
+
.domain(&domain);
+
if let Some(contact) = acme_contact {
+
auto_cert = auto_cert.contact(contact);
+
}
+
if let Some(certs) = certs {
+
auto_cert = auto_cert.cache_path(certs);
+
}
+
let auto_cert = auto_cert.build().map_err(ServerError::AcmeBuildError)?;
+
+
run(
+
TcpListener::bind("0.0.0.0:443").acme(auto_cert),
+
app,
+
shutdown,
+
)
+
.await
+
} else {
+
run(TcpListener::bind("127.0.0.1:3000"), app, shutdown).await
+
}
+
}
+
+
async fn run<L>(listener: L, app: Route, shutdown: CancellationToken) -> Result<(), ServerError>
+
where
+
L: Listener + 'static,
+
{
+
let app = app
+
.with(
+
Cors::new()
+
.allow_origin_regex("*")
+
.allow_methods([Method::GET])
+
.allow_credentials(false),
+
)
+
.with(CatchPanic::new())
+
.with(Tracing);
+
Server::new(listener)
+
.name("slingshot")
+
.run_with_graceful_shutdown(app, shutdown.cancelled(), None)
+
.await
+
.map_err(ServerError::ServerExited)
+
.inspect(|()| log::info!("server ended. goodbye."))
+
}
slingshot/static/favicon.ico

This is a binary file and will not be displayed.

+67
slingshot/static/index.html
···
+
<!doctype html>
+
<html lang="en">
+
<head>
+
<meta charset="utf-8" />
+
<title>Slingshot: atproto edge record cache</title>
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
+
<meta name="description" content="API Documentation for Slingshot, a firehose-listening atproto edge record and identity cache." />
+
<style>
+
:root {
+
--scalar-small: 13px;
+
}
+
.scalar-app .markdown .markdown-alert {
+
font-size: var(--scalar-small);
+
}
+
.sidebar-heading-link-title {
+
line-height: 1.2;
+
}
+
.custom-header {
+
height: 42px;
+
background-color: #221828;
+
box-shadow: inset 0 -1px 0 var(--scalar-border-color);
+
color: var(--scalar-color-1);
+
font-size: var(--scalar-font-size-3);
+
font-family: 'Iowan Old Style', 'Palatino Linotype', 'URW Palladio L', P052, serif;
+
padding: 0 18px;
+
justify-content: space-between;
+
}
+
.custom-header,
+
.custom-header nav {
+
display: flex;
+
align-items: center;
+
gap: 18px;
+
}
+
.custom-header a:hover {
+
color: var(--scalar-color-2);
+
}
+
+
.light-mode .custom-header {
+
background-color: thistle;
+
}
+
</style>
+
</head>
+
<body>
+
<header class="custom-header scalar-app">
+
<p>
+
TODO: thing
+
</p>
+
<nav>
+
<b>a <a href="https://microcosm.blue">microcosm</a> project</b>
+
<a href="https://bsky.app/profile/microcosm.blue">@microcosm.blue</a>
+
<a href="https://github.com/at-microcosm">github</a>
+
</nav>
+
</header>
+
+
<script id="api-reference" type="application/json" data-url="/openapi"></script>
+
+
<script>
+
var configuration = {
+
theme: 'purple',
+
hideModels: true,
+
}
+
document.getElementById('api-reference').dataset.configuration = JSON.stringify(configuration)
+
</script>
+
+
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
+
</body>
+
</html>
+29
spacedust/Cargo.toml
···
+
[package]
+
name = "spacedust"
+
version = "0.1.0"
+
edition = "2024"
+
+
[dependencies]
+
async-trait = "0.1.88"
+
clap = { version = "4.5.40", features = ["derive"] }
+
ctrlc = "3.4.7"
+
dropshot = "0.16.2"
+
env_logger = "0.11.8"
+
futures = "0.3.31"
+
http = "1.3.1"
+
jetstream = { path = "../jetstream", features = ["metrics"] }
+
links = { path = "../links" }
+
log = "0.4.27"
+
metrics = "0.24.2"
+
metrics-exporter-prometheus = { version = "0.17.1", features = ["http-listener"] }
+
rand = "0.9.1"
+
schemars = "0.8.22"
+
semver = "1.0.26"
+
serde = { version = "1.0.219", features = ["derive"] }
+
serde_json = "1.0.140"
+
serde_qs = "1.0.0-rc.3"
+
thiserror = "2.0.12"
+
tinyjson = "2.5.1"
+
tokio = { version = "1.45.1", features = ["full"] }
+
tokio-tungstenite = "0.27.0"
+
tokio-util = "0.7.15"
+116
spacedust/src/consumer.rs
···
+
use crate::ClientMessage;
+
use crate::error::ConsumerError;
+
use crate::removable_delay_queue;
+
use jetstream::{
+
DefaultJetstreamEndpoints, JetstreamCompression, JetstreamConfig, JetstreamConnector,
+
events::{CommitOp, Cursor, EventKind},
+
};
+
use links::collect_links;
+
use std::sync::Arc;
+
use tokio::sync::broadcast;
+
use tokio_util::sync::CancellationToken;
+
+
const MAX_LINKS_PER_EVENT: usize = 100;
+
+
pub async fn consume(
+
b: broadcast::Sender<Arc<ClientMessage>>,
+
d: removable_delay_queue::Input<(String, usize), Arc<ClientMessage>>,
+
jetstream_endpoint: String,
+
cursor: Option<Cursor>,
+
no_zstd: bool,
+
shutdown: CancellationToken,
+
) -> Result<(), ConsumerError> {
+
let endpoint = DefaultJetstreamEndpoints::endpoint_or_shortcut(&jetstream_endpoint);
+
if endpoint == jetstream_endpoint {
+
log::info!("consumer: connecting jetstream at {endpoint}");
+
} else {
+
log::info!("consumer: connecting jetstream at {jetstream_endpoint} => {endpoint}");
+
}
+
let config: JetstreamConfig = JetstreamConfig {
+
endpoint,
+
compression: if no_zstd {
+
JetstreamCompression::None
+
} else {
+
JetstreamCompression::Zstd
+
},
+
replay_on_reconnect: true,
+
channel_size: 1024, // buffer up to ~1s of jetstream events
+
..Default::default()
+
};
+
let mut receiver = JetstreamConnector::new(config)?
+
.connect_cursor(cursor)
+
.await?;
+
+
log::info!("consumer: receiving messages..");
+
loop {
+
if shutdown.is_cancelled() {
+
log::info!("consumer: exiting for shutdown");
+
return Ok(());
+
}
+
let Some(event) = receiver.recv().await else {
+
log::error!("consumer: could not receive event, bailing");
+
break;
+
};
+
+
if event.kind != EventKind::Commit {
+
continue;
+
}
+
let Some(ref commit) = event.commit else {
+
log::warn!("consumer: commit event missing commit data, ignoring");
+
continue;
+
};
+
+
// TODO: something a bit more robust
+
let at_uri = format!(
+
"at://{}/{}/{}",
+
&*event.did, &*commit.collection, &*commit.rkey
+
);
+
+
// TODO: keep a buffer and remove quick deletes to debounce notifs
+
// for now we just drop all deletes eek
+
if commit.operation == CommitOp::Delete {
+
d.remove_range((at_uri.clone(), 0)..=(at_uri.clone(), MAX_LINKS_PER_EVENT))
+
.await;
+
continue;
+
}
+
let Some(ref record) = commit.record else {
+
log::warn!("consumer: commit update/delete missing record, ignoring");
+
continue;
+
};
+
+
let jv = match record.get().parse() {
+
Ok(v) => v,
+
Err(e) => {
+
log::warn!("consumer: record failed to parse, ignoring: {e}");
+
continue;
+
}
+
};
+
+
for (i, link) in collect_links(&jv).into_iter().enumerate() {
+
if i >= MAX_LINKS_PER_EVENT {
+
// todo: indicate if the link limit was reached (-> links omitted)
+
log::warn!("consumer: event has too many links, ignoring the rest");
+
metrics::counter!("consumer_dropped_links", "reason" => "too_many_links")
+
.increment(1);
+
break;
+
}
+
let client_message = match ClientMessage::new_link(link, &at_uri, commit) {
+
Ok(m) => m,
+
Err(e) => {
+
// TODO indicate to clients that a link has been dropped
+
log::warn!("consumer: failed to serialize link to json: {e:?}");
+
metrics::counter!("consumer_dropped_links", "reason" => "failed_to_serialize")
+
.increment(1);
+
continue;
+
}
+
};
+
let message = Arc::new(client_message);
+
let _ = b.send(message.clone()); // only errors if no subscribers are connected, which is just fine.
+
d.enqueue((at_uri.clone(), i), message)
+
.await
+
.map_err(|_| ConsumerError::DelayQueueOutputDropped)?;
+
}
+
}
+
+
Err(ConsumerError::JetstreamEnded)
+
}
+22
spacedust/src/delay.rs
···
+
use crate::error::DelayError;
+
use crate::removable_delay_queue;
+
use tokio::sync::broadcast;
+
use tokio_util::sync::CancellationToken;
+
+
pub async fn to_broadcast<T>(
+
source: removable_delay_queue::Output<(String, usize), T>,
+
dest: broadcast::Sender<T>,
+
shutdown: CancellationToken,
+
) -> Result<(), DelayError> {
+
loop {
+
tokio::select! {
+
ev = source.next() => match ev {
+
Some(event) => {
+
let _ = dest.send(event); // only errors of there are no listeners, but that's normal
+
},
+
None => return Err(DelayError::DelayEnded),
+
},
+
_ = shutdown.cancelled() => return Ok(()),
+
}
+
}
+
}
+55
spacedust/src/error.rs
···
+
use thiserror::Error;
+
+
#[derive(Debug, Error)]
+
pub enum MainTaskError {
+
#[error(transparent)]
+
ConsumerTaskError(#[from] ConsumerError),
+
#[error(transparent)]
+
ServerTaskError(#[from] ServerError),
+
#[error(transparent)]
+
DelayTaskError(#[from] DelayError),
+
}
+
+
#[derive(Debug, Error)]
+
pub enum ConsumerError {
+
#[error(transparent)]
+
JetstreamConnectionError(#[from] jetstream::error::ConnectionError),
+
#[error(transparent)]
+
JetstreamConfigValidationError(#[from] jetstream::error::ConfigValidationError),
+
#[error("jetstream ended")]
+
JetstreamEnded,
+
#[error("delay queue output dropped")]
+
DelayQueueOutputDropped,
+
}
+
+
#[derive(Debug, Error)]
+
pub enum SubscriberUpdateError {
+
#[error("failed to parse json for subscriber update: {0}")]
+
FailedToParseMessage(serde_json::Error),
+
#[error("more wantedSources were requested than allowed (max 1,000)")]
+
TooManySourcesWanted,
+
#[error("more wantedSubjectDids were requested than allowed (max 10,000)")]
+
TooManyDidsWanted,
+
#[error("more wantedSubjects were requested than allowed (max 50,000)")]
+
TooManySubjectsWanted,
+
}
+
+
#[derive(Debug, Error)]
+
pub enum DelayError {
+
#[error("delay ended")]
+
DelayEnded,
+
}
+
+
#[derive(Debug, Error)]
+
pub enum ServerError {
+
#[error("failed to configure server logger: {0}")]
+
ConfigLogError(std::io::Error),
+
#[error("failed to render json for openapi: {0}")]
+
OpenApiJsonFail(serde_json::Error),
+
#[error(transparent)]
+
FailedToBuildServer(#[from] dropshot::BuildError),
+
#[error("server exited: {0}")]
+
ServerExited(String),
+
#[error("server closed badly: {0}")]
+
BadClose(String),
+
}
+104
spacedust/src/lib.rs
···
+
pub mod consumer;
+
pub mod delay;
+
pub mod error;
+
pub mod removable_delay_queue;
+
pub mod server;
+
pub mod subscriber;
+
+
use jetstream::events::CommitEvent;
+
use links::CollectedLink;
+
use serde::{Deserialize, Serialize};
+
use server::MultiSubscribeQuery;
+
use tokio_tungstenite::tungstenite::Message;
+
+
#[derive(Debug)]
+
pub struct FilterableProperties {
+
/// Full unmodified DID, at-uri, or url
+
pub subject: String,
+
/// User/identity DID.
+
///
+
/// Will match both bare-DIDs and DIDs extracted from at-uris.
+
/// `None` for any URL.
+
pub subject_did: Option<String>,
+
/// Link source -- collection NSID joined with `:` to the record property path.
+
pub source: String,
+
}
+
+
/// A serialized message with filterable properties attached
+
#[derive(Debug)]
+
pub struct ClientMessage {
+
pub message: Message, // always Message::Text
+
pub properties: FilterableProperties,
+
}
+
+
impl ClientMessage {
+
pub fn new_link(
+
link: CollectedLink,
+
at_uri: &str,
+
commit: &CommitEvent,
+
) -> Result<Self, serde_json::Error> {
+
let subject_did = link.target.did();
+
+
let subject = link.target.into_string();
+
+
let undotted = link.path.strip_prefix('.').unwrap_or_else(|| {
+
eprintln!("link path did not have expected '.' prefix: {}", link.path);
+
""
+
});
+
let source = format!("{}:{undotted}", &*commit.collection);
+
+
let client_link_event = ClientLinkEvent {
+
operation: "create",
+
source: source.clone(),
+
source_record: at_uri.to_string(),
+
source_rev: commit.rev.to_string(),
+
subject: subject.clone(),
+
};
+
+
let client_event = ClientEvent {
+
kind: "link",
+
origin: "live", // TODO: indicate when we're locally replaying jetstream on reconnect?? maybe not.
+
link: client_link_event,
+
};
+
+
let client_event_json = serde_json::to_string(&client_event)?;
+
+
let message = Message::Text(client_event_json.into());
+
+
let properties = FilterableProperties {
+
subject,
+
subject_did,
+
source,
+
};
+
+
Ok(ClientMessage {
+
message,
+
properties,
+
})
+
}
+
}
+
+
#[derive(Debug, Serialize)]
+
#[serde(rename_all = "snake_case")]
+
pub struct ClientEvent {
+
kind: &'static str, // "link"
+
origin: &'static str, // "live", "replay", "backfill"
+
link: ClientLinkEvent,
+
}
+
+
#[derive(Debug, Serialize)]
+
struct ClientLinkEvent {
+
operation: &'static str, // "create", "delete" (prob no update, though maybe for rev?)
+
source: String,
+
source_record: String,
+
source_rev: String,
+
subject: String,
+
// TODO: include the record too? would save clients a level of hydration
+
// ^^ no, not for now. until we backfill + support broader deletes at *least*.
+
}
+
+
#[derive(Debug, Deserialize)]
+
#[serde(tag = "type", content = "payload", rename_all = "snake_case")]
+
pub enum SubscriberSourcedMessage {
+
OptionsUpdate(MultiSubscribeQuery),
+
}
+144
spacedust/src/main.rs
···
+
use spacedust::consumer;
+
use spacedust::delay;
+
use spacedust::error::MainTaskError;
+
use spacedust::removable_delay_queue::removable_delay_queue;
+
use spacedust::server;
+
+
use clap::Parser;
+
use metrics_exporter_prometheus::PrometheusBuilder;
+
use std::time::Duration;
+
use tokio::sync::broadcast;
+
use tokio_util::sync::CancellationToken;
+
+
/// Aggregate links in the at-mosphere
+
#[derive(Parser, Debug, Clone)]
+
#[command(version, about, long_about = None)]
+
struct Args {
+
/// Jetstream server to connect to (exclusive with --fixture). Provide either a wss:// URL, or a shorhand value:
+
/// 'us-east-1', 'us-east-2', 'us-west-1', or 'us-west-2'
+
#[arg(long)]
+
jetstream: String,
+
/// don't request zstd-compressed jetstream events
+
///
+
/// reduces CPU at the expense of more ingress bandwidth
+
#[arg(long, action)]
+
jetstream_no_zstd: bool,
+
}
+
+
#[tokio::main]
+
async fn main() -> Result<(), String> {
+
env_logger::init();
+
+
// tokio broadcast keeps a single main output queue for all subscribers.
+
// each subscriber clones off a copy of an individual value for each recv.
+
// since there's no large per-client buffer, we can make this one kind of
+
// big and accommodate more slow/bursty clients.
+
//
+
// in fact, we *could* even keep lagging clients alive, inserting lag-
+
// indicating messages to their output.... but for now we'll drop them to
+
// avoid accumulating zombies.
+
//
+
// events on the channel are individual links as they are discovered. a link
+
// contains a source and a target. the target is an at-uri, so it's up to
+
// ~1KB max; source is a collection + link path, which can be more but in
+
// practice the whole link rarely approaches 1KB total.
+
//
+
// TODO: determine if a pathological case could blow this up (eg 1MB link
+
// paths + slow subscriber -> 16GiB queue)
+
let (b, _) = broadcast::channel(16_384);
+
let consumer_sender = b.clone();
+
let (d, _) = broadcast::channel(16_384);
+
let consumer_delayed_sender = d.clone();
+
+
let delay = Duration::from_secs(21);
+
let (delay_queue_sender, delay_queue_receiver) = removable_delay_queue(delay);
+
+
let shutdown = CancellationToken::new();
+
+
let ctrlc_shutdown = shutdown.clone();
+
ctrlc::set_handler(move || ctrlc_shutdown.cancel()).expect("failed to set ctrl-c handler");
+
+
let args = Args::parse();
+
+
if let Err(e) = install_metrics_server() {
+
log::error!("failed to install metrics server: {e:?}");
+
};
+
+
let mut tasks: tokio::task::JoinSet<Result<(), MainTaskError>> = tokio::task::JoinSet::new();
+
+
let server_shutdown = shutdown.clone();
+
tasks.spawn(async move {
+
server::serve(b, d, server_shutdown).await?;
+
Ok(())
+
});
+
+
let consumer_shutdown = shutdown.clone();
+
tasks.spawn(async move {
+
consumer::consume(
+
consumer_sender,
+
delay_queue_sender,
+
args.jetstream,
+
None,
+
args.jetstream_no_zstd,
+
consumer_shutdown,
+
)
+
.await?;
+
Ok(())
+
});
+
+
let delay_shutdown = shutdown.clone();
+
tasks.spawn(async move {
+
delay::to_broadcast(
+
delay_queue_receiver,
+
consumer_delayed_sender,
+
delay_shutdown,
+
)
+
.await?;
+
Ok(())
+
});
+
+
tokio::select! {
+
_ = shutdown.cancelled() => log::warn!("shutdown requested"),
+
Some(r) = tasks.join_next() => {
+
log::warn!("a task exited, shutting down: {r:?}");
+
shutdown.cancel();
+
}
+
}
+
+
tokio::select! {
+
_ = async {
+
while let Some(completed) = tasks.join_next().await {
+
log::info!("shutdown: task completed: {completed:?}");
+
}
+
} => {},
+
_ = tokio::time::sleep(std::time::Duration::from_secs(3)) => {
+
log::info!("shutdown: not all tasks completed on time. aborting...");
+
tasks.shutdown().await;
+
},
+
}
+
+
log::info!("bye!");
+
+
Ok(())
+
}
+
+
fn install_metrics_server() -> Result<(), metrics_exporter_prometheus::BuildError> {
+
log::info!("installing metrics server...");
+
let host = [0, 0, 0, 0];
+
let port = 8765;
+
PrometheusBuilder::new()
+
.set_quantiles(&[0.5, 0.9, 0.99, 1.0])?
+
.set_bucket_duration(std::time::Duration::from_secs(300))?
+
.set_bucket_count(std::num::NonZero::new(12).unwrap()) // count * duration = 60 mins. stuff doesn't happen that fast here.
+
.set_enable_unit_suffix(false) // this seemed buggy for constellation (sometimes wouldn't engage)
+
.with_http_listener((host, port))
+
.install()?;
+
log::info!(
+
"metrics server installed! listening on http://{}.{}.{}.{}:{port}",
+
host[0],
+
host[1],
+
host[2],
+
host[3]
+
);
+
Ok(())
+
}
+125
spacedust/src/removable_delay_queue.rs
···
+
use std::collections::{BTreeMap, VecDeque};
+
use std::ops::RangeBounds;
+
use std::sync::Arc;
+
use std::time::{Duration, Instant};
+
use thiserror::Error;
+
use tokio::sync::Mutex;
+
+
#[derive(Debug, Error)]
+
pub enum EnqueueError<T> {
+
#[error("queue ouput dropped")]
+
OutputDropped(T),
+
}
+
+
pub trait Key: Eq + Ord + Clone {}
+
impl<T: Eq + Ord + Clone> Key for T {}
+
+
#[derive(Debug)]
+
struct Queue<K: Key, T> {
+
queue: VecDeque<(Instant, K)>,
+
items: BTreeMap<K, T>,
+
}
+
+
pub struct Input<K: Key, T> {
+
q: Arc<Mutex<Queue<K, T>>>,
+
}
+
+
impl<K: Key, T> Input<K, T> {
+
/// if a key is already present, its previous item will be overwritten and
+
/// its delay time will be reset for the new item.
+
///
+
/// errors if the remover has been dropped
+
pub async fn enqueue(&self, key: K, item: T) -> Result<(), EnqueueError<T>> {
+
if Arc::strong_count(&self.q) == 1 {
+
return Err(EnqueueError::OutputDropped(item));
+
}
+
// TODO: try to push out an old element first
+
// for now we just hope there's a listener
+
let now = Instant::now();
+
let mut q = self.q.lock().await;
+
q.queue.push_back((now, key.clone()));
+
q.items.insert(key, item);
+
Ok(())
+
}
+
/// remove an item from the queue, by key
+
///
+
/// the item itself is removed, but the key will remain in the queue -- it
+
/// will simply be skipped over when a new output item is requested. this
+
/// keeps the removal cheap (=btreemap remove), for a bit of space overhead
+
pub async fn remove_range(&self, range: impl RangeBounds<K>) {
+
let n = {
+
let mut q = self.q.lock().await;
+
let keys = q
+
.items
+
.range(range)
+
.map(|(k, _)| k)
+
.cloned()
+
.collect::<Vec<_>>();
+
for k in &keys {
+
q.items.remove(k);
+
}
+
keys.len()
+
};
+
if n == 0 {
+
metrics::counter!("delay_queue_remove_not_found").increment(1);
+
} else {
+
metrics::counter!("delay_queue_remove_total_records").increment(1);
+
metrics::counter!("delay_queue_remove_total_links").increment(n as u64);
+
}
+
}
+
}
+
+
pub struct Output<K: Key, T> {
+
delay: Duration,
+
q: Arc<Mutex<Queue<K, T>>>,
+
}
+
+
impl<K: Key, T> Output<K, T> {
+
pub async fn next(&self) -> Option<T> {
+
let get = || async {
+
let mut q = self.q.lock().await;
+
metrics::gauge!("delay_queue_queue_len").set(q.queue.len() as f64);
+
metrics::gauge!("delay_queue_queue_capacity").set(q.queue.capacity() as f64);
+
while let Some((t, k)) = q.queue.pop_front() {
+
// skip over queued keys that were removed from items
+
if let Some(item) = q.items.remove(&k) {
+
return Some((t, item));
+
}
+
}
+
None
+
};
+
loop {
+
if let Some((t, item)) = get().await {
+
let now = Instant::now();
+
let expected_release = t + self.delay;
+
if expected_release.saturating_duration_since(now) > Duration::from_millis(1) {
+
tokio::time::sleep_until(expected_release.into()).await;
+
metrics::counter!("delay_queue_emit_total", "early" => "yes").increment(1);
+
metrics::histogram!("delay_queue_emit_overshoot").record(0);
+
} else {
+
let overshoot = now.saturating_duration_since(expected_release);
+
metrics::counter!("delay_queue_emit_total", "early" => "no").increment(1);
+
metrics::histogram!("delay_queue_emit_overshoot")
+
.record(overshoot.as_secs_f64());
+
}
+
return Some(item);
+
} else if Arc::strong_count(&self.q) == 1 {
+
return None;
+
}
+
// the queue is *empty*, so we need to wait at least as long as the current delay
+
tokio::time::sleep(self.delay).await;
+
metrics::counter!("delay_queue_entirely_empty_total").increment(1);
+
}
+
}
+
}
+
+
pub fn removable_delay_queue<K: Key, T>(delay: Duration) -> (Input<K, T>, Output<K, T>) {
+
let q: Arc<Mutex<Queue<K, T>>> = Arc::new(Mutex::new(Queue {
+
queue: VecDeque::new(),
+
items: BTreeMap::new(),
+
}));
+
+
let input = Input::<K, T> { q: q.clone() };
+
let output = Output::<K, T> { q, delay };
+
(input, output)
+
}
+339
spacedust/src/server.rs
···
+
use crate::ClientMessage;
+
use crate::error::ServerError;
+
use crate::subscriber::Subscriber;
+
use dropshot::{
+
ApiDescription, ApiEndpointBodyContentType, Body, ConfigDropshot, ConfigLogging,
+
ConfigLoggingLevel, ExtractorMetadata, HttpError, HttpResponse, Query, RequestContext,
+
ServerBuilder, ServerContext, SharedExtractor, WebsocketConnection, channel, endpoint,
+
};
+
use http::{
+
Response, StatusCode,
+
header::{ORIGIN, USER_AGENT},
+
};
+
use metrics::{counter, histogram};
+
use std::sync::Arc;
+
+
use async_trait::async_trait;
+
use schemars::JsonSchema;
+
use serde::{Deserialize, Serialize};
+
use std::collections::HashSet;
+
use tokio::sync::broadcast;
+
use tokio::time::Instant;
+
use tokio_tungstenite::tungstenite::protocol::{Role, WebSocketConfig};
+
use tokio_util::sync::CancellationToken;
+
+
const INDEX_HTML: &str = include_str!("../static/index.html");
+
const FAVICON: &[u8] = include_bytes!("../static/favicon.ico");
+
+
pub async fn serve(
+
b: broadcast::Sender<Arc<ClientMessage>>,
+
d: broadcast::Sender<Arc<ClientMessage>>,
+
shutdown: CancellationToken,
+
) -> Result<(), ServerError> {
+
let config_logging = ConfigLogging::StderrTerminal {
+
level: ConfigLoggingLevel::Info,
+
};
+
+
let log = config_logging
+
.to_logger("example-basic")
+
.map_err(ServerError::ConfigLogError)?;
+
+
let mut api = ApiDescription::new();
+
api.register(index).unwrap();
+
api.register(favicon).unwrap();
+
api.register(openapi).unwrap();
+
api.register(subscribe).unwrap();
+
+
// TODO: put spec in a once cell / lazy lock thing?
+
let spec = Arc::new(
+
api.openapi(
+
"Spacedust",
+
env!("CARGO_PKG_VERSION")
+
.parse()
+
.inspect_err(|e| {
+
eprintln!("failed to parse cargo package version for openapi: {e:?}")
+
})
+
.unwrap_or(semver::Version::new(0, 0, 1)),
+
)
+
.description("A configurable ATProto notifications firehose.")
+
.contact_name("part of @microcosm.blue")
+
.contact_url("https://microcosm.blue")
+
.json()
+
.map_err(ServerError::OpenApiJsonFail)?,
+
);
+
+
let sub_shutdown = shutdown.clone();
+
let ctx = Context {
+
spec,
+
b,
+
d,
+
shutdown: sub_shutdown,
+
};
+
+
let server = ServerBuilder::new(api, ctx, log)
+
.config(ConfigDropshot {
+
bind_address: "0.0.0.0:9998".parse().unwrap(),
+
..Default::default()
+
})
+
.start()?;
+
+
tokio::select! {
+
s = server.wait_for_shutdown() => {
+
s.map_err(ServerError::ServerExited)?;
+
log::info!("server shut down normally.");
+
},
+
_ = shutdown.cancelled() => {
+
log::info!("shutting down: closing server");
+
server.close().await.map_err(ServerError::BadClose)?;
+
},
+
}
+
Ok(())
+
}
+
+
#[derive(Debug, Clone)]
+
struct Context {
+
pub spec: Arc<serde_json::Value>,
+
pub b: broadcast::Sender<Arc<ClientMessage>>,
+
pub d: broadcast::Sender<Arc<ClientMessage>>,
+
pub shutdown: CancellationToken,
+
}
+
+
async fn instrument_handler<T, H, R>(ctx: &RequestContext<T>, handler: H) -> Result<R, HttpError>
+
where
+
R: HttpResponse,
+
H: Future<Output = Result<R, HttpError>>,
+
T: ServerContext,
+
{
+
let start = Instant::now();
+
let result = handler.await;
+
let latency = start.elapsed();
+
let status_code = match &result {
+
Ok(response) => response.status_code(),
+
Err(e) => e.status_code.as_status(),
+
}
+
.as_str() // just the number (.to_string()'s Display does eg `200 OK`)
+
.to_string();
+
let endpoint = ctx.endpoint.operation_id.clone();
+
let headers = ctx.request.headers();
+
let origin = headers
+
.get(ORIGIN)
+
.and_then(|v| v.to_str().ok())
+
.unwrap_or("")
+
.to_string();
+
let ua = headers
+
.get(USER_AGENT)
+
.and_then(|v| v.to_str().ok())
+
.map(|ua| {
+
if ua.starts_with("Mozilla/5.0 ") {
+
"browser"
+
} else {
+
ua
+
}
+
})
+
.unwrap_or("")
+
.to_string();
+
counter!("server_requests_total",
+
"endpoint" => endpoint.clone(),
+
"origin" => origin,
+
"ua" => ua,
+
"status_code" => status_code,
+
)
+
.increment(1);
+
histogram!("server_handler_latency", "endpoint" => endpoint).record(latency.as_micros() as f64);
+
result
+
}
+
+
use dropshot::{HttpResponseHeaders, HttpResponseOk};
+
+
pub type OkCorsResponse<T> = Result<HttpResponseHeaders<HttpResponseOk<T>>, HttpError>;
+
+
/// Helper for constructing Ok responses: return OkCors(T).into()
+
/// (not happy with this yet)
+
pub struct OkCors<T: Serialize + JsonSchema + Send + Sync>(pub T);
+
+
impl<T> From<OkCors<T>> for OkCorsResponse<T>
+
where
+
T: Serialize + JsonSchema + Send + Sync,
+
{
+
fn from(ok: OkCors<T>) -> OkCorsResponse<T> {
+
let mut res = HttpResponseHeaders::new_unnamed(HttpResponseOk(ok.0));
+
res.headers_mut()
+
.insert("access-control-allow-origin", "*".parse().unwrap());
+
Ok(res)
+
}
+
}
+
+
// TODO: cors for HttpError
+
+
/// Serve index page as html
+
#[endpoint {
+
method = GET,
+
path = "/",
+
/*
+
* not useful to have this in openapi
+
*/
+
unpublished = true,
+
}]
+
async fn index(ctx: RequestContext<Context>) -> Result<Response<Body>, HttpError> {
+
instrument_handler(&ctx, async {
+
Ok(Response::builder()
+
.status(StatusCode::OK)
+
.header(http::header::CONTENT_TYPE, "text/html")
+
.body(INDEX_HTML.into())?)
+
})
+
.await
+
}
+
+
/// Serve index page as html
+
#[endpoint {
+
method = GET,
+
path = "/favicon.ico",
+
/*
+
* not useful to have this in openapi
+
*/
+
unpublished = true,
+
}]
+
async fn favicon(ctx: RequestContext<Context>) -> Result<Response<Body>, HttpError> {
+
instrument_handler(&ctx, async {
+
Ok(Response::builder()
+
.status(StatusCode::OK)
+
.header(http::header::CONTENT_TYPE, "image/x-icon")
+
.body(FAVICON.to_vec().into())?)
+
})
+
.await
+
}
+
+
/// Meta: get the openapi spec for this api
+
#[endpoint {
+
method = GET,
+
path = "/openapi",
+
/*
+
* not useful to have this in openapi
+
*/
+
unpublished = true,
+
}]
+
async fn openapi(ctx: RequestContext<Context>) -> OkCorsResponse<serde_json::Value> {
+
instrument_handler(&ctx, async {
+
let spec = (*ctx.context().spec).clone();
+
OkCors(spec).into()
+
})
+
.await
+
}
+
+
/// The real type that gets deserialized
+
#[derive(Debug, Deserialize, JsonSchema)]
+
#[serde(rename_all = "camelCase")]
+
pub struct MultiSubscribeQuery {
+
#[serde(default)]
+
pub wanted_subjects: HashSet<String>,
+
#[serde(default)]
+
pub wanted_subject_dids: HashSet<String>,
+
#[serde(default)]
+
pub wanted_sources: HashSet<String>,
+
}
+
/// The fake corresponding type for docs that dropshot won't freak out about a
+
/// vec for
+
#[derive(Deserialize, JsonSchema)]
+
#[allow(dead_code)]
+
#[serde(rename_all = "camelCase")]
+
struct MultiSubscribeQueryForDocs {
+
/// One or more at-uris to receive links about
+
///
+
/// The at-uri must be url-encoded
+
///
+
/// Pass this parameter multiple times to specify multiple collections, like
+
/// `wantedSubjects=[...]&wantedSubjects=[...]`
+
pub wanted_subjects: String,
+
/// One or more DIDs to receive links about
+
///
+
/// Pass this parameter multiple times to specify multiple collections
+
pub wanted_subject_dids: String,
+
/// One or more link sources to receive links about
+
///
+
/// TODO: docs about link sources
+
///
+
/// eg, a bluesky like's link source: `app.bsky.feed.like:subject.uri`
+
///
+
/// Pass this parameter multiple times to specify multiple sources
+
pub wanted_sources: String,
+
}
+
+
// The `SharedExtractor` implementation for Query<QueryType> describes how to
+
// construct an instance of `Query<QueryType>` from an HTTP request: namely, by
+
// parsing the query string to an instance of `QueryType`.
+
#[async_trait]
+
impl SharedExtractor for MultiSubscribeQuery {
+
async fn from_request<Context: ServerContext>(
+
ctx: &RequestContext<Context>,
+
) -> Result<MultiSubscribeQuery, HttpError> {
+
let raw_query = ctx.request.uri().query().unwrap_or("");
+
let q = serde_qs::from_str(raw_query).map_err(|e| {
+
HttpError::for_bad_request(None, format!("unable to parse query string: {e}"))
+
})?;
+
Ok(q)
+
}
+
+
fn metadata(body_content_type: ApiEndpointBodyContentType) -> ExtractorMetadata {
+
// HACK: query type switcheroo: passing MultiSubscribeQuery to
+
// `metadata` would "helpfully" panic because dropshot believes we can
+
// only have scalar types in a query.
+
//
+
// so instead we have a fake second type whose only job is to look the
+
// same as MultiSubscribeQuery exept that it has `String` instead of
+
// `Vec<String>`, which dropshot will accept, and generate ~close-enough
+
// docs for.
+
<Query<MultiSubscribeQueryForDocs> as SharedExtractor>::metadata(body_content_type)
+
}
+
}
+
+
#[derive(Deserialize, JsonSchema)]
+
#[serde(rename_all = "camelCase")]
+
struct ScalarSubscribeQuery {
+
/// Bypass the 21-sec delay buffer
+
///
+
/// By default, spacedust holds all firehose links for 21 seconds before
+
/// emitting them, to prevent quickly- undone interactions from generating
+
/// notifications.
+
///
+
/// Setting `instant` to true bypasses this buffer, allowing faster (and
+
/// noisier) notification delivery.
+
///
+
/// Typically [a little less than 1%](https://bsky.app/profile/bad-example.com/post/3ls32wctsrs2l)
+
/// of links links get deleted within 21s of being created.
+
#[serde(default)]
+
pub instant: bool,
+
}
+
+
#[channel {
+
protocol = WEBSOCKETS,
+
path = "/subscribe",
+
}]
+
async fn subscribe(
+
reqctx: RequestContext<Context>,
+
query: MultiSubscribeQuery,
+
scalar_query: Query<ScalarSubscribeQuery>,
+
upgraded: WebsocketConnection,
+
) -> dropshot::WebsocketChannelResult {
+
let ws = tokio_tungstenite::WebSocketStream::from_raw_socket(
+
upgraded.into_inner(),
+
Role::Server,
+
Some(WebSocketConfig::default().max_message_size(
+
Some(10 * 2_usize.pow(20)), // 10MiB, matching jetstream
+
)),
+
)
+
.await;
+
+
let Context { b, d, shutdown, .. } = reqctx.context();
+
let sub_token = shutdown.child_token();
+
+
let q = scalar_query.into_inner();
+
let subscription = if q.instant { b } else { d }.subscribe();
+
log::info!("starting subscriber with broadcast: instant={}", q.instant);
+
+
Subscriber::new(query, sub_token)
+
.start(ws, subscription)
+
.await
+
.map_err(|e| format!("boo: {e:?}"))?;
+
+
Ok(())
+
}
+164
spacedust/src/subscriber.rs
···
+
use crate::error::SubscriberUpdateError;
+
use crate::server::MultiSubscribeQuery;
+
use crate::{ClientMessage, FilterableProperties, SubscriberSourcedMessage};
+
use dropshot::WebsocketConnectionRaw;
+
use futures::SinkExt;
+
use futures::StreamExt;
+
use std::error::Error;
+
use std::sync::Arc;
+
use std::time::Duration;
+
use tokio::sync::broadcast::{self, error::RecvError};
+
use tokio::time::interval;
+
use tokio_tungstenite::{WebSocketStream, tungstenite::Message};
+
use tokio_util::sync::CancellationToken;
+
+
const PING_PERIOD: Duration = Duration::from_secs(30);
+
+
pub struct Subscriber {
+
query: MultiSubscribeQuery,
+
shutdown: CancellationToken,
+
}
+
+
impl Subscriber {
+
pub fn new(query: MultiSubscribeQuery, shutdown: CancellationToken) -> Self {
+
Self { query, shutdown }
+
}
+
+
pub async fn start(
+
mut self,
+
ws: WebSocketStream<WebsocketConnectionRaw>,
+
mut receiver: broadcast::Receiver<Arc<ClientMessage>>,
+
) -> Result<(), Box<dyn Error>> {
+
let mut ping_state = None;
+
let (mut ws_sender, mut ws_receiver) = ws.split();
+
let mut ping_interval = interval(PING_PERIOD);
+
let _guard = self.shutdown.clone().drop_guard();
+
+
// TODO: do we need to timeout ws sends??
+
+
metrics::counter!("subscribers_connected_total").increment(1);
+
metrics::gauge!("subscribers_connected").increment(1);
+
+
loop {
+
tokio::select! {
+
l = receiver.recv() => match l {
+
Ok(link) => if self.filter(&link.properties) {
+
if let Err(e) = ws_sender.send(link.message.clone()).await {
+
log::warn!("failed to send link, dropping subscriber: {e:?}");
+
break;
+
}
+
},
+
Err(RecvError::Closed) => self.shutdown.cancel(),
+
Err(RecvError::Lagged(n)) => {
+
log::warn!("dropping lagging subscriber (missed {n} messages already)");
+
self.shutdown.cancel();
+
}
+
},
+
cm = ws_receiver.next() => match cm {
+
Some(Ok(Message::Ping(state))) => {
+
if let Err(e) = ws_sender.send(Message::Pong(state)).await {
+
log::error!("failed to reply pong to subscriber: {e:?}");
+
break;
+
}
+
}
+
Some(Ok(Message::Pong(state))) => {
+
if let Some(expected_state) = ping_state {
+
if *state == expected_state {
+
ping_state = None; // good
+
} else {
+
log::error!("subscriber returned a pong with the wrong state, dropping");
+
self.shutdown.cancel();
+
}
+
} else {
+
log::error!("subscriber sent a pong when none was expected");
+
self.shutdown.cancel();
+
}
+
}
+
Some(Ok(Message::Text(raw))) => {
+
if let Err(e) = self.query.update_from_raw(&raw) {
+
log::error!("subscriber options could not be updated, dropping: {e:?}");
+
// TODO: send client an explanation
+
self.shutdown.cancel();
+
}
+
log::trace!("subscriber updated with opts: {:?}", self.query);
+
},
+
Some(Ok(m)) => log::trace!("subscriber sent an unexpected message: {m:?}"),
+
Some(Err(e)) => {
+
log::error!("failed to receive subscriber message: {e:?}");
+
break;
+
}
+
None => {
+
log::trace!("end of subscriber messages. bye!");
+
break;
+
}
+
},
+
_ = ping_interval.tick() => {
+
if ping_state.is_some() {
+
log::warn!("did not recieve pong within {PING_PERIOD:?}, dropping subscriber");
+
self.shutdown.cancel();
+
} else {
+
let new_state: [u8; 8] = rand::random();
+
let ping = new_state.to_vec().into();
+
ping_state = Some(new_state);
+
if let Err(e) = ws_sender.send(Message::Ping(ping)).await {
+
log::error!("failed to send ping to subscriber, dropping: {e:?}");
+
self.shutdown.cancel();
+
}
+
}
+
}
+
_ = self.shutdown.cancelled() => {
+
log::info!("subscriber shutdown requested, bye!");
+
if let Err(e) = ws_sender.close().await {
+
log::warn!("failed to close subscriber: {e:?}");
+
}
+
break;
+
},
+
}
+
}
+
log::trace!("end of subscriber. bye!");
+
metrics::gauge!("subscribers_connected").decrement(1);
+
Ok(())
+
}
+
+
fn filter(&self, properties: &FilterableProperties) -> bool {
+
let query = &self.query;
+
+
// subject + subject DIDs are logical OR
+
if !(query.wanted_subjects.is_empty() && query.wanted_subject_dids.is_empty()
+
|| query.wanted_subjects.contains(&properties.subject)
+
|| properties
+
.subject_did
+
.as_ref()
+
.map(|did| query.wanted_subject_dids.contains(did))
+
.unwrap_or(false))
+
{
+
// wowwww ^^ fix that
+
return false;
+
}
+
+
// subjects together with sources are logical AND
+
if !(query.wanted_sources.is_empty() || query.wanted_sources.contains(&properties.source)) {
+
return false;
+
}
+
+
true
+
}
+
}
+
+
impl MultiSubscribeQuery {
+
pub fn update_from_raw(&mut self, s: &str) -> Result<(), SubscriberUpdateError> {
+
let SubscriberSourcedMessage::OptionsUpdate(opts) =
+
serde_json::from_str(s).map_err(SubscriberUpdateError::FailedToParseMessage)?;
+
if opts.wanted_sources.len() > 1_000 {
+
return Err(SubscriberUpdateError::TooManySourcesWanted);
+
}
+
if opts.wanted_subject_dids.len() > 10_000 {
+
return Err(SubscriberUpdateError::TooManyDidsWanted);
+
}
+
if opts.wanted_subjects.len() > 50_000 {
+
return Err(SubscriberUpdateError::TooManySubjectsWanted);
+
}
+
*self = opts;
+
Ok(())
+
}
+
}
spacedust/static/favicon.ico

This is a binary file and will not be displayed.

+54
spacedust/static/index.html
···
+
<!doctype html>
+
<html lang="en">
+
<head>
+
<meta charset="utf-8" />
+
<title>Spacedust documentation</title>
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
+
<meta name="description" content="API Documentation for Spacedust, a configurable ATProto notifications firehose" />
+
<style>
+
.custom-header {
+
height: 42px;
+
background-color: #221828;
+
box-shadow: inset 0 -1px 0 var(--scalar-border-color);
+
color: var(--scalar-color-1);
+
font-size: var(--scalar-font-size-3);
+
font-family: 'Iowan Old Style', 'Palatino Linotype', 'URW Palladio L', P052, serif;
+
padding: 0 18px;
+
justify-content: space-between;
+
}
+
.custom-header,
+
.custom-header nav {
+
display: flex;
+
align-items: center;
+
gap: 18px;
+
}
+
.custom-header a:hover {
+
color: var(--scalar-color-2);
+
}
+
</style>
+
</head>
+
<body>
+
<header class="custom-header scalar-app">
+
<p>
+
TODO: pdsls jetstream link
+
<a href="https://ufos.microcosm.blue">Launch 🛸 UFOs app</a>: Explore lexicons
+
</p>
+
<nav>
+
<b>a <a href="https://microcosm.blue">microcosm</a> project</b>
+
<a href="https://bsky.app/profile/microcosm.blue">@microcosm.blue</a>
+
<a href="https://github.com/at-microcosm">github</a>
+
</nav>
+
</header>
+
+
<script id="api-reference" type="application/json" data-url="/openapi"></script>
+
+
<script>
+
var configuration = {
+
theme: 'purple',
+
}
+
document.getElementById('api-reference').dataset.configuration = JSON.stringify(configuration)
+
</script>
+
+
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
+
</body>
+
</html>
+5 -3
ufos/Cargo.toml
···
async-trait = "0.1.88"
base64 = "0.22.1"
bincode = { version = "2.0.1", features = ["serde"] }
-
cardinality-estimator-safe = { version = "4.0.1", features = ["with_serde", "with_digest"] }
+
cardinality-estimator-safe = { version = "4.0.2", features = ["with_serde", "with_digest"] }
chrono = { version = "0.4.41", features = ["serde"] }
clap = { version = "4.5.31", features = ["derive"] }
dropshot = "0.16.0"
env_logger = "0.11.7"
-
fjall = { version = "2.8.0", features = ["lz4"] }
+
fjall = { git = "https://github.com/fjall-rs/fjall.git", features = ["lz4"] }
getrandom = "0.3.3"
http = "1.3.1"
-
jetstream = { path = "../jetstream" }
+
jetstream = { path = "../jetstream", features = ["metrics"] }
log = "0.4.26"
lsm-tree = "2.6.6"
+
metrics = "0.24.2"
+
metrics-exporter-prometheus = { version = "0.17.0", default-features = false, features = ["http-listener"] }
schemars = { version = "0.8.22", features = ["raw_value", "chrono"] }
semver = "1.0.26"
serde = "1.0.219"
+38 -5
ufos/src/consumer.rs
···
DefaultJetstreamEndpoints, JetstreamCompression, JetstreamConfig, JetstreamConnector,
JetstreamReceiver,
};
+
use metrics::{
+
counter, describe_counter, describe_gauge, describe_histogram, gauge, histogram, Unit,
+
};
use std::mem;
use std::time::Duration;
use tokio::sync::mpsc::{channel, Receiver, Sender};
···
batch_sender: Sender<LimitedBatch>,
sketch_secret: SketchSecretPrefix,
) -> Self {
+
describe_counter!(
+
"batcher_batches_sent",
+
Unit::Count,
+
"how many batches of events were sent from Batcher to storage"
+
);
+
describe_gauge!(
+
"batcher_batch_age",
+
Unit::Microseconds,
+
"how old the last-sent batch was"
+
);
+
describe_gauge!(
+
"batcher_send_queue_capacity",
+
Unit::Count,
+
"how many spaces are available for batches in the send queue"
+
);
+
describe_histogram!(
+
"batcher_total_collections",
+
Unit::Count,
+
"how many collections are in this batch"
+
);
let mut rate_limit = tokio::time::interval(std::time::Duration::from_millis(3));
rate_limit.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
Self {
···
// holds up all consumer progress until it can send to the channel
// use this when the current batch is too full to add more to it
async fn send_current_batch_now(&mut self, small: bool, referrer: &str) -> anyhow::Result<()> {
+
let size_label = if small { "small" } else { "full" };
+
let queue_cap = self.batch_sender.capacity();
+
+
if let Some(cursor) = self.current_batch.initial_cursor {
+
gauge!("batcher_batch_age", "size" => size_label).set(cursor.elapsed_micros_f64());
+
}
+
histogram!("batcher_total_collections", "size" => size_label)
+
.record(self.current_batch.batch.total_collections() as f64);
+
gauge!("batcher_send_queue_capacity").set(queue_cap as f64);
+
let beginning = match self.current_batch.initial_cursor.map(|c| c.elapsed()) {
None => "unknown".to_string(),
-
Some(Ok(t)) => format!("{:?}", t),
+
Some(Ok(t)) => format!("{t:?}"),
Some(Err(e)) => format!("+{:?}", e.duration()),
};
-
log::info!(
-
"sending batch now from {beginning}, {}, queue capacity: {}, referrer: {referrer}",
-
if small { "small" } else { "full" },
-
self.batch_sender.capacity(),
+
log::trace!(
+
"sending batch now from {beginning}, {size_label}, queue capacity: {queue_cap}, referrer: {referrer}",
);
let current = mem::take(&mut self.current_batch);
self.rate_limit.tick().await;
self.batch_sender
.send_timeout(current.batch, Duration::from_secs_f64(SEND_TIMEOUT_S))
.await?;
+
counter!("batcher_batches_sent", "size" => size_label, "referrer" => referrer.to_string())
+
.increment(1);
Ok(())
}
}
+2 -2
ufos/src/db_types.rs
···
] {
let serialized = s.to_string().to_db_bytes()?;
let prefixed = String::sub_prefix(pre)?;
-
assert_eq!(serialized.starts_with(&prefixed), is_pre, "{}", desc);
+
assert_eq!(serialized.starts_with(&prefixed), is_pre, "{desc}");
}
Ok(())
}
···
] {
let serialized = Nsid::new(s.to_string()).unwrap().to_db_bytes()?;
let prefixed = Nsid::sub_prefix(pre)?;
-
assert_eq!(serialized.starts_with(&prefixed), is_pre, "{}", desc);
+
assert_eq!(serialized.starts_with(&prefixed), is_pre, "{desc}");
}
Ok(())
}
+6 -3
ufos/src/index_html.rs
···
<html lang="en">
<head>
<meta charset="utf-8" />
-
<title>UFOs API Documentation</title>
+
<title>UFOs API documentation</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="API Documentation for UFOs: Samples and stats for all atproto lexicons." />
<style>
.custom-header {
height: 42px;
-
background-color: var(--scalar-background-1);
+
background-color: #221828;
box-shadow: inset 0 -1px 0 var(--scalar-border-color);
color: var(--scalar-color-1);
font-size: var(--scalar-font-size-3);
···
</head>
<body>
<header class="custom-header scalar-app">
-
<b>a <a href="https://microcosm.blue">microcosm</a> project</b>
+
<p>
+
<a href="https://ufos.microcosm.blue">Launch 🛸 UFOs app</a>: Explore lexicons
+
</p>
<nav>
+
<b>a <a href="https://microcosm.blue">microcosm</a> project</b>
<a href="https://bsky.app/profile/microcosm.blue">@microcosm.blue</a>
<a href="https://github.com/at-microcosm">github</a>
</nav>
+29 -3
ufos/src/lib.rs
···
use crate::db_types::{EncodingError, EncodingResult};
use crate::error::BatchInsertError;
-
use crate::store_types::SketchSecretPrefix;
+
use crate::store_types::{CountsValue, SketchSecretPrefix};
use cardinality_estimator_safe::{Element, Sketch};
use error::FirehoseEventError;
use jetstream::events::{CommitEvent, CommitOp, Cursor};
···
pub struct NsidCount {
nsid: String,
creates: u64,
-
// TODO: add updates and deletes
+
updates: u64,
+
deletes: u64,
dids_estimate: u64,
+
}
+
impl NsidCount {
+
pub fn new(nsid: &Nsid, counts: &CountsValue) -> Self {
+
let crud = counts.counts();
+
Self {
+
nsid: nsid.to_string(),
+
creates: crud.creates,
+
updates: crud.updates,
+
deletes: crud.deletes,
+
dids_estimate: counts.dids().estimate() as u64,
+
}
+
}
}
#[derive(Debug, PartialEq, Serialize, JsonSchema)]
pub struct PrefixCount {
prefix: String,
creates: u64,
-
// TODO: add updates and deletes
+
updates: u64,
+
deletes: u64,
dids_estimate: u64,
+
}
+
impl PrefixCount {
+
pub fn new(prefix: &str, counts: &CountsValue) -> Self {
+
let crud = counts.counts();
+
Self {
+
prefix: prefix.to_string(),
+
creates: crud.creates,
+
updates: crud.updates,
+
deletes: crud.deletes,
+
dids_estimate: counts.dids().estimate() as u64,
+
}
+
}
}
#[derive(Debug, PartialEq, Serialize, JsonSchema)]
+85 -11
ufos/src/main.rs
···
use clap::Parser;
use jetstream::events::Cursor;
+
use metrics::{describe_gauge, gauge, Unit};
+
use metrics_exporter_prometheus::PrometheusBuilder;
use std::path::PathBuf;
use std::time::{Duration, SystemTime};
+
use tokio::task::JoinSet;
use ufos::consumer;
use ufos::file_consumer;
use ufos::server;
···
Ok(())
}
-
async fn go<B: StoreBackground>(
+
async fn go<B: StoreBackground + 'static>(
args: Args,
read_store: impl StoreReader + 'static + Clone,
mut write_store: impl StoreWriter<B> + 'static,
cursor: Option<Cursor>,
sketch_secret: SketchSecretPrefix,
) -> anyhow::Result<()> {
+
let mut whatever_tasks: JoinSet<anyhow::Result<()>> = JoinSet::new();
+
let mut consumer_tasks: JoinSet<anyhow::Result<()>> = JoinSet::new();
+
println!("starting server with storage...");
let serving = server::serve(read_store.clone());
+
whatever_tasks.spawn(async move {
+
serving.await.map_err(|e| {
+
log::warn!("server ended: {e}");
+
anyhow::anyhow!(e)
+
})
+
});
if args.pause_writer {
log::info!("not starting jetstream or the write loop.");
-
serving.await.map_err(|e| anyhow::anyhow!(e))?;
+
for t in whatever_tasks.join_all().await {
+
if let Err(e) = t {
+
return Err(anyhow::anyhow!(e));
+
}
+
}
return Ok(());
}
···
let rolling = write_store
.background_tasks(args.reroll)?
.run(args.backfill);
-
let consuming = write_store.receive_batches(batches);
+
whatever_tasks.spawn(async move {
+
rolling
+
.await
+
.inspect_err(|e| log::warn!("rollup ended: {e}"))?;
+
Ok(())
+
});
-
let stating = do_update_stuff(read_store);
+
consumer_tasks.spawn(async move {
+
write_store
+
.receive_batches(batches)
+
.await
+
.inspect_err(|e| log::warn!("consumer ended: {e}"))?;
+
Ok(())
+
});
-
tokio::select! {
-
z = serving => log::warn!("serve task ended: {z:?}"),
-
z = rolling => log::warn!("rollup task ended: {z:?}"),
-
z = consuming => log::warn!("consuming task ended: {z:?}"),
-
z = stating => log::warn!("status task ended: {z:?}"),
-
};
+
whatever_tasks.spawn(async move {
+
do_update_stuff(read_store).await;
+
log::warn!("status task ended");
+
Ok(())
+
});
+
+
install_metrics_server()?;
+
+
for (i, t) in consumer_tasks.join_all().await.iter().enumerate() {
+
log::warn!("task {i} done: {t:?}");
+
}
+
+
println!("consumer tasks all completed, killing the others");
+
whatever_tasks.shutdown().await;
println!("bye!");
Ok(())
}
+
fn install_metrics_server() -> anyhow::Result<()> {
+
log::info!("installing metrics server...");
+
let host = [0, 0, 0, 0];
+
let port = 8765;
+
PrometheusBuilder::new()
+
.set_quantiles(&[0.5, 0.9, 0.99, 1.0])?
+
.set_bucket_duration(Duration::from_secs(60))?
+
.set_bucket_count(std::num::NonZero::new(10).unwrap()) // count * duration = 10 mins. stuff doesn't happen that fast here.
+
.set_enable_unit_suffix(false) // this seemed buggy for constellation (sometimes wouldn't engage)
+
.with_http_listener((host, port))
+
.install()?;
+
log::info!(
+
"metrics server installed! listening on http://{}.{}.{}.{}:{port}",
+
host[0],
+
host[1],
+
host[2],
+
host[3]
+
);
+
Ok(())
+
}
+
async fn do_update_stuff(read_store: impl StoreReader) {
+
describe_gauge!(
+
"persisted_cursor_age",
+
Unit::Microseconds,
+
"microseconds between our clock and the latest persisted event's cursor"
+
);
+
describe_gauge!(
+
"rollup_cursor_age",
+
Unit::Microseconds,
+
"microseconds between our clock and the latest rollup cursor"
+
);
let started_at = std::time::SystemTime::now();
let mut first_cursor = None;
let mut first_rollup = None;
···
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
loop {
interval.tick().await;
+
read_store.update_metrics();
match read_store.get_consumer_info().await {
Err(e) => log::warn!("failed to get jetstream consumer info: {e:?}"),
Ok(ConsumerInfo::Jetstream {
···
started_at: SystemTime,
now: SystemTime,
) {
+
if let Some(cursor) = latest_cursor {
+
gauge!("persisted_cursor_age").set(cursor.elapsed_micros_f64());
+
}
+
if let Some(cursor) = rollup_cursor {
+
gauge!("rollup_cursor_age").set(cursor.elapsed_micros_f64());
+
}
+
let nice_dt_two_maybes = |earlier: Option<Cursor>, later: Option<Cursor>| match (earlier, later)
{
(Some(earlier), Some(later)) => match later.duration_since(&earlier) {
···
let rollup_rate = rate(rollup_cursor, last_rollup, dt_real);
let rollup_avg = rate(rollup_cursor, first_rollup, dt_real_total);
-
log::info!(
+
log::trace!(
"cursor: {} behind (→{}, {cursor_rate}x, {cursor_avg}x avg). rollup: {} behind (→{}, {rollup_rate}x, {rollup_avg}x avg).",
latest_cursor.map(|c| c.elapsed().map(nice_duration).unwrap_or("++".to_string())).unwrap_or("?".to_string()),
nice_dt_two_maybes(last_cursor, latest_cursor),
+1 -1
ufos/src/server/collections_query.rs
···
) -> Result<MultiCollectionQuery, HttpError> {
let raw_query = ctx.request.uri().query().unwrap_or("");
let q = serde_qs::from_str(raw_query).map_err(|e| {
-
HttpError::for_bad_request(None, format!("unable to parse query string: {}", e))
+
HttpError::for_bad_request(None, format!("unable to parse query string: {e}"))
})?;
Ok(q)
}
+310 -181
ufos/src/server/mod.rs
···
use dropshot::ConfigLogging;
use dropshot::ConfigLoggingLevel;
use dropshot::HttpError;
+
use dropshot::HttpResponse;
use dropshot::Query;
use dropshot::RequestContext;
use dropshot::ServerBuilder;
-
-
use http::{Response, StatusCode};
+
use dropshot::ServerContext;
+
use http::{
+
header::{ORIGIN, USER_AGENT},
+
Response, StatusCode,
+
};
+
use metrics::{counter, describe_counter, describe_histogram, histogram, Unit};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
+
use std::future::Future;
use std::sync::Arc;
+
use std::time::Instant;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
+
fn describe_metrics() {
+
describe_counter!(
+
"server_requests_total",
+
Unit::Count,
+
"total requests handled"
+
);
+
describe_histogram!(
+
"server_handler_latency",
+
Unit::Microseconds,
+
"time to respond to a request in microseconds, excluding dropshot overhead"
+
);
+
}
+
+
async fn instrument_handler<T, H, R>(ctx: &RequestContext<T>, handler: H) -> Result<R, HttpError>
+
where
+
R: HttpResponse,
+
H: Future<Output = Result<R, HttpError>>,
+
T: ServerContext,
+
{
+
let start = Instant::now();
+
let result = handler.await;
+
let latency = start.elapsed();
+
let status_code = match &result {
+
Ok(response) => response.status_code(),
+
Err(ref e) => e.status_code.as_status(),
+
}
+
.as_str() // just the number (.to_string()'s Display does eg `200 OK`)
+
.to_string();
+
let endpoint = ctx.endpoint.operation_id.clone();
+
let headers = ctx.request.headers();
+
let origin = headers
+
.get(ORIGIN)
+
.and_then(|v| v.to_str().ok())
+
.unwrap_or("")
+
.to_string();
+
let ua = headers
+
.get(USER_AGENT)
+
.and_then(|v| v.to_str().ok())
+
.map(|ua| {
+
if ua.starts_with("Mozilla/5.0 ") {
+
"browser"
+
} else {
+
ua
+
}
+
})
+
.unwrap_or("")
+
.to_string();
+
counter!("server_requests_total",
+
"endpoint" => endpoint.clone(),
+
"origin" => origin,
+
"ua" => ua,
+
"status_code" => status_code,
+
)
+
.increment(1);
+
histogram!("server_handler_latency", "endpoint" => endpoint).record(latency.as_micros() as f64);
+
result
+
}
+
struct Context {
pub spec: Arc<serde_json::Value>,
storage: Box<dyn StoreReader>,
···
*/
unpublished = true,
}]
-
async fn index(_ctx: RequestContext<Context>) -> Result<Response<Body>, HttpError> {
-
Ok(Response::builder()
-
.status(StatusCode::OK)
-
.header(http::header::CONTENT_TYPE, "text/html")
-
.body(INDEX_HTML.into())?)
+
async fn index(ctx: RequestContext<Context>) -> Result<Response<Body>, HttpError> {
+
instrument_handler(&ctx, async {
+
Ok(Response::builder()
+
.status(StatusCode::OK)
+
.header(http::header::CONTENT_TYPE, "text/html")
+
.body(INDEX_HTML.into())?)
+
})
+
.await
}
/// Meta: get the openapi spec for this api
···
unpublished = true,
}]
async fn get_openapi(ctx: RequestContext<Context>) -> OkCorsResponse<serde_json::Value> {
-
let spec = (*ctx.context().spec).clone();
-
OkCors(spec).into()
+
instrument_handler(&ctx, async {
+
let spec = (*ctx.context().spec).clone();
+
OkCors(spec).into()
+
})
+
.await
}
#[derive(Debug, Serialize, JsonSchema)]
···
let failed_to_get =
|what| move |e| HttpError::for_internal_error(format!("failed to get {what}: {e:?}"));
-
let storage_info = storage
-
.get_storage_stats()
-
.await
-
.map_err(failed_to_get("storage info"))?;
+
instrument_handler(&ctx, async {
+
let storage_info = storage
+
.get_storage_stats()
+
.await
+
.map_err(failed_to_get("storage info"))?;
-
let consumer = storage
-
.get_consumer_info()
-
.await
-
.map_err(failed_to_get("consumer info"))?;
+
let consumer = storage
+
.get_consumer_info()
+
.await
+
.map_err(failed_to_get("consumer info"))?;
-
OkCors(MetaInfo {
-
storage_name: storage.name(),
-
storage: storage_info,
-
consumer,
+
OkCors(MetaInfo {
+
storage_name: storage.name(),
+
storage: storage_info,
+
consumer,
+
})
+
.into()
})
-
.into()
+
.await
}
// TODO: replace with normal (🙃) multi-qs value somehow
···
collection_query: Query<RecordsCollectionsQuery>,
) -> OkCorsResponse<Vec<ApiRecord>> {
let Context { storage, .. } = ctx.context();
-
let mut limit = 42;
-
let query = collection_query.into_inner();
-
let collections = if let Some(provided_collection) = query.collection {
-
to_multiple_nsids(&provided_collection)
-
.map_err(|reason| HttpError::for_bad_request(None, reason))?
-
} else {
-
limit = 12;
-
let min_time_ago = SystemTime::now() - Duration::from_secs(86_400 * 3); // we want at least 3 days of data
-
let since: WeekTruncatedCursor = Cursor::at(min_time_ago).into();
-
let (collections, _) = storage
-
.get_collections(
-
1000,
-
Default::default(),
-
Some(since.try_as().unwrap()),
-
None,
-
)
+
instrument_handler(&ctx, async {
+
let mut limit = 42;
+
let query = collection_query.into_inner();
+
let collections = if let Some(provided_collection) = query.collection {
+
to_multiple_nsids(&provided_collection)
+
.map_err(|reason| HttpError::for_bad_request(None, reason))?
+
} else {
+
limit = 12;
+
let min_time_ago = SystemTime::now() - Duration::from_secs(86_400 * 3); // we want at least 3 days of data
+
let since: WeekTruncatedCursor = Cursor::at(min_time_ago).into();
+
let (collections, _) = storage
+
.get_collections(
+
1000,
+
Default::default(),
+
Some(since.try_as().unwrap()),
+
None,
+
)
+
.await
+
.map_err(|e| HttpError::for_internal_error(e.to_string()))?;
+
collections
+
.into_iter()
+
.map(|c| Nsid::new(c.nsid).unwrap())
+
.collect()
+
};
+
+
let records = storage
+
.get_records_by_collections(collections, limit, true)
.await
-
.map_err(|e| HttpError::for_internal_error(e.to_string()))?;
-
collections
+
.map_err(|e| HttpError::for_internal_error(e.to_string()))?
.into_iter()
-
.map(|c| Nsid::new(c.nsid).unwrap())
-
.collect()
-
};
+
.map(|r| r.into())
+
.collect();
-
let records = storage
-
.get_records_by_collections(collections, limit, true)
-
.await
-
.map_err(|e| HttpError::for_internal_error(e.to_string()))?
-
.into_iter()
-
.map(|r| r.into())
-
.collect();
-
-
OkCors(records).into()
+
OkCors(records).into()
+
})
+
.await
}
#[derive(Debug, Deserialize, JsonSchema)]
···
query: Query<CollectionsStatsQuery>,
) -> OkCorsResponse<HashMap<String, JustCount>> {
let Context { storage, .. } = ctx.context();
-
let q = query.into_inner();
-
let collections: HashSet<Nsid> = collections_query.try_into()?;
+
+
instrument_handler(&ctx, async {
+
let q = query.into_inner();
+
let collections: HashSet<Nsid> = collections_query.try_into()?;
-
let since = q.since.map(dt_to_cursor).transpose()?.unwrap_or_else(|| {
-
let week_ago_secs = 7 * 86_400;
-
let week_ago = SystemTime::now() - Duration::from_secs(week_ago_secs);
-
Cursor::at(week_ago).into()
-
});
+
let since = q.since.map(dt_to_cursor).transpose()?.unwrap_or_else(|| {
+
let week_ago_secs = 7 * 86_400;
+
let week_ago = SystemTime::now() - Duration::from_secs(week_ago_secs);
+
Cursor::at(week_ago).into()
+
});
-
let until = q.until.map(dt_to_cursor).transpose()?;
+
let until = q.until.map(dt_to_cursor).transpose()?;
-
let mut seen_by_collection = HashMap::with_capacity(collections.len());
+
let mut seen_by_collection = HashMap::with_capacity(collections.len());
-
for collection in &collections {
-
let counts = storage
-
.get_collection_counts(collection, since, until)
-
.await
-
.map_err(|e| HttpError::for_internal_error(format!("boooo: {e:?}")))?;
+
for collection in &collections {
+
let counts = storage
+
.get_collection_counts(collection, since, until)
+
.await
+
.map_err(|e| HttpError::for_internal_error(format!("boooo: {e:?}")))?;
-
seen_by_collection.insert(collection.to_string(), counts);
-
}
+
seen_by_collection.insert(collection.to_string(), counts);
+
}
-
OkCors(seen_by_collection).into()
+
OkCors(seen_by_collection).into()
+
})
+
.await
}
#[derive(Debug, Serialize, JsonSchema)]
···
let Context { storage, .. } = ctx.context();
let q = query.into_inner();
-
if q.cursor.is_some() && q.order.is_some() {
-
let msg = "`cursor` is mutually exclusive with `order`. ordered results cannot be paged.";
-
return Err(HttpError::for_bad_request(None, msg.to_string()));
-
}
+
instrument_handler(&ctx, async {
+
if q.cursor.is_some() && q.order.is_some() {
+
let msg =
+
"`cursor` is mutually exclusive with `order`. ordered results cannot be paged.";
+
return Err(HttpError::for_bad_request(None, msg.to_string()));
+
}
-
let order = if let Some(ref o) = q.order {
-
o.into()
-
} else {
-
let cursor = q
-
.cursor
-
.and_then(|c| if c.is_empty() { None } else { Some(c) })
-
.map(|c| URL_SAFE_NO_PAD.decode(&c))
-
.transpose()
-
.map_err(|e| HttpError::for_bad_request(None, format!("invalid cursor: {e:?}")))?;
-
OrderCollectionsBy::Lexi { cursor }
-
};
+
let order = if let Some(ref o) = q.order {
+
o.into()
+
} else {
+
let cursor = q
+
.cursor
+
.and_then(|c| if c.is_empty() { None } else { Some(c) })
+
.map(|c| URL_SAFE_NO_PAD.decode(&c))
+
.transpose()
+
.map_err(|e| HttpError::for_bad_request(None, format!("invalid cursor: {e:?}")))?;
+
OrderCollectionsBy::Lexi { cursor }
+
};
-
let limit = match (q.limit, q.order) {
-
(Some(limit), _) => limit,
-
(None, Some(_)) => 32,
-
(None, None) => 100,
-
};
+
let limit = match (q.limit, q.order) {
+
(Some(limit), _) => limit,
+
(None, Some(_)) => 32,
+
(None, None) => 100,
+
};
-
if !(1..=200).contains(&limit) {
-
let msg = format!("limit not in 1..=200: {}", limit);
-
return Err(HttpError::for_bad_request(None, msg));
-
}
+
if !(1..=200).contains(&limit) {
+
let msg = format!("limit not in 1..=200: {limit}");
+
return Err(HttpError::for_bad_request(None, msg));
+
}
-
let since = q.since.map(dt_to_cursor).transpose()?;
-
let until = q.until.map(dt_to_cursor).transpose()?;
+
let since = q.since.map(dt_to_cursor).transpose()?;
+
let until = q.until.map(dt_to_cursor).transpose()?;
-
let (collections, next_cursor) = storage
-
.get_collections(limit, order, since, until)
-
.await
-
.map_err(|e| HttpError::for_internal_error(format!("oh shoot: {e:?}")))?;
+
let (collections, next_cursor) = storage
+
.get_collections(limit, order, since, until)
+
.await
+
.map_err(|e| HttpError::for_internal_error(format!("oh shoot: {e:?}")))?;
-
let next_cursor = next_cursor.map(|c| URL_SAFE_NO_PAD.encode(c));
+
let next_cursor = next_cursor.map(|c| URL_SAFE_NO_PAD.encode(c));
-
OkCors(CollectionsResponse {
-
collections,
-
cursor: next_cursor,
+
OkCors(CollectionsResponse {
+
collections,
+
cursor: next_cursor,
+
})
+
.into()
})
-
.into()
+
.await
}
#[derive(Debug, Serialize, JsonSchema)]
···
let Context { storage, .. } = ctx.context();
let q = query.into_inner();
-
let prefix = NsidPrefix::new(&q.prefix).map_err(|e| {
-
HttpError::for_bad_request(
-
None,
-
format!("{:?} was not a valid NSID prefix: {e:?}", q.prefix),
-
)
-
})?;
+
instrument_handler(&ctx, async {
+
let prefix = NsidPrefix::new(&q.prefix).map_err(|e| {
+
HttpError::for_bad_request(
+
None,
+
format!("{:?} was not a valid NSID prefix: {e:?}", q.prefix),
+
)
+
})?;
-
if q.cursor.is_some() && q.order.is_some() {
-
let msg = "`cursor` is mutually exclusive with `order`. ordered results cannot be paged.";
-
return Err(HttpError::for_bad_request(None, msg.to_string()));
-
}
+
if q.cursor.is_some() && q.order.is_some() {
+
let msg =
+
"`cursor` is mutually exclusive with `order`. ordered results cannot be paged.";
+
return Err(HttpError::for_bad_request(None, msg.to_string()));
+
}
-
let order = if let Some(ref o) = q.order {
-
o.into()
-
} else {
-
let cursor = q
-
.cursor
-
.and_then(|c| if c.is_empty() { None } else { Some(c) })
-
.map(|c| URL_SAFE_NO_PAD.decode(&c))
-
.transpose()
-
.map_err(|e| HttpError::for_bad_request(None, format!("invalid cursor: {e:?}")))?;
-
OrderCollectionsBy::Lexi { cursor }
-
};
+
let order = if let Some(ref o) = q.order {
+
o.into()
+
} else {
+
let cursor = q
+
.cursor
+
.and_then(|c| if c.is_empty() { None } else { Some(c) })
+
.map(|c| URL_SAFE_NO_PAD.decode(&c))
+
.transpose()
+
.map_err(|e| HttpError::for_bad_request(None, format!("invalid cursor: {e:?}")))?;
+
OrderCollectionsBy::Lexi { cursor }
+
};
-
let limit = match (q.limit, q.order) {
-
(Some(limit), _) => limit,
-
(None, Some(_)) => 32,
-
(None, None) => 100,
-
};
+
let limit = match (q.limit, q.order) {
+
(Some(limit), _) => limit,
+
(None, Some(_)) => 32,
+
(None, None) => 100,
+
};
-
if !(1..=200).contains(&limit) {
-
let msg = format!("limit not in 1..=200: {}", limit);
-
return Err(HttpError::for_bad_request(None, msg));
-
}
+
if !(1..=200).contains(&limit) {
+
let msg = format!("limit not in 1..=200: {limit}");
+
return Err(HttpError::for_bad_request(None, msg));
+
}
-
let since = q.since.map(dt_to_cursor).transpose()?;
-
let until = q.until.map(dt_to_cursor).transpose()?;
+
let since = q.since.map(dt_to_cursor).transpose()?;
+
let until = q.until.map(dt_to_cursor).transpose()?;
-
let (total, children, next_cursor) = storage
-
.get_prefix(prefix, limit, order, since, until)
-
.await
-
.map_err(|e| HttpError::for_internal_error(format!("oh shoot: {e:?}")))?;
+
let (total, children, next_cursor) = storage
+
.get_prefix(prefix, limit, order, since, until)
+
.await
+
.map_err(|e| HttpError::for_internal_error(format!("oh shoot: {e:?}")))?;
-
let next_cursor = next_cursor.map(|c| URL_SAFE_NO_PAD.encode(c));
+
let next_cursor = next_cursor.map(|c| URL_SAFE_NO_PAD.encode(c));
-
OkCors(PrefixResponse {
-
total,
-
children,
-
cursor: next_cursor,
+
OkCors(PrefixResponse {
+
total,
+
children,
+
cursor: next_cursor,
+
})
+
.into()
})
-
.into()
+
.await
}
#[derive(Debug, Deserialize, JsonSchema)]
···
let Context { storage, .. } = ctx.context();
let q = query.into_inner();
-
let since = q.since.map(dt_to_cursor).transpose()?.unwrap_or_else(|| {
-
let week_ago_secs = 7 * 86_400;
-
let week_ago = SystemTime::now() - Duration::from_secs(week_ago_secs);
-
Cursor::at(week_ago).into()
-
});
+
instrument_handler(&ctx, async {
+
let since = q.since.map(dt_to_cursor).transpose()?.unwrap_or_else(|| {
+
let week_ago_secs = 7 * 86_400;
+
let week_ago = SystemTime::now() - Duration::from_secs(week_ago_secs);
+
Cursor::at(week_ago).into()
+
});
-
let until = q.until.map(dt_to_cursor).transpose()?;
+
let until = q.until.map(dt_to_cursor).transpose()?;
-
let step = if let Some(secs) = q.step {
-
if secs < 3600 {
-
let msg = format!("step is too small: {}", secs);
-
Err(HttpError::for_bad_request(None, msg))?;
-
}
-
(secs / 3600) * 3600 // trucate to hour
-
} else {
-
86_400
-
};
+
let step = if let Some(secs) = q.step {
+
if secs < 3600 {
+
let msg = format!("step is too small: {secs}");
+
Err(HttpError::for_bad_request(None, msg))?;
+
}
+
(secs / 3600) * 3600 // trucate to hour
+
} else {
+
86_400
+
};
-
let nsid = Nsid::new(q.collection).map_err(|e| {
-
HttpError::for_bad_request(None, format!("collection was not a valid NSID: {:?}", e))
-
})?;
+
let nsid = Nsid::new(q.collection).map_err(|e| {
+
HttpError::for_bad_request(None, format!("collection was not a valid NSID: {e:?}"))
+
})?;
-
let (range_cursors, series) = storage
-
.get_timeseries(vec![nsid], since, until, step)
-
.await
-
.map_err(|e| HttpError::for_internal_error(format!("oh shoot: {e:?}")))?;
+
let (range_cursors, series) = storage
+
.get_timeseries(vec![nsid], since, until, step)
+
.await
+
.map_err(|e| HttpError::for_internal_error(format!("oh shoot: {e:?}")))?;
-
let range = range_cursors
-
.into_iter()
-
.map(|c| DateTime::<Utc>::from_timestamp_micros(c.to_raw_u64() as i64).unwrap())
-
.collect();
+
let range = range_cursors
+
.into_iter()
+
.map(|c| DateTime::<Utc>::from_timestamp_micros(c.to_raw_u64() as i64).unwrap())
+
.collect();
-
let series = series
-
.into_iter()
-
.map(|(k, v)| (k.to_string(), v.iter().map(Into::into).collect()))
-
.collect();
+
let series = series
+
.into_iter()
+
.map(|(k, v)| (k.to_string(), v.iter().map(Into::into).collect()))
+
.collect();
+
+
OkCors(CollectionTimeseriesResponse { range, series }).into()
+
})
+
.await
+
}
-
OkCors(CollectionTimeseriesResponse { range, series }).into()
+
#[derive(Debug, Deserialize, JsonSchema)]
+
struct SearchQuery {
+
/// Query
+
///
+
/// at least two alphanumeric (+hyphen) characters must be present
+
q: String,
+
}
+
#[derive(Debug, Serialize, JsonSchema)]
+
struct SearchResponse {
+
matches: Vec<NsidCount>,
+
}
+
/// Search lexicons
+
#[endpoint {
+
method = GET,
+
path = "/search"
+
}]
+
async fn search_collections(
+
ctx: RequestContext<Context>,
+
query: Query<SearchQuery>,
+
) -> OkCorsResponse<SearchResponse> {
+
let Context { storage, .. } = ctx.context();
+
let q = query.into_inner();
+
instrument_handler(&ctx, async {
+
// TODO: query validation
+
// TODO: also handle multi-space stuff (ufos-app tries to on client)
+
let terms: Vec<String> = q.q.split(' ').map(Into::into).collect();
+
let matches = storage
+
.search_collections(terms)
+
.await
+
.map_err(|e| HttpError::for_internal_error(format!("oh ugh: {e:?}")))?;
+
OkCors(SearchResponse { matches }).into()
+
})
+
.await
}
pub async fn serve(storage: impl StoreReader + 'static) -> Result<(), String> {
+
describe_metrics();
let log = ConfigLogging::StderrTerminal {
-
level: ConfigLoggingLevel::Info,
+
level: ConfigLoggingLevel::Warn,
}
-
.to_logger("hello-ufos")
+
.to_logger("server")
.map_err(|e| e.to_string())?;
let mut api = ApiDescription::new();
···
api.register(get_collections).unwrap();
api.register(get_prefix).unwrap();
api.register(get_timeseries).unwrap();
+
api.register(search_collections).unwrap();
let context = Context {
spec: Arc::new(
api.openapi(
-
"UFOs: Every lexicon in the ATmosphere",
+
"UFOs API: Every lexicon in the ATmosphere",
env!("CARGO_PKG_VERSION")
.parse()
.inspect_err(|e| {
···
..Default::default()
})
.start()
-
.map_err(|error| format!("failed to start server: {}", error))?
+
.map_err(|error| format!("failed to start server: {error}"))?
.await
}
+26 -5
ufos/src/storage.rs
···
};
use async_trait::async_trait;
use jetstream::exports::{Did, Nsid};
+
use metrics::{describe_histogram, histogram, Unit};
use std::collections::{HashMap, HashSet};
use std::path::Path;
-
use std::time::{Duration, SystemTime};
+
use std::time::{Duration, Instant};
use tokio::sync::mpsc::Receiver;
use tokio_util::sync::CancellationToken;
···
self,
mut batches: Receiver<EventBatch<LIMIT>>,
) -> StorageResult<()> {
+
describe_histogram!(
+
"storage_slow_batches",
+
Unit::Microseconds,
+
"batches that took more than 3s to insert"
+
);
+
describe_histogram!(
+
"storage_batch_insert_time",
+
Unit::Microseconds,
+
"total time to insert one commit batch"
+
);
while let Some(event_batch) = batches.recv().await {
let token = CancellationToken::new();
let cancelled = token.clone();
tokio::spawn(async move {
-
let started = SystemTime::now();
+
let started = Instant::now();
let mut concerned = false;
loop {
tokio::select! {
-
_ = tokio::time::sleep(Duration::from_secs_f64(3.)) => {
-
log::warn!("taking a long time to insert an event batch ({:?})...", started.elapsed());
+
_ = tokio::time::sleep(Duration::from_secs(3)) => {
+
if !concerned {
+
log::warn!("taking a long time to insert an event batch...");
+
}
concerned = true;
}
_ = cancelled.cancelled() => {
if concerned {
log::warn!("finally inserted slow event batch (or failed) after {:?}", started.elapsed());
+
histogram!("storage_slow_batches").record(started.elapsed().as_micros() as f64);
}
break
}
···
let mut me = self.clone();
move || {
let _guard = token.drop_guard();
-
me.insert_batch(event_batch)
+
let t0 = Instant::now();
+
let r = me.insert_batch(event_batch);
+
histogram!("storage_batch_insert_time").record(t0.elapsed().as_micros() as f64);
+
r
}
})
.await??;
···
#[async_trait]
pub trait StoreReader: Send + Sync {
fn name(&self) -> String;
+
+
fn update_metrics(&self) {}
async fn get_storage_stats(&self) -> StorageResult<serde_json::Value>;
···
limit: usize,
expand_each_collection: bool,
) -> StorageResult<Vec<UFOsRecord>>;
+
+
async fn search_collections(&self, terms: Vec<String>) -> StorageResult<Vec<NsidCount>>;
}
+182 -54
ufos/src/storage_fjall.rs
···
Batch as FjallBatch, Config, Keyspace, PartitionCreateOptions, PartitionHandle, Snapshot,
};
use jetstream::events::Cursor;
+
use lsm_tree::AbstractTree;
+
use metrics::{
+
counter, describe_counter, describe_gauge, describe_histogram, gauge, histogram, Unit,
+
};
use std::collections::{HashMap, HashSet};
use std::iter::Peekable;
use std::ops::Bound;
···
///
/// new data format, roughly:
///
-
/// Partion: 'global'
+
/// Partition: 'global'
///
/// - Global sequence counter (is the jetstream cursor -- monotonic with many gaps)
/// - key: "js_cursor" (literal)
···
feeds: feeds.clone(),
records: records.clone(),
rollups: rollups.clone(),
+
queues: queues.clone(),
};
+
reader.describe_metrics();
let writer = FjallWriter {
bg_taken: Arc::new(AtomicBool::new(false)),
keyspace,
···
rollups,
queues,
};
+
writer.describe_metrics();
Ok((reader, writer, js_cursor, sketch_secret))
}
}
···
feeds: PartitionHandle,
records: PartitionHandle,
rollups: PartitionHandle,
+
queues: PartitionHandle,
}
/// An iterator that knows how to skip over deleted/invalidated records
···
type CollectionSerieses = HashMap<Nsid, Vec<CountsValue>>;
impl FjallReader {
+
fn describe_metrics(&self) {
+
describe_gauge!(
+
"storage_fjall_l0_run_count",
+
Unit::Count,
+
"number of L0 runs in a partition"
+
);
+
describe_gauge!(
+
"storage_fjall_keyspace_disk_space",
+
Unit::Bytes,
+
"total storage used according to fjall"
+
);
+
describe_gauge!(
+
"storage_fjall_journal_count",
+
Unit::Count,
+
"total keyspace journals according to fjall"
+
);
+
describe_gauge!(
+
"storage_fjall_keyspace_sequence",
+
Unit::Count,
+
"fjall keyspace sequence"
+
);
+
}
+
fn get_storage_stats(&self) -> StorageResult<serde_json::Value> {
let rollup_cursor =
get_static_neu::<NewRollupCursorKey, NewRollupCursorValue>(&self.global)?
···
merged.merge(&counts);
}
}
-
out.push(NsidCount {
-
nsid: nsid.to_string(),
-
creates: merged.counts().creates,
-
dids_estimate: merged.dids().estimate() as u64,
-
});
+
out.push(NsidCount::new(&nsid, &merged));
}
let next_cursor = current_nsid.map(|s| s.to_db_bytes()).transpose()?;
···
.into_iter()
.rev()
.take(limit)
-
.map(|(nsid, cv)| NsidCount {
-
nsid: nsid.to_string(),
-
creates: cv.counts().creates,
-
dids_estimate: cv.dids().estimate() as u64,
-
})
+
.map(|(nsid, cv)| NsidCount::new(&nsid, &cv))
.collect();
Ok(counts)
}
···
let mut prefix_count = CountsValue::default();
#[derive(Debug, Clone, PartialEq)]
enum Child {
-
FullNsid(String),
+
FullNsid(Nsid),
ChildPrefix(String),
}
impl Child {
fn from_prefix(nsid: &Nsid, prefix: &NsidPrefix) -> Option<Self> {
if prefix.is_group_of(nsid) {
-
return Some(Child::FullNsid(nsid.to_string()));
+
return Some(Child::FullNsid(nsid.clone()));
}
let suffix = nsid.as_str().strip_prefix(&format!("{}.", prefix.0))?;
let (segment, _) = suffix.split_once('.').unwrap();
···
}
fn is_before(&self, other: &Child) -> bool {
match (self, other) {
-
(Child::FullNsid(s), Child::ChildPrefix(o)) if s == o => true,
-
(Child::ChildPrefix(s), Child::FullNsid(o)) if s == o => false,
-
(Child::FullNsid(s), Child::FullNsid(o)) => s < o,
+
(Child::FullNsid(s), Child::ChildPrefix(o)) if s.as_str() == o => true,
+
(Child::ChildPrefix(s), Child::FullNsid(o)) if s == o.as_str() => false,
+
(Child::FullNsid(s), Child::FullNsid(o)) => s.as_str() < o.as_str(),
(Child::ChildPrefix(s), Child::ChildPrefix(o)) => s < o,
-
(Child::FullNsid(s), Child::ChildPrefix(o)) => s < o,
-
(Child::ChildPrefix(s), Child::FullNsid(o)) => s < o,
+
(Child::FullNsid(s), Child::ChildPrefix(o)) => s.to_string() < *o,
+
(Child::ChildPrefix(s), Child::FullNsid(o)) => *s < o.to_string(),
}
}
fn into_inner(self) -> String {
match self {
-
Child::FullNsid(s) => s,
+
Child::FullNsid(s) => s.to_string(),
Child::ChildPrefix(s) => s,
}
}
···
}
}
items.push(match child {
-
Child::FullNsid(nsid) => PrefixChild::Collection(NsidCount {
-
nsid,
-
creates: merged.counts().creates,
-
dids_estimate: merged.dids().estimate() as u64,
-
}),
-
Child::ChildPrefix(prefix) => PrefixChild::Prefix(PrefixCount {
-
prefix,
-
creates: merged.counts().creates,
-
dids_estimate: merged.dids().estimate() as u64,
-
}),
+
Child::FullNsid(nsid) => PrefixChild::Collection(NsidCount::new(&nsid, &merged)),
+
Child::ChildPrefix(prefix) => {
+
PrefixChild::Prefix(PrefixCount::new(&prefix, &merged))
+
}
});
}
···
}
Ok(merged)
}
+
+
fn search_collections(&self, terms: Vec<String>) -> StorageResult<Vec<NsidCount>> {
+
let start = AllTimeRollupKey::start()?;
+
let end = AllTimeRollupKey::end()?;
+
let mut matches = Vec::new();
+
let limit = 16; // TODO: param
+
for kv in self.rollups.range((start, end)) {
+
let (key_bytes, val_bytes) = kv?;
+
let key = db_complete::<AllTimeRollupKey>(&key_bytes)?;
+
let nsid = key.collection();
+
for term in &terms {
+
if nsid.contains(term) {
+
let counts = db_complete::<CountsValue>(&val_bytes)?;
+
matches.push(NsidCount::new(nsid, &counts));
+
break;
+
}
+
}
+
if matches.len() >= limit {
+
break;
+
}
+
}
+
// TODO: indicate incomplete results
+
Ok(matches)
+
}
}
#[async_trait]
impl StoreReader for FjallReader {
fn name(&self) -> String {
"fjall storage v2".into()
+
}
+
fn update_metrics(&self) {
+
gauge!("storage_fjall_l0_run_count", "partition" => "global")
+
.set(self.global.tree.l0_run_count() as f64);
+
gauge!("storage_fjall_l0_run_count", "partition" => "feeds")
+
.set(self.feeds.tree.l0_run_count() as f64);
+
gauge!("storage_fjall_l0_run_count", "partition" => "records")
+
.set(self.records.tree.l0_run_count() as f64);
+
gauge!("storage_fjall_l0_run_count", "partition" => "rollups")
+
.set(self.rollups.tree.l0_run_count() as f64);
+
gauge!("storage_fjall_l0_run_count", "partition" => "queues")
+
.set(self.queues.tree.l0_run_count() as f64);
+
gauge!("storage_fjall_keyspace_disk_space").set(self.keyspace.disk_space() as f64);
+
gauge!("storage_fjall_journal_count").set(self.keyspace.journal_count() as f64);
+
gauge!("storage_fjall_keyspace_sequence").set(self.keyspace.instant() as f64);
}
async fn get_storage_stats(&self) -> StorageResult<serde_json::Value> {
let s = self.clone();
···
FjallReader::get_records_by_collections(&s, collections, limit, expand_each_collection)
})
.await?
+
}
+
async fn search_collections(&self, terms: Vec<String>) -> StorageResult<Vec<NsidCount>> {
+
let s = self.clone();
+
tokio::task::spawn_blocking(move || FjallReader::search_collections(&s, terms)).await?
···
impl FjallWriter {
+
fn describe_metrics(&self) {
+
describe_histogram!(
+
"storage_insert_batch_db_batch_items",
+
Unit::Count,
+
"how many items are in the fjall batch for batched inserts"
+
);
+
describe_histogram!(
+
"storage_rollup_counts_db_batch_items",
+
Unit::Count,
+
"how many items are in the fjall batch for a timlies rollup"
+
);
+
describe_counter!(
+
"storage_delete_account_partial_commits",
+
Unit::Count,
+
"fjall checkpoint commits for cleaning up accounts with too many records"
+
);
+
describe_counter!(
+
"storage_delete_account_completions",
+
Unit::Count,
+
"total count of account deletes handled"
+
);
+
describe_counter!(
+
"storage_delete_account_records_deleted",
+
Unit::Count,
+
"total records deleted when handling account deletes"
+
);
+
describe_histogram!(
+
"storage_trim_dirty_nsids",
+
Unit::Count,
+
"number of NSIDs trimmed"
+
);
+
describe_histogram!(
+
"storage_trim_duration",
+
Unit::Microseconds,
+
"how long it took to trim the dirty NSIDs"
+
);
+
describe_counter!(
+
"storage_trim_removed",
+
Unit::Count,
+
"how many records were removed during trim"
+
);
+
}
fn rollup_delete_account(
&mut self,
cursor: Cursor,
···
AllTimeRecordsKey::new(new_creates_count.into(), &nsid).to_db_bytes()?,
),
};
-
batch.remove(&self.rollups, &old_k); // TODO: when fjall gets weak delete, this will hopefully work way better
+
// remove_weak is allowed here because the secondary ranking index only ever inserts once at a key
+
batch.remove_weak(&self.rollups, &old_k);
batch.insert(&self.rollups, &new_k, "");
···
AllTimeDidsKey::new(new_dids_estimate.into(), &nsid).to_db_bytes()?,
),
};
-
batch.remove(&self.rollups, &old_k); // TODO: when fjall gets weak delete, this will hopefully work way better
+
// remove_weak is allowed here because the secondary ranking index only ever inserts once at a key
+
batch.remove_weak(&self.rollups, &old_k);
batch.insert(&self.rollups, &new_k, "");
···
insert_batch_static_neu::<NewRollupCursorKey>(&mut batch, &self.global, last_cursor)?;
+
histogram!("storage_rollup_counts_db_batch_items").record(batch.len() as f64);
batch.commit()?;
Ok((cursors_advanced, dirty_nsids))
···
impl StoreWriter<FjallBackground> for FjallWriter {
fn background_tasks(&mut self, reroll: bool) -> StorageResult<FjallBackground> {
if self.bg_taken.swap(true, Ordering::SeqCst) {
-
Err(StorageError::BackgroundAlreadyStarted)
-
} else {
-
if reroll {
-
log::info!("reroll: resetting rollup cursor...");
-
insert_static_neu::<NewRollupCursorKey>(&self.global, Cursor::from_start())?;
-
log::info!("reroll: clearing trim cursors...");
-
let mut batch = self.keyspace.batch();
-
for kv in self
-
.global
-
.prefix(TrimCollectionCursorKey::from_prefix_to_db_bytes(
-
&Default::default(),
-
)?)
-
{
-
let (k, _) = kv?;
-
batch.remove(&self.global, k);
-
}
-
let n = batch.len();
-
batch.commit()?;
-
log::info!("reroll: cleared {n} trim cursors.");
+
return Err(StorageError::BackgroundAlreadyStarted);
+
}
+
if reroll {
+
log::info!("reroll: resetting rollup cursor...");
+
insert_static_neu::<NewRollupCursorKey>(&self.global, Cursor::from_start())?;
+
log::info!("reroll: clearing trim cursors...");
+
let mut batch = self.keyspace.batch();
+
for kv in self
+
.global
+
.prefix(TrimCollectionCursorKey::from_prefix_to_db_bytes(
+
&Default::default(),
+
)?)
+
{
+
let (k, _) = kv?;
+
batch.remove(&self.global, k);
-
Ok(FjallBackground(self.clone()))
+
let n = batch.len();
+
batch.commit()?;
+
log::info!("reroll: cleared {n} trim cursors.");
+
Ok(FjallBackground(self.clone()))
fn insert_batch<const LIMIT: usize>(
···
latest.to_db_bytes()?,
);
+
histogram!("storage_insert_batch_db_batch_items").record(batch.len() as f64);
batch.commit()?;
Ok(())
···
candidate_new_feed_lower_cursor = Some(feed_key.cursor());
-
self.feeds.remove(&location_key_bytes)?;
+
self.records.remove(&location_key_bytes)?;
self.feeds.remove(key_bytes)?;
records_deleted += 1;
···
batch.remove(&self.records, key_bytes);
records_deleted += 1;
if batch.len() >= MAX_BATCHED_ACCOUNT_DELETE_RECORDS {
+
counter!("storage_delete_account_partial_commits").increment(1);
batch.commit()?;
batch = self.keyspace.batch();
+
counter!("storage_delete_account_completions").increment(1);
+
counter!("storage_delete_account_records_deleted").increment(records_deleted as u64);
batch.commit()?;
Ok(records_deleted)
···
break;
+
let dt = t0.elapsed();
+
log::trace!("finished trimming {n} nsids in {dt:?}: {total_danglers} dangling and {total_deleted} total removed.");
+
histogram!("storage_trim_dirty_nsids").record(completed.len() as f64);
+
histogram!("storage_trim_duration").record(dt.as_micros() as f64);
+
counter!("storage_trim_removed", "dangling" => "true").increment(total_danglers as u64);
+
if total_deleted >= total_danglers {
+
counter!("storage_trim_removed", "dangling" => "false").increment((total_deleted - total_danglers) as u64);
+
} else {
+
// TODO: probably think through what's happening here
+
log::warn!("weird trim case: more danglers than deleted? metric will be missing for dangling=false. deleted={total_deleted} danglers={total_danglers}");
+
}
for c in completed {
dirty_nsids.remove(&c);
-
log::info!("finished trimming {n} nsids in {:?}: {total_danglers} dangling and {total_deleted} total removed.", t0.elapsed());
},
};
···
vec![PrefixChild::Collection(NsidCount {
nsid: "a.a.a".to_string(),
creates: 1,
+
updates: 0,
+
deletes: 0,
dids_estimate: 1
}),]
);
···
vec![PrefixChild::Prefix(PrefixCount {
prefix: "a.a.a".to_string(),
creates: 1,
-
dids_estimate: 1
+
updates: 0,
+
deletes: 0,
+
dids_estimate: 1,
}),]
);
assert_eq!(cursor, None);
···
vec![PrefixChild::Prefix(PrefixCount {
prefix: "a.a.a".to_string(),
creates: 2,
+
updates: 0,
+
deletes: 0,
dids_estimate: 1
}),]
);
···
PrefixChild::Collection(NsidCount {
nsid: "a.a.a.a".to_string(),
creates: 1,
+
updates: 0,
+
deletes: 0,
dids_estimate: 1
}),
PrefixChild::Prefix(PrefixCount {
prefix: "a.a.a.a".to_string(),
creates: 1,
+
updates: 0,
+
deletes: 0,
dids_estimate: 1
}),
+2
who-am-i/.gitignore
···
+
*.pem
+
jwks.json
+37
who-am-i/Cargo.toml
···
+
[package]
+
name = "who-am-i"
+
version = "0.1.0"
+
edition = "2024"
+
+
[dependencies]
+
atrium-api = { version = "0.25.4", default-features = false }
+
atrium-common = "0.1.2"
+
atrium-identity = "0.1.5"
+
atrium-oauth = "0.1.3"
+
axum = "0.8.4"
+
axum-extra = { version = "0.10.1", features = ["cookie-signed", "typed-header"] }
+
axum-template = { version = "3.0.0", features = ["handlebars"] }
+
clap = { version = "4.5.40", features = ["derive", "env"] }
+
ctrlc = "3.4.7"
+
dashmap = "6.1.0"
+
elliptic-curve = "0.13.8"
+
handlebars = { version = "6.3.2", features = ["dir_source"] }
+
hickory-resolver = "0.25.2"
+
jose-jwk = "0.1.2"
+
jsonwebtoken = "9.3.1"
+
metrics = "0.24.2"
+
p256 = "0.13.2"
+
pkcs8 = "0.10.2"
+
rand = "0.9.1"
+
reqwest = { version = "0.12.22", features = ["native-tls-vendored"] }
+
serde = { version = "1.0.219", features = ["derive"] }
+
serde_json = "1.0.140"
+
thiserror = "2.0.12"
+
tokio = { version = "1.45.1", features = ["full", "macros"] }
+
tokio-util = "0.7.15"
+
url = "2.5.4"
+
+
[dependencies.metrics-exporter-prometheus]
+
version = "0.17.2"
+
default-features = false
+
features = ["http-listener", "async-runtime"]
+37
who-am-i/demo/index.html
···
+
<!doctype html>
+
<html>
+
<head>
+
<style>
+
body {
+
background: #333;
+
color: #ccc;
+
font-family: sans-serif;
+
}
+
</style>
+
</head>
+
+
<body>
+
<h1>hey <span id="who"></span></h1>
+
<p><code id="jwt"></code></p>
+
+
<iframe src="http://127.0.0.1:9997/prompt" id="whoami" style="border: none" height="160" width="320"></iframe>
+
+
<script type="text/javascript">
+
(whoami => {
+
const handleMessage = ev => {
+
if (ev.source !== whoami.contentWindow) {
+
// TODO: ALSO CHECK ev.origin!!!!
+
console.log('nah');
+
return;
+
}
+
whoami.remove();
+
window.removeEventListener('message', handleMessage);
+
+
document.getElementById('who').textContent = ev.data.handle;
+
document.getElementById('jwt').textContent = ev.data.token;
+
}
+
window.addEventListener('message', handleMessage);
+
})(document.getElementById('whoami'));
+
</script>
+
</body>
+
</html>
+4
who-am-i/demo/serve
···
+
#!/usr/bin/env bash
+
+
echo "note: you might need to access via http://127.0.0.1:8888 (not localhost) for the iframe to get its cookies"
+
python3 -m http.server 8888
+66
who-am-i/readme.md
···
+
# who am i
+
+
a little auth service for microcosm demos
+
+
**you probably SHOULD NOT USE THIS in any serious environment**
+
+
for now the deployment is restricted to microcosm -- expanding it for wider use likely requires solving a number of challenges that oauth exists for.
+
+
+
## a little auth service
+
+
- you drop an iframe and a short few lines of JS on your web page, and get a nice-ish atproto login prompt.
+
- 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.
+
- otherwise they get bounced over to the normal atproto oauth flow (in a popup or new tab)
+
- you get a callback containing
+
- a verified DID and handle
+
- a JWT containing the same that can be verified by public key
+
- **no write permissions** or any atproto permissions at all, just a verified identity
+
+
**you probably SHOULD NOT USE THIS in any serious environment**
+
+
+
### problems
+
+
- clickjacking: if this were allowed on arbitrary domains, malicious sites could trick users into proving their atproto identity.
+
- 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.
+
- 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.
+
+
so, **you probably SHOULD NOT USE THIS in any serious environment**
+
+
+
## why
+
+
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.
+
+
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.
+
+
note: **you probably SHOULD NOT USE THIS in any serious environment**
+
+
---
+
+
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.
+
+
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.
+
+
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.
+
+
+
### todo
+
+
provide a pubkey-signed JWT of the identity (just the DID as `sub` probably). (**you probably SHOULD NOT USE THIS in any serious environment**)
+
+
+
## building
+
+
for raspi 1 model b:
+
+
atrium-oauth uses reqwest with default tls config that requires openssl which `cross` doesn't have a good time getting the os deps for.
+
+
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,
+
+
it builds with
+
+
```bash
+
cross build --release --target arm-unknown-linux-gnueabihf
+
```
+89
who-am-i/src/expiring_task_map.rs
···
+
use dashmap::DashMap;
+
use rand::{Rng, distr::Alphanumeric};
+
use std::sync::Arc;
+
use std::time::Duration;
+
use tokio::task::{JoinHandle, spawn};
+
use tokio::time::sleep;
+
use tokio_util::sync::{CancellationToken, DropGuard};
+
+
pub struct ExpiringTaskMap<T>(TaskMap<T>);
+
+
/// need to manually implement clone because T is allowed to not be clone
+
impl<T> Clone for ExpiringTaskMap<T> {
+
fn clone(&self) -> Self {
+
Self(self.0.clone())
+
}
+
}
+
+
impl<T: Send + 'static> ExpiringTaskMap<T> {
+
pub fn new(expiration: Duration) -> Self {
+
let map = TaskMap {
+
map: Arc::new(DashMap::new()),
+
expiration,
+
};
+
Self(map)
+
}
+
+
pub fn dispatch<F>(&self, task: F, cancel: CancellationToken) -> String
+
where
+
F: Future<Output = T> + Send + 'static,
+
{
+
let TaskMap {
+
ref map,
+
expiration,
+
} = self.0;
+
let task_key: String = rand::rng()
+
.sample_iter(&Alphanumeric)
+
.take(24)
+
.map(char::from)
+
.collect();
+
+
// spawn a tokio task and put the join handle in the map for later retrieval
+
map.insert(task_key.clone(), (cancel.clone().drop_guard(), spawn(task)));
+
+
// spawn a second task to clean up the map in case it doesn't get claimed
+
let k = task_key.clone();
+
let map = map.clone();
+
spawn(async move {
+
if cancel
+
.run_until_cancelled(sleep(expiration))
+
.await
+
.is_some()
+
// the (sleep) task completed first
+
{
+
map.remove(&k);
+
cancel.cancel();
+
metrics::counter!("whoami_task_map_completions", "result" => "expired")
+
.increment(1);
+
}
+
});
+
+
task_key
+
}
+
+
pub fn take(&self, key: &str) -> Option<JoinHandle<T>> {
+
if let Some((_key, (_guard, handle))) = self.0.map.remove(key) {
+
// when the _guard drops, it cancels the token for us
+
metrics::counter!("whoami_task_map_completions", "result" => "retrieved").increment(1);
+
Some(handle)
+
} else {
+
metrics::counter!("whoami_task_map_gones").increment(1);
+
None
+
}
+
}
+
}
+
+
struct TaskMap<T> {
+
map: Arc<DashMap<String, (DropGuard, JoinHandle<T>)>>,
+
expiration: Duration,
+
}
+
+
/// need to manually implement clone because T is allowed to not be clone
+
impl<T> Clone for TaskMap<T> {
+
fn clone(&self) -> Self {
+
Self {
+
map: self.map.clone(),
+
expiration: self.expiration,
+
}
+
}
+
}
+93
who-am-i/src/jwt.rs
···
+
use elliptic_curve::SecretKey;
+
use jose_jwk::{Class, Jwk, Key, Parameters};
+
use jsonwebtoken::{Algorithm, EncodingKey, Header, encode, errors::Error as JWTError};
+
use pkcs8::DecodePrivateKey;
+
use serde::Serialize;
+
use std::fs;
+
use std::io::Error as IOError;
+
use std::path::Path;
+
use std::string::FromUtf8Error;
+
use std::time::{Duration, SystemTime, UNIX_EPOCH};
+
use thiserror::Error;
+
+
#[derive(Debug, Error)]
+
pub enum TokensSetupError {
+
#[error("failed to read private key")]
+
ReadPrivateKey(IOError),
+
#[error("failed to retrieve private key: {0}")]
+
PrivateKey(JWTError),
+
#[error("failed to read private key")]
+
ReadJwks(IOError),
+
#[error("failed to retrieve jwks: {0}")]
+
DecodeJwks(FromUtf8Error),
+
}
+
+
#[derive(Debug, Error)]
+
pub enum TokenMintingError {
+
#[error("failed to mint: {0}")]
+
EncodingError(#[from] JWTError),
+
}
+
+
pub struct Tokens {
+
encoding_key: EncodingKey,
+
jwk: Jwk,
+
}
+
+
impl Tokens {
+
pub fn from_files(priv_f: impl AsRef<Path>) -> Result<Self, TokensSetupError> {
+
let private_key_data: Vec<u8> =
+
fs::read(priv_f).map_err(TokensSetupError::ReadPrivateKey)?;
+
let encoding_key =
+
EncodingKey::from_ec_pem(&private_key_data).map_err(TokensSetupError::PrivateKey)?;
+
+
let jwk_key_string = String::from_utf8(private_key_data).unwrap();
+
let mut jwk = SecretKey::<p256::NistP256>::from_pkcs8_pem(&jwk_key_string)
+
.map(|secret_key| Jwk {
+
key: Key::from(&secret_key.into()),
+
prm: Parameters {
+
kid: Some("who-am-i-00".to_string()),
+
cls: Some(Class::Signing),
+
..Default::default()
+
},
+
})
+
.expect("to get private key");
+
+
// CRITICAL: this is what turns the private jwk into a public one: the
+
// `d` parameter is the secret for an EC key; a pubkey just has no `d`.
+
//
+
// this feels baaaadd but hey we're just copying atrium
+
// https://github.com/atrium-rs/atrium/blob/b48810f84d83d037ee89b79b8566df9e0f2a6dae/atrium-oauth/src/keyset.rs#L41
+
let Key::Ec(ref mut ec) = jwk.key else {
+
unimplemented!()
+
};
+
ec.d = None; // CRITICAL
+
+
Ok(Self { encoding_key, jwk })
+
}
+
+
pub fn mint(&self, t: impl ToString) -> Result<String, TokenMintingError> {
+
let sub = t.to_string();
+
+
let dt_now = SystemTime::now()
+
.duration_since(UNIX_EPOCH)
+
.expect("unix epoch is in the past");
+
let dt_exp = dt_now + Duration::from_secs(30 * 86_400);
+
let exp = dt_exp.as_secs();
+
+
let mut header = Header::new(Algorithm::ES256);
+
header.kid = Some("who-am-i-00".to_string());
+
// todo: consider setting jku?
+
+
Ok(encode(&header, &Claims { sub, exp }, &self.encoding_key)?)
+
}
+
+
pub fn jwk(&self) -> Jwk {
+
self.jwk.clone()
+
}
+
}
+
+
#[derive(Debug, Serialize)]
+
struct Claims {
+
sub: String,
+
exp: u64,
+
}
+9
who-am-i/src/lib.rs
···
+
mod expiring_task_map;
+
mod jwt;
+
mod oauth;
+
mod server;
+
+
pub use expiring_task_map::ExpiringTaskMap;
+
pub use jwt::Tokens;
+
pub use oauth::{OAuth, OAuthCallbackParams, OAuthCompleteError, ResolveHandleError};
+
pub use server::serve;
+120
who-am-i/src/main.rs
···
+
use clap::{ArgAction, Parser};
+
use metrics_exporter_prometheus::{BuildError as PromBuildError, PrometheusBuilder};
+
use std::path::PathBuf;
+
use tokio_util::sync::CancellationToken;
+
use who_am_i::{Tokens, serve};
+
+
/// Aggregate links in the at-mosphere
+
#[derive(Parser, Debug, Clone)]
+
#[command(version, about, long_about = None)]
+
struct Args {
+
/// secret key from which the cookie-signing key is derived
+
///
+
/// must have at least 512 bits (64 bytes) of randomness
+
///
+
/// eg: `cat /dev/urandom | head -c 64 | base64`
+
#[arg(long, env)]
+
app_secret: String,
+
/// path to at-oauth private key (PEM pk8 format)
+
///
+
/// generate with:
+
///
+
/// openssl ecparam -genkey -noout -name prime256v1 \
+
/// | openssl pkcs8 -topk8 -nocrypt -out <PATH-TO-PRIV-KEY>.pem
+
#[arg(long, env)]
+
oauth_private_key: Option<PathBuf>,
+
/// path to jwt private key (PEM pk8 format)
+
///
+
/// generate with:
+
///
+
/// openssl ecparam -genkey -noout -name prime256v1 \
+
/// | openssl pkcs8 -topk8 -nocrypt -out <PATH-TO-PRIV-KEY>.pem
+
#[arg(long)]
+
jwt_private_key: PathBuf,
+
/// this server's client-reachable base url, for oauth redirect + jwt check
+
///
+
/// required unless running in localhost mode with --dev
+
#[arg(long, env)]
+
base_url: Option<String>,
+
/// host:port to bind to on startup
+
#[arg(long, env, default_value = "127.0.0.1:9997")]
+
bind: String,
+
/// Enable dev mode
+
///
+
/// enables automatic template reloading, uses localhost oauth config, etc
+
#[arg(long, action)]
+
dev: bool,
+
/// Hosts who are allowed to one-click auth
+
///
+
/// Pass this argument multiple times to allow multiple hosts
+
#[arg(long = "allow_host", short = 'a', action = ArgAction::Append)]
+
allowed_hosts: Vec<String>,
+
}
+
+
#[tokio::main(flavor = "current_thread")]
+
async fn main() {
+
let shutdown = CancellationToken::new();
+
+
let ctrlc_shutdown = shutdown.clone();
+
ctrlc::set_handler(move || ctrlc_shutdown.cancel()).expect("failed to set ctrl-c handler");
+
+
let args = Args::parse();
+
+
// let bind = args.bind.to_socket_addrs().expect("--bind must be ToSocketAddrs");
+
+
let base = args.base_url.unwrap_or_else(|| {
+
if args.dev {
+
format!("http://{}", args.bind)
+
} else {
+
panic!("not in --dev mode so --base-url is required")
+
}
+
});
+
+
if !args.dev && args.oauth_private_key.is_none() {
+
panic!("--at-oauth-key is required except in --dev");
+
} else if args.dev && args.oauth_private_key.is_some() {
+
eprintln!("warn: --at-oauth-key is ignored in dev (localhost config)");
+
}
+
+
if args.allowed_hosts.is_empty() {
+
panic!("at least one --allowed-host host must be set");
+
}
+
+
println!("starting with allowed_hosts hosts:");
+
for host in &args.allowed_hosts {
+
println!(" - {host}");
+
}
+
+
let tokens = Tokens::from_files(args.jwt_private_key).unwrap();
+
+
if let Err(e) = install_metrics_server() {
+
eprintln!("failed to install metrics server: {e:?}");
+
};
+
+
serve(
+
shutdown,
+
args.app_secret,
+
args.oauth_private_key,
+
tokens,
+
base,
+
args.bind,
+
args.allowed_hosts,
+
args.dev,
+
)
+
.await;
+
}
+
+
fn install_metrics_server() -> Result<(), PromBuildError> {
+
println!("installing metrics server...");
+
let host = [0, 0, 0, 0];
+
let port = 8765;
+
PrometheusBuilder::new()
+
.set_enable_unit_suffix(false)
+
.with_http_listener((host, port))
+
.install()?;
+
println!(
+
"metrics server installed! listening on http://{}.{}.{}.{}:{port}",
+
host[0], host[1], host[2], host[3]
+
);
+
Ok(())
+
}
+268
who-am-i/src/oauth.rs
···
+
use jose_jwk::Class;
+
use jose_jwk::Jwk;
+
use jose_jwk::Key;
+
use jose_jwk::Parameters;
+
use std::fs;
+
use std::path::PathBuf;
+
// use p256::SecretKey;
+
use atrium_api::{agent::SessionManager, types::string::Did};
+
use atrium_common::resolver::Resolver;
+
use atrium_identity::{
+
did::{CommonDidResolver, CommonDidResolverConfig, DEFAULT_PLC_DIRECTORY_URL},
+
handle::{AtprotoHandleResolver, AtprotoHandleResolverConfig, DnsTxtResolver},
+
};
+
use atrium_oauth::{
+
AtprotoClientMetadata, AtprotoLocalhostClientMetadata, AuthMethod, AuthorizeOptions,
+
CallbackParams, DefaultHttpClient, GrantType, KnownScope, OAuthClient, OAuthClientConfig,
+
OAuthClientMetadata, OAuthResolverConfig, Scope,
+
store::{session::MemorySessionStore, state::MemoryStateStore},
+
};
+
use elliptic_curve::SecretKey;
+
use hickory_resolver::{ResolveError, TokioResolver};
+
use jose_jwk::JwkSet;
+
use pkcs8::DecodePrivateKey;
+
use serde::Deserialize;
+
use std::sync::Arc;
+
use thiserror::Error;
+
+
const READONLY_SCOPE: [Scope; 1] = [Scope::Known(KnownScope::Atproto)];
+
+
#[derive(Debug, Deserialize)]
+
pub struct CallbackErrorParams {
+
error: String,
+
error_description: Option<String>,
+
#[allow(dead_code)]
+
state: Option<String>, // TODO: we _should_ use state to associate the auth request but how to do that with atrium is unclear
+
iss: Option<String>,
+
}
+
+
#[derive(Debug, Deserialize)]
+
#[serde(untagged)]
+
pub enum OAuthCallbackParams {
+
Granted(CallbackParams),
+
Failed(CallbackErrorParams),
+
}
+
+
type Client = OAuthClient<
+
MemoryStateStore,
+
MemorySessionStore,
+
CommonDidResolver<DefaultHttpClient>,
+
AtprotoHandleResolver<HickoryDnsTxtResolver, DefaultHttpClient>,
+
>;
+
+
#[derive(Clone)]
+
pub struct OAuth {
+
client: Arc<Client>,
+
did_resolver: Arc<CommonDidResolver<DefaultHttpClient>>,
+
}
+
+
#[derive(Debug, Error)]
+
pub enum AuthSetupError {
+
#[error("failed to intiialize atrium client: {0}")]
+
AtriumClientError(atrium_oauth::Error),
+
#[error("failed to initialize hickory dns resolver: {0}")]
+
HickoryResolverError(ResolveError),
+
}
+
+
#[derive(Debug, Error)]
+
pub enum OAuthCompleteError {
+
#[error("the user denied request: {description:?} (from {issuer:?})")]
+
Denied {
+
description: Option<String>,
+
issuer: Option<String>,
+
},
+
#[error("the request failed: {error}: {description:?} (from {issuer:?})")]
+
Failed {
+
error: String,
+
description: Option<String>,
+
issuer: Option<String>,
+
},
+
#[error("failed to complete oauth callback: {0}")]
+
CallbackFailed(atrium_oauth::Error),
+
#[error("the authorized session did not contain a DID")]
+
NoDid,
+
}
+
+
#[derive(Debug, Error)]
+
pub enum ResolveHandleError {
+
#[error("failed to resolve: {0}")]
+
ResolutionFailed(#[from] atrium_identity::Error),
+
#[error("identity resolved but no handle found for user")]
+
NoHandle,
+
#[error("found handle {0:?} but it appears invalid: {1}")]
+
InvalidHandle(String, &'static str),
+
}
+
+
impl OAuth {
+
pub fn new(oauth_private_key: Option<PathBuf>, base: String) -> Result<Self, AuthSetupError> {
+
let http_client = Arc::new(DefaultHttpClient::default());
+
let did_resolver = || {
+
CommonDidResolver::new(CommonDidResolverConfig {
+
plc_directory_url: DEFAULT_PLC_DIRECTORY_URL.to_string(),
+
http_client: http_client.clone(),
+
})
+
};
+
let dns_txt_resolver =
+
HickoryDnsTxtResolver::new().map_err(AuthSetupError::HickoryResolverError)?;
+
+
let resolver = OAuthResolverConfig {
+
did_resolver: did_resolver(),
+
handle_resolver: AtprotoHandleResolver::new(AtprotoHandleResolverConfig {
+
dns_txt_resolver,
+
http_client: Arc::clone(&http_client),
+
}),
+
authorization_server_metadata: Default::default(),
+
protected_resource_metadata: Default::default(),
+
};
+
+
let state_store = MemoryStateStore::default();
+
let session_store = MemorySessionStore::default();
+
+
let client = if let Some(path) = oauth_private_key {
+
let key_contents: Vec<u8> = fs::read(path).unwrap();
+
let key_string = String::from_utf8(key_contents).unwrap();
+
let key = SecretKey::<p256::NistP256>::from_pkcs8_pem(&key_string)
+
.map(|secret_key| Jwk {
+
key: Key::from(&secret_key.into()),
+
prm: Parameters {
+
kid: Some("at-oauth-00".to_string()),
+
cls: Some(Class::Signing),
+
..Default::default()
+
},
+
})
+
.expect("to get private key");
+
OAuthClient::new(OAuthClientConfig {
+
client_metadata: AtprotoClientMetadata {
+
client_id: format!("{base}/client-metadata.json"),
+
client_uri: Some(base.clone()),
+
redirect_uris: vec![format!("{base}/authorized")],
+
token_endpoint_auth_method: AuthMethod::PrivateKeyJwt,
+
grant_types: vec![GrantType::AuthorizationCode, GrantType::RefreshToken],
+
scopes: READONLY_SCOPE.to_vec(),
+
jwks_uri: Some(format!("{base}/.well-known/jwks.json")),
+
token_endpoint_auth_signing_alg: Some(String::from("ES256")),
+
},
+
keys: Some(vec![key]),
+
resolver,
+
state_store,
+
session_store,
+
})
+
.map_err(AuthSetupError::AtriumClientError)?
+
} else {
+
OAuthClient::new(OAuthClientConfig {
+
client_metadata: AtprotoLocalhostClientMetadata {
+
redirect_uris: Some(vec![String::from("http://127.0.0.1:9997/authorized")]),
+
scopes: Some(READONLY_SCOPE.to_vec()),
+
},
+
keys: None,
+
resolver,
+
state_store,
+
session_store,
+
})
+
.map_err(AuthSetupError::AtriumClientError)?
+
};
+
+
Ok(Self {
+
client: Arc::new(client),
+
did_resolver: Arc::new(did_resolver()),
+
})
+
}
+
+
pub fn client_metadata(&self) -> OAuthClientMetadata {
+
self.client.client_metadata.clone()
+
}
+
+
pub fn jwks(&self) -> JwkSet {
+
self.client.jwks()
+
}
+
+
pub async fn begin(&self, handle: &str) -> Result<String, atrium_oauth::Error> {
+
let auth_opts = AuthorizeOptions {
+
scopes: READONLY_SCOPE.to_vec(),
+
..Default::default()
+
};
+
self.client.authorize(handle, auth_opts).await
+
}
+
+
/// Finally, resolve the oauth flow to a verified DID
+
pub async fn complete(&self, params: OAuthCallbackParams) -> Result<Did, OAuthCompleteError> {
+
let params = match params {
+
OAuthCallbackParams::Granted(params) => params,
+
OAuthCallbackParams::Failed(p) if p.error == "access_denied" => {
+
return Err(OAuthCompleteError::Denied {
+
description: p.error_description.clone(),
+
issuer: p.iss.clone(),
+
});
+
}
+
OAuthCallbackParams::Failed(p) => {
+
return Err(OAuthCompleteError::Failed {
+
error: p.error.clone(),
+
description: p.error_description.clone(),
+
issuer: p.iss.clone(),
+
});
+
}
+
};
+
let (session, _) = self
+
.client
+
.callback(params)
+
.await
+
.map_err(OAuthCompleteError::CallbackFailed)?;
+
let Some(did) = session.did().await else {
+
return Err(OAuthCompleteError::NoDid);
+
};
+
Ok(did)
+
}
+
+
pub async fn resolve_handle(&self, did: Did) -> Result<String, ResolveHandleError> {
+
// TODO: this is only half the resolution? or is atrium checking dns?
+
let doc = self.did_resolver.resolve(&did).await?;
+
let Some(aka) = doc.also_known_as else {
+
return Err(ResolveHandleError::NoHandle);
+
};
+
let Some(at_uri_handle) = aka.first() else {
+
return Err(ResolveHandleError::NoHandle);
+
};
+
if aka.len() > 1 {
+
eprintln!("more than one handle found for {did:?}");
+
}
+
let Some(bare_handle) = at_uri_handle.strip_prefix("at://") else {
+
return Err(ResolveHandleError::InvalidHandle(
+
at_uri_handle.to_string(),
+
"did not start with 'at://'",
+
));
+
};
+
if bare_handle.is_empty() {
+
return Err(ResolveHandleError::InvalidHandle(
+
at_uri_handle.to_string(),
+
"empty handle",
+
));
+
}
+
Ok(bare_handle.to_string())
+
}
+
}
+
+
pub struct HickoryDnsTxtResolver(TokioResolver);
+
+
impl HickoryDnsTxtResolver {
+
fn new() -> Result<Self, ResolveError> {
+
Ok(Self(TokioResolver::builder_tokio()?.build()))
+
}
+
}
+
+
impl DnsTxtResolver for HickoryDnsTxtResolver {
+
async fn resolve(
+
&self,
+
query: &str,
+
) -> core::result::Result<Vec<String>, Box<dyn std::error::Error + Send + Sync>> {
+
match self.0.txt_lookup(query).await {
+
Ok(r) => {
+
metrics::counter!("whoami_resolve_dns_txt", "success" => "true").increment(1);
+
Ok(r.iter().map(|r| r.to_string()).collect())
+
}
+
Err(e) => {
+
metrics::counter!("whoami_resolve_dns_txt", "success" => "false").increment(1);
+
Err(e.into())
+
}
+
}
+
}
+
}
+525
who-am-i/src/server.rs
···
+
use atrium_api::types::string::Did;
+
use atrium_oauth::OAuthClientMetadata;
+
use axum::{
+
Router,
+
extract::{FromRef, Json as ExtractJson, Query, State},
+
http::{
+
StatusCode,
+
header::{CONTENT_SECURITY_POLICY, CONTENT_TYPE, HeaderMap, ORIGIN, REFERER},
+
},
+
response::{IntoResponse, Json, Redirect, Response},
+
routing::{get, post},
+
};
+
use axum_extra::extract::cookie::{Cookie, Expiration, Key, SameSite, SignedCookieJar};
+
use axum_template::{RenderHtml, engine::Engine};
+
use handlebars::{Handlebars, handlebars_helper};
+
use jose_jwk::JwkSet;
+
use std::path::PathBuf;
+
+
use serde::Deserialize;
+
use serde_json::{Value, json};
+
use std::collections::HashSet;
+
use std::sync::Arc;
+
use std::time::{Duration, SystemTime};
+
use tokio::net::TcpListener;
+
use tokio_util::sync::CancellationToken;
+
use url::Url;
+
+
use crate::{
+
ExpiringTaskMap, OAuth, OAuthCallbackParams, OAuthCompleteError, ResolveHandleError, Tokens,
+
};
+
+
const FAVICON: &[u8] = include_bytes!("../static/favicon.ico");
+
const STYLE_CSS: &str = include_str!("../static/style.css");
+
+
const HELLO_COOKIE_KEY: &str = "hello-who-am-i";
+
const DID_COOKIE_KEY: &str = "did";
+
+
const COOKIE_EXPIRATION: Duration = Duration::from_secs(30 * 86_400);
+
+
type AppEngine = Engine<Handlebars<'static>>;
+
+
#[derive(Clone)]
+
struct AppState {
+
pub key: Key,
+
pub allowed_hosts: Arc<HashSet<String>>,
+
pub engine: AppEngine,
+
pub oauth: Arc<OAuth>,
+
pub resolve_handles: ExpiringTaskMap<Result<String, ResolveHandleError>>,
+
pub shutdown: CancellationToken,
+
pub tokens: Arc<Tokens>,
+
}
+
+
impl FromRef<AppState> for Key {
+
fn from_ref(state: &AppState) -> Self {
+
state.key.clone()
+
}
+
}
+
+
#[allow(clippy::too_many_arguments)]
+
pub async fn serve(
+
shutdown: CancellationToken,
+
app_secret: String,
+
oauth_private_key: Option<PathBuf>,
+
tokens: Tokens,
+
base: String,
+
bind: String,
+
allowed_hosts: Vec<String>,
+
dev: bool,
+
) {
+
let mut hbs = Handlebars::new();
+
hbs.set_dev_mode(dev);
+
hbs.register_templates_directory("templates", Default::default())
+
.unwrap();
+
+
handlebars_helper!(json: |v: Value| serde_json::to_string(&v).unwrap());
+
hbs.register_helper("json", Box::new(json));
+
+
// clients have to pick up their identity-resolving tasks within this period
+
let task_pickup_expiration = Duration::from_secs(15);
+
+
let oauth = OAuth::new(oauth_private_key, base).unwrap();
+
+
let state = AppState {
+
engine: Engine::new(hbs),
+
key: Key::from(app_secret.as_bytes()), // TODO: via config
+
allowed_hosts: Arc::new(HashSet::from_iter(allowed_hosts)),
+
oauth: Arc::new(oauth),
+
resolve_handles: ExpiringTaskMap::new(task_pickup_expiration),
+
shutdown: shutdown.clone(),
+
tokens: Arc::new(tokens),
+
};
+
+
let app = Router::new()
+
.route("/", get(hello))
+
.route("/favicon.ico", get(favicon)) // todo MIME
+
.route("/style.css", get(css))
+
.route("/prompt", get(prompt))
+
.route("/user-info", post(user_info))
+
.route("/client-metadata.json", get(client_metadata))
+
.route("/auth", get(start_oauth))
+
.route("/authorized", get(complete_oauth))
+
.route("/disconnect", post(disconnect))
+
.route("/.well-known/jwks.json", get(jwks))
+
.with_state(state);
+
+
eprintln!("starting server at http://{bind}");
+
let listener = TcpListener::bind(bind)
+
.await
+
.expect("listener binding to work");
+
+
axum::serve(listener, app)
+
.with_graceful_shutdown(async move { shutdown.cancelled().await })
+
.await
+
.unwrap();
+
}
+
+
#[derive(Debug, Deserialize)]
+
struct HelloQuery {
+
auth_reload: Option<String>,
+
auth_failed: Option<String>,
+
}
+
async fn hello(
+
State(AppState {
+
engine,
+
resolve_handles,
+
shutdown,
+
oauth,
+
..
+
}): State<AppState>,
+
Query(params): Query<HelloQuery>,
+
mut jar: SignedCookieJar,
+
) -> Response {
+
let is_auth_reload = params.auth_reload.is_some();
+
let auth_failed = params.auth_failed.is_some();
+
let no_cookie = jar.get(HELLO_COOKIE_KEY).is_none();
+
jar = jar.add(hello_cookie());
+
+
let info = if let Some(did) = jar.get(DID_COOKIE_KEY) {
+
if let Ok(did) = Did::new(did.value_trimmed().to_string()) {
+
// push cookie expiry
+
jar = jar.add(cookie(&did));
+
let fetch_key = resolve_handles.dispatch(
+
{
+
let oauth = oauth.clone();
+
let did = did.clone();
+
async move { oauth.resolve_handle(did.clone()).await }
+
},
+
shutdown.child_token(),
+
);
+
json!({
+
"did": did,
+
"fetch_key": fetch_key,
+
"is_auth_reload": is_auth_reload,
+
"auth_failed": auth_failed,
+
"no_cookie": no_cookie,
+
})
+
} else {
+
jar = jar.remove(DID_COOKIE_KEY);
+
json!({
+
"is_auth_reload": is_auth_reload,
+
"auth_failed": auth_failed,
+
"no_cookie": no_cookie,
+
})
+
}
+
} else {
+
json!({
+
"is_auth_reload": is_auth_reload,
+
"auth_failed": auth_failed,
+
"no_cookie": no_cookie,
+
})
+
};
+
let frame_headers = [(CONTENT_SECURITY_POLICY, "frame-ancestors 'none'")];
+
(frame_headers, jar, RenderHtml("hello", engine, info)).into_response()
+
}
+
+
async fn css() -> impl IntoResponse {
+
let headers = [
+
(CONTENT_TYPE, "text/css"),
+
// (CACHE_CONTROL, "") // TODO
+
];
+
(headers, STYLE_CSS)
+
}
+
+
async fn favicon() -> impl IntoResponse {
+
([(CONTENT_TYPE, "image/x-icon")], FAVICON)
+
}
+
+
fn hello_cookie() -> Cookie<'static> {
+
Cookie::build((HELLO_COOKIE_KEY, "hiiii"))
+
.http_only(true)
+
.secure(true)
+
.same_site(SameSite::None)
+
.expires(Expiration::DateTime(
+
(SystemTime::now() + COOKIE_EXPIRATION).into(),
+
)) // wtf safari needs this to not be a session cookie??
+
.max_age(COOKIE_EXPIRATION.try_into().unwrap())
+
.path("/")
+
.into()
+
}
+
+
fn cookie(did: &Did) -> Cookie<'static> {
+
Cookie::build((DID_COOKIE_KEY, did.to_string()))
+
.http_only(true)
+
.secure(true)
+
.same_site(SameSite::None)
+
.expires(Expiration::DateTime(
+
(SystemTime::now() + COOKIE_EXPIRATION).into(),
+
)) // wtf safari needs this to not be a session cookie??
+
.max_age(COOKIE_EXPIRATION.try_into().unwrap())
+
.path("/")
+
.into()
+
}
+
+
#[derive(Debug, Deserialize)]
+
struct PromptQuery {
+
// this must *ONLY* be used for the postmessage target origin
+
app: Option<String>,
+
}
+
async fn prompt(
+
State(AppState {
+
allowed_hosts,
+
engine,
+
oauth,
+
resolve_handles,
+
shutdown,
+
tokens,
+
..
+
}): State<AppState>,
+
Query(params): Query<PromptQuery>,
+
jar: SignedCookieJar,
+
headers: HeaderMap,
+
) -> impl IntoResponse {
+
let err = |reason, check_frame, detail| {
+
metrics::counter!("whoami_auth_prompt", "ok" => "false", "reason" => reason).increment(1);
+
let info = json!({
+
"reason": reason,
+
"check_frame": check_frame,
+
"detail": detail,
+
});
+
let html = RenderHtml("prompt-error", engine.clone(), info);
+
(StatusCode::BAD_REQUEST, html).into_response()
+
};
+
+
let Some(parent) = headers.get(ORIGIN).or_else(|| {
+
eprintln!("referrer fallback");
+
// TODO: referer should only be used for localhost??
+
headers.get(REFERER)
+
}) else {
+
return err("Missing origin and no referrer for fallback", true, None);
+
};
+
let Ok(parent) = parent.to_str() else {
+
return err("Unreadable origin or referrer", true, None);
+
};
+
eprintln!(
+
"rolling with parent: {parent:?} (from origin? {})",
+
headers.get(ORIGIN).is_some()
+
);
+
let Ok(url) = Url::parse(parent) else {
+
return err("Bad origin or referrer", true, None);
+
};
+
let Some(parent_host) = url.host_str() else {
+
return err("Origin or referrer missing host", true, None);
+
};
+
if !allowed_hosts.contains(parent_host) {
+
return err(
+
"Login is not allowed on this page",
+
false,
+
Some(parent_host),
+
);
+
}
+
if let Some(ref app) = params.app {
+
if !allowed_hosts.contains(app) {
+
return err("Login is not allowed for this app", false, Some(app));
+
}
+
}
+
let parent_origin = url.origin().ascii_serialization();
+
if parent_origin == "null" {
+
return err("Origin or referrer header value is opaque", true, None);
+
}
+
+
let all_allowed = allowed_hosts
+
.iter()
+
.map(|h| format!("https://{h}"))
+
.collect::<Vec<_>>()
+
.join(" ");
+
let csp = format!("frame-ancestors 'self' {parent_origin} {all_allowed}");
+
let frame_headers = [(CONTENT_SECURITY_POLICY, &csp)];
+
+
if let Some(did) = jar.get(DID_COOKIE_KEY) {
+
let Ok(did) = Did::new(did.value_trimmed().to_string()) else {
+
return err("Bad cookie", false, None);
+
};
+
+
// push cookie expiry
+
let jar = jar.add(cookie(&did));
+
+
let token = match tokens.mint(&*did) {
+
Ok(t) => t,
+
Err(e) => {
+
eprintln!("failed to create JWT: {e:?}");
+
return err("failed to create JWT", false, None);
+
}
+
};
+
+
let fetch_key = resolve_handles.dispatch(
+
{
+
let oauth = oauth.clone();
+
let did = did.clone();
+
async move { oauth.resolve_handle(did.clone()).await }
+
},
+
shutdown.child_token(),
+
);
+
+
metrics::counter!("whoami_auth_prompt", "ok" => "true", "known" => "true").increment(1);
+
let info = json!({
+
"did": did,
+
"token": token,
+
"fetch_key": fetch_key,
+
"parent_host": parent_host,
+
"parent_origin": parent_origin,
+
"parent_target": params.app.map(|h| format!("https://{h}")),
+
});
+
(frame_headers, jar, RenderHtml("prompt", engine, info)).into_response()
+
} else {
+
metrics::counter!("whoami_auth_prompt", "ok" => "true", "known" => "false").increment(1);
+
let info = json!({
+
"parent_host": parent_host,
+
"parent_origin": parent_origin,
+
});
+
(frame_headers, RenderHtml("prompt", engine, info)).into_response()
+
}
+
}
+
+
#[derive(Debug, Deserialize)]
+
struct UserInfoParams {
+
fetch_key: String,
+
}
+
async fn user_info(
+
State(AppState {
+
resolve_handles, ..
+
}): State<AppState>,
+
ExtractJson(params): ExtractJson<UserInfoParams>,
+
) -> impl IntoResponse {
+
let err = |status, reason: &str| {
+
metrics::counter!("whoami_user_info", "found" => "false", "reason" => reason.to_string())
+
.increment(1);
+
(status, Json(json!({ "reason": reason }))).into_response()
+
};
+
+
let Some(task_handle) = resolve_handles.take(&params.fetch_key) else {
+
return err(StatusCode::NOT_FOUND, "fetch key does not exist or expired");
+
};
+
+
match task_handle.await {
+
Err(task_err) => {
+
eprintln!("task join error? {task_err:?}");
+
err(StatusCode::INTERNAL_SERVER_ERROR, "server errored")
+
}
+
Ok(Err(ResolveHandleError::ResolutionFailed(atrium_identity::Error::NotFound))) => {
+
err(StatusCode::NOT_FOUND, "handle not found")
+
}
+
Ok(Err(ResolveHandleError::ResolutionFailed(e))) => {
+
eprintln!("handle resolution failed: {e:?}");
+
err(
+
StatusCode::INTERNAL_SERVER_ERROR,
+
"handle resolution failed",
+
)
+
}
+
Ok(Err(ResolveHandleError::NoHandle)) => err(
+
StatusCode::INTERNAL_SERVER_ERROR,
+
"resolved identity but did not find a handle",
+
),
+
Ok(Err(ResolveHandleError::InvalidHandle(_h, reason))) => err(
+
StatusCode::INTERNAL_SERVER_ERROR,
+
&format!("handle appears invalid: {reason}"),
+
),
+
Ok(Ok(handle)) => {
+
metrics::counter!("whoami_user_info", "found" => "true").increment(1);
+
Json(json!({ "handle": handle })).into_response()
+
}
+
}
+
}
+
+
async fn client_metadata(
+
State(AppState { oauth, .. }): State<AppState>,
+
) -> Json<OAuthClientMetadata> {
+
Json(oauth.client_metadata())
+
}
+
+
#[derive(Debug, Deserialize)]
+
struct BeginOauthParams {
+
handle: String,
+
}
+
async fn start_oauth(
+
State(AppState { oauth, engine, .. }): State<AppState>,
+
Query(params): Query<BeginOauthParams>,
+
jar: SignedCookieJar,
+
) -> Response {
+
// if any existing session was active, clear it first
+
// ...this might help a confusion attack w multiple sign-in flows or smth
+
let jar = jar.remove(DID_COOKIE_KEY);
+
+
use atrium_identity::Error as IdError;
+
use atrium_oauth::Error as OAuthError;
+
+
let err = |code, reason: &str| {
+
metrics::counter!("whoami_auth_start", "ok" => "false", "reason" => reason.to_string())
+
.increment(1);
+
let info = json!({
+
"result": "fail",
+
"reason": reason,
+
});
+
(code, RenderHtml("auth-fail", engine.clone(), info)).into_response()
+
};
+
+
match oauth.begin(&params.handle).await {
+
Err(OAuthError::Identity(
+
IdError::NotFound | IdError::HttpStatus(StatusCode::NOT_FOUND),
+
)) => err(StatusCode::NOT_FOUND, "handle not found"),
+
Err(OAuthError::Identity(IdError::AtIdentifier(r))) => err(StatusCode::BAD_REQUEST, &r),
+
Err(e) => {
+
eprintln!("begin auth failed: {e:?}");
+
err(StatusCode::INTERNAL_SERVER_ERROR, "unknown")
+
}
+
Ok(auth_url) => {
+
metrics::counter!("whoami_auth_start", "ok" => "true").increment(1);
+
(jar, Redirect::to(&auth_url)).into_response()
+
}
+
}
+
}
+
+
async fn complete_oauth(
+
State(AppState {
+
engine,
+
resolve_handles,
+
oauth,
+
shutdown,
+
tokens,
+
..
+
}): State<AppState>,
+
Query(params): Query<OAuthCallbackParams>,
+
jar: SignedCookieJar,
+
) -> Response {
+
let err = |code, result, reason: &str| {
+
metrics::counter!("whoami_auth_complete", "ok" => "false", "reason" => reason.to_string())
+
.increment(1);
+
let info = json!({
+
"result": result,
+
"reason": reason,
+
});
+
(code, RenderHtml("auth-fail", engine.clone(), info)).into_response()
+
};
+
+
let did = match oauth.complete(params).await {
+
Ok(did) => did,
+
Err(e) => {
+
return match e {
+
OAuthCompleteError::Denied { description, .. } => {
+
let desc = description.unwrap_or("permission to share was denied".to_string());
+
err(StatusCode::FORBIDDEN, "deny", desc.as_str())
+
}
+
OAuthCompleteError::Failed { .. } => {
+
eprintln!("auth completion failed: {e:?}");
+
err(
+
StatusCode::INTERNAL_SERVER_ERROR,
+
"fail",
+
"failed to complete",
+
)
+
}
+
OAuthCompleteError::CallbackFailed(e) => {
+
eprintln!("auth callback failed: {e:?}");
+
err(
+
StatusCode::INTERNAL_SERVER_ERROR,
+
"fail",
+
"failed to complete callback",
+
)
+
}
+
OAuthCompleteError::NoDid => err(StatusCode::BAD_REQUEST, "fail", "no DID found"),
+
};
+
}
+
};
+
+
let jar = jar.add(cookie(&did));
+
+
let token = match tokens.mint(&*did) {
+
Ok(t) => t,
+
Err(e) => {
+
eprintln!("failed to create JWT: {e:?}");
+
return err(
+
StatusCode::INTERNAL_SERVER_ERROR,
+
"fail",
+
"failed to create JWT",
+
);
+
}
+
};
+
+
let fetch_key = resolve_handles.dispatch(
+
{
+
let oauth = oauth.clone();
+
let did = did.clone();
+
async move { oauth.resolve_handle(did.clone()).await }
+
},
+
shutdown.child_token(),
+
);
+
+
metrics::counter!("whoami_auth_complete", "ok" => "true").increment(1);
+
let info = json!({
+
"did": did,
+
"token": token,
+
"fetch_key": fetch_key,
+
});
+
(jar, RenderHtml("authorized", engine, info)).into_response()
+
}
+
+
async fn disconnect(jar: SignedCookieJar) -> impl IntoResponse {
+
metrics::counter!("whoami_disconnect").increment(1);
+
let jar = jar.remove(DID_COOKIE_KEY);
+
(jar, Json(json!({ "ok": true })))
+
}
+
+
async fn jwks(State(AppState { oauth, tokens, .. }): State<AppState>) -> Json<JwkSet> {
+
let mut jwks = oauth.jwks();
+
jwks.keys.push(tokens.jwk());
+
Json(jwks)
+
}
who-am-i/static/favicon.ico

This is a binary file and will not be displayed.

+195
who-am-i/static/style.css
···
+
body {
+
color: #434;
+
font-family: 'Iowan Old Style', 'Palatino Linotype', 'URW Palladio L', P052, serif;
+
margin: 0;
+
min-height: 100vh;
+
padding: 0;
+
}
+
.wrap {
+
border: 2px solid #221828;
+
border-radius: 0.5rem;
+
box-sizing: border-box;
+
overflow: hidden;
+
display: flex;
+
flex-direction: column;
+
min-height: 100vh;
+
}
+
.wrap.unframed {
+
border-radius: 0;
+
border-width: 0.4rem;
+
}
+
header {
+
background: #221828;
+
display: flex;
+
justify-content: space-between;
+
padding: 0 0.25rem;
+
color: #c9b;
+
display: flex;
+
gap: 0.5rem;
+
align-items: baseline;
+
}
+
header > * {
+
flex-basis: 33%;
+
}
+
header > .empty {
+
font-size: 0.8rem;
+
opacity: 0.5;
+
}
+
header > .title {
+
text-align: center;
+
}
+
header > a.micro {
+
text-decoration: none;
+
font-size: 0.8rem;
+
text-align: right;
+
opacity: 0.5;
+
}
+
header > a.micro:hover {
+
opacity: 1;
+
}
+
main {
+
background: #ccc;
+
display: flex;
+
flex-direction: column;
+
flex-grow: 1;
+
padding: 0.25rem 0.5rem;
+
}
+
.mini-content {
+
margin: 1rem auto 0;
+
padding: 1rem 0.5rem;
+
max-width: 21rem;
+
}
+
+
.explain {
+
border-bottom: 1px dashed #888;
+
margin-bottom: 1rem;
+
padding-bottom: 2rem;
+
}
+
.explain p {
+
text-align: left;
+
}
+
+
#error-message {
+
font-size: 0.8rem;
+
color: #a31;
+
}
+
+
#error-message:not(.hidden) + #prompt {
+
display: none !important;
+
}
+
+
#error-message,
+
p {
+
margin: 1rem 0 0;
+
text-align: center;
+
}
+
p.detail {
+
font-size: 0.8rem;
+
}
+
p.detail.no {
+
font-style: italic;
+
}
+
.parent-host {
+
font-weight: bold;
+
color: #48c;
+
display: inline-block;
+
padding: 0 0.125rem;
+
border-radius: 0.25rem;
+
border: 1px solid #aaa;
+
font-size: 0.8rem;
+
}
+
+
#loader {
+
display: flex;
+
flex-grow: 1;
+
justify-content: center;
+
align-items: center;
+
}
+
.spinner {
+
animation: rotation 1.618s ease-in-out infinite;
+
border-radius: 50%;
+
border: 3px dashed #434;
+
box-sizing: border-box;
+
display: inline-block;
+
height: 1.5em;
+
width: 1.5em;
+
}
+
@keyframes rotation {
+
0% { transform: rotate(0deg) }
+
100% { transform: rotate(360deg) }
+
}
+
/* loader visibility is mutually exclusive with its immediate sibling */
+
#loader:not(.hidden) + * {
+
display: none !important;
+
}
+
+
#user-info {
+
flex-grow: 1;
+
display: flex;
+
flex-direction: column;
+
justify-content: center;
+
}
+
.action {
+
background: #eee;
+
display: flex;
+
justify-content: space-between;
+
padding: 0.5rem 0.25rem 0.5rem 0.5rem;
+
font-size: 0.8rem;
+
align-items: baseline;
+
border-radius: 0.5rem;
+
border: 1px solid #bbb;
+
cursor: pointer;
+
}
+
.action:hover {
+
background: #fff;
+
}
+
#form-action:not(.hidden) + .action {
+
display: none !important;
+
}
+
+
#connect,
+
#allow,
+
#revoke {
+
background: transparent;
+
border: none;
+
border-left: 1px solid #bbb;
+
padding: 0 0.5rem;
+
color: #375;
+
font: inherit;
+
cursor: pointer;
+
}
+
#revoke {
+
color: #a31;
+
}
+
#action:hover #allow {
+
color: #285;
+
}
+
+
#need-storage {
+
font-size: 0.8rem;
+
}
+
.problem {
+
color: #a31;
+
}
+
+
#or {
+
font-size: 0.8rem;
+
text-align: center;
+
}
+
#or p {
+
margin: 0 0 1rem;
+
}
+
+
input.handle {
+
border: none;
+
border-bottom: 1px dashed #aaa;
+
background: transparent;
+
}
+
+
.hidden {
+
display: none !important;
+
}
+
+
.hello-connect-plz {
+
margin: 1.667rem 0 0.667rem;
+
}
+20
who-am-i/templates/auth-fail.hbs
···
+
{{#*inline "main"}}
+
<p>
+
Auth failed: {{ reason }}
+
</p>
+
+
<div id="user-info">
+
auth failed.
+
</div>
+
+
<script>
+
localStorage.setItem("who-am-i", JSON.stringify({
+
result: {{{json result}}},
+
reason: {{{json reason}}},
+
}));
+
+
window.close();
+
</script>
+
{{/inline}}
+
+
{{#> base-framed}}{{/base-framed}}
+19
who-am-i/templates/authorized.hbs
···
+
<!doctype html>
+
<meta charset="utf-8" />
+
<title>great job!</title>
+
+
<h1>oauth success!</h1>
+
<p>this window should automatically close itself (probably a bug if it hasn't)</p>
+
+
<script>
+
// TODO: tie this back to its source...........
+
+
localStorage.setItem("who-am-i", JSON.stringify({
+
result: "success",
+
did: {{{json did}}},
+
token: {{{json token}}},
+
fetch_key: {{{json fetch_key}}},
+
}));
+
// TODO: probably also wait for a reply from the frame and show an error if not
+
window.close();
+
</script>
+17
who-am-i/templates/base-base.hbs
···
+
<!doctype html>
+
<html lang="en">
+
<head>
+
<meta charset="utf-8" />
+
<title>who-am-i</title>
+
<meta name="description" content="{{> description }}">
+
<meta property="og:type" content="website">
+
<meta property="og:description" content="{{> description}}">
+
<!-- <meta property="og:image" content=""> -->
+
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
+
<link href="/style.css" rel="stylesheet" type="text/css" />
+
</head>
+
<body>
+
{{> body}}
+
</body>
+
</html>
+28
who-am-i/templates/base-framed.hbs
···
+
{{#*inline "description"}}{{/inline}}
+
+
{{#*inline "body"}}
+
<div class="wrap">
+
<header>
+
<div class="empty">🔒</div>
+
<code class="title" style="font-family: monospace;"
+
>who-am-i</code>
+
<a href="https://microcosm.blue" target="_blank" class="micro"
+
><span style="color: #f396a9">m</span
+
><span style="color: #f49c5c">i</span
+
><span style="color: #c7b04c">c</span
+
><span style="color: #92be4c">r</span
+
><span style="color: #4ec688">o</span
+
><span style="color: #51c2b6">c</span
+
><span style="color: #54bed7">o</span
+
><span style="color: #8fb1f1">s</span
+
><span style="color: #ce9df1">m</span
+
></a>
+
</header>
+
+
<main>
+
{{> main}}
+
</main>
+
</div>
+
{{/inline}}
+
+
{{#> base-base}}{{/base-base}}
+26
who-am-i/templates/base-full.hbs
···
+
{{#*inline "body"}}
+
<div class="wrap unframed">
+
<header>
+
<div class="empty">🔒</div>
+
<code class="title" style="font-family: monospace;"
+
>who-am-i</code>
+
<a href="https://microcosm.blue" target="_blank" class="micro"
+
><span style="color: #f396a9">m</span
+
><span style="color: #f49c5c">i</span
+
><span style="color: #c7b04c">c</span
+
><span style="color: #92be4c">r</span
+
><span style="color: #4ec688">o</span
+
><span style="color: #51c2b6">c</span
+
><span style="color: #54bed7">o</span
+
><span style="color: #8fb1f1">s</span
+
><span style="color: #ce9df1">m</span
+
></a>
+
</header>
+
+
<main>
+
{{> main}}
+
</main>
+
</div>
+
{{/inline}}
+
+
{{#> base-base}}{{/base-base}}
+122
who-am-i/templates/hello.hbs
···
+
{{#*inline "description"}}A little identity-verifying auth service for microcosm demos{{/inline}}
+
+
{{#*inline "main"}}
+
<div class="mini-content">
+
<div class="explain">
+
<p>This is a little identity-verifying service for microcosm demos.</p>
+
<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>
+
</div>
+
+
{{#if did}}
+
<p id="error-message" class="hidden"></p>
+
+
<p id="prompt" class="detail">
+
Connected identity:
+
</p>
+
+
<div id="loader">
+
<span class="spinner"></span>
+
</div>
+
+
<div id="user-info">
+
<div id="handle-action" class="action">
+
<span id="handle-view" class="handle"></span>
+
<button id="revoke">disconnect</button>
+
</div>
+
</div>
+
<script>
+
const errorEl = document.getElementById('error-message');
+
const loaderEl = document.getElementById('loader');
+
const handleViewEl = document.getElementById('handle-view');
+
const revokeEl = document.getElementById('revoke'); // for known-did
+
+
function err(e, msg) {
+
loaderEl.classList.add('hidden');
+
errorEl.classList.remove('hidden');
+
errorEl.textContent = msg || e;
+
throw new Error(e);
+
}
+
+
// already-known user
+
({{{json did}}}) && (async () => {
+
+
const handle = await lookUp({{{json fetch_key}}});
+
+
loaderEl.classList.add('hidden');
+
handleViewEl.textContent = `@${handle}`;
+
revokeEl.addEventListener('click', async () => {
+
try {
+
let res = await fetch('/disconnect', { method: 'POST', credentials: 'include' });
+
if (!res.ok) throw res;
+
} catch (e) {
+
err(e, 'failed to clear session, sorry');
+
}
+
window.location.replace(location.pathname);
+
window.location.reload(); // backup, in case there is no query?
+
});
+
})();
+
+
async function lookUp(fetch_key) {
+
let info;
+
try {
+
const resp = await fetch('/user-info', {
+
method: 'POST',
+
headers: {'Content-Type': 'application/json'},
+
body: JSON.stringify({ fetch_key }),
+
});
+
if (!resp.ok) throw resp;
+
info = await resp.json();
+
} catch (e) {
+
err(e, 'failed to resolve handle from DID')
+
}
+
return info.handle;
+
}
+
</script>
+
{{else}}
+
+
<p class="hello-connect-plz">Connect your handle</p>
+
+
{{#if is_auth_reload}}
+
{{#if no_cookie}}
+
<p id="prompt" class="detail no">
+
No identity connected. Your browser may be blocking access for connecting.
+
</p>
+
{{else}}
+
{{#if auth_failed}}
+
<p id="prompt" class="detail no">
+
No identity connected. Connecting failed or was denied.
+
</p>
+
{{else}}
+
<p id="prompt" class="detail no">
+
No identity connected.
+
</p>
+
{{/if}}
+
{{/if}}
+
{{/if}}
+
+
<div id="user-info">
+
<form id="form-action" action="/auth" target="_blank" method="GET" class="action {{#if did}}hidden{{/if}}">
+
<label>
+
@<input id="handle-input" class="handle" name="handle" placeholder="example.bsky.social" />
+
</label>
+
<button id="connect" type="submit">connect</button>
+
</form>
+
</div>
+
{{/if}}
+
+
</div>
+
<script>
+
window.addEventListener('storage', e => {
+
console.log('eyyy got storage', e);
+
if (e.key !== 'who-am-i') return;
+
if (!e.newValue) return;
+
if (e.newValue.result === 'success') {
+
window.location = '/?auth_reload=1';
+
} else {
+
window.location = '/?auth_reload=1&auth_failed=1';
+
}
+
});
+
</script>
+
{{/inline}}
+
+
{{#> base-full}}{{/base-full}}
+18
who-am-i/templates/prompt-error.hbs
···
+
{{#*inline "main"}}
+
<div class="prompt-error">
+
<p class="went-wrong">Something went wrong :(</p>
+
<p class="reason">{{ reason }}</p>
+
<p class="reason detail">{{ detail }}</p>
+
<p id="maybe-not-in-iframe" class="hidden">
+
Possibly related: this prompt is meant to be shown in an iframe, but it seems like it's not.
+
</p>
+
</div>
+
+
<script>
+
if ({{{json check_frame}}} && window.self === window.top) {
+
document.getElementById('maybe-not-in-iframe').classList.remove('hidden');
+
}
+
</script>
+
{{/inline}}
+
+
{{#> base-framed}}{{/base-framed}}
+187
who-am-i/templates/prompt.hbs
···
+
{{#*inline "main"}}
+
<p>
+
Connect in the ATmosphere
+
</p>
+
+
<p id="error-message" class="hidden"></p>
+
+
<p id="prompt" class="detail">
+
<span class="parent-host">{{ parent_host }}</span> wants to confirm your handle
+
</p>
+
+
<div id="loader" {{#unless did}}class="hidden"{{/unless}}>
+
<span class="spinner"></span>
+
</div>
+
+
<div id="user-info">
+
<form id="form-action" action="/auth" method="GET" target="_blank" class="action {{#if did}}hidden{{/if}}">
+
<label>
+
@<input id="handle-input" class="handle" name="handle" placeholder="example.bsky.social" />
+
</label>
+
<button id="connect" type="submit">connect</button>
+
</form>
+
+
<div id="handle-action" class="action">
+
<span id="handle-view" class="handle"></span>
+
<button id="allow">Allow</button>
+
</div>
+
</div>
+
+
<div id="need-storage" class="hidden">
+
<p class="problem">Sorry, your browser is blocking access.</p>
+
<p>
+
Try <a href="/" target="_blank">connecting directly</a> first (but no promises).
+
Clicking <button id="desperation">this button</button> might also help.
+
</p>
+
</div>
+
+
+
+
<script>
+
const errorEl = document.getElementById('error-message');
+
const promptEl = document.getElementById('prompt');
+
const loaderEl = document.getElementById('loader');
+
const infoEl = document.getElementById('user-info');
+
const handleInputEl = document.getElementById('handle-input');
+
const handleViewEl = document.getElementById('handle-view');
+
const formEl = document.getElementById('form-action'); // for anon
+
const allowEl = document.getElementById('handle-action'); // for known-did
+
const connectEl = document.getElementById('connect'); // for anon
+
const needStorageEl = document.getElementById('need-storage'); // for safari/frame isolation
+
const desperationEl = document.getElementById('desperation');
+
+
function err(e, msg) {
+
loaderEl.classList.add('hidden');
+
errorEl.classList.remove('hidden');
+
errorEl.textContent = msg || e;
+
throw new Error(e);
+
}
+
+
// already-known user
+
({{{json did}}}) && (async () => {
+
const handle = await lookUp({{{json fetch_key}}});
+
loaderEl.classList.add('hidden');
+
handleViewEl.textContent = `@${handle}`;
+
allowEl.addEventListener('click', () => shareAllow(handle, {{{json token}}}));
+
})();
+
+
// anon user
+
formEl.onsubmit = e => {
+
e.preventDefault();
+
loaderEl.classList.remove('hidden');
+
// TODO: include expected referer! (..this system is probably bad)
+
// maybe a random localstorage key that we specifically listen for?
+
const url = new URL('/auth', window.location);
+
url.searchParams.set('handle', handleInputEl.value);
+
window.open(url, '_blank');
+
};
+
+
// check if we may be partitioned, preventing access after auth completion
+
// this should only happen if on a browser that implements storage access api
+
if ('hasStorageAccess' in document) {
+
document.hasStorageAccess().then((hasAccess) => {
+
if (!hasAccess) {
+
promptEl.classList.add('hidden');
+
infoEl.classList.add('hidden');
+
needStorageEl.classList.remove('hidden');
+
desperation.addEventListener('click', () => {
+
document.requestStorageAccess({
+
cookies: true,
+
localStorage: true,
+
}).then(
+
() => {
+
desperation.textContent = "(maybe helped?)";
+
setTimeout(() => location.reload(), 350);
+
},
+
() => desperation.textContent = "(doubtful)",
+
);
+
})
+
}
+
});
+
}
+
+
window.addEventListener('storage', async e => {
+
// here's a fun minor vuln: we can't tell which flow triggers the storage event.
+
// so if you have two flows going, it grants for both (or the first responder?) if you grant for either.
+
// (letting this slide while parent pages are allowlisted to microcosm only)
+
+
if (e.key !== 'who-am-i') return;
+
if (e.newValue === null) return;
+
+
const details = e.newValue;
+
if (!details) {
+
console.error("hmm, heard from localstorage but did not get DID", details, e);
+
err('sorry, something went wrong getting your details');
+
}
+
+
let parsed;
+
try {
+
parsed = JSON.parse(details);
+
} catch (e) {
+
err(e, "something went wrong getting the details back");
+
}
+
+
const fail = (e, msg) => {
+
loaderEl.classList.add('hidden');
+
formEl.classList.remove('hidden');
+
handleInputEl.focus();
+
handleInputEl.select();
+
err(e, msg);
+
}
+
+
if (parsed.result === "fail") {
+
fail(`uh oh: ${parsed.reason}`);
+
}
+
+
if (parsed.result === "deny") {
+
fail(parsed.reason);
+
}
+
+
infoEl.classList.add('hidden');
+
+
const handle = await lookUp(parsed.fetch_key);
+
+
shareAllow(handle, parsed.token);
+
});
+
+
async function lookUp(fetch_key) {
+
let info;
+
try {
+
const resp = await fetch('/user-info', {
+
method: 'POST',
+
headers: { 'Content-Type': 'application/json' },
+
body: JSON.stringify({ fetch_key }),
+
});
+
if (!resp.ok) throw resp;
+
info = await resp.json();
+
} catch (e) {
+
err(e, `failed to resolve handle from DID with ${fetch_key}`);
+
}
+
return info.handle;
+
}
+
+
const parentTarget = {{{json parent_target}}} ?? {{{json parent_origin}}};
+
+
const shareAllow = (handle, token) => {
+
try {
+
top.postMessage(
+
{ action: "allow", handle, token },
+
parentTarget,
+
);
+
} catch (e) {
+
err(e, 'Identity verified but failed to connect with app');
+
};
+
promptEl.textContent = '✔️ shared';
+
}
+
+
const shareDeny = reason => {
+
top.postMessage(
+
{ action: "deny", reason },
+
parentTarget,
+
);
+
}
+
</script>
+
+
{{/inline}}
+
+
{{#> base-framed}}{{/base-framed}}