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

Compare changes

Choose any two refs to compare.

+167 -137
Cargo.lock
···
"proc-macro2",
"quote",
"serde",
-
"syn 2.0.103",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
"synstructure",
]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
"derive_utils",
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
"axum-core",
"bytes",
"cookie",
"futures-util",
"headers",
"http",
···
"pin-project-lite",
"rustversion",
"serde",
"tower",
"tower-layer",
"tower-service",
···
"regex",
"rustc-hash 1.1.0",
"shlex",
-
"syn 2.0.103",
"which",
]
···
"regex",
"rustc-hash 1.1.0",
"shlex",
-
"syn 2.0.103",
]
[[package]]
···
"regex",
"rustc-hash 2.1.1",
"shlex",
-
"syn 2.0.103",
]
[[package]]
···
[[package]]
name = "camino"
-
version = "1.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "8b96ec4966b5813e2c0507c1f86115c8c5abaadc3980879c3424042a02fd1ad3"
dependencies = [
-
"serde",
]
[[package]]
···
[[package]]
name = "clap"
-
version = "4.5.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "7eac00902d9d136acd712710d71823fb8ac8004ca445a89e73a41d45aa712931"
dependencies = [
"clap_builder",
"clap_derive",
···
[[package]]
name = "clap_builder"
-
version = "4.5.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "2ad9bbf750e73b5884fb8a211a9424a1906c1e156724260fdae972f31d70e1d6"
dependencies = [
"anstream",
"anstyle",
···
"heck",
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
"proc-macro2",
"quote",
"strsim 0.11.1",
-
"syn 2.0.103",
]
[[package]]
···
dependencies = [
"darling_core 0.20.11",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
checksum = "18e4fdb82bd54a12e42fb58a800dcae6b9e13982238ce2296dc3570b92148e1f"
dependencies = [
"data-encoding",
-
"syn 2.0.103",
]
[[package]]
···
"darling 0.20.11",
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c"
dependencies = [
"derive_builder_core",
-
"syn 2.0.103",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
"unicode-xid",
]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
[[package]]
name = "dropshot"
-
version = "0.16.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "50e8fed669e35e757646ad10f97c4d26dd22cce3da689b307954f7000d2719d0"
dependencies = [
"async-stream",
"async-trait",
···
"http-body-util",
"hyper",
"hyper-util",
-
"indexmap 2.9.0",
"multer",
"openapiv3",
"paste",
···
"thiserror 2.0.16",
"tokio",
"tokio-rustls 0.25.0",
-
"toml",
"uuid",
"version_check",
"waitgroup",
···
[[package]]
name = "dropshot_endpoint"
-
version = "0.16.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "acebb687581abdeaa2c89fa448818a5f803b0e68e5d7e7a1cf585a8f3c5c57ac"
dependencies = [
"heck",
"proc-macro2",
···
"semver",
"serde",
"serde_tokenstream",
-
"syn 2.0.103",
]
[[package]]
···
"heck",
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
"once_cell",
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
"futures-core",
"futures-sink",
"http",
-
"indexmap 2.9.0",
"slab",
"tokio",
"tokio-util",
···
"js-sys",
"log",
"wasm-bindgen",
-
"windows-core 0.61.0",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
[[package]]
name = "indexmap"
-
version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "cea70ddb795996207ad57735b50c5982d8844f38ba9ee5f1aedcfb708a2aa11e"
dependencies = [
"equivalent",
"hashbrown 0.15.2",
"serde",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
"spin",
"tokio",
"tokio-util",
-
"toml",
"tracing",
"tracing-subscriber",
]
···
"http-body-util",
"hyper",
"hyper-util",
-
"indexmap 2.9.0",
"ipnet",
"metrics",
"metrics-util 0.19.0",
···
"hyper",
"hyper-rustls",
"hyper-util",
-
"indexmap 2.9.0",
"ipnet",
"metrics",
"metrics-util 0.20.0",
···
[[package]]
name = "openapiv3"
-
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "cc02deea53ffe807708244e5914f6b099ad7015a207ee24317c22112e17d9c5c"
dependencies = [
-
"indexmap 2.9.0",
"serde",
"serde_json",
]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
"pest_meta",
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
"proc-macro-crate",
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
"bytes",
"derive_more",
"futures-util",
-
"indexmap 2.9.0",
"itertools 0.14.0",
"mime",
"num-traits",
···
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",
]
···
checksum = "6837b9e10d61f45f987d50808f83d1ee3d206c66acf650c3e4ae2e1f6ddedf55"
dependencies = [
"proc-macro2",
-
"syn 2.0.103",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
[[package]]
name = "reqwest"
-
version = "0.12.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "cbc931937e6ca3a06e3b6c0aa7841849b160a90351d6ab467a8b9b9959767531"
dependencies = [
"async-compression",
"base64 0.22.1",
···
"proc-macro2",
"quote",
"serde_derive_internals",
-
"syn 2.0.103",
]
[[package]]
···
[[package]]
name = "serde"
-
version = "1.0.219"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6"
dependencies = [
"serde_derive",
]
···
checksum = "8437fd221bde2d4ca316d61b90e337e9e702b3820b87d63caa9ba6c02bd06d96"
dependencies = [
"serde",
]
[[package]]
name = "serde_derive"
-
version = "1.0.219"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00"
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
checksum = "9d2de91cf02bbc07cde38891769ccd5d4f073d22a40683aa4bc7a95781aaa2c4"
dependencies = [
"form_urlencoded",
-
"indexmap 2.9.0",
"itoa",
"ryu",
"serde",
···
[[package]]
name = "serde_json"
-
version = "1.0.141"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "30b9eff21ebe718216c6ec64e1d9ac57087aad11efc64e32002bce4a0d4c03d3"
dependencies = [
"itoa",
"memchr",
"ryu",
"serde",
]
[[package]]
···
]
[[package]]
name = "serde_tokenstream"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
"proc-macro2",
"quote",
"serde",
-
"syn 2.0.103",
]
[[package]]
···
"chrono",
"hex",
"indexmap 1.9.3",
-
"indexmap 2.9.0",
"serde",
"serde_derive",
"serde_json",
···
"darling 0.20.11",
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"
dependencies = [
-
"indexmap 2.9.0",
"itoa",
"ryu",
"serde",
···
[[package]]
name = "syn"
-
version = "2.0.103"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "e4307e30089d6fd6aff212f2da3a1f9e32f3223b1f010fb09b7c95f90f3ca1e8"
dependencies = [
"proc-macro2",
"quote",
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"
dependencies = [
"serde",
-
"serde_spanned",
-
"toml_datetime",
"toml_edit",
]
[[package]]
name = "toml_datetime"
version = "0.6.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
]
[[package]]
name = "toml_edit"
version = "0.22.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
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"
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
[[package]]
name = "uuid"
-
version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "458f7a779bf54acc9f347480ac654f68407d3aab21269a6e3c9f922acd9e2da9"
dependencies = [
"getrandom 0.3.3",
"serde",
]
[[package]]
···
"log",
"proc-macro2",
"quote",
-
"syn 2.0.103",
"wasm-bindgen-shared",
]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
···
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6"
dependencies = [
-
"windows-core 0.58.0",
"windows-targets 0.52.6",
]
···
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99"
dependencies = [
-
"windows-implement 0.58.0",
-
"windows-interface 0.58.0",
"windows-result 0.2.0",
"windows-strings 0.1.0",
"windows-targets 0.52.6",
]
[[package]]
-
name = "windows-core"
-
version = "0.61.0"
-
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "4763c1de310c86d75a878046489e2e5ba02c649d185f21c67d4cf8a56d098980"
-
dependencies = [
-
"windows-implement 0.60.0",
-
"windows-interface 0.59.1",
-
"windows-link",
-
"windows-result 0.3.4",
-
"windows-strings 0.4.2",
-
]
-
-
[[package]]
name = "windows-implement"
version = "0.58.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
-
]
-
-
[[package]]
-
name = "windows-implement"
-
version = "0.60.0"
-
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "a47fddd13af08290e67f4acabf4b459f647552718f683a7b415d290ac744a836"
-
dependencies = [
-
"proc-macro2",
-
"quote",
-
"syn 2.0.103",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
-
]
-
-
[[package]]
-
name = "windows-interface"
-
version = "0.59.1"
-
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "bd9211b69f8dcdfa817bfd14bf1c97c9188afa36f4750130fcdf3f400eca9fa8"
-
dependencies = [
-
"proc-macro2",
-
"quote",
-
"syn 2.0.103",
]
[[package]]
···
[[package]]
name = "winnow"
-
version = "0.7.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
-
checksum = "74c7b26e3480b707944fc872477815d29a8e429d2f93a1ce000f5fa84a15cbcd"
dependencies = [
"memchr",
]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
"synstructure",
]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
"synstructure",
]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
-
"syn 2.0.103",
]
[[package]]
···
"proc-macro2",
"quote",
"serde",
+
"syn 2.0.106",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
"synstructure",
]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
"derive_utils",
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
"axum-core",
"bytes",
"cookie",
+
"form_urlencoded",
"futures-util",
"headers",
"http",
···
"pin-project-lite",
"rustversion",
"serde",
+
"serde_html_form",
+
"serde_path_to_error",
"tower",
"tower-layer",
"tower-service",
···
"regex",
"rustc-hash 1.1.0",
"shlex",
+
"syn 2.0.106",
"which",
]
···
"regex",
"rustc-hash 1.1.0",
"shlex",
+
"syn 2.0.106",
]
[[package]]
···
"regex",
"rustc-hash 2.1.1",
"shlex",
+
"syn 2.0.106",
]
[[package]]
···
[[package]]
name = "camino"
+
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "276a59bf2b2c967788139340c9f0c5b12d7fd6630315c15c217e559de85d2609"
dependencies = [
+
"serde_core",
]
[[package]]
···
[[package]]
name = "clap"
+
version = "4.5.48"
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "e2134bb3ea021b78629caa971416385309e0131b351b25e01dc16fb54e1b5fae"
dependencies = [
"clap_builder",
"clap_derive",
···
[[package]]
name = "clap_builder"
+
version = "4.5.48"
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "c2ba64afa3c0a6df7fa517765e31314e983f51dda798ffba27b988194fb65dc9"
dependencies = [
"anstream",
"anstyle",
···
"heck",
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
"proc-macro2",
"quote",
"strsim 0.11.1",
+
"syn 2.0.106",
]
[[package]]
···
dependencies = [
"darling_core 0.20.11",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
checksum = "18e4fdb82bd54a12e42fb58a800dcae6b9e13982238ce2296dc3570b92148e1f"
dependencies = [
"data-encoding",
+
"syn 2.0.106",
]
[[package]]
···
"darling 0.20.11",
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c"
dependencies = [
"derive_builder_core",
+
"syn 2.0.106",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
"unicode-xid",
]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
[[package]]
name = "dropshot"
+
version = "0.16.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "eedf902e40c1024b8ed9ca16378a54e9655cdf0e698245ba82d81a3778dcbc54"
dependencies = [
"async-stream",
"async-trait",
···
"http-body-util",
"hyper",
"hyper-util",
+
"indexmap 2.11.4",
"multer",
"openapiv3",
"paste",
···
"thiserror 2.0.16",
"tokio",
"tokio-rustls 0.25.0",
+
"toml 0.9.7",
"uuid",
"version_check",
"waitgroup",
···
[[package]]
name = "dropshot_endpoint"
+
version = "0.16.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "89d09440e73a9dcf8a0f7fbd6ab889a7751d59f0fe76e5082a0a6d5623ec6da3"
dependencies = [
"heck",
"proc-macro2",
···
"semver",
"serde",
"serde_tokenstream",
+
"syn 2.0.106",
]
[[package]]
···
"heck",
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
"once_cell",
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
"futures-core",
"futures-sink",
"http",
+
"indexmap 2.11.4",
"slab",
"tokio",
"tokio-util",
···
"js-sys",
"log",
"wasm-bindgen",
+
"windows-core",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
[[package]]
name = "indexmap"
+
version = "2.11.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "4b0f83760fb341a774ed326568e19f5a863af4a952def8c39f9ab92fd95b88e5"
dependencies = [
"equivalent",
"hashbrown 0.15.2",
"serde",
+
"serde_core",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
"spin",
"tokio",
"tokio-util",
+
"toml 0.8.23",
"tracing",
"tracing-subscriber",
]
···
"http-body-util",
"hyper",
"hyper-util",
+
"indexmap 2.11.4",
"ipnet",
"metrics",
"metrics-util 0.19.0",
···
"hyper",
"hyper-rustls",
"hyper-util",
+
"indexmap 2.11.4",
"ipnet",
"metrics",
"metrics-util 0.20.0",
···
[[package]]
name = "openapiv3"
+
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "5c8d427828b22ae1fff2833a03d8486c2c881367f1c336349f307f321e7f4d05"
dependencies = [
+
"indexmap 2.11.4",
"serde",
"serde_json",
]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
"pest_meta",
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
"proc-macro-crate",
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
"bytes",
"derive_more",
"futures-util",
+
"indexmap 2.11.4",
"itertools 0.14.0",
"mime",
"num-traits",
···
dependencies = [
"darling 0.20.11",
"http",
+
"indexmap 2.11.4",
"mime",
"proc-macro-crate",
"proc-macro2",
"quote",
"regex",
+
"syn 2.0.106",
"thiserror 2.0.16",
]
···
checksum = "6837b9e10d61f45f987d50808f83d1ee3d206c66acf650c3e4ae2e1f6ddedf55"
dependencies = [
"proc-macro2",
+
"syn 2.0.106",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
[[package]]
name = "reqwest"
+
version = "0.12.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "d429f34c8092b2d42c7c93cec323bb4adeb7c67698f70839adec842ec10c7ceb"
dependencies = [
"async-compression",
"base64 0.22.1",
···
"proc-macro2",
"quote",
"serde_derive_internals",
+
"syn 2.0.106",
]
[[package]]
···
[[package]]
name = "serde"
+
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
dependencies = [
+
"serde_core",
"serde_derive",
]
···
checksum = "8437fd221bde2d4ca316d61b90e337e9e702b3820b87d63caa9ba6c02bd06d96"
dependencies = [
"serde",
+
]
+
+
[[package]]
+
name = "serde_core"
+
version = "1.0.228"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
+
dependencies = [
+
"serde_derive",
]
[[package]]
name = "serde_derive"
+
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
checksum = "9d2de91cf02bbc07cde38891769ccd5d4f073d22a40683aa4bc7a95781aaa2c4"
dependencies = [
"form_urlencoded",
+
"indexmap 2.11.4",
"itoa",
"ryu",
"serde",
···
[[package]]
name = "serde_json"
+
version = "1.0.145"
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c"
dependencies = [
"itoa",
"memchr",
"ryu",
"serde",
+
"serde_core",
]
[[package]]
···
]
[[package]]
+
name = "serde_spanned"
+
version = "1.0.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "5417783452c2be558477e104686f7de5dae53dba813c28435e0e70f82d9b04ee"
+
dependencies = [
+
"serde_core",
+
]
+
+
[[package]]
name = "serde_tokenstream"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
"proc-macro2",
"quote",
"serde",
+
"syn 2.0.106",
]
[[package]]
···
"chrono",
"hex",
"indexmap 1.9.3",
+
"indexmap 2.11.4",
"serde",
"serde_derive",
"serde_json",
···
"darling 0.20.11",
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"
dependencies = [
+
"indexmap 2.11.4",
"itoa",
"ryu",
"serde",
···
[[package]]
name = "syn"
+
version = "2.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6"
dependencies = [
"proc-macro2",
"quote",
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"
dependencies = [
"serde",
+
"serde_spanned 0.6.9",
+
"toml_datetime 0.6.11",
"toml_edit",
]
[[package]]
+
name = "toml"
+
version = "0.9.7"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "00e5e5d9bf2475ac9d4f0d9edab68cc573dc2fd644b0dba36b0c30a92dd9eaa0"
+
dependencies = [
+
"indexmap 2.11.4",
+
"serde_core",
+
"serde_spanned 1.0.2",
+
"toml_datetime 0.7.2",
+
"toml_parser",
+
"toml_writer",
+
"winnow",
+
]
+
+
[[package]]
name = "toml_datetime"
version = "0.6.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
]
[[package]]
+
name = "toml_datetime"
+
version = "0.7.2"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "32f1085dec27c2b6632b04c80b3bb1b4300d6495d1e129693bdda7d91e72eec1"
+
dependencies = [
+
"serde_core",
+
]
+
+
[[package]]
name = "toml_edit"
version = "0.22.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
dependencies = [
+
"indexmap 2.11.4",
"serde",
+
"serde_spanned 0.6.9",
+
"toml_datetime 0.6.11",
"toml_write",
"winnow",
]
[[package]]
+
name = "toml_parser"
+
version = "1.0.3"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "4cf893c33be71572e0e9aa6dd15e6677937abd686b066eac3f8cd3531688a627"
+
dependencies = [
+
"winnow",
+
]
+
+
[[package]]
name = "toml_write"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
[[package]]
+
name = "toml_writer"
+
version = "1.0.3"
+
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "d163a63c116ce562a22cda521fcc4d79152e7aba014456fb5eb442f6d6a10109"
+
+
[[package]]
name = "tower"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
[[package]]
name = "uuid"
+
version = "1.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "2f87b8aa10b915a06587d0dec516c282ff295b475d94abf425d62b57710070a2"
dependencies = [
"getrandom 0.3.3",
+
"js-sys",
"serde",
+
"wasm-bindgen",
]
[[package]]
···
"log",
"proc-macro2",
"quote",
+
"syn 2.0.106",
"wasm-bindgen-shared",
]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
···
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6"
dependencies = [
+
"windows-core",
"windows-targets 0.52.6",
]
···
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99"
dependencies = [
+
"windows-implement",
+
"windows-interface",
"windows-result 0.2.0",
"windows-strings 0.1.0",
"windows-targets 0.52.6",
]
[[package]]
name = "windows-implement"
version = "0.58.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
[[package]]
name = "winnow"
+
version = "0.7.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
+
checksum = "21a0236b59786fed61e2a80582dd500fe61f18b5dca67a4a067d0bc9039339cf"
dependencies = [
"memchr",
]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
"synstructure",
]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
"synstructure",
]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
···
dependencies = [
"proc-macro2",
"quote",
+
"syn 2.0.106",
]
[[package]]
+1 -1
constellation/Cargo.toml
···
anyhow = "1.0.95"
askama = { version = "0.12.1", features = ["serde-json"] }
axum = "0.8.1"
-
axum-extra = { version = "0.10.0", features = ["typed-header"] }
axum-metrics = "0.2"
bincode = "1.3.3"
clap = { version = "4.5.26", features = ["derive"] }
···
anyhow = "1.0.95"
askama = { version = "0.12.1", features = ["serde-json"] }
axum = "0.8.1"
+
axum-extra = { version = "0.10.0", features = ["query", "typed-header"] }
axum-metrics = "0.2"
bincode = "1.3.3"
clap = { version = "4.5.26", features = ["derive"] }
+661
constellation/LICENSE
···
···
+
GNU AFFERO GENERAL PUBLIC LICENSE
+
Version 3, 19 November 2007
+
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+
Everyone is permitted to copy and distribute verbatim copies
+
of this license document, but changing it is not allowed.
+
+
Preamble
+
+
The GNU Affero General Public License is a free, copyleft license for
+
software and other kinds of works, specifically designed to ensure
+
cooperation with the community in the case of network server software.
+
+
The licenses for most software and other practical works are designed
+
to take away your freedom to share and change the works. By contrast,
+
our General Public Licenses are intended to guarantee your freedom to
+
share and change all versions of a program--to make sure it remains free
+
software for all its users.
+
+
When we speak of free software, we are referring to freedom, not
+
price. Our General Public Licenses are designed to make sure that you
+
have the freedom to distribute copies of free software (and charge for
+
them if you wish), that you receive source code or can get it if you
+
want it, that you can change the software or use pieces of it in new
+
free programs, and that you know you can do these things.
+
+
Developers that use our General Public Licenses protect your rights
+
with two steps: (1) assert copyright on the software, and (2) offer
+
you this License which gives you legal permission to copy, distribute
+
and/or modify the software.
+
+
A secondary benefit of defending all users' freedom is that
+
improvements made in alternate versions of the program, if they
+
receive widespread use, become available for other developers to
+
incorporate. Many developers of free software are heartened and
+
encouraged by the resulting cooperation. However, in the case of
+
software used on network servers, this result may fail to come about.
+
The GNU General Public License permits making a modified version and
+
letting the public access it on a server without ever releasing its
+
source code to the public.
+
+
The GNU Affero General Public License is designed specifically to
+
ensure that, in such cases, the modified source code becomes available
+
to the community. It requires the operator of a network server to
+
provide the source code of the modified version running there to the
+
users of that server. Therefore, public use of a modified version, on
+
a publicly accessible server, gives the public access to the source
+
code of the modified version.
+
+
An older license, called the Affero General Public License and
+
published by Affero, was designed to accomplish similar goals. This is
+
a different license, not a version of the Affero GPL, but Affero has
+
released a new version of the Affero GPL which permits relicensing under
+
this license.
+
+
The precise terms and conditions for copying, distribution and
+
modification follow.
+
+
TERMS AND CONDITIONS
+
+
0. Definitions.
+
+
"This License" refers to version 3 of the GNU Affero General Public License.
+
+
"Copyright" also means copyright-like laws that apply to other kinds of
+
works, such as semiconductor masks.
+
+
"The Program" refers to any copyrightable work licensed under this
+
License. Each licensee is addressed as "you". "Licensees" and
+
"recipients" may be individuals or organizations.
+
+
To "modify" a work means to copy from or adapt all or part of the work
+
in a fashion requiring copyright permission, other than the making of an
+
exact copy. The resulting work is called a "modified version" of the
+
earlier work or a work "based on" the earlier work.
+
+
A "covered work" means either the unmodified Program or a work based
+
on the Program.
+
+
To "propagate" a work means to do anything with it that, without
+
permission, would make you directly or secondarily liable for
+
infringement under applicable copyright law, except executing it on a
+
computer or modifying a private copy. Propagation includes copying,
+
distribution (with or without modification), making available to the
+
public, and in some countries other activities as well.
+
+
To "convey" a work means any kind of propagation that enables other
+
parties to make or receive copies. Mere interaction with a user through
+
a computer network, with no transfer of a copy, is not conveying.
+
+
An interactive user interface displays "Appropriate Legal Notices"
+
to the extent that it includes a convenient and prominently visible
+
feature that (1) displays an appropriate copyright notice, and (2)
+
tells the user that there is no warranty for the work (except to the
+
extent that warranties are provided), that licensees may convey the
+
work under this License, and how to view a copy of this License. If
+
the interface presents a list of user commands or options, such as a
+
menu, a prominent item in the list meets this criterion.
+
+
1. Source Code.
+
+
The "source code" for a work means the preferred form of the work
+
for making modifications to it. "Object code" means any non-source
+
form of a work.
+
+
A "Standard Interface" means an interface that either is an official
+
standard defined by a recognized standards body, or, in the case of
+
interfaces specified for a particular programming language, one that
+
is widely used among developers working in that language.
+
+
The "System Libraries" of an executable work include anything, other
+
than the work as a whole, that (a) is included in the normal form of
+
packaging a Major Component, but which is not part of that Major
+
Component, and (b) serves only to enable use of the work with that
+
Major Component, or to implement a Standard Interface for which an
+
implementation is available to the public in source code form. A
+
"Major Component", in this context, means a major essential component
+
(kernel, window system, and so on) of the specific operating system
+
(if any) on which the executable work runs, or a compiler used to
+
produce the work, or an object code interpreter used to run it.
+
+
The "Corresponding Source" for a work in object code form means all
+
the source code needed to generate, install, and (for an executable
+
work) run the object code and to modify the work, including scripts to
+
control those activities. However, it does not include the work's
+
System Libraries, or general-purpose tools or generally available free
+
programs which are used unmodified in performing those activities but
+
which are not part of the work. For example, Corresponding Source
+
includes interface definition files associated with source files for
+
the work, and the source code for shared libraries and dynamically
+
linked subprograms that the work is specifically designed to require,
+
such as by intimate data communication or control flow between those
+
subprograms and other parts of the work.
+
+
The Corresponding Source need not include anything that users
+
can regenerate automatically from other parts of the Corresponding
+
Source.
+
+
The Corresponding Source for a work in source code form is that
+
same work.
+
+
2. Basic Permissions.
+
+
All rights granted under this License are granted for the term of
+
copyright on the Program, and are irrevocable provided the stated
+
conditions are met. This License explicitly affirms your unlimited
+
permission to run the unmodified Program. The output from running a
+
covered work is covered by this License only if the output, given its
+
content, constitutes a covered work. This License acknowledges your
+
rights of fair use or other equivalent, as provided by copyright law.
+
+
You may make, run and propagate covered works that you do not
+
convey, without conditions so long as your license otherwise remains
+
in force. You may convey covered works to others for the sole purpose
+
of having them make modifications exclusively for you, or provide you
+
with facilities for running those works, provided that you comply with
+
the terms of this License in conveying all material for which you do
+
not control copyright. Those thus making or running the covered works
+
for you must do so exclusively on your behalf, under your direction
+
and control, on terms that prohibit them from making any copies of
+
your copyrighted material outside their relationship with you.
+
+
Conveying under any other circumstances is permitted solely under
+
the conditions stated below. Sublicensing is not allowed; section 10
+
makes it unnecessary.
+
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+
No covered work shall be deemed part of an effective technological
+
measure under any applicable law fulfilling obligations under article
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
+
similar laws prohibiting or restricting circumvention of such
+
measures.
+
+
When you convey a covered work, you waive any legal power to forbid
+
circumvention of technological measures to the extent such circumvention
+
is effected by exercising rights under this License with respect to
+
the covered work, and you disclaim any intention to limit operation or
+
modification of the work as a means of enforcing, against the work's
+
users, your or third parties' legal rights to forbid circumvention of
+
technological measures.
+
+
4. Conveying Verbatim Copies.
+
+
You may convey verbatim copies of the Program's source code as you
+
receive it, in any medium, provided that you conspicuously and
+
appropriately publish on each copy an appropriate copyright notice;
+
keep intact all notices stating that this License and any
+
non-permissive terms added in accord with section 7 apply to the code;
+
keep intact all notices of the absence of any warranty; and give all
+
recipients a copy of this License along with the Program.
+
+
You may charge any price or no price for each copy that you convey,
+
and you may offer support or warranty protection for a fee.
+
+
5. Conveying Modified Source Versions.
+
+
You may convey a work based on the Program, or the modifications to
+
produce it from the Program, in the form of source code under the
+
terms of section 4, provided that you also meet all of these conditions:
+
+
a) The work must carry prominent notices stating that you modified
+
it, and giving a relevant date.
+
+
b) The work must carry prominent notices stating that it is
+
released under this License and any conditions added under section
+
7. This requirement modifies the requirement in section 4 to
+
"keep intact all notices".
+
+
c) You must license the entire work, as a whole, under this
+
License to anyone who comes into possession of a copy. This
+
License will therefore apply, along with any applicable section 7
+
additional terms, to the whole of the work, and all its parts,
+
regardless of how they are packaged. This License gives no
+
permission to license the work in any other way, but it does not
+
invalidate such permission if you have separately received it.
+
+
d) If the work has interactive user interfaces, each must display
+
Appropriate Legal Notices; however, if the Program has interactive
+
interfaces that do not display Appropriate Legal Notices, your
+
work need not make them do so.
+
+
A compilation of a covered work with other separate and independent
+
works, which are not by their nature extensions of the covered work,
+
and which are not combined with it such as to form a larger program,
+
in or on a volume of a storage or distribution medium, is called an
+
"aggregate" if the compilation and its resulting copyright are not
+
used to limit the access or legal rights of the compilation's users
+
beyond what the individual works permit. Inclusion of a covered work
+
in an aggregate does not cause this License to apply to the other
+
parts of the aggregate.
+
+
6. Conveying Non-Source Forms.
+
+
You may convey a covered work in object code form under the terms
+
of sections 4 and 5, provided that you also convey the
+
machine-readable Corresponding Source under the terms of this License,
+
in one of these ways:
+
+
a) Convey the object code in, or embodied in, a physical product
+
(including a physical distribution medium), accompanied by the
+
Corresponding Source fixed on a durable physical medium
+
customarily used for software interchange.
+
+
b) Convey the object code in, or embodied in, a physical product
+
(including a physical distribution medium), accompanied by a
+
written offer, valid for at least three years and valid for as
+
long as you offer spare parts or customer support for that product
+
model, to give anyone who possesses the object code either (1) a
+
copy of the Corresponding Source for all the software in the
+
product that is covered by this License, on a durable physical
+
medium customarily used for software interchange, for a price no
+
more than your reasonable cost of physically performing this
+
conveying of source, or (2) access to copy the
+
Corresponding Source from a network server at no charge.
+
+
c) Convey individual copies of the object code with a copy of the
+
written offer to provide the Corresponding Source. This
+
alternative is allowed only occasionally and noncommercially, and
+
only if you received the object code with such an offer, in accord
+
with subsection 6b.
+
+
d) Convey the object code by offering access from a designated
+
place (gratis or for a charge), and offer equivalent access to the
+
Corresponding Source in the same way through the same place at no
+
further charge. You need not require recipients to copy the
+
Corresponding Source along with the object code. If the place to
+
copy the object code is a network server, the Corresponding Source
+
may be on a different server (operated by you or a third party)
+
that supports equivalent copying facilities, provided you maintain
+
clear directions next to the object code saying where to find the
+
Corresponding Source. Regardless of what server hosts the
+
Corresponding Source, you remain obligated to ensure that it is
+
available for as long as needed to satisfy these requirements.
+
+
e) Convey the object code using peer-to-peer transmission, provided
+
you inform other peers where the object code and Corresponding
+
Source of the work are being offered to the general public at no
+
charge under subsection 6d.
+
+
A separable portion of the object code, whose source code is excluded
+
from the Corresponding Source as a System Library, need not be
+
included in conveying the object code work.
+
+
A "User Product" is either (1) a "consumer product", which means any
+
tangible personal property which is normally used for personal, family,
+
or household purposes, or (2) anything designed or sold for incorporation
+
into a dwelling. In determining whether a product is a consumer product,
+
doubtful cases shall be resolved in favor of coverage. For a particular
+
product received by a particular user, "normally used" refers to a
+
typical or common use of that class of product, regardless of the status
+
of the particular user or of the way in which the particular user
+
actually uses, or expects or is expected to use, the product. A product
+
is a consumer product regardless of whether the product has substantial
+
commercial, industrial or non-consumer uses, unless such uses represent
+
the only significant mode of use of the product.
+
+
"Installation Information" for a User Product means any methods,
+
procedures, authorization keys, or other information required to install
+
and execute modified versions of a covered work in that User Product from
+
a modified version of its Corresponding Source. The information must
+
suffice to ensure that the continued functioning of the modified object
+
code is in no case prevented or interfered with solely because
+
modification has been made.
+
+
If you convey an object code work under this section in, or with, or
+
specifically for use in, a User Product, and the conveying occurs as
+
part of a transaction in which the right of possession and use of the
+
User Product is transferred to the recipient in perpetuity or for a
+
fixed term (regardless of how the transaction is characterized), the
+
Corresponding Source conveyed under this section must be accompanied
+
by the Installation Information. But this requirement does not apply
+
if neither you nor any third party retains the ability to install
+
modified object code on the User Product (for example, the work has
+
been installed in ROM).
+
+
The requirement to provide Installation Information does not include a
+
requirement to continue to provide support service, warranty, or updates
+
for a work that has been modified or installed by the recipient, or for
+
the User Product in which it has been modified or installed. Access to a
+
network may be denied when the modification itself materially and
+
adversely affects the operation of the network or violates the rules and
+
protocols for communication across the network.
+
+
Corresponding Source conveyed, and Installation Information provided,
+
in accord with this section must be in a format that is publicly
+
documented (and with an implementation available to the public in
+
source code form), and must require no special password or key for
+
unpacking, reading or copying.
+
+
7. Additional Terms.
+
+
"Additional permissions" are terms that supplement the terms of this
+
License by making exceptions from one or more of its conditions.
+
Additional permissions that are applicable to the entire Program shall
+
be treated as though they were included in this License, to the extent
+
that they are valid under applicable law. If additional permissions
+
apply only to part of the Program, that part may be used separately
+
under those permissions, but the entire Program remains governed by
+
this License without regard to the additional permissions.
+
+
When you convey a copy of a covered work, you may at your option
+
remove any additional permissions from that copy, or from any part of
+
it. (Additional permissions may be written to require their own
+
removal in certain cases when you modify the work.) You may place
+
additional permissions on material, added by you to a covered work,
+
for which you have or can give appropriate copyright permission.
+
+
Notwithstanding any other provision of this License, for material you
+
add to a covered work, you may (if authorized by the copyright holders of
+
that material) supplement the terms of this License with terms:
+
+
a) Disclaiming warranty or limiting liability differently from the
+
terms of sections 15 and 16 of this License; or
+
+
b) Requiring preservation of specified reasonable legal notices or
+
author attributions in that material or in the Appropriate Legal
+
Notices displayed by works containing it; or
+
+
c) Prohibiting misrepresentation of the origin of that material, or
+
requiring that modified versions of such material be marked in
+
reasonable ways as different from the original version; or
+
+
d) Limiting the use for publicity purposes of names of licensors or
+
authors of the material; or
+
+
e) Declining to grant rights under trademark law for use of some
+
trade names, trademarks, or service marks; or
+
+
f) Requiring indemnification of licensors and authors of that
+
material by anyone who conveys the material (or modified versions of
+
it) with contractual assumptions of liability to the recipient, for
+
any liability that these contractual assumptions directly impose on
+
those licensors and authors.
+
+
All other non-permissive additional terms are considered "further
+
restrictions" within the meaning of section 10. If the Program as you
+
received it, or any part of it, contains a notice stating that it is
+
governed by this License along with a term that is a further
+
restriction, you may remove that term. If a license document contains
+
a further restriction but permits relicensing or conveying under this
+
License, you may add to a covered work material governed by the terms
+
of that license document, provided that the further restriction does
+
not survive such relicensing or conveying.
+
+
If you add terms to a covered work in accord with this section, you
+
must place, in the relevant source files, a statement of the
+
additional terms that apply to those files, or a notice indicating
+
where to find the applicable terms.
+
+
Additional terms, permissive or non-permissive, may be stated in the
+
form of a separately written license, or stated as exceptions;
+
the above requirements apply either way.
+
+
8. Termination.
+
+
You may not propagate or modify a covered work except as expressly
+
provided under this License. Any attempt otherwise to propagate or
+
modify it is void, and will automatically terminate your rights under
+
this License (including any patent licenses granted under the third
+
paragraph of section 11).
+
+
However, if you cease all violation of this License, then your
+
license from a particular copyright holder is reinstated (a)
+
provisionally, unless and until the copyright holder explicitly and
+
finally terminates your license, and (b) permanently, if the copyright
+
holder fails to notify you of the violation by some reasonable means
+
prior to 60 days after the cessation.
+
+
Moreover, your license from a particular copyright holder is
+
reinstated permanently if the copyright holder notifies you of the
+
violation by some reasonable means, this is the first time you have
+
received notice of violation of this License (for any work) from that
+
copyright holder, and you cure the violation prior to 30 days after
+
your receipt of the notice.
+
+
Termination of your rights under this section does not terminate the
+
licenses of parties who have received copies or rights from you under
+
this License. If your rights have been terminated and not permanently
+
reinstated, you do not qualify to receive new licenses for the same
+
material under section 10.
+
+
9. Acceptance Not Required for Having Copies.
+
+
You are not required to accept this License in order to receive or
+
run a copy of the Program. Ancillary propagation of a covered work
+
occurring solely as a consequence of using peer-to-peer transmission
+
to receive a copy likewise does not require acceptance. However,
+
nothing other than this License grants you permission to propagate or
+
modify any covered work. These actions infringe copyright if you do
+
not accept this License. Therefore, by modifying or propagating a
+
covered work, you indicate your acceptance of this License to do so.
+
+
10. Automatic Licensing of Downstream Recipients.
+
+
Each time you convey a covered work, the recipient automatically
+
receives a license from the original licensors, to run, modify and
+
propagate that work, subject to this License. You are not responsible
+
for enforcing compliance by third parties with this License.
+
+
An "entity transaction" is a transaction transferring control of an
+
organization, or substantially all assets of one, or subdividing an
+
organization, or merging organizations. If propagation of a covered
+
work results from an entity transaction, each party to that
+
transaction who receives a copy of the work also receives whatever
+
licenses to the work the party's predecessor in interest had or could
+
give under the previous paragraph, plus a right to possession of the
+
Corresponding Source of the work from the predecessor in interest, if
+
the predecessor has it or can get it with reasonable efforts.
+
+
You may not impose any further restrictions on the exercise of the
+
rights granted or affirmed under this License. For example, you may
+
not impose a license fee, royalty, or other charge for exercise of
+
rights granted under this License, and you may not initiate litigation
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
+
any patent claim is infringed by making, using, selling, offering for
+
sale, or importing the Program or any portion of it.
+
+
11. Patents.
+
+
A "contributor" is a copyright holder who authorizes use under this
+
License of the Program or a work on which the Program is based. The
+
work thus licensed is called the contributor's "contributor version".
+
+
A contributor's "essential patent claims" are all patent claims
+
owned or controlled by the contributor, whether already acquired or
+
hereafter acquired, that would be infringed by some manner, permitted
+
by this License, of making, using, or selling its contributor version,
+
but do not include claims that would be infringed only as a
+
consequence of further modification of the contributor version. For
+
purposes of this definition, "control" includes the right to grant
+
patent sublicenses in a manner consistent with the requirements of
+
this License.
+
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
+
patent license under the contributor's essential patent claims, to
+
make, use, sell, offer for sale, import and otherwise run, modify and
+
propagate the contents of its contributor version.
+
+
In the following three paragraphs, a "patent license" is any express
+
agreement or commitment, however denominated, not to enforce a patent
+
(such as an express permission to practice a patent or covenant not to
+
sue for patent infringement). To "grant" such a patent license to a
+
party means to make such an agreement or commitment not to enforce a
+
patent against the party.
+
+
If you convey a covered work, knowingly relying on a patent license,
+
and the Corresponding Source of the work is not available for anyone
+
to copy, free of charge and under the terms of this License, through a
+
publicly available network server or other readily accessible means,
+
then you must either (1) cause the Corresponding Source to be so
+
available, or (2) arrange to deprive yourself of the benefit of the
+
patent license for this particular work, or (3) arrange, in a manner
+
consistent with the requirements of this License, to extend the patent
+
license to downstream recipients. "Knowingly relying" means you have
+
actual knowledge that, but for the patent license, your conveying the
+
covered work in a country, or your recipient's use of the covered work
+
in a country, would infringe one or more identifiable patents in that
+
country that you have reason to believe are valid.
+
+
If, pursuant to or in connection with a single transaction or
+
arrangement, you convey, or propagate by procuring conveyance of, a
+
covered work, and grant a patent license to some of the parties
+
receiving the covered work authorizing them to use, propagate, modify
+
or convey a specific copy of the covered work, then the patent license
+
you grant is automatically extended to all recipients of the covered
+
work and works based on it.
+
+
A patent license is "discriminatory" if it does not include within
+
the scope of its coverage, prohibits the exercise of, or is
+
conditioned on the non-exercise of one or more of the rights that are
+
specifically granted under this License. You may not convey a covered
+
work if you are a party to an arrangement with a third party that is
+
in the business of distributing software, under which you make payment
+
to the third party based on the extent of your activity of conveying
+
the work, and under which the third party grants, to any of the
+
parties who would receive the covered work from you, a discriminatory
+
patent license (a) in connection with copies of the covered work
+
conveyed by you (or copies made from those copies), or (b) primarily
+
for and in connection with specific products or compilations that
+
contain the covered work, unless you entered into that arrangement,
+
or that patent license was granted, prior to 28 March 2007.
+
+
Nothing in this License shall be construed as excluding or limiting
+
any implied license or other defenses to infringement that may
+
otherwise be available to you under applicable patent law.
+
+
12. No Surrender of Others' Freedom.
+
+
If conditions are imposed on you (whether by court order, agreement or
+
otherwise) that contradict the conditions of this License, they do not
+
excuse you from the conditions of this License. If you cannot convey a
+
covered work so as to satisfy simultaneously your obligations under this
+
License and any other pertinent obligations, then as a consequence you may
+
not convey it at all. For example, if you agree to terms that obligate you
+
to collect a royalty for further conveying from those to whom you convey
+
the Program, the only way you could satisfy both those terms and this
+
License would be to refrain entirely from conveying the Program.
+
+
13. Remote Network Interaction; Use with the GNU General Public License.
+
+
Notwithstanding any other provision of this License, if you modify the
+
Program, your modified version must prominently offer all users
+
interacting with it remotely through a computer network (if your version
+
supports such interaction) an opportunity to receive the Corresponding
+
Source of your version by providing access to the Corresponding Source
+
from a network server at no charge, through some standard or customary
+
means of facilitating copying of software. This Corresponding Source
+
shall include the Corresponding Source for any work covered by version 3
+
of the GNU General Public License that is incorporated pursuant to the
+
following paragraph.
+
+
Notwithstanding any other provision of this License, you have
+
permission to link or combine any covered work with a work licensed
+
under version 3 of the GNU General Public License into a single
+
combined work, and to convey the resulting work. The terms of this
+
License will continue to apply to the part which is the covered work,
+
but the work with which it is combined will remain governed by version
+
3 of the GNU General Public License.
+
+
14. Revised Versions of this License.
+
+
The Free Software Foundation may publish revised and/or new versions of
+
the GNU Affero General Public License from time to time. Such new versions
+
will be similar in spirit to the present version, but may differ in detail to
+
address new problems or concerns.
+
+
Each version is given a distinguishing version number. If the
+
Program specifies that a certain numbered version of the GNU Affero General
+
Public License "or any later version" applies to it, you have the
+
option of following the terms and conditions either of that numbered
+
version or of any later version published by the Free Software
+
Foundation. If the Program does not specify a version number of the
+
GNU Affero General Public License, you may choose any version ever published
+
by the Free Software Foundation.
+
+
If the Program specifies that a proxy can decide which future
+
versions of the GNU Affero General Public License can be used, that proxy's
+
public statement of acceptance of a version permanently authorizes you
+
to choose that version for the Program.
+
+
Later license versions may give you additional or different
+
permissions. However, no additional obligations are imposed on any
+
author or copyright holder as a result of your choosing to follow a
+
later version.
+
+
15. Disclaimer of Warranty.
+
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+
16. Limitation of Liability.
+
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+
SUCH DAMAGES.
+
+
17. Interpretation of Sections 15 and 16.
+
+
If the disclaimer of warranty and limitation of liability provided
+
above cannot be given local legal effect according to their terms,
+
reviewing courts shall apply local law that most closely approximates
+
an absolute waiver of all civil liability in connection with the
+
Program, unless a warranty or assumption of liability accompanies a
+
copy of the Program in return for a fee.
+
+
END OF TERMS AND CONDITIONS
+
+
How to Apply These Terms to Your New Programs
+
+
If you develop a new program, and you want it to be of the greatest
+
possible use to the public, the best way to achieve this is to make it
+
free software which everyone can redistribute and change under these terms.
+
+
To do so, attach the following notices to the program. It is safest
+
to attach them to the start of each source file to most effectively
+
state the exclusion of warranty; and each file should have at least
+
the "copyright" line and a pointer to where the full notice is found.
+
+
<one line to give the program's name and a brief idea of what it does.>
+
Copyright (C) <year> <name of author>
+
+
This program is free software: you can redistribute it and/or modify
+
it under the terms of the GNU Affero General Public License as published
+
by the Free Software Foundation, either version 3 of the License, or
+
(at your option) any later version.
+
+
This program is distributed in the hope that it will be useful,
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+
GNU Affero General Public License for more details.
+
+
You should have received a copy of the GNU Affero General Public License
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+
Also add information on how to contact you by electronic and paper mail.
+
+
If your software can interact with users remotely through a computer
+
network, you should also make sure that it provides a way for users to
+
get its source. For example, if your program is a web application, its
+
interface could display a "Source" link that leads users to an archive
+
of the code. There are many ways you could offer source, and different
+
solutions will be better for different programs; see section 13 for the
+
specific requirements.
+
+
You should also get your employer (if you work as a programmer) or school,
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
+
For more information on this, and how to apply and follow the GNU AGPL, see
+
<https://www.gnu.org/licenses/>.
+3
constellation/LICENSE.future
···
···
+
constellation's source code is currently only available under the AGPL license.
+
+
it MAY be relicensed in the future to MIT and/or Apache 2.0, at the sole discretion of the microcosm organization, but is not available under these licenses today.
+9
constellation/readme.md
···
```
some todos
- [x] find links and write them to rocksdb
···
```
+
## Contributions
+
+
### Licensing
+
+
Constellation's source code is currently available exclusively under the AGPL license (see [LICENSE](./LICENSE)).
+
+
In the future, its code MAY become available under the MIT and/or Apache2.0 licenses, at the sole discretion of the microcosm organization. Contributing implies acceptance with this possible future licensing change. The change has not happed yet and is not guaranteed.
+
+
some todos
- [x] find links and write them to rocksdb
+57 -14
constellation/src/bin/main.rs
···
use anyhow::{bail, Result};
use clap::{Parser, ValueEnum};
use metrics_exporter_prometheus::PrometheusBuilder;
use std::num::NonZero;
use std::path::PathBuf;
use std::sync::{atomic::AtomicU32, Arc};
···
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
-
#[arg(short, long)]
/// 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(short, long)]
···
/// Saved jsonl from jetstream to use instead of a live subscription
#[arg(short, long)]
fixture: Option<PathBuf>,
}
#[derive(Debug, Clone, ValueEnum)]
···
let stream = jetstream_url(&args.jetstream);
println!("using jetstream server {stream:?}...",);
let stay_alive = CancellationToken::new();
match args.backend {
-
StorageBackend::Memory => run(MemStorage::new(), fixture, None, stream, stay_alive),
#[cfg(feature = "rocks")]
StorageBackend::Rocks => {
let storage_dir = args.data.clone().unwrap_or("rocks.test".into());
···
rocks.start_backup(backup_dir, auto_backup, stay_alive.clone())?;
}
println!("rocks ready.");
-
run(rocks, fixture, args.data, stream, stay_alive)
}
}
}
···
fixture: Option<PathBuf>,
data_dir: Option<PathBuf>,
stream: String,
stay_alive: CancellationToken,
) -> Result<()> {
ctrlc::set_handler({
···
.build()
.expect("axum startup")
.block_on(async {
-
install_metrics_server()?;
-
serve(readable, "0.0.0.0:6789", staying_alive).await
})
.unwrap();
stay_alive.drop_guard();
···
'monitor: loop {
match readable.get_stats() {
-
Ok(StorageStats { dids, targetables, linking_records }) => {
metrics::gauge!("storage.stats.dids").set(dids as f64);
metrics::gauge!("storage.stats.targetables").set(targetables as f64);
metrics::gauge!("storage.stats.linking_records").set(linking_records as f64);
···
Ok(())
}
-
fn install_metrics_server() -> Result<()> {
println!("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(time::Duration::from_secs(30))?
.set_bucket_count(NonZero::new(10).unwrap()) // count * duration = 5 mins. stuff doesn't happen that fast here.
.set_enable_unit_suffix(true)
-
.with_http_listener((host, port))
.install()?;
-
println!(
-
"metrics server installed! listening on http://{}.{}.{}.{}:{port}",
-
host[0], host[1], host[2], host[3]
-
);
Ok(())
}
···
use anyhow::{bail, Result};
use clap::{Parser, ValueEnum};
use metrics_exporter_prometheus::PrometheusBuilder;
+
use std::net::SocketAddr;
use std::num::NonZero;
use std::path::PathBuf;
use std::sync::{atomic::AtomicU32, Arc};
···
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
+
/// constellation server's listen address
+
#[arg(long)]
+
#[clap(default_value = "0.0.0.0:6789")]
+
bind: SocketAddr,
+
/// metrics server's listen address
+
#[arg(long)]
+
#[clap(default_value = "0.0.0.0:8765")]
+
bind_metrics: SocketAddr,
/// 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(short, long)]
···
/// Saved jsonl from jetstream to use instead of a live subscription
#[arg(short, long)]
fixture: Option<PathBuf>,
+
/// run a scan across the target id table and write all key -> ids to id -> keys
+
#[arg(long, action)]
+
repair_target_ids: bool,
}
#[derive(Debug, Clone, ValueEnum)]
···
let stream = jetstream_url(&args.jetstream);
println!("using jetstream server {stream:?}...",);
+
let bind = args.bind;
+
let metrics_bind = args.bind_metrics;
+
let stay_alive = CancellationToken::new();
match args.backend {
+
StorageBackend::Memory => run(
+
MemStorage::new(),
+
fixture,
+
None,
+
stream,
+
bind,
+
metrics_bind,
+
stay_alive,
+
),
#[cfg(feature = "rocks")]
StorageBackend::Rocks => {
let storage_dir = args.data.clone().unwrap_or("rocks.test".into());
···
rocks.start_backup(backup_dir, auto_backup, stay_alive.clone())?;
}
println!("rocks ready.");
+
std::thread::scope(|s| {
+
if args.repair_target_ids {
+
let rocks = rocks.clone();
+
let stay_alive = stay_alive.clone();
+
s.spawn(move || {
+
let rep = rocks.run_repair(time::Duration::from_millis(0), stay_alive);
+
eprintln!("repair finished: {rep:?}");
+
rep
+
});
+
}
+
s.spawn(|| {
+
let r = run(
+
rocks,
+
fixture,
+
args.data,
+
stream,
+
bind,
+
metrics_bind,
+
stay_alive,
+
);
+
eprintln!("run finished: {r:?}");
+
r
+
});
+
});
+
Ok(())
}
}
}
···
fixture: Option<PathBuf>,
data_dir: Option<PathBuf>,
stream: String,
+
bind: SocketAddr,
+
metrics_bind: SocketAddr,
stay_alive: CancellationToken,
) -> Result<()> {
ctrlc::set_handler({
···
.build()
.expect("axum startup")
.block_on(async {
+
install_metrics_server(metrics_bind)?;
+
serve(readable, bind, staying_alive).await
})
.unwrap();
stay_alive.drop_guard();
···
'monitor: loop {
match readable.get_stats() {
+
Ok(StorageStats { dids, targetables, linking_records, .. }) => {
metrics::gauge!("storage.stats.dids").set(dids as f64);
metrics::gauge!("storage.stats.targetables").set(targetables as f64);
metrics::gauge!("storage.stats.linking_records").set(linking_records as f64);
···
Ok(())
}
+
fn install_metrics_server(metrics_bind: SocketAddr) -> Result<()> {
println!("installing metrics server...");
PrometheusBuilder::new()
.set_quantiles(&[0.5, 0.9, 0.99, 1.0])?
.set_bucket_duration(time::Duration::from_secs(30))?
.set_bucket_count(NonZero::new(10).unwrap()) // count * duration = 5 mins. stuff doesn't happen that fast here.
.set_enable_unit_suffix(true)
+
.with_http_listener(metrics_bind)
.install()?;
+
println!("metrics server installed! listening at {metrics_bind:?}");
Ok(())
}
+2
constellation/src/bin/rocks-restore-from-backup.rs
···
use clap::Parser;
use std::path::PathBuf;
use rocksdb::backup::{BackupEngine, BackupEngineOptions, RestoreOptions};
use std::time;
···
to_data_dir: PathBuf,
}
fn main() -> Result<()> {
let args = Args::parse();
···
use clap::Parser;
use std::path::PathBuf;
+
#[cfg(feature = "rocks")]
use rocksdb::backup::{BackupEngine, BackupEngineOptions, RestoreOptions};
use std::time;
···
to_data_dir: PathBuf,
}
+
#[cfg(feature = "rocks")]
fn main() -> Result<()> {
let args = Args::parse();
+13 -6
constellation/src/consumer/jetstream.rs
···
println!("jetstream closed the websocket cleanly.");
break;
}
-
r => eprintln!("jetstream: close result after error: {r:?}"),
}
-
counter!("jetstream_read_fail", "url" => stream.clone(), "reason" => "read error")
-
.increment(1);
-
// if we didn't immediately get ConnectionClosed, we should keep polling read
-
// until we get it.
-
continue;
}
};
···
println!("jetstream closed the websocket cleanly.");
break;
}
+
Err(_) => {
+
counter!("jetstream_read_fail", "url" => stream.clone(), "reason" => "dirty close").increment(1);
+
println!("jetstream failed to close the websocket cleanly.");
+
break;
+
}
+
Ok(r) => {
+
eprintln!("jetstream: close result after error: {r:?}");
+
counter!("jetstream_read_fail", "url" => stream.clone(), "reason" => "read error")
+
.increment(1);
+
// if we didn't immediately get ConnectionClosed, we should keep polling read
+
// until we get it.
+
continue;
+
}
}
}
};
+8 -6
constellation/src/server/filters.rs
···
Ok({
if let Some(link) = parse_any_link(s) {
match link {
-
Link::AtUri(at_uri) => at_uri.strip_prefix("at://").map(|noproto| {
-
format!("https://atproto-browser-plus-links.vercel.app/at/{noproto}")
-
}),
-
Link::Did(did) => Some(format!(
-
"https://atproto-browser-plus-links.vercel.app/at/{did}"
-
)),
Link::Uri(uri) => Some(uri),
}
} else {
···
pub fn human_number(n: &u64) -> askama::Result<String> {
Ok(n.to_formatted_string(&Locale::en))
}
···
Ok({
if let Some(link) = parse_any_link(s) {
match link {
+
Link::AtUri(at_uri) => at_uri
+
.strip_prefix("at://")
+
.map(|noproto| format!("https://pdsls.dev/at://{noproto}")),
+
Link::Did(did) => Some(format!("https://pdsls.dev/at://{did}")),
Link::Uri(uri) => Some(uri),
}
} else {
···
pub fn human_number(n: &u64) -> askama::Result<String> {
Ok(n.to_formatted_string(&Locale::en))
}
+
+
pub fn to_u64(n: usize) -> askama::Result<u64> {
+
Ok(n as u64)
+
}
+332 -19
constellation/src/server/mod.rs
···
use bincode::Options;
use serde::{Deserialize, Serialize};
use serde_with::serde_as;
-
use std::collections::HashMap;
use std::time::{Duration, UNIX_EPOCH};
use tokio::net::{TcpListener, ToSocketAddrs};
-
use tokio::task::block_in_place;
use tokio_util::sync::CancellationToken;
use crate::storage::{LinkReader, StorageStats};
···
const DEFAULT_CURSOR_LIMIT: u64 = 16;
const DEFAULT_CURSOR_LIMIT_MAX: u64 = 100;
-
const INDEX_BEGAN_AT_TS: u64 = 1738083600; // TODO: not this
pub async fn serve<S, A>(store: S, addr: A, stay_alive: CancellationToken) -> anyhow::Result<()>
where
···
"/",
get({
let store = store.clone();
-
move |accept| async { block_in_place(|| hello(accept, store)) }
}),
)
.route(
"/links/count",
get({
let store = store.clone();
-
move |accept, query| async { block_in_place(|| count_links(accept, query, store)) }
}),
)
.route(
···
get({
let store = store.clone();
move |accept, query| async {
-
block_in_place(|| count_distinct_dids(accept, query, store))
}
}),
)
···
"/links",
get({
let store = store.clone();
-
move |accept, query| async { block_in_place(|| get_links(accept, query, store)) }
}),
)
.route(
···
get({
let store = store.clone();
move |accept, query| async {
-
block_in_place(|| get_distinct_dids(accept, query, store))
}
}),
)
···
get({
let store = store.clone();
move |accept, query| async {
-
block_in_place(|| count_all_links(accept, query, store))
}
}),
)
···
get({
let store = store.clone();
move |accept, query| async {
-
block_in_place(|| explore_links(accept, query, store))
}
}),
)
···
#[template(path = "hello.html.j2")]
struct HelloReponse {
help: &'static str,
-
days_indexed: u64,
stats: StorageStats,
}
fn hello(
···
let stats = store
.get_stats()
.map_err(|_| http::StatusCode::INTERNAL_SERVER_ERROR)?;
-
let days_indexed = (UNIX_EPOCH + Duration::from_secs(INDEX_BEGAN_AT_TS))
-
.elapsed()
.map_err(|_| http::StatusCode::INTERNAL_SERVER_ERROR)?
-
.as_secs()
-
/ 86400;
Ok(acceptable(accept, HelloReponse {
help: "open this URL in a web browser (or request with Accept: text/html) for information about this API.",
days_indexed,
···
}
#[derive(Clone, Deserialize)]
struct GetLinksCountQuery {
target: String,
collection: String,
···
}
#[derive(Clone, Deserialize)]
struct GetLinkItemsQuery {
target: String,
collection: String,
path: String,
cursor: Option<OpaqueApiCursor>,
-
limit: Option<u64>,
// TODO: allow reverse (er, forward) order as well
}
#[derive(Template, Serialize)]
···
}
fn get_links(
accept: ExtractAccept,
-
query: Query<GetLinkItemsQuery>,
store: impl LinkReader,
) -> Result<impl IntoResponse, http::StatusCode> {
let until = query
···
.transpose()?
.map(|c| c.next);
-
let limit = query.limit.unwrap_or(DEFAULT_CURSOR_LIMIT);
if limit > DEFAULT_CURSOR_LIMIT_MAX {
return Err(http::StatusCode::BAD_REQUEST);
}
let paged = store
-
.get_links(&query.target, &query.collection, &query.path, limit, until)
.map_err(|_| http::StatusCode::INTERNAL_SERVER_ERROR)?;
let cursor = paged.next.map(|next| {
···
OpaqueApiCursor(bincode::DefaultOptions::new().serialize(&item).unwrap())
}
}
···
use bincode::Options;
use serde::{Deserialize, Serialize};
use serde_with::serde_as;
+
use std::collections::{HashMap, HashSet};
use std::time::{Duration, UNIX_EPOCH};
use tokio::net::{TcpListener, ToSocketAddrs};
+
use tokio::task::spawn_blocking;
use tokio_util::sync::CancellationToken;
use crate::storage::{LinkReader, StorageStats};
···
const DEFAULT_CURSOR_LIMIT: u64 = 16;
const DEFAULT_CURSOR_LIMIT_MAX: u64 = 100;
+
fn get_default_cursor_limit() -> u64 {
+
DEFAULT_CURSOR_LIMIT
+
}
+
+
fn to500(e: tokio::task::JoinError) -> http::StatusCode {
+
eprintln!("handler error: {e}");
+
http::StatusCode::INTERNAL_SERVER_ERROR
+
}
pub async fn serve<S, A>(store: S, addr: A, stay_alive: CancellationToken) -> anyhow::Result<()>
where
···
"/",
get({
let store = store.clone();
+
move |accept| async {
+
spawn_blocking(|| hello(accept, store))
+
.await
+
.map_err(to500)?
+
}
+
}),
+
)
+
.route(
+
"/xrpc/blue.microcosm.links.getManyToManyCounts",
+
get({
+
let store = store.clone();
+
move |accept, query| async {
+
spawn_blocking(|| get_many_to_many_counts(accept, query, store))
+
.await
+
.map_err(to500)?
+
}
}),
)
.route(
"/links/count",
get({
let store = store.clone();
+
move |accept, query| async {
+
spawn_blocking(|| count_links(accept, query, store))
+
.await
+
.map_err(to500)?
+
}
}),
)
.route(
···
get({
let store = store.clone();
move |accept, query| async {
+
spawn_blocking(|| count_distinct_dids(accept, query, store))
+
.await
+
.map_err(to500)?
+
}
+
}),
+
)
+
.route(
+
"/xrpc/blue.microcosm.links.getBacklinks",
+
get({
+
let store = store.clone();
+
move |accept, query| async {
+
spawn_blocking(|| get_backlinks(accept, query, store))
+
.await
+
.map_err(to500)?
}
}),
)
···
"/links",
get({
let store = store.clone();
+
move |accept, query| async {
+
spawn_blocking(|| get_links(accept, query, store))
+
.await
+
.map_err(to500)?
+
}
}),
)
.route(
···
get({
let store = store.clone();
move |accept, query| async {
+
spawn_blocking(|| get_distinct_dids(accept, query, store))
+
.await
+
.map_err(to500)?
}
}),
)
···
get({
let store = store.clone();
move |accept, query| async {
+
spawn_blocking(|| count_all_links(accept, query, store))
+
.await
+
.map_err(to500)?
}
}),
)
···
get({
let store = store.clone();
move |accept, query| async {
+
spawn_blocking(|| explore_links(accept, query, store))
+
.await
+
.map_err(to500)?
}
}),
)
···
#[template(path = "hello.html.j2")]
struct HelloReponse {
help: &'static str,
+
days_indexed: Option<u64>,
stats: StorageStats,
}
fn hello(
···
let stats = store
.get_stats()
.map_err(|_| http::StatusCode::INTERNAL_SERVER_ERROR)?;
+
let days_indexed = stats
+
.started_at
+
.map(|c| (UNIX_EPOCH + Duration::from_micros(c)).elapsed())
+
.transpose()
.map_err(|_| http::StatusCode::INTERNAL_SERVER_ERROR)?
+
.map(|d| d.as_secs() / 86_400);
Ok(acceptable(accept, HelloReponse {
help: "open this URL in a web browser (or request with Accept: text/html) for information about this API.",
days_indexed,
···
}
#[derive(Clone, Deserialize)]
+
#[serde(rename_all = "camelCase")]
+
struct GetManyToManyCountsQuery {
+
subject: String,
+
source: String,
+
/// path to the secondary link in the linking record
+
path_to_other: String,
+
/// filter to linking records (join of the m2m) by these DIDs
+
#[serde(default)]
+
did: Vec<String>,
+
/// filter to specific secondary records
+
#[serde(default)]
+
other_subject: Vec<String>,
+
cursor: Option<OpaqueApiCursor>,
+
/// Set the max number of links to return per page of results
+
#[serde(default = "get_default_cursor_limit")]
+
limit: u64,
+
}
+
#[derive(Serialize)]
+
struct OtherSubjectCount {
+
subject: String,
+
total: u64,
+
distinct: u64,
+
}
+
#[derive(Template, Serialize)]
+
#[template(path = "get-many-to-many-counts.html.j2")]
+
struct GetManyToManyCountsResponse {
+
counts_by_other_subject: Vec<OtherSubjectCount>,
+
cursor: Option<OpaqueApiCursor>,
+
#[serde(skip_serializing)]
+
query: GetManyToManyCountsQuery,
+
}
+
fn get_many_to_many_counts(
+
accept: ExtractAccept,
+
query: axum_extra::extract::Query<GetManyToManyCountsQuery>,
+
store: impl LinkReader,
+
) -> Result<impl IntoResponse, http::StatusCode> {
+
let cursor_key = query
+
.cursor
+
.clone()
+
.map(|oc| ApiKeyedCursor::try_from(oc).map_err(|_| http::StatusCode::BAD_REQUEST))
+
.transpose()?
+
.map(|c| c.next);
+
+
let limit = query.limit;
+
if limit > DEFAULT_CURSOR_LIMIT_MAX {
+
return Err(http::StatusCode::BAD_REQUEST);
+
}
+
+
let filter_dids: HashSet<Did> = HashSet::from_iter(
+
query
+
.did
+
.iter()
+
.map(|d| d.trim())
+
.filter(|d| !d.is_empty())
+
.map(|d| Did(d.to_string())),
+
);
+
+
let filter_other_subjects: HashSet<String> = HashSet::from_iter(
+
query
+
.other_subject
+
.iter()
+
.map(|s| s.trim().to_string())
+
.filter(|s| !s.is_empty()),
+
);
+
+
let Some((collection, path)) = query.source.split_once(':') else {
+
return Err(http::StatusCode::BAD_REQUEST);
+
};
+
let path = format!(".{path}");
+
+
let path_to_other = format!(".{}", query.path_to_other);
+
+
let paged = store
+
.get_many_to_many_counts(
+
&query.subject,
+
collection,
+
&path,
+
&path_to_other,
+
limit,
+
cursor_key,
+
&filter_dids,
+
&filter_other_subjects,
+
)
+
.map_err(|_| http::StatusCode::INTERNAL_SERVER_ERROR)?;
+
+
let cursor = paged.next.map(|next| ApiKeyedCursor { next }.into());
+
+
let items = paged
+
.items
+
.into_iter()
+
.map(|(subject, total, distinct)| OtherSubjectCount {
+
subject,
+
total,
+
distinct,
+
})
+
.collect();
+
+
Ok(acceptable(
+
accept,
+
GetManyToManyCountsResponse {
+
counts_by_other_subject: items,
+
cursor,
+
query: (*query).clone(),
+
},
+
))
+
}
+
+
#[derive(Clone, Deserialize)]
struct GetLinksCountQuery {
target: String,
collection: String,
···
}
#[derive(Clone, Deserialize)]
+
struct GetBacklinksQuery {
+
/// The link target
+
///
+
/// can be an AT-URI, plain DID, or regular URI
+
subject: String,
+
/// Filter links only from this link source
+
///
+
/// eg.: `app.bsky.feed.like:subject.uri`
+
source: String,
+
cursor: Option<OpaqueApiCursor>,
+
/// Filter links only from these DIDs
+
///
+
/// include multiple times to filter by multiple source DIDs
+
#[serde(default)]
+
did: Vec<String>,
+
/// Set the max number of links to return per page of results
+
#[serde(default = "get_default_cursor_limit")]
+
limit: u64,
+
// TODO: allow reverse (er, forward) order as well
+
}
+
#[derive(Template, Serialize)]
+
#[template(path = "get-backlinks.html.j2")]
+
struct GetBacklinksResponse {
+
total: u64,
+
records: Vec<RecordId>,
+
cursor: Option<OpaqueApiCursor>,
+
#[serde(skip_serializing)]
+
query: GetBacklinksQuery,
+
#[serde(skip_serializing)]
+
collection: String,
+
#[serde(skip_serializing)]
+
path: String,
+
}
+
fn get_backlinks(
+
accept: ExtractAccept,
+
query: axum_extra::extract::Query<GetBacklinksQuery>, // supports multiple param occurrences
+
store: impl LinkReader,
+
) -> Result<impl IntoResponse, http::StatusCode> {
+
let until = query
+
.cursor
+
.clone()
+
.map(|oc| ApiCursor::try_from(oc).map_err(|_| http::StatusCode::BAD_REQUEST))
+
.transpose()?
+
.map(|c| c.next);
+
+
let limit = query.limit;
+
if limit > DEFAULT_CURSOR_LIMIT_MAX {
+
return Err(http::StatusCode::BAD_REQUEST);
+
}
+
+
let filter_dids: HashSet<Did> = HashSet::from_iter(
+
query
+
.did
+
.iter()
+
.map(|d| d.trim())
+
.filter(|d| !d.is_empty())
+
.map(|d| Did(d.to_string())),
+
);
+
+
let Some((collection, path)) = query.source.split_once(':') else {
+
return Err(http::StatusCode::BAD_REQUEST);
+
};
+
let path = format!(".{path}");
+
+
let paged = store
+
.get_links(
+
&query.subject,
+
collection,
+
&path,
+
limit,
+
until,
+
&filter_dids,
+
)
+
.map_err(|_| http::StatusCode::INTERNAL_SERVER_ERROR)?;
+
+
let cursor = paged.next.map(|next| {
+
ApiCursor {
+
version: paged.version,
+
next,
+
}
+
.into()
+
});
+
+
Ok(acceptable(
+
accept,
+
GetBacklinksResponse {
+
total: paged.total,
+
records: paged.items,
+
cursor,
+
query: (*query).clone(),
+
collection: collection.to_string(),
+
path,
+
},
+
))
+
}
+
+
#[derive(Clone, Deserialize)]
struct GetLinkItemsQuery {
target: String,
collection: String,
path: String,
cursor: Option<OpaqueApiCursor>,
+
/// Filter links only from these DIDs
+
///
+
/// include multiple times to filter by multiple source DIDs
+
#[serde(default)]
+
did: Vec<String>,
+
/// [deprecated] Filter links only from these DIDs
+
///
+
/// format: comma-separated sequence of DIDs
+
///
+
/// errors: if `did` parameter is also present
+
///
+
/// deprecated: use `did`, which can be repeated multiple times
+
from_dids: Option<String>, // comma separated: gross
+
#[serde(default = "get_default_cursor_limit")]
+
limit: u64,
// TODO: allow reverse (er, forward) order as well
}
#[derive(Template, Serialize)]
···
}
fn get_links(
accept: ExtractAccept,
+
query: axum_extra::extract::Query<GetLinkItemsQuery>, // supports multiple param occurrences
store: impl LinkReader,
) -> Result<impl IntoResponse, http::StatusCode> {
let until = query
···
.transpose()?
.map(|c| c.next);
+
let limit = query.limit;
if limit > DEFAULT_CURSOR_LIMIT_MAX {
return Err(http::StatusCode::BAD_REQUEST);
}
+
let mut filter_dids: HashSet<Did> = HashSet::from_iter(
+
query
+
.did
+
.iter()
+
.map(|d| d.trim())
+
.filter(|d| !d.is_empty())
+
.map(|d| Did(d.to_string())),
+
);
+
+
if let Some(comma_joined) = &query.from_dids {
+
if !filter_dids.is_empty() {
+
return Err(http::StatusCode::BAD_REQUEST);
+
}
+
for did in comma_joined.split(',') {
+
filter_dids.insert(Did(did.to_string()));
+
}
+
}
+
let paged = store
+
.get_links(
+
&query.target,
+
&query.collection,
+
&query.path,
+
limit,
+
until,
+
&filter_dids,
+
)
.map_err(|_| http::StatusCode::INTERNAL_SERVER_ERROR)?;
let cursor = paged.next.map(|next| {
···
OpaqueApiCursor(bincode::DefaultOptions::new().serialize(&item).unwrap())
}
}
+
+
#[derive(Serialize, Deserialize)] // for bincode
+
struct ApiKeyedCursor {
+
next: String, // the key
+
}
+
+
impl TryFrom<OpaqueApiCursor> for ApiKeyedCursor {
+
type Error = bincode::Error;
+
+
fn try_from(item: OpaqueApiCursor) -> Result<Self, Self::Error> {
+
bincode::DefaultOptions::new().deserialize(&item.0)
+
}
+
}
+
+
impl From<ApiKeyedCursor> for OpaqueApiCursor {
+
fn from(item: ApiKeyedCursor) -> Self {
+
OpaqueApiCursor(bincode::DefaultOptions::new().serialize(&item).unwrap())
+
}
+
}
+93 -1
constellation/src/storage/mem_store.rs
···
-
use super::{LinkReader, LinkStorage, PagedAppendingCollection, StorageStats};
use crate::{ActionableEvent, CountsByCount, Did, RecordId};
use anyhow::Result;
use links::CollectedLink;
···
}
impl LinkReader for MemStorage {
fn get_count(&self, target: &str, collection: &str, path: &str) -> Result<u64> {
let data = self.0.lock().unwrap();
let Some(paths) = data.targets.get(&Target::new(target)) else {
···
path: &str,
limit: u64,
until: Option<u64>,
) -> Result<PagedAppendingCollection<RecordId>> {
let data = self.0.lock().unwrap();
let Some(paths) = data.targets.get(&Target::new(target)) else {
···
next: None,
total: 0,
});
};
let total = did_rkeys.len();
···
dids,
targetables,
linking_records,
})
}
}
···
+
use super::{
+
LinkReader, LinkStorage, PagedAppendingCollection, PagedOrderedCollection, StorageStats,
+
};
use crate::{ActionableEvent, CountsByCount, Did, RecordId};
use anyhow::Result;
use links::CollectedLink;
···
}
impl LinkReader for MemStorage {
+
fn get_many_to_many_counts(
+
&self,
+
target: &str,
+
collection: &str,
+
path: &str,
+
path_to_other: &str,
+
limit: u64,
+
after: Option<String>,
+
filter_dids: &HashSet<Did>,
+
filter_to_targets: &HashSet<String>,
+
) -> Result<PagedOrderedCollection<(String, u64, u64), String>> {
+
let data = self.0.lock().unwrap();
+
let Some(paths) = data.targets.get(&Target::new(target)) else {
+
return Ok(PagedOrderedCollection::default());
+
};
+
let Some(linkers) = paths.get(&Source::new(collection, path)) else {
+
return Ok(PagedOrderedCollection::default());
+
};
+
+
let path_to_other = RecordPath::new(path_to_other);
+
let filter_to_targets: HashSet<Target> =
+
HashSet::from_iter(filter_to_targets.iter().map(|s| Target::new(s)));
+
+
let mut grouped_counts: HashMap<Target, (u64, HashSet<Did>)> = HashMap::new();
+
for (did, rkey) in linkers.iter().flatten().cloned() {
+
if !filter_dids.is_empty() && !filter_dids.contains(&did) {
+
continue;
+
}
+
if let Some(fwd_target) = data
+
.links
+
.get(&did)
+
.unwrap_or(&HashMap::new())
+
.get(&RepoId {
+
collection: collection.to_string(),
+
rkey,
+
})
+
.unwrap_or(&Vec::new())
+
.iter()
+
.filter_map(|(path, target)| {
+
if *path == path_to_other
+
&& (filter_to_targets.is_empty() || filter_to_targets.contains(target))
+
{
+
Some(target)
+
} else {
+
None
+
}
+
})
+
.take(1)
+
.next()
+
{
+
let e = grouped_counts.entry(fwd_target.clone()).or_default();
+
e.0 += 1;
+
e.1.insert(did.clone());
+
}
+
}
+
let mut items: Vec<(String, u64, u64)> = grouped_counts
+
.iter()
+
.map(|(k, (n, u))| (k.0.clone(), *n, u.len() as u64))
+
.collect();
+
items.sort();
+
items = items
+
.into_iter()
+
.skip_while(|(t, _, _)| after.as_ref().map(|a| t <= a).unwrap_or(false))
+
.take(limit as usize)
+
.collect();
+
let next = if items.len() as u64 >= limit {
+
items.last().map(|(t, _, _)| t.clone())
+
} else {
+
None
+
};
+
Ok(PagedOrderedCollection { items, next })
+
}
+
fn get_count(&self, target: &str, collection: &str, path: &str) -> Result<u64> {
let data = self.0.lock().unwrap();
let Some(paths) = data.targets.get(&Target::new(target)) else {
···
path: &str,
limit: u64,
until: Option<u64>,
+
filter_dids: &HashSet<Did>,
) -> Result<PagedAppendingCollection<RecordId>> {
let data = self.0.lock().unwrap();
let Some(paths) = data.targets.get(&Target::new(target)) else {
···
next: None,
total: 0,
});
+
};
+
+
let did_rkeys: Vec<_> = if !filter_dids.is_empty() {
+
did_rkeys
+
.iter()
+
.filter(|m| {
+
Option::<(Did, RKey)>::clone(m)
+
.map(|(did, _)| filter_dids.contains(&did))
+
.unwrap_or(false)
+
})
+
.cloned()
+
.collect()
+
} else {
+
did_rkeys.to_vec()
};
let total = did_rkeys.len();
···
dids,
targetables,
linking_records,
+
started_at: None,
+
other_data: Default::default(),
})
}
}
+484 -14
constellation/src/storage/mod.rs
···
use crate::{ActionableEvent, CountsByCount, Did, RecordId};
use anyhow::Result;
use serde::{Deserialize, Serialize};
-
use std::collections::HashMap;
pub mod mem_store;
pub use mem_store::MemStorage;
···
pub total: u64,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
pub struct StorageStats {
/// estimate of how many accounts we've seen create links. the _subjects_ of any links are not represented here.
···
/// records with multiple links are single-counted.
/// for LSM stores, deleted links don't decrement this, and updated records with any links will likely increment it.
pub linking_records: u64,
}
pub trait LinkStorage: Send + Sync {
···
}
pub trait LinkReader: Clone + Send + Sync + 'static {
fn get_count(&self, target: &str, collection: &str, path: &str) -> Result<u64>;
fn get_distinct_did_count(&self, target: &str, collection: &str, path: &str) -> Result<u64>;
···
path: &str,
limit: u64,
until: Option<u64>,
) -> Result<PagedAppendingCollection<RecordId>>;
fn get_distinct_dids(
···
);
assert_eq!(storage.get_distinct_did_count("", "", "")?, 0);
assert_eq!(
-
storage.get_links("a.com", "app.t.c", ".abc.uri", 100, None)?,
PagedAppendingCollection {
version: (0, 0),
items: vec![],
···
0,
)?;
assert_eq!(
-
storage.get_links("a.com", "app.t.c", ".abc.uri", 100, None)?,
PagedAppendingCollection {
version: (1, 0),
items: vec![RecordId {
···
0,
)?;
}
-
let links = storage.get_links("a.com", "app.t.c", ".abc.uri", 2, None)?;
let dids = storage.get_distinct_dids("a.com", "app.t.c", ".abc.uri", 2, None)?;
assert_eq!(
links,
···
total: 5,
}
);
-
let links = storage.get_links("a.com", "app.t.c", ".abc.uri", 2, links.next)?;
let dids = storage.get_distinct_dids("a.com", "app.t.c", ".abc.uri", 2, dids.next)?;
assert_eq!(
links,
···
total: 5,
}
);
-
let links = storage.get_links("a.com", "app.t.c", ".abc.uri", 2, links.next)?;
let dids = storage.get_distinct_dids("a.com", "app.t.c", ".abc.uri", 2, dids.next)?;
assert_eq!(
links,
···
assert_stats(storage.get_stats()?, 5..=5, 1..=1, 5..=5);
});
test_each_storage!(get_links_exact_multiple, |storage| {
for i in 1..=4 {
storage.push(
···
0,
)?;
}
-
let links = storage.get_links("a.com", "app.t.c", ".abc.uri", 2, None)?;
assert_eq!(
links,
PagedAppendingCollection {
···
total: 4,
}
);
-
let links = storage.get_links("a.com", "app.t.c", ".abc.uri", 2, links.next)?;
assert_eq!(
links,
PagedAppendingCollection {
···
0,
)?;
}
-
let links = storage.get_links("a.com", "app.t.c", ".abc.uri", 2, None)?;
assert_eq!(
links,
PagedAppendingCollection {
···
},
0,
)?;
-
let links = storage.get_links("a.com", "app.t.c", ".abc.uri", 2, links.next)?;
assert_eq!(
links,
PagedAppendingCollection {
···
0,
)?;
}
-
let links = storage.get_links("a.com", "app.t.c", ".abc.uri", 2, None)?;
assert_eq!(
links,
PagedAppendingCollection {
···
}),
0,
)?;
-
let links = storage.get_links("a.com", "app.t.c", ".abc.uri", 2, links.next)?;
assert_eq!(
links,
PagedAppendingCollection {
···
0,
)?;
}
-
let links = storage.get_links("a.com", "app.t.c", ".abc.uri", 2, None)?;
assert_eq!(
links,
PagedAppendingCollection {
···
&ActionableEvent::DeactivateAccount("did:plc:asdf-1".into()),
0,
)?;
-
let links = storage.get_links("a.com", "app.t.c", ".abc.uri", 2, links.next)?;
assert_eq!(
links,
PagedAppendingCollection {
···
counts
});
assert_stats(storage.get_stats()?, 1..=1, 2..=2, 1..=1);
});
}
···
use crate::{ActionableEvent, CountsByCount, Did, RecordId};
use anyhow::Result;
use serde::{Deserialize, Serialize};
+
use std::collections::{HashMap, HashSet};
pub mod mem_store;
pub use mem_store::MemStorage;
···
pub total: u64,
}
+
/// A paged collection whose keys are sorted instead of indexed
+
///
+
/// this has weaker guarantees than PagedAppendingCollection: it might
+
/// return a totally consistent snapshot. but it should avoid duplicates
+
/// and each page should at least be internally consistent.
+
#[derive(Debug, PartialEq, Default)]
+
pub struct PagedOrderedCollection<T, K: Ord> {
+
pub items: Vec<T>,
+
pub next: Option<K>,
+
}
+
#[derive(Debug, Deserialize, Serialize, PartialEq)]
pub struct StorageStats {
/// estimate of how many accounts we've seen create links. the _subjects_ of any links are not represented here.
···
/// records with multiple links are single-counted.
/// for LSM stores, deleted links don't decrement this, and updated records with any links will likely increment it.
pub linking_records: u64,
+
+
/// first jetstream cursor when this instance first started
+
pub started_at: Option<u64>,
+
+
/// anything else we want to throw in
+
pub other_data: HashMap<String, u64>,
}
pub trait LinkStorage: Send + Sync {
···
}
pub trait LinkReader: Clone + Send + Sync + 'static {
+
#[allow(clippy::too_many_arguments)]
+
fn get_many_to_many_counts(
+
&self,
+
target: &str,
+
collection: &str,
+
path: &str,
+
path_to_other: &str,
+
limit: u64,
+
after: Option<String>,
+
filter_dids: &HashSet<Did>,
+
filter_to_targets: &HashSet<String>,
+
) -> Result<PagedOrderedCollection<(String, u64, u64), String>>;
+
fn get_count(&self, target: &str, collection: &str, path: &str) -> Result<u64>;
fn get_distinct_did_count(&self, target: &str, collection: &str, path: &str) -> Result<u64>;
···
path: &str,
limit: u64,
until: Option<u64>,
+
filter_dids: &HashSet<Did>,
) -> Result<PagedAppendingCollection<RecordId>>;
fn get_distinct_dids(
···
);
assert_eq!(storage.get_distinct_did_count("", "", "")?, 0);
assert_eq!(
+
storage.get_links(
+
"a.com",
+
"app.t.c",
+
".abc.uri",
+
100,
+
None,
+
&HashSet::default()
+
)?,
PagedAppendingCollection {
version: (0, 0),
items: vec![],
···
0,
)?;
assert_eq!(
+
storage.get_links(
+
"a.com",
+
"app.t.c",
+
".abc.uri",
+
100,
+
None,
+
&HashSet::default()
+
)?,
PagedAppendingCollection {
version: (1, 0),
items: vec![RecordId {
···
0,
)?;
}
+
let links =
+
storage.get_links("a.com", "app.t.c", ".abc.uri", 2, None, &HashSet::default())?;
let dids = storage.get_distinct_dids("a.com", "app.t.c", ".abc.uri", 2, None)?;
assert_eq!(
links,
···
total: 5,
}
);
+
let links = storage.get_links(
+
"a.com",
+
"app.t.c",
+
".abc.uri",
+
2,
+
links.next,
+
&HashSet::default(),
+
)?;
let dids = storage.get_distinct_dids("a.com", "app.t.c", ".abc.uri", 2, dids.next)?;
assert_eq!(
links,
···
total: 5,
}
);
+
let links = storage.get_links(
+
"a.com",
+
"app.t.c",
+
".abc.uri",
+
2,
+
links.next,
+
&HashSet::default(),
+
)?;
let dids = storage.get_distinct_dids("a.com", "app.t.c", ".abc.uri", 2, dids.next)?;
assert_eq!(
links,
···
assert_stats(storage.get_stats()?, 5..=5, 1..=1, 5..=5);
});
+
test_each_storage!(get_filtered_links, |storage| {
+
let links = storage.get_links(
+
"a.com",
+
"app.t.c",
+
".abc.uri",
+
2,
+
None,
+
&HashSet::from([Did("did:plc:linker".to_string())]),
+
)?;
+
assert_eq!(
+
links,
+
PagedAppendingCollection {
+
version: (0, 0),
+
items: vec![],
+
next: None,
+
total: 0,
+
}
+
);
+
+
storage.push(
+
&ActionableEvent::CreateLinks {
+
record_id: RecordId {
+
did: "did:plc:linker".into(),
+
collection: "app.t.c".into(),
+
rkey: "asdf".into(),
+
},
+
links: vec![CollectedLink {
+
target: Link::Uri("a.com".into()),
+
path: ".abc.uri".into(),
+
}],
+
},
+
0,
+
)?;
+
+
let links = storage.get_links(
+
"a.com",
+
"app.t.c",
+
".abc.uri",
+
2,
+
None,
+
&HashSet::from([Did("did:plc:linker".to_string())]),
+
)?;
+
assert_eq!(
+
links,
+
PagedAppendingCollection {
+
version: (1, 0),
+
items: vec![RecordId {
+
did: "did:plc:linker".into(),
+
collection: "app.t.c".into(),
+
rkey: "asdf".into(),
+
},],
+
next: None,
+
total: 1,
+
}
+
);
+
+
let links = storage.get_links(
+
"a.com",
+
"app.t.c",
+
".abc.uri",
+
2,
+
None,
+
&HashSet::from([Did("did:plc:someone-else".to_string())]),
+
)?;
+
assert_eq!(
+
links,
+
PagedAppendingCollection {
+
version: (0, 0),
+
items: vec![],
+
next: None,
+
total: 0,
+
}
+
);
+
+
storage.push(
+
&ActionableEvent::CreateLinks {
+
record_id: RecordId {
+
did: "did:plc:linker".into(),
+
collection: "app.t.c".into(),
+
rkey: "asdf-2".into(),
+
},
+
links: vec![CollectedLink {
+
target: Link::Uri("a.com".into()),
+
path: ".abc.uri".into(),
+
}],
+
},
+
0,
+
)?;
+
storage.push(
+
&ActionableEvent::CreateLinks {
+
record_id: RecordId {
+
did: "did:plc:someone-else".into(),
+
collection: "app.t.c".into(),
+
rkey: "asdf".into(),
+
},
+
links: vec![CollectedLink {
+
target: Link::Uri("a.com".into()),
+
path: ".abc.uri".into(),
+
}],
+
},
+
0,
+
)?;
+
+
let links = storage.get_links(
+
"a.com",
+
"app.t.c",
+
".abc.uri",
+
2,
+
None,
+
&HashSet::from([Did("did:plc:linker".to_string())]),
+
)?;
+
assert_eq!(
+
links,
+
PagedAppendingCollection {
+
version: (2, 0),
+
items: vec![
+
RecordId {
+
did: "did:plc:linker".into(),
+
collection: "app.t.c".into(),
+
rkey: "asdf-2".into(),
+
},
+
RecordId {
+
did: "did:plc:linker".into(),
+
collection: "app.t.c".into(),
+
rkey: "asdf".into(),
+
},
+
],
+
next: None,
+
total: 2,
+
}
+
);
+
+
let links = storage.get_links(
+
"a.com",
+
"app.t.c",
+
".abc.uri",
+
2,
+
None,
+
&HashSet::from([
+
Did("did:plc:linker".to_string()),
+
Did("did:plc:someone-else".to_string()),
+
]),
+
)?;
+
assert_eq!(
+
links,
+
PagedAppendingCollection {
+
version: (3, 0),
+
items: vec![
+
RecordId {
+
did: "did:plc:someone-else".into(),
+
collection: "app.t.c".into(),
+
rkey: "asdf".into(),
+
},
+
RecordId {
+
did: "did:plc:linker".into(),
+
collection: "app.t.c".into(),
+
rkey: "asdf-2".into(),
+
},
+
],
+
next: Some(1),
+
total: 3,
+
}
+
);
+
+
let links = storage.get_links(
+
"a.com",
+
"app.t.c",
+
".abc.uri",
+
2,
+
None,
+
&HashSet::from([Did("did:plc:someone-unknown".to_string())]),
+
)?;
+
assert_eq!(
+
links,
+
PagedAppendingCollection {
+
version: (0, 0),
+
items: vec![],
+
next: None,
+
total: 0,
+
}
+
);
+
});
+
test_each_storage!(get_links_exact_multiple, |storage| {
for i in 1..=4 {
storage.push(
···
0,
)?;
}
+
let links =
+
storage.get_links("a.com", "app.t.c", ".abc.uri", 2, None, &HashSet::default())?;
assert_eq!(
links,
PagedAppendingCollection {
···
total: 4,
}
);
+
let links = storage.get_links(
+
"a.com",
+
"app.t.c",
+
".abc.uri",
+
2,
+
links.next,
+
&HashSet::default(),
+
)?;
assert_eq!(
links,
PagedAppendingCollection {
···
0,
)?;
}
+
let links =
+
storage.get_links("a.com", "app.t.c", ".abc.uri", 2, None, &HashSet::default())?;
assert_eq!(
links,
PagedAppendingCollection {
···
},
0,
)?;
+
let links = storage.get_links(
+
"a.com",
+
"app.t.c",
+
".abc.uri",
+
2,
+
links.next,
+
&HashSet::default(),
+
)?;
assert_eq!(
links,
PagedAppendingCollection {
···
0,
)?;
}
+
let links =
+
storage.get_links("a.com", "app.t.c", ".abc.uri", 2, None, &HashSet::default())?;
assert_eq!(
links,
PagedAppendingCollection {
···
}),
0,
)?;
+
let links = storage.get_links(
+
"a.com",
+
"app.t.c",
+
".abc.uri",
+
2,
+
links.next,
+
&HashSet::default(),
+
)?;
assert_eq!(
links,
PagedAppendingCollection {
···
0,
)?;
}
+
let links =
+
storage.get_links("a.com", "app.t.c", ".abc.uri", 2, None, &HashSet::default())?;
assert_eq!(
links,
PagedAppendingCollection {
···
&ActionableEvent::DeactivateAccount("did:plc:asdf-1".into()),
0,
)?;
+
let links = storage.get_links(
+
"a.com",
+
"app.t.c",
+
".abc.uri",
+
2,
+
links.next,
+
&HashSet::default(),
+
)?;
assert_eq!(
links,
PagedAppendingCollection {
···
counts
});
assert_stats(storage.get_stats()?, 1..=1, 2..=2, 1..=1);
+
});
+
+
//////// many-to-many /////////
+
+
test_each_storage!(get_m2m_counts_empty, |storage| {
+
assert_eq!(
+
storage.get_many_to_many_counts(
+
"a.com",
+
"a.b.c",
+
".d.e",
+
".f.g",
+
10,
+
None,
+
&HashSet::new(),
+
&HashSet::new(),
+
)?,
+
PagedOrderedCollection {
+
items: vec![],
+
next: None,
+
}
+
);
+
});
+
+
test_each_storage!(get_m2m_counts_single, |storage| {
+
storage.push(
+
&ActionableEvent::CreateLinks {
+
record_id: RecordId {
+
did: "did:plc:asdf".into(),
+
collection: "app.t.c".into(),
+
rkey: "asdf".into(),
+
},
+
links: vec![
+
CollectedLink {
+
target: Link::Uri("a.com".into()),
+
path: ".abc.uri".into(),
+
},
+
CollectedLink {
+
target: Link::Uri("b.com".into()),
+
path: ".def.uri".into(),
+
},
+
CollectedLink {
+
target: Link::Uri("b.com".into()),
+
path: ".ghi.uri".into(),
+
},
+
],
+
},
+
0,
+
)?;
+
assert_eq!(
+
storage.get_many_to_many_counts(
+
"a.com",
+
"app.t.c",
+
".abc.uri",
+
".def.uri",
+
10,
+
None,
+
&HashSet::new(),
+
&HashSet::new(),
+
)?,
+
PagedOrderedCollection {
+
items: vec![("b.com".to_string(), 1, 1)],
+
next: None,
+
}
+
);
+
});
+
+
test_each_storage!(get_m2m_counts_filters, |storage| {
+
storage.push(
+
&ActionableEvent::CreateLinks {
+
record_id: RecordId {
+
did: "did:plc:asdf".into(),
+
collection: "app.t.c".into(),
+
rkey: "asdf".into(),
+
},
+
links: vec![
+
CollectedLink {
+
target: Link::Uri("a.com".into()),
+
path: ".abc.uri".into(),
+
},
+
CollectedLink {
+
target: Link::Uri("b.com".into()),
+
path: ".def.uri".into(),
+
},
+
],
+
},
+
0,
+
)?;
+
storage.push(
+
&ActionableEvent::CreateLinks {
+
record_id: RecordId {
+
did: "did:plc:asdfasdf".into(),
+
collection: "app.t.c".into(),
+
rkey: "asdf".into(),
+
},
+
links: vec![
+
CollectedLink {
+
target: Link::Uri("a.com".into()),
+
path: ".abc.uri".into(),
+
},
+
CollectedLink {
+
target: Link::Uri("b.com".into()),
+
path: ".def.uri".into(),
+
},
+
],
+
},
+
1,
+
)?;
+
storage.push(
+
&ActionableEvent::CreateLinks {
+
record_id: RecordId {
+
did: "did:plc:fdsa".into(),
+
collection: "app.t.c".into(),
+
rkey: "asdf".into(),
+
},
+
links: vec![
+
CollectedLink {
+
target: Link::Uri("a.com".into()),
+
path: ".abc.uri".into(),
+
},
+
CollectedLink {
+
target: Link::Uri("c.com".into()),
+
path: ".def.uri".into(),
+
},
+
],
+
},
+
2,
+
)?;
+
storage.push(
+
&ActionableEvent::CreateLinks {
+
record_id: RecordId {
+
did: "did:plc:fdsa".into(),
+
collection: "app.t.c".into(),
+
rkey: "asdf2".into(),
+
},
+
links: vec![
+
CollectedLink {
+
target: Link::Uri("a.com".into()),
+
path: ".abc.uri".into(),
+
},
+
CollectedLink {
+
target: Link::Uri("c.com".into()),
+
path: ".def.uri".into(),
+
},
+
],
+
},
+
3,
+
)?;
+
assert_eq!(
+
storage.get_many_to_many_counts(
+
"a.com",
+
"app.t.c",
+
".abc.uri",
+
".def.uri",
+
10,
+
None,
+
&HashSet::new(),
+
&HashSet::new(),
+
)?,
+
PagedOrderedCollection {
+
items: vec![("b.com".to_string(), 2, 2), ("c.com".to_string(), 2, 1),],
+
next: None,
+
}
+
);
+
assert_eq!(
+
storage.get_many_to_many_counts(
+
"a.com",
+
"app.t.c",
+
".abc.uri",
+
".def.uri",
+
10,
+
None,
+
&HashSet::from_iter([Did("did:plc:fdsa".to_string())]),
+
&HashSet::new(),
+
)?,
+
PagedOrderedCollection {
+
items: vec![("c.com".to_string(), 2, 1),],
+
next: None,
+
}
+
);
+
assert_eq!(
+
storage.get_many_to_many_counts(
+
"a.com",
+
"app.t.c",
+
".abc.uri",
+
".def.uri",
+
10,
+
None,
+
&HashSet::new(),
+
&HashSet::from_iter(["b.com".to_string()]),
+
)?,
+
PagedOrderedCollection {
+
items: vec![("b.com".to_string(), 2, 2),],
+
next: None,
+
}
+
);
});
}
+361 -41
constellation/src/storage/rocks_store.rs
···
-
use super::{ActionableEvent, LinkReader, LinkStorage, PagedAppendingCollection, StorageStats};
use crate::{CountsByCount, Did, RecordId};
use anyhow::{bail, Result};
use bincode::Options as BincodeOptions;
···
MultiThreaded, Options, PrefixRange, ReadOptions, WriteBatch,
};
use serde::{Deserialize, Serialize};
-
use std::collections::{HashMap, HashSet};
use std::io::Read;
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
···
Arc,
};
use std::thread;
-
use std::time::{Duration, Instant};
use tokio_util::sync::CancellationToken;
static DID_IDS_CF: &str = "did_ids";
···
static LINK_TARGETS_CF: &str = "link_targets";
static JETSTREAM_CURSOR_KEY: &str = "jetstream_cursor";
// todo: actually understand and set these options probably better
fn rocks_opts_base() -> Options {
···
#[derive(Debug, Clone)]
pub struct RocksStorage {
pub db: Arc<DBWithThreadMode<MultiThreaded>>, // TODO: mov seqs here (concat merge op will be fun)
-
did_id_table: IdTable<Did, DidIdValue, true>,
-
target_id_table: IdTable<TargetKey, TargetId, false>,
is_writer: bool,
backup_task: Arc<Option<thread::JoinHandle<Result<()>>>>,
}
···
fn cf_descriptor(&self) -> ColumnFamilyDescriptor {
ColumnFamilyDescriptor::new(&self.name, rocks_opts_base())
}
-
fn init<const WITH_REVERSE: bool>(
-
self,
-
db: &DBWithThreadMode<MultiThreaded>,
-
) -> Result<IdTable<Orig, IdVal, WITH_REVERSE>> {
if db.cf_handle(&self.name).is_none() {
bail!("failed to get cf handle from db -- was the db open with our .cf_descriptor()?");
}
···
}
}
#[derive(Debug, Clone)]
-
struct IdTable<Orig, IdVal: IdTableValue, const WITH_REVERSE: bool>
where
Orig: KeyFromRocks,
for<'a> &'a Orig: AsRocksKey,
···
base: IdTableBase<Orig, IdVal>,
priv_id_seq: u64,
}
-
impl<Orig: Clone, IdVal: IdTableValue, const WITH_REVERSE: bool> IdTable<Orig, IdVal, WITH_REVERSE>
where
Orig: KeyFromRocks,
for<'v> &'v IdVal: AsRocksValue,
···
_key_marker: PhantomData,
_val_marker: PhantomData,
name: name.into(),
-
id_seq: Arc::new(AtomicU64::new(0)), // zero is "uninint", first seq num will be 1
}
}
fn get_id_val(
···
id_value
}))
}
fn estimate_count(&self) -> u64 {
self.base.id_seq.load(Ordering::SeqCst) - 1 // -1 because seq zero is reserved
}
-
}
-
impl<Orig: Clone, IdVal: IdTableValue> IdTable<Orig, IdVal, true>
-
where
-
Orig: KeyFromRocks,
-
for<'v> &'v IdVal: AsRocksValue,
-
for<'k> &'k Orig: AsRocksKey,
-
{
fn get_or_create_id_val(
&mut self,
db: &DBWithThreadMode<MultiThreaded>,
···
}
}
}
-
impl<Orig: Clone, IdVal: IdTableValue> IdTable<Orig, IdVal, false>
-
where
-
Orig: KeyFromRocks,
-
for<'v> &'v IdVal: AsRocksValue,
-
for<'k> &'k Orig: AsRocksKey,
-
{
-
fn get_or_create_id_val(
-
&mut self,
-
db: &DBWithThreadMode<MultiThreaded>,
-
batch: &mut WriteBatch,
-
orig: &Orig,
-
) -> Result<IdVal> {
-
let cf = db.cf_handle(&self.base.name).unwrap();
-
self.__get_or_create_id_val(&cf, db, batch, orig)
-
}
-
}
impl IdTableValue for DidIdValue {
fn new(v: u64) -> Self {
···
}
}
impl RocksStorage {
pub fn new(path: impl AsRef<Path>) -> Result<Self> {
Self::describe_metrics();
-
RocksStorage::open_readmode(path, false)
}
pub fn open_readonly(path: impl AsRef<Path>) -> Result<Self> {
···
}
fn open_readmode(path: impl AsRef<Path>, readonly: bool) -> Result<Self> {
-
let did_id_table = IdTable::<_, _, true>::setup(DID_IDS_CF);
-
let target_id_table = IdTable::<_, _, false>::setup(TARGET_IDS_CF);
let cfs = vec![
// id reference tables
did_id_table.cf_descriptor(),
···
is_writer: !readonly,
backup_task: None.into(),
})
}
pub fn start_backup(
···
}
impl LinkReader for RocksStorage {
fn get_count(&self, target: &str, collection: &str, path: &str) -> Result<u64> {
let target_key = TargetKey(
Target(target.to_string()),
···
path: &str,
limit: u64,
until: Option<u64>,
) -> Result<PagedAppendingCollection<RecordId>> {
let target_key = TargetKey(
Target(target.to_string()),
···
});
};
-
let linkers = self.get_target_linkers(&target_id)?;
let (alive, gone) = linkers.count();
let total = alive + gone;
···
.map(|s| s.parse::<u64>())
.transpose()?
.unwrap_or(0);
Ok(StorageStats {
dids,
targetables,
linking_records,
})
}
}
···
impl AsRocksValue for &TargetId {}
impl KeyFromRocks for TargetKey {}
impl ValueFromRocks for TargetId {}
// target_links table
impl AsRocksKey for &TargetId {}
···
}
// target ids
-
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TargetId(u64); // key
-
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Target(pub String); // the actual target/uri
// targets (uris, dids, etc.): the reverse index
···
+
use super::{
+
ActionableEvent, LinkReader, LinkStorage, PagedAppendingCollection, PagedOrderedCollection,
+
StorageStats,
+
};
use crate::{CountsByCount, Did, RecordId};
use anyhow::{bail, Result};
use bincode::Options as BincodeOptions;
···
MultiThreaded, Options, PrefixRange, ReadOptions, WriteBatch,
};
use serde::{Deserialize, Serialize};
+
use std::collections::{BTreeMap, HashMap, HashSet};
use std::io::Read;
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
···
Arc,
};
use std::thread;
+
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use tokio_util::sync::CancellationToken;
static DID_IDS_CF: &str = "did_ids";
···
static LINK_TARGETS_CF: &str = "link_targets";
static JETSTREAM_CURSOR_KEY: &str = "jetstream_cursor";
+
static STARTED_AT_KEY: &str = "jetstream_first_cursor";
+
// add reverse mappings for targets if this db was running before that was a thing
+
static TARGET_ID_REPAIR_STATE_KEY: &str = "target_id_table_repair_state";
+
+
static COZY_FIRST_CURSOR: u64 = 1_738_083_600_000_000; // constellation.microcosm.blue started
+
+
#[derive(Debug, Clone, Serialize, Deserialize)]
+
struct TargetIdRepairState {
+
/// start time for repair, microseconds timestamp
+
current_us_started_at: u64,
+
/// id table's latest id when repair started
+
id_when_started: u64,
+
/// id table id
+
latest_repaired_i: u64,
+
}
+
impl AsRocksValue for TargetIdRepairState {}
+
impl ValueFromRocks for TargetIdRepairState {}
// todo: actually understand and set these options probably better
fn rocks_opts_base() -> Options {
···
#[derive(Debug, Clone)]
pub struct RocksStorage {
pub db: Arc<DBWithThreadMode<MultiThreaded>>, // TODO: mov seqs here (concat merge op will be fun)
+
did_id_table: IdTable<Did, DidIdValue>,
+
target_id_table: IdTable<TargetKey, TargetId>,
is_writer: bool,
backup_task: Arc<Option<thread::JoinHandle<Result<()>>>>,
}
···
fn cf_descriptor(&self) -> ColumnFamilyDescriptor {
ColumnFamilyDescriptor::new(&self.name, rocks_opts_base())
}
+
fn init(self, db: &DBWithThreadMode<MultiThreaded>) -> Result<IdTable<Orig, IdVal>> {
if db.cf_handle(&self.name).is_none() {
bail!("failed to get cf handle from db -- was the db open with our .cf_descriptor()?");
}
···
}
}
#[derive(Debug, Clone)]
+
struct IdTable<Orig, IdVal: IdTableValue>
where
Orig: KeyFromRocks,
for<'a> &'a Orig: AsRocksKey,
···
base: IdTableBase<Orig, IdVal>,
priv_id_seq: u64,
}
+
impl<Orig: Clone, IdVal: IdTableValue> IdTable<Orig, IdVal>
where
Orig: KeyFromRocks,
for<'v> &'v IdVal: AsRocksValue,
···
_key_marker: PhantomData,
_val_marker: PhantomData,
name: name.into(),
+
id_seq: Arc::new(AtomicU64::new(0)), // zero is "uninit", first seq num will be 1
}
}
fn get_id_val(
···
id_value
}))
}
+
fn estimate_count(&self) -> u64 {
self.base.id_seq.load(Ordering::SeqCst) - 1 // -1 because seq zero is reserved
}
+
fn get_or_create_id_val(
&mut self,
db: &DBWithThreadMode<MultiThreaded>,
···
}
}
}
impl IdTableValue for DidIdValue {
fn new(v: u64) -> Self {
···
}
}
+
fn now() -> u64 {
+
SystemTime::now()
+
.duration_since(UNIX_EPOCH)
+
.unwrap()
+
.as_micros() as u64
+
}
+
impl RocksStorage {
pub fn new(path: impl AsRef<Path>) -> Result<Self> {
Self::describe_metrics();
+
let me = RocksStorage::open_readmode(path, false)?;
+
me.global_init()?;
+
Ok(me)
}
pub fn open_readonly(path: impl AsRef<Path>) -> Result<Self> {
···
}
fn open_readmode(path: impl AsRef<Path>, readonly: bool) -> Result<Self> {
+
let did_id_table = IdTable::setup(DID_IDS_CF);
+
let target_id_table = IdTable::setup(TARGET_IDS_CF);
+
// note: global stuff like jetstream cursor goes in the default cf
+
// these are bonus extra cfs
let cfs = vec![
// id reference tables
did_id_table.cf_descriptor(),
···
is_writer: !readonly,
backup_task: None.into(),
})
+
}
+
+
fn global_init(&self) -> Result<()> {
+
let first_run = self.db.get(JETSTREAM_CURSOR_KEY)?.is_some();
+
if first_run {
+
self.db.put(STARTED_AT_KEY, _rv(now()))?;
+
+
// hack / temporary: if we're a new db, put in a completed repair
+
// state so we don't run repairs (repairs are for old-code dbs)
+
let completed = TargetIdRepairState {
+
id_when_started: 0,
+
current_us_started_at: 0,
+
latest_repaired_i: 0,
+
};
+
self.db.put(TARGET_ID_REPAIR_STATE_KEY, _rv(completed))?;
+
}
+
Ok(())
+
}
+
+
pub fn run_repair(&self, breather: Duration, stay_alive: CancellationToken) -> Result<bool> {
+
let mut state = match self
+
.db
+
.get(TARGET_ID_REPAIR_STATE_KEY)?
+
.map(|s| _vr(&s))
+
.transpose()?
+
{
+
Some(s) => s,
+
None => TargetIdRepairState {
+
id_when_started: self.did_id_table.priv_id_seq,
+
current_us_started_at: now(),
+
latest_repaired_i: 0,
+
},
+
};
+
+
eprintln!("initial repair state: {state:?}");
+
+
let cf = self.db.cf_handle(TARGET_IDS_CF).unwrap();
+
+
let mut iter = self.db.raw_iterator_cf(&cf);
+
iter.seek_to_first();
+
+
eprintln!("repair iterator sent to first key");
+
+
// skip ahead if we're done some, or take a single first step
+
for _ in 0..state.latest_repaired_i {
+
iter.next();
+
}
+
+
eprintln!(
+
"repair iterator skipped to {}th key",
+
state.latest_repaired_i
+
);
+
+
let mut maybe_done = false;
+
+
let mut write_fast = rocksdb::WriteOptions::default();
+
write_fast.set_sync(false);
+
write_fast.disable_wal(true);
+
+
while !stay_alive.is_cancelled() && !maybe_done {
+
// let mut batch = WriteBatch::default();
+
+
let mut any_written = false;
+
+
for _ in 0..1000 {
+
if state.latest_repaired_i % 1_000_000 == 0 {
+
eprintln!("target iter at {}", state.latest_repaired_i);
+
}
+
state.latest_repaired_i += 1;
+
+
if !iter.valid() {
+
eprintln!("invalid iter, are we done repairing?");
+
maybe_done = true;
+
break;
+
};
+
+
// eprintln!("iterator seems to be valid! getting the key...");
+
let raw_key = iter.key().unwrap();
+
if raw_key.len() == 8 {
+
// eprintln!("found an 8-byte key, skipping it since it's probably an id...");
+
iter.next();
+
continue;
+
}
+
let target: TargetKey = _kr::<TargetKey>(raw_key)?;
+
let target_id: TargetId = _vr(iter.value().unwrap())?;
+
+
self.db
+
.put_cf_opt(&cf, target_id.id().to_be_bytes(), _rv(&target), &write_fast)?;
+
any_written = true;
+
iter.next();
+
}
+
+
if any_written {
+
self.db
+
.put(TARGET_ID_REPAIR_STATE_KEY, _rv(state.clone()))?;
+
std::thread::sleep(breather);
+
}
+
}
+
+
eprintln!("repair iterator done.");
+
+
Ok(false)
}
pub fn start_backup(
···
}
impl LinkReader for RocksStorage {
+
fn get_many_to_many_counts(
+
&self,
+
target: &str,
+
collection: &str,
+
path: &str,
+
path_to_other: &str,
+
limit: u64,
+
after: Option<String>,
+
filter_dids: &HashSet<Did>,
+
filter_to_targets: &HashSet<String>,
+
) -> Result<PagedOrderedCollection<(String, u64, u64), String>> {
+
let collection = Collection(collection.to_string());
+
let path = RPath(path.to_string());
+
+
let target_key = TargetKey(Target(target.to_string()), collection.clone(), path.clone());
+
+
// unfortunately the cursor is a, uh, stringified number.
+
// this was easier for the memstore (plain target, not target id), and
+
// making it generic is a bit awful.
+
// so... parse the number out of a string here :(
+
// TODO: this should bubble up to a BAD_REQUEST response
+
let after = after.map(|s| s.parse::<u64>().map(TargetId)).transpose()?;
+
+
let Some(target_id) = self.target_id_table.get_id_val(&self.db, &target_key)? else {
+
eprintln!("nothin doin for this target, {target_key:?}");
+
return Ok(Default::default());
+
};
+
+
let filter_did_ids: HashMap<DidId, bool> = filter_dids
+
.iter()
+
.filter_map(|did| self.did_id_table.get_id_val(&self.db, did).transpose())
+
.collect::<Result<Vec<DidIdValue>>>()?
+
.into_iter()
+
.map(|DidIdValue(id, active)| (id, active))
+
.collect();
+
+
// stored targets are keyed by triples of (target, collection, path).
+
// target filtering only consideres the target itself, so we actually
+
// need to do a prefix iteration of all target ids for this target and
+
// keep them all.
+
// i *think* the number of keys at a target prefix should usually be
+
// pretty small, so this is hopefully fine. but if it turns out to be
+
// large, we can push this filtering back into the main links loop and
+
// do forward db queries per backlink to get the raw target back out.
+
let mut filter_to_target_ids: HashSet<TargetId> = HashSet::new();
+
for t in filter_to_targets {
+
for (_, target_id) in self.iter_targets_for_target(&Target(t.to_string())) {
+
filter_to_target_ids.insert(target_id);
+
}
+
}
+
+
let linkers = self.get_target_linkers(&target_id)?;
+
+
let mut grouped_counts: BTreeMap<TargetId, (u64, HashSet<DidId>)> = BTreeMap::new();
+
+
for (did_id, rkey) in linkers.0 {
+
if did_id.is_empty() {
+
continue;
+
}
+
+
if !filter_did_ids.is_empty() && filter_did_ids.get(&did_id) != Some(&true) {
+
continue;
+
}
+
+
let record_link_key = RecordLinkKey(did_id, collection.clone(), rkey);
+
let Some(targets) = self.get_record_link_targets(&record_link_key)? else {
+
continue;
+
};
+
+
let Some(fwd_target) = targets
+
.0
+
.into_iter()
+
.filter_map(|RecordLinkTarget(rpath, target_id)| {
+
if rpath.0 == path_to_other
+
&& (filter_to_target_ids.is_empty()
+
|| filter_to_target_ids.contains(&target_id))
+
{
+
Some(target_id)
+
} else {
+
None
+
}
+
})
+
.take(1)
+
.next()
+
else {
+
eprintln!("no forward match");
+
continue;
+
};
+
+
// small relief: we page over target ids, so we can already bail
+
// reprocessing previous pages here
+
if after.as_ref().map(|a| fwd_target <= *a).unwrap_or(false) {
+
continue;
+
}
+
+
// aand we can skip target ids that must be on future pages
+
// (this check continues after the did-lookup, which we have to do)
+
let page_is_full = grouped_counts.len() as u64 >= limit;
+
if page_is_full {
+
let current_max = grouped_counts.keys().next_back().unwrap(); // limit should be non-zero bleh
+
if fwd_target > *current_max {
+
continue;
+
}
+
}
+
+
// bit painful: 2-step lookup to make sure this did is active
+
let Some(did) = self.did_id_table.get_val_from_id(&self.db, did_id.0)? else {
+
eprintln!("failed to look up did from did_id {did_id:?}");
+
continue;
+
};
+
let Some(DidIdValue(_, active)) = self.did_id_table.get_id_val(&self.db, &did)? else {
+
eprintln!("failed to look up did_value from did_id {did_id:?}: {did:?}: data consistency bug?");
+
continue;
+
};
+
if !active {
+
continue;
+
}
+
+
// page-management, continued
+
// if we have a full page, and we're inserting a *new* key less than
+
// the current max, then we can evict the current max
+
let mut should_evict = false;
+
let entry = grouped_counts.entry(fwd_target.clone()).or_insert_with(|| {
+
// this is a *new* key, so kick the max if we're full
+
should_evict = page_is_full;
+
Default::default()
+
});
+
entry.0 += 1;
+
entry.1.insert(did_id);
+
+
if should_evict {
+
grouped_counts.pop_last();
+
}
+
}
+
+
let mut items: Vec<(String, u64, u64)> = Vec::with_capacity(grouped_counts.len());
+
for (target_id, (n, dids)) in &grouped_counts {
+
let Some(target) = self
+
.target_id_table
+
.get_val_from_id(&self.db, target_id.0)?
+
else {
+
eprintln!("failed to look up target from target_id {target_id:?}");
+
continue;
+
};
+
items.push((target.0 .0, *n, dids.len() as u64));
+
}
+
+
let next = if grouped_counts.len() as u64 >= limit {
+
// yeah.... it's a number saved as a string......sorry
+
grouped_counts
+
.keys()
+
.next_back()
+
.map(|k| format!("{}", k.0))
+
} else {
+
None
+
};
+
+
Ok(PagedOrderedCollection { items, next })
+
}
+
fn get_count(&self, target: &str, collection: &str, path: &str) -> Result<u64> {
let target_key = TargetKey(
Target(target.to_string()),
···
path: &str,
limit: u64,
until: Option<u64>,
+
filter_dids: &HashSet<Did>,
) -> Result<PagedAppendingCollection<RecordId>> {
let target_key = TargetKey(
Target(target.to_string()),
···
});
};
+
let mut linkers = self.get_target_linkers(&target_id)?;
+
if !filter_dids.is_empty() {
+
let mut did_filter = HashSet::new();
+
for did in filter_dids {
+
let Some(DidIdValue(did_id, active)) =
+
self.did_id_table.get_id_val(&self.db, did)?
+
else {
+
eprintln!("failed to find a did_id for {did:?}");
+
continue;
+
};
+
if !active {
+
eprintln!("excluding inactive did from filtered results");
+
continue;
+
}
+
did_filter.insert(did_id);
+
}
+
linkers.0.retain(|linker| did_filter.contains(&linker.0));
+
}
let (alive, gone) = linkers.count();
let total = alive + gone;
···
.map(|s| s.parse::<u64>())
.transpose()?
.unwrap_or(0);
+
let started_at = self
+
.db
+
.get(STARTED_AT_KEY)?
+
.map(|c| _vr(&c))
+
.transpose()?
+
.unwrap_or(COZY_FIRST_CURSOR);
+
+
let other_data = self
+
.db
+
.get(TARGET_ID_REPAIR_STATE_KEY)?
+
.map(|s| _vr(&s))
+
.transpose()?
+
.map(
+
|TargetIdRepairState {
+
current_us_started_at,
+
id_when_started,
+
latest_repaired_i,
+
}| {
+
HashMap::from([
+
("current_us_started_at".to_string(), current_us_started_at),
+
("id_when_started".to_string(), id_when_started),
+
("latest_repaired_i".to_string(), latest_repaired_i),
+
])
+
},
+
)
+
.unwrap_or(HashMap::default());
+
Ok(StorageStats {
dids,
targetables,
linking_records,
+
started_at: Some(started_at),
+
other_data,
})
}
}
···
impl AsRocksValue for &TargetId {}
impl KeyFromRocks for TargetKey {}
impl ValueFromRocks for TargetId {}
+
+
// temp?
+
impl KeyFromRocks for TargetId {}
+
impl AsRocksValue for &TargetKey {}
// target_links table
impl AsRocksKey for &TargetId {}
···
}
// target ids
+
#[derive(Debug, Clone, Serialize, Deserialize, PartialOrd, Ord, PartialEq, Eq, Hash)]
struct TargetId(u64); // key
+
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct Target(pub String); // the actual target/uri
// targets (uris, dids, etc.): the reverse index
+1 -1
constellation/templates/dids.html.j2
···
{% for did in linking_dids %}
<pre style="display: block; margin: 1em 2em" class="code"><strong>DID</strong>: {{ did.0 }}
-> see <a href="/links/all?target={{ did.0|urlencode }}">links to this DID</a>
-
-> browse <a href="https://atproto-browser-plus-links.vercel.app/at/{{ did.0|urlencode }}">this DID record</a></pre>
{% endfor %}
{% if let Some(c) = cursor %}
···
{% for did in linking_dids %}
<pre style="display: block; margin: 1em 2em" class="code"><strong>DID</strong>: {{ did.0 }}
-> see <a href="/links/all?target={{ did.0|urlencode }}">links to this DID</a>
+
-> browse <a href="https://pdsls.dev/at://{{ did.0|urlencode }}">this DID record</a></pre>
{% endfor %}
{% if let Some(c) = cursor %}
+54
constellation/templates/get-backlinks.html.j2
···
···
+
{% extends "base.html.j2" %}
+
{% import "try-it-macros.html.j2" as try_it %}
+
+
{% block title %}Backlinks{% endblock %}
+
{% block description %}All {{ query.source }} records with links to {{ query.subject }}{% endblock %}
+
+
{% block content %}
+
+
{% call try_it::get_backlinks(query.subject, query.source, query.did, query.limit) %}
+
+
<h2>
+
Links to <code>{{ query.subject }}</code>
+
{% if let Some(browseable_uri) = query.subject|to_browseable %}
+
<small style="font-weight: normal; font-size: 1rem"><a href="{{ browseable_uri }}">browse record</a></small>
+
{% endif %}
+
</h2>
+
+
<p><strong>{{ total|human_number }} links</strong> from <code>{{ query.source }}</code>.</p>
+
+
<ul>
+
<li>See distinct linking DIDs at <code>/links/distinct-dids</code>: <a href="/links/distinct-dids?target={{ query.subject|urlencode }}&collection={{ collection|urlencode }}&path={{ path|urlencode }}">/links/distinct-dids?target={{ query.subject }}&collection={{ collection }}&path={{ path }}</a></li>
+
<li>See all links to this target at <code>/links/all</code>: <a href="/links/all?target={{ query.subject|urlencode }}">/links/all?target={{ query.subject }}</a></li>
+
</ul>
+
+
<h3>Links, most recent first:</h3>
+
+
{% for record in records %}
+
<pre style="display: block; margin: 1em 2em" class="code"><strong>DID</strong>: {{ record.did().0 }} (<a href="/links/all?target={{ record.did().0|urlencode }}">DID links</a>)
+
<strong>Collection</strong>: {{ record.collection }}
+
<strong>RKey</strong>: {{ record.rkey }}
+
-> <a href="https://pdsls.dev/at://{{ record.did().0 }}/{{ record.collection }}/{{ record.rkey }}">browse record</a></pre>
+
{% endfor %}
+
+
{% if let Some(c) = cursor %}
+
<form method="get" action="/xrpc/blue.microcosm.links.getBacklinks">
+
<input type="hidden" name="subject" value="{{ query.subject }}" />
+
<input type="hidden" name="source" value="{{ query.source }}" />
+
<input type="hidden" name="limit" value="{{ query.limit }}" />
+
{% for did in query.did %}
+
<input type="hidden" name="did" value="{{ did }}" />
+
{% endfor %}
+
<input type="hidden" name="cursor" value={{ c|json|safe }} />
+
<button type="submit">next page&hellip;</button>
+
</form>
+
{% else %}
+
<button disabled><em>end of results</em></button>
+
{% endif %}
+
+
<details>
+
<summary>Raw JSON response</summary>
+
<pre class="code">{{ self|tojson }}</pre>
+
</details>
+
+
{% endblock %}
+67
constellation/templates/get-many-to-many-counts.html.j2
···
···
+
{% extends "base.html.j2" %}
+
{% import "try-it-macros.html.j2" as try_it %}
+
+
{% block title %}Many to Many counts{% endblock %}
+
{% block description %}Counts of many-to-many {{ query.source }} join records with links to {{ query.subject }} and a secondary target at {{ query.path_to_other }}{% endblock %}
+
+
{% block content %}
+
+
{% call try_it::get_many_to_many_counts(
+
query.subject,
+
query.source,
+
query.path_to_other,
+
query.did,
+
query.other_subject,
+
query.limit,
+
) %}
+
+
<h2>
+
Many-to-many links to <code>{{ query.subject }}</code> joining through <code>{{ query.path_to_other }}</code>
+
{% if let Some(browseable_uri) = query.subject|to_browseable %}
+
<small style="font-weight: normal; font-size: 1rem"><a href="{{ browseable_uri }}">browse record</a></small>
+
{% endif %}
+
</h2>
+
+
<p><strong>{% if cursor.is_some() || query.cursor.is_some() %}more than {% endif %}{{ counts_by_other_subject.len()|to_u64|human_number }} joins</strong> <code>{{ query.source }}โ†’{{ query.path_to_other }}</code></p>
+
+
<ul>
+
<li>See direct backlinks at <code>/xrpc/blue.microcosm.links.getBacklinks</code>: <a href="/xrpc/blue.microcosm.links.getBacklinks?subject={{ query.subject|urlencode }}&source={{ query.source|urlencode }}">/xrpc/blue.microcosm.links.getBacklinks?subject={{ query.subject }}&source={{ query.source }}</a></li>
+
<li>See all links to this target at <code>/links/all</code>: <a href="/links/all?target={{ query.subject|urlencode }}">/links/all?target={{ query.subject }}</a></li>
+
</ul>
+
+
<h3>Counts by other subject:</h3>
+
+
{% for counts in counts_by_other_subject %}
+
<pre style="display: block; margin: 1em 2em" class="code"><strong>Joined subject</strong>: {{ counts.subject }}
+
<strong>Joining records</strong>: {{ counts.total }}
+
<strong>Unique joiner ids</strong>: {{ counts.distinct }}
+
-> {% if let Some(browseable_uri) = counts.subject|to_browseable -%}
+
<a href="{{ browseable_uri }}">browse record</a>
+
{%- endif %}</pre>
+
{% endfor %}
+
+
{% if let Some(c) = cursor %}
+
<form method="get" action="/xrpc/blue.microcosm.links.getManyToManyCounts">
+
<input type="hidden" name="subject" value="{{ query.subject }}" />
+
<input type="hidden" name="source" value="{{ query.source }}" />
+
<input type="hidden" name="pathToOther" value="{{ query.path_to_other }}" />
+
{% for did in query.did %}
+
<input type="hidden" name="did" value="{{ did }}" />
+
{% endfor %}
+
{% for otherSubject in query.other_subject %}
+
<input type="hidden" name="otherSubject" value="{{ otherSubject }}" />
+
{% endfor %}
+
<input type="hidden" name="limit" value="{{ query.limit }}" />
+
<input type="hidden" name="cursor" value={{ c|json|safe }} />
+
<button type="submit">next page&hellip;</button>
+
</form>
+
{% else %}
+
<button disabled><em>end of results</em></button>
+
{% endif %}
+
+
<details>
+
<summary>Raw JSON response</summary>
+
<pre class="code">{{ self|tojson }}</pre>
+
</details>
+
+
{% endblock %}
+65 -7
constellation/templates/hello.html.j2
···
<p>It works by recursively walking <em>all</em> records coming through the firehose, searching for anything that looks like a link. Links are indexed by the target they point at, the collection the record came from, and the JSON path to the link in that record.</p>
<p>
-
This server has indexed <span class="stat">{{ stats.linking_records|human_number }}</span> links between <span class="stat">{{ stats.targetables|human_number }}</span> targets and sources from <span class="stat">{{ stats.dids|human_number }}</span> identities over <span class="stat">{{ days_indexed|human_number }}</span> days.<br/>
-
<small>(indexing new records in real time, backfill still TODO)</small>
</p>
-
<p>The API is currently <strong>unstable</strong>. But feel free to use it! If you want to be nice, put your project name and bsky username (or email) in your user-agent header for api requests.</p>
<h2>API Endpoints</h2>
<h3 class="route"><code>GET /links</code></h3>
<p>A list of records linking to a target.</p>
<h4>Query parameters:</h4>
<ul>
-
<li><code>target</code>: required, must url-encode. Example: <code>at://did:plc:vc7f4oafdgxsihk4cry2xpze/app.bsky.feed.post/3lgwdn7vd722r</code></li>
-
<li><code>collection</code>: required. Example: <code>app.bsky.feed.like</code></li>
-
<li><code>path</code>: required, must url-encode. Example: <code>.subject.uri</code></li>
</ul>
<p style="margin-bottom: 0"><strong>Try it:</strong></p>
-
{% call try_it::links("at://did:plc:vc7f4oafdgxsihk4cry2xpze/app.bsky.feed.post/3lgwdn7vd722r", "app.bsky.feed.like", ".subject.uri") %}
<h3 class="route"><code>GET /links/distinct-dids</code></h3>
···
<p>It works by recursively walking <em>all</em> records coming through the firehose, searching for anything that looks like a link. Links are indexed by the target they point at, the collection the record came from, and the JSON path to the link in that record.</p>
<p>
+
This server has indexed <span class="stat">{{ stats.linking_records|human_number }}</span> links between <span class="stat">{{ stats.targetables|human_number }}</span> targets and sources from <span class="stat">{{ stats.dids|human_number }}</span> identities over <span class="stat">
+
{%- if let Some(days) = days_indexed %}
+
{{ days|human_number }}
+
{% else %}
+
???
+
{% endif -%}
+
</span> days.<br/>
+
<small>(indexing new records in real time, backfill coming soon!)</small>
</p>
+
{# {% for k, v in stats.other_data.iter() %}
+
<p><strong>{{ k }}</strong>: {{ v }}</p>
+
{% endfor %} #}
+
+
<p>You're welcome to use this public instance! Please do not build the torment nexus. If you want to be nice, put your project name and bsky username (or email) in your user-agent header for api requests.</p>
<h2>API Endpoints</h2>
+
<h3 class="route"><code>GET /xrpc/blue.microcosm.links.getBacklinks</code></h3>
+
+
<p>A list of records linking to any record, identity, or uri.</p>
+
+
<h4>Query parameters:</h4>
+
+
<ul>
+
<li><p><code>subject</code>: required, must url-encode. Example: <code>at://did:plc:vc7f4oafdgxsihk4cry2xpze/app.bsky.feed.post/3lgwdn7vd722r</code></p></li>
+
<li><p><code>source</code>: required. Example: <code>app.bsky.feed.like:subject.uri</code></p></li>
+
<li><p><code>did</code>: optional, filter links to those from specific users. Include multiple times to filter by multiple users. Example: <code>did=did:plc:vc7f4oafdgxsihk4cry2xpze&did=did:plc:vc7f4oafdgxsihk4cry2xpze</code></p></li>
+
<li><p><code>limit</code>: optional. Default: <code>16</code>. Maximum: <code>100</code></p></li>
+
</ul>
+
+
<p style="margin-bottom: 0"><strong>Try it:</strong></p>
+
{% call try_it::get_backlinks("at://did:plc:a4pqq234yw7fqbddawjo7y35/app.bsky.feed.post/3m237ilwc372e", "app.bsky.feed.like:subject.uri", [""], 16) %}
+
+
+
<h3 class="route"><code>GET /xrpc/blue.microcosm.links.getManyToManyCounts</code></h3>
+
+
<p>TODO: description</p>
+
+
<h4>Query parameters:</h4>
+
+
<ul>
+
<li><p><code>subject</code>: required, must url-encode. Example: <code>at://did:plc:vc7f4oafdgxsihk4cry2xpze/app.bsky.feed.post/3lgwdn7vd722r</code></p></li>
+
<li><p><code>source</code>: required. Example: <code>app.bsky.feed.like:subject.uri</code></p></li>
+
<li><p><code>pathToOther</code>: required. Path to the secondary link in the many-to-many record. Example: <code>otherThing.uri</code></p></li>
+
<li><p><code>did</code>: optional, filter links to those from specific users. Include multiple times to filter by multiple users. Example: <code>did=did:plc:vc7f4oafdgxsihk4cry2xpze&did=did:plc:vc7f4oafdgxsihk4cry2xpze</code></p></li>
+
<li><p><code>otherSubject</code>: optional, filter secondary links to specific subjects. Include multiple times to filter by multiple users. Example: <code>at://did:plc:vc7f4oafdgxsihk4cry2xpze/app.bsky.feed.post/3lgwdn7vd722r</code></p></li>
+
<li><p><code>limit</code>: optional. Default: <code>16</code>. Maximum: <code>100</code></p></li>
+
</ul>
+
+
<p style="margin-bottom: 0"><strong>Try it:</strong></p>
+
{% call try_it::get_many_to_many_counts(
+
"at://did:plc:wshs7t2adsemcrrd4snkeqli/sh.tangled.label.definition/good-first-issue",
+
"sh.tangled.label.op:add[].key",
+
"subject",
+
[""],
+
[""],
+
25,
+
) %}
+
+
<h3 class="route"><code>GET /links</code></h3>
<p>A list of records linking to a target.</p>
+
<p>[DEPRECATED]: use <code>GET /xrpc/blue.microcosm.links.getBacklinks</code>. New apps should avoid it, but this endpoint <strong>will</strong> remain supported for the forseeable future.</p>
+
<h4>Query parameters:</h4>
<ul>
+
<li><p><code>target</code>: required, must url-encode. Example: <code>at://did:plc:vc7f4oafdgxsihk4cry2xpze/app.bsky.feed.post/3lgwdn7vd722r</code></p></li>
+
<li><p><code>collection</code>: required. Example: <code>app.bsky.feed.like</code></p></li>
+
<li><p><code>path</code>: required, must url-encode. Example: <code>.subject.uri</code></p></li>
+
<li><p><code>did</code>: optional, filter links to those from specific users. Include multiple times to filter by multiple users. Example: <code>did=did:plc:vc7f4oafdgxsihk4cry2xpze&did=did:plc:vc7f4oafdgxsihk4cry2xpze</code></p></li>
+
<li><p><code>from_dids</code> [deprecated]: optional. Use <code>did</code> instead. Example: <code>from_dids=did:plc:vc7f4oafdgxsihk4cry2xpze,did:plc:vc7f4oafdgxsihk4cry2xpze</code></p></li>
+
<li><p><code>limit</code>: optional. Default: <code>16</code>. Maximum: <code>100</code></p></li>
</ul>
<p style="margin-bottom: 0"><strong>Try it:</strong></p>
+
{% call try_it::links("at://did:plc:a4pqq234yw7fqbddawjo7y35/app.bsky.feed.post/3m237ilwc372e", "app.bsky.feed.like", ".subject.uri", [""], 16) %}
<h3 class="route"><code>GET /links/distinct-dids</code></h3>
+2 -2
constellation/templates/links.html.j2
···
{% block content %}
-
{% call try_it::links(query.target, query.collection, query.path) %}
<h2>
Links to <code>{{ query.target }}</code>
···
<pre style="display: block; margin: 1em 2em" class="code"><strong>DID</strong>: {{ record.did().0 }} (<a href="/links/all?target={{ record.did().0|urlencode }}">DID links</a>)
<strong>Collection</strong>: {{ record.collection }}
<strong>RKey</strong>: {{ record.rkey }}
-
-> <a href="https://atproto-browser-plus-links.vercel.app/at/{{ record.did().0|urlencode }}/{{ record.collection }}/{{ record.rkey }}">browse record</a></pre>
{% endfor %}
{% if let Some(c) = cursor %}
···
{% block content %}
+
{% call try_it::links(query.target, query.collection, query.path, query.did, query.limit) %}
<h2>
Links to <code>{{ query.target }}</code>
···
<pre style="display: block; margin: 1em 2em" class="code"><strong>DID</strong>: {{ record.did().0 }} (<a href="/links/all?target={{ record.did().0|urlencode }}">DID links</a>)
<strong>Collection</strong>: {{ record.collection }}
<strong>RKey</strong>: {{ record.rkey }}
+
-> <a href="https://pdsls.dev/at://{{ record.did().0 }}/{{ record.collection }}/{{ record.rkey }}">browse record</a></pre>
{% endfor %}
{% if let Some(c) = cursor %}
+88 -3
constellation/templates/try-it-macros.html.j2
···
-
{% macro links(target, collection, path) %}
<form method="get" action="/links">
<pre class="code"><strong>GET</strong> /links
?target= <input type="text" name="target" value="{{ target }}" placeholder="target" />
&collection= <input type="text" name="collection" value="{{ collection }}" placeholder="collection" />
-
&path= <input type="text" name="path" value="{{ path }}" placeholder="path" /> <button type="submit">get links</button></pre>
</form>
{% endmacro %}
-
{% macro dids(target, collection, path) %}
<form method="get" action="/links/distinct-dids">
···
+
{% macro get_backlinks(subject, source, dids, limit) %}
+
<form method="get" action="/xrpc/blue.microcosm.links.getBacklinks">
+
<pre class="code"><strong>GET</strong> /xrpc/blue.microcosm.links.getBacklinks
+
?subject= <input type="text" name="subject" value="{{ subject }}" placeholder="at-uri, did, uri..." />
+
&source= <input type="text" name="source" value="{{ source }}" placeholder="app.bsky.feed.like:subject.uri" />
+
{%- for did in dids %}{% if !did.is_empty() %}
+
&did= <input type="text" name="did" value="{{ did }}" placeholder="did:plc:..." />{% endif %}{% endfor %}
+
<span id="did-placeholder"></span> <button id="add-did">+ did filter</button>
+
&limit= <input type="number" name="limit" value="{{ limit }}" max="100" placeholder="100" /> <button type="submit">get links</button></pre>
+
</form>
+
<script>
+
const addDidButton = document.getElementById('add-did');
+
const didPlaceholder = document.getElementById('did-placeholder');
+
addDidButton.addEventListener('click', e => {
+
e.preventDefault();
+
const i = document.createElement('input');
+
i.placeholder = 'did:plc:...';
+
i.name = "did"
+
const p = addDidButton.parentNode;
+
p.insertBefore(document.createTextNode('&did= '), didPlaceholder);
+
p.insertBefore(i, didPlaceholder);
+
p.insertBefore(document.createTextNode('\n '), didPlaceholder);
+
});
+
</script>
+
{% endmacro %}
+
+
{% macro get_many_to_many_counts(subject, source, pathToOther, dids, otherSubjects, limit) %}
+
<form method="get" action="/xrpc/blue.microcosm.links.getManyToManyCounts">
+
<pre class="code"><strong>GET</strong> /xrpc/blue.microcosm.links.getManyToManyCounts
+
?subject= <input type="text" name="subject" value="{{ subject }}" placeholder="at-uri, did, uri..." />
+
&source= <input type="text" name="source" value="{{ source }}" placeholder="app.bsky.feed.like:subject.uri" />
+
&pathToOther= <input type="text" name="pathToOther" value="{{ pathToOther }}" placeholder="otherThing.uri" />
+
{%- for did in dids %}{% if !did.is_empty() %}
+
&did= <input type="text" name="did" value="{{ did }}" placeholder="did:plc:..." />{% endif %}{% endfor %}
+
<span id="m2m-subject-placeholder"></span> <button id="m2m-add-subject">+ other subject filter</button>
+
{%- for otherSubject in otherSubjects %}{% if !otherSubject.is_empty() %}
+
&otherSubject= <input type="text" name="did" value="{{ otherSubject }}" placeholder="at-uri, did, uri..." />{% endif %}{% endfor %}
+
<span id="m2m-did-placeholder"></span> <button id="m2m-add-did">+ did filter</button>
+
&limit= <input type="number" name="limit" value="{{ limit }}" max="100" placeholder="100" /> <button type="submit">get links</button></pre>
+
</form>
+
<script>
+
const m2mAddDidButton = document.getElementById('m2m-add-did');
+
const m2mDidPlaceholder = document.getElementById('m2m-did-placeholder');
+
m2mAddDidButton.addEventListener('click', e => {
+
e.preventDefault();
+
const i = document.createElement('input');
+
i.placeholder = 'did:plc:...';
+
i.name = "did"
+
const p = m2mAddDidButton.parentNode;
+
p.insertBefore(document.createTextNode('&did= '), m2mDidPlaceholder);
+
p.insertBefore(i, m2mDidPlaceholder);
+
p.insertBefore(document.createTextNode('\n '), m2mDidPlaceholder);
+
});
+
const m2mAddSubjectButton = document.getElementById('m2m-add-subject');
+
const m2mSubjectPlaceholder = document.getElementById('m2m-subject-placeholder');
+
m2mAddSubjectButton.addEventListener('click', e => {
+
e.preventDefault();
+
const i = document.createElement('input');
+
i.placeholder = 'at-uri, did, uri...';
+
i.name = "otherSubject"
+
const p = m2mAddSubjectButton.parentNode;
+
p.insertBefore(document.createTextNode('&otherSubject= '), m2mSubjectPlaceholder);
+
p.insertBefore(i, m2mSubjectPlaceholder);
+
p.insertBefore(document.createTextNode('\n '), m2mSubjectPlaceholder);
+
});
+
</script>
+
{% endmacro %}
+
+
{% macro links(target, collection, path, dids, limit) %}
<form method="get" action="/links">
<pre class="code"><strong>GET</strong> /links
?target= <input type="text" name="target" value="{{ target }}" placeholder="target" />
&collection= <input type="text" name="collection" value="{{ collection }}" placeholder="collection" />
+
&path= <input type="text" name="path" value="{{ path }}" placeholder="path" />
+
{%- for did in dids %}{% if !did.is_empty() %}
+
&did= <input type="text" name="did" value="{{ did }}" placeholder="did:plc:..." />{% endif %}{% endfor %}
+
<span id="did-placeholder"></span> <button id="add-did">+ did filter</button>
+
&limit= <input type="number" name="limit" value="{{ limit }}" max="100" placeholder="100" /> <button type="submit">get links</button></pre>
</form>
+
<script>
+
const addDidButton = document.getElementById('add-did');
+
const didPlaceholder = document.getElementById('did-placeholder');
+
addDidButton.addEventListener('click', e => {
+
e.preventDefault();
+
const i = document.createElement('input');
+
i.placeholder = 'did:plc:...';
+
i.name = "did"
+
const p = addDidButton.parentNode;
+
p.insertBefore(document.createTextNode('&did= '), didPlaceholder);
+
p.insertBefore(i, didPlaceholder);
+
p.insertBefore(document.createTextNode('\n '), didPlaceholder);
+
});
+
</script>
{% endmacro %}
{% macro dids(target, collection, path) %}
<form method="get" action="/links/distinct-dids">
+1
pocket/.gitignore
···
···
+
prefs.sqlite3*
+2
pocket/src/lib.rs
···
mod server;
mod token;
pub use server::serve;
pub use token::TokenVerifier;
···
mod server;
+
mod storage;
mod token;
pub use server::serve;
+
pub use storage::Storage;
pub use token::TokenVerifier;
+29 -3
pocket/src/main.rs
···
-
use pocket::serve;
#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();
-
println!("Hello, world!");
-
serve("mac.cinnebar-tet.ts.net").await
}
···
+
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
+
}
}
+100 -37
pocket/src/server.rs
···
-
use crate::TokenVerifier;
use poem::{
Endpoint, EndpointExt, Route, Server,
endpoint::{StaticFileEndpoint, make_sync},
···
};
use serde::Serialize;
use serde_json::{Value, json};
#[derive(Debug, SecurityScheme)]
#[oai(ty = "bearer")]
···
})
}
-
#[derive(Object)]
#[oai(example = true)]
-
struct GetBskyPrefsResponseObject {
/// at-uri for this record
preferences: Value,
}
-
impl Example for GetBskyPrefsResponseObject {
fn example() -> Self {
Self {
preferences: json!({
···
enum GetBskyPrefsResponse {
/// Record found
#[oai(status = 200)]
-
Ok(Json<GetBskyPrefsResponseObject>),
/// Bad request or no preferences to return
#[oai(status = 400)]
BadRequest(XrpcError),
···
struct Xrpc {
verifier: TokenVerifier,
}
#[OpenApi]
impl Xrpc {
/// com.bad-example.pocket.getPreferences
///
-
/// get stored bluesky prefs
#[oai(
path = "/com.bad-example.pocket.getPreferences",
method = "get",
tag = "ApiTags::Pocket"
)]
-
async fn app_bsky_get_prefs(&self, XrpcAuth(auth): XrpcAuth) -> GetBskyPrefsResponse {
-
let did = match self
.verifier
-
.verify("app.bsky.actor.getPreferences", &auth.token)
.await
{
Ok(d) => d,
Err(e) => return GetBskyPrefsResponse::BadRequest(xrpc_error("boooo", e.to_string())),
};
-
log::info!("verified did: {did}");
-
// TODO: fetch from storage
-
GetBskyPrefsResponse::Ok(Json(GetBskyPrefsResponseObject::example()))
}
/// com.bad-example.pocket.putPreferences
···
method = "post",
tag = "ApiTags::Pocket"
)]
-
async fn app_bsky_put_prefs(
&self,
XrpcAuth(auth): XrpcAuth,
-
Json(prefs): Json<Value>,
) -> PutBskyPrefsResponse {
-
let did = match self
.verifier
-
.verify("app.bsky.actor.getPreferences", &auth.token)
.await
{
Ok(d) => d,
Err(e) => return PutBskyPrefsResponse::BadRequest(xrpc_error("boooo", e.to_string())),
};
-
log::info!("verified did: {did}");
log::warn!("received prefs: {prefs:?}");
-
// TODO: put prefs into storage
-
PutBskyPrefsResponse::Ok(PlainText("hiiiiii".to_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
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}"),
-
}],
});
make_sync(move |_| doc.clone())
}
-
pub async fn serve(domain: &str) -> () {
-
let verifier = TokenVerifier::new(domain);
-
let api_service = OpenApiService::new(Xrpc { verifier }, "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())
···
+
use crate::{Storage, TokenVerifier};
use poem::{
Endpoint, EndpointExt, Route, Server,
endpoint::{StaticFileEndpoint, make_sync},
···
};
use serde::Serialize;
use serde_json::{Value, json};
+
use std::sync::{Arc, Mutex};
#[derive(Debug, SecurityScheme)]
#[oai(ty = "bearer")]
···
})
}
+
#[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!({
···
enum GetBskyPrefsResponse {
/// Record found
#[oai(status = 200)]
+
Ok(Json<BskyPrefsObject>),
/// Bad request or no preferences to return
#[oai(status = 400)]
BadRequest(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
···
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)]
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())
+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()
+
}
+
}
+20 -10
pocket/src/token.rs
···
}
pub struct TokenVerifier {
-
domain: String,
client: reqwest::Client,
}
impl TokenVerifier {
-
pub fn new(domain: &str) -> Self {
let client = reqwest::Client::builder()
.user_agent(format!(
"microcosm pocket v{} (dev: @bad-example.com)",
···
.timeout(Duration::from_secs(12)) // slingshot timeout is 10s
.build()
.unwrap();
-
Self {
-
client,
-
domain: domain.to_string(),
-
}
}
-
pub async fn verify(&self, expected_lxm: &str, token: &str) -> Result<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 Some(aud) = claims.custom.get("aud") else {
return Err(VerifyError::VerificationFailed("missing aud"));
};
-
if *aud != format!("did:web:{}#bsky_appview", self.domain) {
-
return Err(VerifyError::VerificationFailed("wrong aud"));
}
let Some(lxm) = claims.custom.get("lxm") else {
return Err(VerifyError::VerificationFailed("missing lxm"));
···
return Err(VerifyError::VerificationFailed("wrong lxm"));
}
-
Ok(did.to_string())
}
}
···
}
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)",
···
.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 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"));
···
return Err(VerifyError::VerificationFailed("wrong lxm"));
}
+
Ok((did.to_string(), aud.to_string()))
+
}
+
}
+
+
impl Default for TokenVerifier {
+
fn default() -> Self {
+
Self::new()
}
}
+7 -7
reflector/src/main.rs
···
}
#[derive(Debug, Clone, Serialize)]
struct DidService {
id: String,
r#type: String,
···
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)
···
}
#[derive(Debug, Clone, Serialize)]
+
#[serde(rename_all = "camelCase")]
struct DidService {
id: String,
r#type: String,
···
Data(parent): Data<&Option<String>>,
Query(AskQuery { domain }): Query<AskQuery>,
) -> Response {
+
if let Some(parent) = parent
+
&& let Some(prefix) = domain.strip_suffix(&format!(".{parent}"))
+
&& !prefix.contains('.')
+
{
+
// no sub-sub-domains allowed
+
return Response::builder().body("ok");
};
Response::builder()
.status(StatusCode::FORBIDDEN)
+4 -2
slingshot/src/firehose_cache.rs
···
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()
···
pub async fn firehose_cache(
cache_dir: impl AsRef<Path>,
+
memory_mb: usize,
+
disk_gb: usize,
) -> Result<HybridCache<String, CachedRecord>, String> {
let cache = HybridCacheBuilder::new()
.with_name("firehose")
+
.memory(memory_mb * 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(disk_gb * 2_usize.pow(30))
.with_file_size(16 * 2_usize.pow(20)), // note: this does limit the max cached item size, warning jumbo records
)
.build()
+26 -5
slingshot/src/main.rs
···
/// where to keep disk caches
#[arg(long)]
cache_dir: PathBuf,
/// the domain pointing to this server
///
/// if present:
···
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| {
···
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();
···
args.domain,
args.acme_contact,
args.certs,
server_shutdown,
)
.await?;
···
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))?
···
/// where to keep disk caches
#[arg(long)]
cache_dir: PathBuf,
+
/// memory cache size in MB
+
#[arg(long, default_value_t = 64)]
+
cache_memory_mb: usize,
+
/// disk cache size in GB
+
#[arg(long, default_value_t = 1)]
+
cache_disk_gb: usize,
+
/// host for HTTP server (when not using --domain)
+
#[arg(long, default_value = "127.0.0.1")]
+
host: String,
+
/// port for HTTP server (when not using --domain)
+
#[arg(long, default_value_t = 3000)]
+
port: u16,
+
/// port for metrics/prometheus server
+
#[arg(long, default_value_t = 8765)]
+
metrics_port: u16,
/// the domain pointing to this server
///
/// if present:
···
let args = Args::parse();
+
if let Err(e) = install_metrics_server(args.metrics_port) {
log::error!("failed to install metrics server: {e:?}");
} else {
+
log::info!("metrics listening at http://0.0.0.0:{}", args.metrics_port);
}
std::fs::create_dir_all(&args.cache_dir).map_err(|e| {
···
log::info!("cache dir ready at at {cache_dir:?}.");
log::info!("setting up firehose cache...");
+
let cache = firehose_cache(
+
cache_dir.join("./firehose"),
+
args.cache_memory_mb,
+
args.cache_disk_gb,
+
)
+
.await?;
log::info!("firehose cache ready.");
let mut tasks: tokio::task::JoinSet<Result<(), MainTaskError>> = tokio::task::JoinSet::new();
···
args.domain,
args.acme_contact,
args.certs,
+
args.host,
+
args.port,
server_shutdown,
)
.await?;
···
Ok(())
}
+
fn install_metrics_server(port: u16) -> Result<(), metrics_exporter_prometheus::BuildError> {
log::info!("installing metrics server...");
let host = [0, 0, 0, 0];
PrometheusBuilder::new()
.set_quantiles(&[0.5, 0.9, 0.99, 1.0])?
.set_bucket_duration(std::time::Duration::from_secs(300))?
+19 -12
slingshot/src/server.rs
···
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 {
···
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:
···
.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()
···
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 {
···
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 {
···
domain: Option<String>,
acme_contact: Option<String>,
certs: Option<PathBuf>,
shutdown: CancellationToken,
) -> Result<(), ServerError> {
let repo = Arc::new(repo);
···
)
.await
} else {
-
run(TcpListener::bind("127.0.0.1:3000"), app, shutdown).await
}
}
···
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 {
···
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:
···
.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()
···
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 {
···
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 {
···
domain: Option<String>,
acme_contact: Option<String>,
certs: Option<PathBuf>,
+
host: String,
+
port: u16,
shutdown: CancellationToken,
) -> Result<(), ServerError> {
let repo = Arc::new(repo);
···
)
.await
} else {
+
run(
+
TcpListener::bind(format!("{host}:{port}")),
+
app,
+
shutdown,
+
)
+
.await
}
}
+5 -5
spacedust/src/subscriber.rs
···
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)) => {
···
loop {
tokio::select! {
l = receiver.recv() => match l {
+
Ok(link) => if self.filter(&link.properties)
+
&& 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)) => {
+4 -4
who-am-i/src/server.rs
···
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" {
···
Some(parent_host),
);
}
+
if let Some(ref app) = params.app
+
&& !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" {