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

Add new get_many_to_many XRPC endpoint #7

merged opened by seoul.systems targeting main from seoul.systems/microcosm-rs: xrpc_many2many

Added a new XRPC API endpoint to fetch joined record URIs, termed get_many_to_many (we talked about this briefly on Discord already). It is implemented and functions almost identical to the existing get_many_to_many_counts endpoint and handler. Some of its possible flaws like the two step lookup to verify a matching DID is indeed active are duplicated as well. On the plus side, this should make the PR pretty straightforward to review and make it easier to modify both endpoints later on when a more efficient way to validate the status of DIDs is possible.

If you have comments remarks etc. I am happy to work on some parts again.

Labels

None yet.

Participants 2
AT URI
at://did:plc:53wellrw53o7sw4zlpfenvuh/sh.tangled.repo.pull/3mbkyehqooh22
+1100 -20
Diff #6
+1
Cargo.lock
··· 1058 "axum", 1059 "axum-extra", 1060 "axum-metrics", 1061 "bincode 1.3.3", 1062 "clap", 1063 "ctrlc",
··· 1058 "axum", 1059 "axum-extra", 1060 "axum-metrics", 1061 + "base64 0.22.1", 1062 "bincode 1.3.3", 1063 "clap", 1064 "ctrlc",
+1
constellation/Cargo.toml
··· 10 axum = "0.8.1" 11 axum-extra = { version = "0.10.0", features = ["query", "typed-header"] } 12 axum-metrics = "0.2" 13 bincode = "1.3.3" 14 clap = { workspace = true } 15 ctrlc = "3.4.5"
··· 10 axum = "0.8.1" 11 axum-extra = { version = "0.10.0", features = ["query", "typed-header"] } 12 axum-metrics = "0.2" 13 + base64 = "0.22.1" 14 bincode = "1.3.3" 15 clap = { workspace = true } 16 ctrlc = "3.4.5"
+2 -2
constellation/src/lib.rs
··· 22 DeleteAccount(Did), 23 } 24 25 - #[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)] 26 pub struct Did(pub String); 27 28 impl<T: Into<String>> From<T> for Did { ··· 31 } 32 } 33 34 - #[derive(Debug, PartialEq, Serialize, Deserialize)] 35 pub struct RecordId { 36 pub did: Did, 37 pub collection: String,
··· 22 DeleteAccount(Did), 23 } 24 25 + #[derive(Debug, Hash, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] 26 pub struct Did(pub String); 27 28 impl<T: Into<String>> From<T> for Did { ··· 31 } 32 } 33 34 + #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, PartialOrd, Ord)] 35 pub struct RecordId { 36 pub did: Did, 37 pub collection: String,
+116
constellation/src/server/mod.rs
··· 114 }), 115 ) 116 .route( 117 "/xrpc/blue.microcosm.links.getBacklinks", 118 get({ 119 let store = store.clone(); ··· 661 GetLinkItemsResponse { 662 total: paged.total, 663 linking_records: paged.items, 664 cursor, 665 query: (*query).clone(), 666 },
··· 114 }), 115 ) 116 .route( 117 + "/xrpc/blue.microcosm.links.getManyToMany", 118 + get({ 119 + let store = store.clone(); 120 + move |accept, query| async { 121 + spawn_blocking(|| get_many_to_many(accept, query, store)) 122 + .await 123 + .map_err(to500)? 124 + } 125 + }), 126 + ) 127 + .route( 128 "/xrpc/blue.microcosm.links.getBacklinks", 129 get({ 130 let store = store.clone(); ··· 672 GetLinkItemsResponse { 673 total: paged.total, 674 linking_records: paged.items, 675 + cursor, 676 + query: (*query).clone(), 677 + }, 678 + )) 679 + } 680 + 681 + #[derive(Clone, Deserialize)] 682 + #[serde(rename_all = "camelCase")] 683 + struct GetManyToManyItemsQuery { 684 + subject: String, 685 + source: String, 686 + /// path to the secondary link in the linking record 687 + path_to_other: String, 688 + /// filter to linking records (join of the m2m) by these DIDs 689 + #[serde(default)] 690 + did: Vec<String>, 691 + /// filter to specific secondary records 692 + #[serde(default)] 693 + other_subject: Vec<String>, 694 + cursor: Option<OpaqueApiCursor>, 695 + #[serde(default = "get_default_cursor_limit")] 696 + limit: u64, 697 + } 698 + #[derive(Debug, Serialize, Clone)] 699 + struct ManyToManyItem { 700 + link: RecordId, 701 + subject: String, 702 + } 703 + #[derive(Template, Serialize)] 704 + #[template(path = "get-many-to-many.html.j2")] 705 + struct GetManyToManyItemsResponse { 706 + items: Vec<ManyToManyItem>, 707 + cursor: Option<OpaqueApiCursor>, 708 + #[serde(skip_serializing)] 709 + query: GetManyToManyItemsQuery, 710 + } 711 + fn get_many_to_many( 712 + accept: ExtractAccept, 713 + query: axum_extra::extract::Query<GetManyToManyItemsQuery>, // supports multiple param occurrences 714 + store: impl LinkReader, 715 + ) -> Result<impl IntoResponse, http::StatusCode> { 716 + let after = query 717 + .cursor 718 + .clone() 719 + .map(|oc| ApiKeyedCursor::try_from(oc).map_err(|_| http::StatusCode::BAD_REQUEST)) 720 + .transpose()? 721 + .map(|c| c.next); 722 + 723 + let limit = query.limit; 724 + if limit > DEFAULT_CURSOR_LIMIT_MAX { 725 + return Err(http::StatusCode::BAD_REQUEST); 726 + } 727 + 728 + let filter_dids: HashSet<Did> = HashSet::from_iter( 729 + query 730 + .did 731 + .iter() 732 + .map(|d| d.trim()) 733 + .filter(|d| !d.is_empty()) 734 + .map(|d| Did(d.to_string())), 735 + ); 736 + 737 + let filter_other_subjects: HashSet<String> = HashSet::from_iter( 738 + query 739 + .other_subject 740 + .iter() 741 + .map(|s| s.trim().to_string()) 742 + .filter(|s| !s.is_empty()), 743 + ); 744 + 745 + let Some((collection, path)) = query.source.split_once(':') else { 746 + return Err(http::StatusCode::BAD_REQUEST); 747 + }; 748 + let path = format!(".{path}"); 749 + 750 + let path_to_other = format!(".{}", query.path_to_other); 751 + 752 + let paged = store 753 + .get_many_to_many( 754 + &query.subject, 755 + collection, 756 + &path, 757 + &path_to_other, 758 + limit, 759 + after, 760 + &filter_dids, 761 + &filter_other_subjects, 762 + ) 763 + .map_err(|_| http::StatusCode::INTERNAL_SERVER_ERROR)?; 764 + 765 + let cursor = paged.next.map(|next| ApiKeyedCursor { next }.into()); 766 + 767 + let items: Vec<ManyToManyItem> = paged 768 + .items 769 + .into_iter() 770 + .map(|(record_id, subject)| ManyToManyItem { 771 + link: record_id, 772 + subject, 773 + }) 774 + .collect(); 775 + 776 + Ok(acceptable( 777 + accept, 778 + GetManyToManyItemsResponse { 779 + items, 780 cursor, 781 query: (*query).clone(), 782 },
+117 -3
constellation/src/storage/mem_store.rs
··· 2 LinkReader, LinkStorage, Order, PagedAppendingCollection, PagedOrderedCollection, StorageStats, 3 }; 4 use crate::{ActionableEvent, CountsByCount, Did, RecordId}; 5 - use anyhow::Result; 6 use links::CollectedLink; 7 use std::collections::{HashMap, HashSet}; 8 use std::sync::{Arc, Mutex}; 9 ··· 197 items = items 198 .into_iter() 199 .skip_while(|(t, _, _)| after.as_ref().map(|a| t <= a).unwrap_or(false)) 200 - .take(limit as usize) 201 .collect(); 202 - let next = if items.len() as u64 >= limit { 203 items.last().map(|(t, _, _)| t.clone()) 204 } else { 205 None ··· 232 .map(|(did, _)| did) 233 .collect::<HashSet<_>>() 234 .len() as u64) 235 } 236 237 fn get_links(
··· 2 LinkReader, LinkStorage, Order, PagedAppendingCollection, PagedOrderedCollection, StorageStats, 3 }; 4 use crate::{ActionableEvent, CountsByCount, Did, RecordId}; 5 + 6 + use anyhow::{anyhow, Result}; 7 + use base64::engine::general_purpose as b64; 8 + use base64::Engine as _; 9 use links::CollectedLink; 10 + 11 use std::collections::{HashMap, HashSet}; 12 use std::sync::{Arc, Mutex}; 13 ··· 201 items = items 202 .into_iter() 203 .skip_while(|(t, _, _)| after.as_ref().map(|a| t <= a).unwrap_or(false)) 204 + .take(limit as usize + 1) 205 .collect(); 206 + let next = if items.len() as u64 > limit { 207 + items.truncate(limit as usize); 208 items.last().map(|(t, _, _)| t.clone()) 209 } else { 210 None ··· 237 .map(|(did, _)| did) 238 .collect::<HashSet<_>>() 239 .len() as u64) 240 + } 241 + 242 + fn get_many_to_many( 243 + &self, 244 + target: &str, 245 + collection: &str, 246 + path: &str, 247 + path_to_other: &str, 248 + limit: u64, 249 + after: Option<String>, 250 + filter_dids: &HashSet<Did>, 251 + filter_targets: &HashSet<String>, 252 + ) -> Result<PagedOrderedCollection<(RecordId, String), String>> { 253 + // setup variables that we need later 254 + let path_to_other = RecordPath(path_to_other.to_string()); 255 + let filter_targets: HashSet<Target> = 256 + HashSet::from_iter(filter_targets.iter().map(|s| Target::new(s))); 257 + 258 + // extract parts form composite cursor 259 + let (backward_idx, forward_idx) = match after { 260 + Some(a) => { 261 + let after_str = String::from_utf8(b64::URL_SAFE.decode(a)?)?; 262 + let (b, f) = after_str 263 + .split_once(',') 264 + .ok_or_else(|| anyhow!("invalid cursor format"))?; 265 + ( 266 + (!b.is_empty()).then(|| b.parse::<u64>()).transpose()?, 267 + (!f.is_empty()).then(|| f.parse::<u64>()).transpose()?, 268 + ) 269 + } 270 + None => (None, None), 271 + }; 272 + 273 + let data = self.0.lock().unwrap(); 274 + let Some(sources) = data.targets.get(&Target::new(target)) else { 275 + return Ok(PagedOrderedCollection::empty()); 276 + }; 277 + let Some(linkers) = sources.get(&Source::new(collection, path)) else { 278 + return Ok(PagedOrderedCollection::empty()); 279 + }; 280 + 281 + let mut items: Vec<(usize, usize, RecordId, String)> = Vec::new(); 282 + 283 + // iterate backwards (who linked to the target?) 284 + for (linker_idx, (did, rkey)) in linkers 285 + .iter() 286 + .enumerate() 287 + .filter_map(|(i, opt)| opt.as_ref().map(|v| (i, v))) 288 + .skip_while(|(linker_idx, _)| { 289 + backward_idx.is_some_and(|idx| match forward_idx { 290 + Some(_) => *linker_idx < idx as usize, // inclusive: depend on link idx for skipping 291 + None => *linker_idx <= idx as usize, // exclusive: skip right here 292 + }) 293 + }) 294 + .filter(|(_, (did, _))| filter_dids.is_empty() || filter_dids.contains(&did)) 295 + { 296 + let Some(links) = data.links.get(&did).and_then(|m| { 297 + m.get(&RepoId { 298 + collection: collection.to_string(), 299 + rkey: rkey.clone(), 300 + }) 301 + }) else { 302 + continue; 303 + }; 304 + 305 + // iterate forward (which of these links point to the __other__ target?) 306 + for (link_idx, (_, fwd_target)) in links 307 + .iter() 308 + .enumerate() 309 + .filter(|(_, (p, t))| { 310 + *p == path_to_other && (filter_targets.is_empty() || filter_targets.contains(t)) 311 + }) 312 + .skip_while(|(link_idx, _)| { 313 + backward_idx.is_some_and(|bl_idx| { 314 + linker_idx == bl_idx as usize 315 + && forward_idx.is_some_and(|fwd_idx| *link_idx <= fwd_idx as usize) 316 + }) 317 + }) 318 + .take(limit as usize + 1 - items.len()) 319 + { 320 + items.push(( 321 + linker_idx, 322 + link_idx, 323 + RecordId { 324 + did: did.clone(), 325 + collection: collection.to_string(), 326 + rkey: rkey.0.clone(), 327 + }, 328 + fwd_target.0.clone(), 329 + )); 330 + } 331 + 332 + // page full - eject 333 + if items.len() > limit as usize { 334 + break; 335 + } 336 + } 337 + 338 + let next = if items.len() as u64 > limit { 339 + items.truncate(limit as usize); 340 + items 341 + .last() 342 + .map(|(l, f, _, _)| b64::URL_SAFE.encode(format!("{},{}", *l as u64, *f as u64))) 343 + } else { 344 + None 345 + }; 346 + 347 + let items = items.into_iter().map(|(_, _, rid, t)| (rid, t)).collect(); 348 + Ok(PagedOrderedCollection { items, next }) 349 } 350 351 fn get_links(
+461
constellation/src/storage/mod.rs
··· 135 fn get_all_record_counts(&self, _target: &str) 136 -> Result<HashMap<String, HashMap<String, u64>>>; 137 138 fn get_all_counts( 139 &self, 140 _target: &str, ··· 1669 items: vec![("b.com".to_string(), 2, 2),], 1670 next: None, 1671 } 1672 ); 1673 }); 1674 }
··· 135 fn get_all_record_counts(&self, _target: &str) 136 -> Result<HashMap<String, HashMap<String, u64>>>; 137 138 + fn get_many_to_many( 139 + &self, 140 + target: &str, 141 + collection: &str, 142 + path: &str, 143 + path_to_other: &str, 144 + limit: u64, 145 + after: Option<String>, 146 + filter_dids: &HashSet<Did>, 147 + filter_to_targets: &HashSet<String>, 148 + ) -> Result<PagedOrderedCollection<(RecordId, String), String>>; 149 + 150 fn get_all_counts( 151 &self, 152 _target: &str, ··· 1681 items: vec![("b.com".to_string(), 2, 2),], 1682 next: None, 1683 } 1684 + ); 1685 + 1686 + // Pagination edge cases: we have 2 grouped results (b.com and c.com) 1687 + 1688 + // Case 1: limit > items (limit=10, items=2) -> next should be None 1689 + let result = storage.get_many_to_many_counts( 1690 + "a.com", 1691 + "app.t.c", 1692 + ".abc.uri", 1693 + ".def.uri", 1694 + 10, 1695 + None, 1696 + &HashSet::new(), 1697 + &HashSet::new(), 1698 + )?; 1699 + assert_eq!(result.items.len(), 2); 1700 + assert_eq!(result.next, None, "next should be None when items < limit"); 1701 + 1702 + // Case 2: limit == items (limit=2, items=2) -> next should be None 1703 + let result = storage.get_many_to_many_counts( 1704 + "a.com", 1705 + "app.t.c", 1706 + ".abc.uri", 1707 + ".def.uri", 1708 + 2, 1709 + None, 1710 + &HashSet::new(), 1711 + &HashSet::new(), 1712 + )?; 1713 + assert_eq!(result.items.len(), 2); 1714 + assert_eq!( 1715 + result.next, None, 1716 + "next should be None when items == limit (no more pages)" 1717 + ); 1718 + 1719 + // Case 3: limit < items (limit=1, items=2) -> next should be Some 1720 + let result = storage.get_many_to_many_counts( 1721 + "a.com", 1722 + "app.t.c", 1723 + ".abc.uri", 1724 + ".def.uri", 1725 + 1, 1726 + None, 1727 + &HashSet::new(), 1728 + &HashSet::new(), 1729 + )?; 1730 + assert_eq!(result.items.len(), 1); 1731 + assert!( 1732 + result.next.is_some(), 1733 + "next should be Some when items > limit" 1734 + ); 1735 + 1736 + // Verify second page returns remaining item with no cursor 1737 + let result2 = storage.get_many_to_many_counts( 1738 + "a.com", 1739 + "app.t.c", 1740 + ".abc.uri", 1741 + ".def.uri", 1742 + 1, 1743 + result.next, 1744 + &HashSet::new(), 1745 + &HashSet::new(), 1746 + )?; 1747 + assert_eq!(result2.items.len(), 1); 1748 + assert_eq!(result2.next, None, "next should be None on final page"); 1749 + }); 1750 + 1751 + test_each_storage!(get_m2m_empty, |storage| { 1752 + assert_eq!( 1753 + storage.get_many_to_many( 1754 + "a.com", 1755 + "a.b.c", 1756 + ".d.e", 1757 + ".f.g", 1758 + 10, 1759 + None, 1760 + &HashSet::new(), 1761 + &HashSet::new(), 1762 + )?, 1763 + PagedOrderedCollection { 1764 + items: vec![], 1765 + next: None, 1766 + } 1767 + ); 1768 + }); 1769 + 1770 + test_each_storage!(get_m2m_single, |storage| { 1771 + // One record linking to a.com (backward), with two forward links at 1772 + // the same path_to_other (.def.uri) pointing to b.com and c.com. 1773 + // Both forward targets must appear in the output. 1774 + storage.push( 1775 + &ActionableEvent::CreateLinks { 1776 + record_id: RecordId { 1777 + did: "did:plc:asdf".into(), 1778 + collection: "app.t.c".into(), 1779 + rkey: "asdf".into(), 1780 + }, 1781 + links: vec![ 1782 + CollectedLink { 1783 + target: Link::Uri("a.com".into()), 1784 + path: ".abc.uri".into(), 1785 + }, 1786 + CollectedLink { 1787 + target: Link::Uri("b.com".into()), 1788 + path: ".def.uri".into(), 1789 + }, 1790 + CollectedLink { 1791 + target: Link::Uri("c.com".into()), 1792 + path: ".def.uri".into(), 1793 + }, 1794 + ], 1795 + }, 1796 + 0, 1797 + )?; 1798 + let result = storage.get_many_to_many( 1799 + "a.com", 1800 + "app.t.c", 1801 + ".abc.uri", 1802 + ".def.uri", 1803 + 10, 1804 + None, 1805 + &HashSet::new(), 1806 + &HashSet::new(), 1807 + )?; 1808 + assert_eq!( 1809 + result.items.len(), 1810 + 2, 1811 + "both forward links at path_to_other should be emitted" 1812 + ); 1813 + let mut targets: Vec<_> = result.items.iter().map(|(_, t)| t.as_str()).collect(); 1814 + targets.sort(); 1815 + assert_eq!(targets, vec!["b.com", "c.com"]); 1816 + assert!(result 1817 + .items 1818 + .iter() 1819 + .all(|(r, _)| r.did.0 == "did:plc:asdf" && r.rkey == "asdf")); 1820 + assert_eq!(result.next, None); 1821 + }); 1822 + 1823 + test_each_storage!(get_m2m_filters, |storage| { 1824 + storage.push( 1825 + &ActionableEvent::CreateLinks { 1826 + record_id: RecordId { 1827 + did: "did:plc:asdf".into(), 1828 + collection: "app.t.c".into(), 1829 + rkey: "asdf".into(), 1830 + }, 1831 + links: vec![ 1832 + CollectedLink { 1833 + target: Link::Uri("a.com".into()), 1834 + path: ".abc.uri".into(), 1835 + }, 1836 + CollectedLink { 1837 + target: Link::Uri("b.com".into()), 1838 + path: ".def.uri".into(), 1839 + }, 1840 + ], 1841 + }, 1842 + 0, 1843 + )?; 1844 + storage.push( 1845 + &ActionableEvent::CreateLinks { 1846 + record_id: RecordId { 1847 + did: "did:plc:asdf".into(), 1848 + collection: "app.t.c".into(), 1849 + rkey: "asdf2".into(), 1850 + }, 1851 + links: vec![ 1852 + CollectedLink { 1853 + target: Link::Uri("a.com".into()), 1854 + path: ".abc.uri".into(), 1855 + }, 1856 + CollectedLink { 1857 + target: Link::Uri("b.com".into()), 1858 + path: ".def.uri".into(), 1859 + }, 1860 + ], 1861 + }, 1862 + 1, 1863 + )?; 1864 + storage.push( 1865 + &ActionableEvent::CreateLinks { 1866 + record_id: RecordId { 1867 + did: "did:plc:fdsa".into(), 1868 + collection: "app.t.c".into(), 1869 + rkey: "fdsa".into(), 1870 + }, 1871 + links: vec![ 1872 + CollectedLink { 1873 + target: Link::Uri("a.com".into()), 1874 + path: ".abc.uri".into(), 1875 + }, 1876 + CollectedLink { 1877 + target: Link::Uri("c.com".into()), 1878 + path: ".def.uri".into(), 1879 + }, 1880 + ], 1881 + }, 1882 + 2, 1883 + )?; 1884 + storage.push( 1885 + &ActionableEvent::CreateLinks { 1886 + record_id: RecordId { 1887 + did: "did:plc:fdsa".into(), 1888 + collection: "app.t.c".into(), 1889 + rkey: "fdsa2".into(), 1890 + }, 1891 + links: vec![ 1892 + CollectedLink { 1893 + target: Link::Uri("a.com".into()), 1894 + path: ".abc.uri".into(), 1895 + }, 1896 + CollectedLink { 1897 + target: Link::Uri("c.com".into()), 1898 + path: ".def.uri".into(), 1899 + }, 1900 + ], 1901 + }, 1902 + 3, 1903 + )?; 1904 + 1905 + // Test without filters - should get all records as flat items 1906 + let result = storage.get_many_to_many( 1907 + "a.com", 1908 + "app.t.c", 1909 + ".abc.uri", 1910 + ".def.uri", 1911 + 10, 1912 + None, 1913 + &HashSet::new(), 1914 + &HashSet::new(), 1915 + )?; 1916 + assert_eq!(result.items.len(), 4); 1917 + assert_eq!(result.next, None); 1918 + // Check b.com items 1919 + let b_items: Vec<_> = result 1920 + .items 1921 + .iter() 1922 + .filter(|(_, subject)| subject == "b.com") 1923 + .collect(); 1924 + assert_eq!(b_items.len(), 2); 1925 + assert!(b_items 1926 + .iter() 1927 + .any(|(r, _)| r.did.0 == "did:plc:asdf" && r.rkey == "asdf")); 1928 + assert!(b_items 1929 + .iter() 1930 + .any(|(r, _)| r.did.0 == "did:plc:asdf" && r.rkey == "asdf2")); 1931 + // Check c.com items 1932 + let c_items: Vec<_> = result 1933 + .items 1934 + .iter() 1935 + .filter(|(_, subject)| subject == "c.com") 1936 + .collect(); 1937 + assert_eq!(c_items.len(), 2); 1938 + assert!(c_items 1939 + .iter() 1940 + .any(|(r, _)| r.did.0 == "did:plc:fdsa" && r.rkey == "fdsa")); 1941 + assert!(c_items 1942 + .iter() 1943 + .any(|(r, _)| r.did.0 == "did:plc:fdsa" && r.rkey == "fdsa2")); 1944 + 1945 + // Test with DID filter - should only get records from did:plc:fdsa 1946 + let result = storage.get_many_to_many( 1947 + "a.com", 1948 + "app.t.c", 1949 + ".abc.uri", 1950 + ".def.uri", 1951 + 10, 1952 + None, 1953 + &HashSet::from_iter([Did("did:plc:fdsa".to_string())]), 1954 + &HashSet::new(), 1955 + )?; 1956 + assert_eq!(result.items.len(), 2); 1957 + assert!(result.items.iter().all(|(_, subject)| subject == "c.com")); 1958 + assert!(result.items.iter().all(|(r, _)| r.did.0 == "did:plc:fdsa")); 1959 + 1960 + // Test with target filter - should only get records linking to b.com 1961 + let result = storage.get_many_to_many( 1962 + "a.com", 1963 + "app.t.c", 1964 + ".abc.uri", 1965 + ".def.uri", 1966 + 10, 1967 + None, 1968 + &HashSet::new(), 1969 + &HashSet::from_iter(["b.com".to_string()]), 1970 + )?; 1971 + assert_eq!(result.items.len(), 2); 1972 + assert!(result.items.iter().all(|(_, subject)| subject == "b.com")); 1973 + assert!(result.items.iter().all(|(r, _)| r.did.0 == "did:plc:asdf")); 1974 + 1975 + // Pagination edge cases: we have 4 flat items 1976 + 1977 + // Case 1: limit > items (limit=10, items=4) -> next should be None 1978 + let result = storage.get_many_to_many( 1979 + "a.com", 1980 + "app.t.c", 1981 + ".abc.uri", 1982 + ".def.uri", 1983 + 10, 1984 + None, 1985 + &HashSet::new(), 1986 + &HashSet::new(), 1987 + )?; 1988 + assert_eq!(result.items.len(), 4); 1989 + assert_eq!(result.next, None, "next should be None when items < limit"); 1990 + 1991 + // Case 2: limit == items (limit=4, items=4) -> next should be None 1992 + let result = storage.get_many_to_many( 1993 + "a.com", 1994 + "app.t.c", 1995 + ".abc.uri", 1996 + ".def.uri", 1997 + 4, 1998 + None, 1999 + &HashSet::new(), 2000 + &HashSet::new(), 2001 + )?; 2002 + assert_eq!(result.items.len(), 4); 2003 + assert_eq!( 2004 + result.next, None, 2005 + "next should be None when items == limit (no more pages)" 2006 + ); 2007 + 2008 + // Case 3: limit < items (limit=3, items=4) -> next should be Some 2009 + let result = storage.get_many_to_many( 2010 + "a.com", 2011 + "app.t.c", 2012 + ".abc.uri", 2013 + ".def.uri", 2014 + 3, 2015 + None, 2016 + &HashSet::new(), 2017 + &HashSet::new(), 2018 + )?; 2019 + assert_eq!(result.items.len(), 3); 2020 + assert!( 2021 + result.next.is_some(), 2022 + "next should be Some when items > limit" 2023 + ); 2024 + 2025 + // Verify second page returns remaining item with no cursor. 2026 + // This now works correctly because we use a composite cursor that includes 2027 + // (target, did, rkey), allowing pagination even when multiple records share 2028 + // the same target string. 2029 + let result2 = storage.get_many_to_many( 2030 + "a.com", 2031 + "app.t.c", 2032 + ".abc.uri", 2033 + ".def.uri", 2034 + 3, 2035 + result.next, 2036 + &HashSet::new(), 2037 + &HashSet::new(), 2038 + )?; 2039 + assert_eq!( 2040 + result2.items.len(), 2041 + 1, 2042 + "second page should have 1 remaining item" 2043 + ); 2044 + assert_eq!(result2.next, None, "next should be None on final page"); 2045 + 2046 + // Verify we got all 4 unique items across both pages (no duplicates, no gaps) 2047 + let mut all_rkeys: Vec<_> = result.items.iter().map(|(r, _)| r.rkey.clone()).collect(); 2048 + all_rkeys.extend(result2.items.iter().map(|(r, _)| r.rkey.clone())); 2049 + all_rkeys.sort(); 2050 + assert_eq!( 2051 + all_rkeys, 2052 + vec!["asdf", "asdf2", "fdsa", "fdsa2"], 2053 + "should have all 4 records across both pages" 2054 + ); 2055 + }); 2056 + 2057 + // Pagination that splits across forward links within a single backlinker. 2058 + // The cursor should correctly resume mid-record on the next page. 2059 + test_each_storage!(get_m2m_paginate_within_forward_links, |storage| { 2060 + // Record with 1 backward link and 3 forward links at the same path 2061 + storage.push( 2062 + &ActionableEvent::CreateLinks { 2063 + record_id: RecordId { 2064 + did: "did:plc:lister".into(), 2065 + collection: "app.t.c".into(), 2066 + rkey: "list1".into(), 2067 + }, 2068 + links: vec![ 2069 + CollectedLink { 2070 + target: Link::Uri("a.com".into()), 2071 + path: ".subject.uri".into(), 2072 + }, 2073 + CollectedLink { 2074 + target: Link::Uri("x.com".into()), 2075 + path: ".items[].uri".into(), 2076 + }, 2077 + CollectedLink { 2078 + target: Link::Uri("y.com".into()), 2079 + path: ".items[].uri".into(), 2080 + }, 2081 + CollectedLink { 2082 + target: Link::Uri("z.com".into()), 2083 + path: ".items[].uri".into(), 2084 + }, 2085 + ], 2086 + }, 2087 + 0, 2088 + )?; 2089 + 2090 + // Page 1: limit=2, should get 2 of the 3 forward links 2091 + let page1 = storage.get_many_to_many( 2092 + "a.com", 2093 + "app.t.c", 2094 + ".subject.uri", 2095 + ".items[].uri", 2096 + 2, 2097 + None, 2098 + &HashSet::new(), 2099 + &HashSet::new(), 2100 + )?; 2101 + assert_eq!(page1.items.len(), 2, "first page should have 2 items"); 2102 + assert!( 2103 + page1.next.is_some(), 2104 + "should have a next cursor for remaining item" 2105 + ); 2106 + 2107 + // Page 2: should get the remaining 1 forward link 2108 + let page2 = storage.get_many_to_many( 2109 + "a.com", 2110 + "app.t.c", 2111 + ".subject.uri", 2112 + ".items[].uri", 2113 + 2, 2114 + page1.next, 2115 + &HashSet::new(), 2116 + &HashSet::new(), 2117 + )?; 2118 + assert_eq!(page2.items.len(), 1, "second page should have 1 item"); 2119 + assert_eq!(page2.next, None, "no more pages"); 2120 + 2121 + // Verify all 3 targets appear across pages with no duplicates 2122 + let mut all_targets: Vec<_> = page1 2123 + .items 2124 + .iter() 2125 + .chain(page2.items.iter()) 2126 + .map(|(_, t)| t.clone()) 2127 + .collect(); 2128 + all_targets.sort(); 2129 + assert_eq!( 2130 + all_targets, 2131 + vec!["x.com", "y.com", "z.com"], 2132 + "all forward targets should appear exactly once across pages" 2133 ); 2134 }); 2135 }
+191 -15
constellation/src/storage/rocks_store.rs
··· 3 PagedOrderedCollection, StorageStats, 4 }; 5 use crate::{CountsByCount, Did, RecordId}; 6 - use anyhow::{bail, Result}; 7 use bincode::Options as BincodeOptions; 8 use links::CollectedLink; 9 use metrics::{counter, describe_counter, describe_histogram, histogram, Unit}; ··· 14 MultiThreaded, Options, PrefixRange, ReadOptions, WriteBatch, 15 }; 16 use serde::{Deserialize, Serialize}; 17 use std::collections::{BTreeMap, HashMap, HashSet}; 18 use std::io::Read; 19 use std::marker::PhantomData; ··· 24 }; 25 use std::thread; 26 use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; 27 - use tokio_util::sync::CancellationToken; 28 29 static DID_IDS_CF: &str = "did_ids"; 30 static TARGET_IDS_CF: &str = "target_ids"; ··· 1032 1033 // aand we can skip target ids that must be on future pages 1034 // (this check continues after the did-lookup, which we have to do) 1035 - let page_is_full = grouped_counts.len() as u64 >= limit; 1036 if page_is_full { 1037 - let current_max = grouped_counts.keys().next_back().unwrap(); // limit should be non-zero bleh 1038 if fwd_target > *current_max { 1039 continue; 1040 } ··· 1070 } 1071 } 1072 1073 let mut items: Vec<(String, u64, u64)> = Vec::with_capacity(grouped_counts.len()); 1074 for (target_id, (n, dids)) in &grouped_counts { 1075 let Some(target) = self ··· 1082 items.push((target.0 .0, *n, dids.len() as u64)); 1083 } 1084 1085 - let next = if grouped_counts.len() as u64 >= limit { 1086 - // yeah.... it's a number saved as a string......sorry 1087 - grouped_counts 1088 - .keys() 1089 - .next_back() 1090 - .map(|k| format!("{}", k.0)) 1091 - } else { 1092 - None 1093 - }; 1094 - 1095 Ok(PagedOrderedCollection { items, next }) 1096 } 1097 ··· 1120 } else { 1121 Ok(0) 1122 } 1123 } 1124 1125 fn get_links( ··· 1460 } 1461 1462 // target ids 1463 - #[derive(Debug, Clone, Serialize, Deserialize, PartialOrd, Ord, PartialEq, Eq, Hash)] 1464 struct TargetId(u64); // key 1465 1466 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
··· 3 PagedOrderedCollection, StorageStats, 4 }; 5 use crate::{CountsByCount, Did, RecordId}; 6 + 7 + use anyhow::{anyhow, bail, Result}; 8 + use base64::engine::general_purpose as b64; 9 + use base64::Engine as _; 10 use bincode::Options as BincodeOptions; 11 use links::CollectedLink; 12 use metrics::{counter, describe_counter, describe_histogram, histogram, Unit}; ··· 17 MultiThreaded, Options, PrefixRange, ReadOptions, WriteBatch, 18 }; 19 use serde::{Deserialize, Serialize}; 20 + use tokio_util::sync::CancellationToken; 21 + 22 use std::collections::{BTreeMap, HashMap, HashSet}; 23 use std::io::Read; 24 use std::marker::PhantomData; ··· 29 }; 30 use std::thread; 31 use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; 32 33 static DID_IDS_CF: &str = "did_ids"; 34 static TARGET_IDS_CF: &str = "target_ids"; ··· 1036 1037 // aand we can skip target ids that must be on future pages 1038 // (this check continues after the did-lookup, which we have to do) 1039 + let page_is_full = grouped_counts.len() as u64 > limit; 1040 if page_is_full { 1041 + let current_max = grouped_counts.keys().next_back().unwrap(); 1042 if fwd_target > *current_max { 1043 continue; 1044 } ··· 1074 } 1075 } 1076 1077 + // If we accumulated more than limit groups, there's another page. 1078 + // Pop the extra before building items so it doesn't appear in results. 1079 + let next = if grouped_counts.len() as u64 > limit { 1080 + grouped_counts.pop_last(); 1081 + grouped_counts 1082 + .keys() 1083 + .next_back() 1084 + .map(|k| format!("{}", k.0)) 1085 + } else { 1086 + None 1087 + }; 1088 + 1089 let mut items: Vec<(String, u64, u64)> = Vec::with_capacity(grouped_counts.len()); 1090 for (target_id, (n, dids)) in &grouped_counts { 1091 let Some(target) = self ··· 1098 items.push((target.0 .0, *n, dids.len() as u64)); 1099 } 1100 1101 Ok(PagedOrderedCollection { items, next }) 1102 } 1103 ··· 1126 } else { 1127 Ok(0) 1128 } 1129 + } 1130 + 1131 + fn get_many_to_many( 1132 + &self, 1133 + target: &str, 1134 + collection: &str, 1135 + path: &str, 1136 + path_to_other: &str, 1137 + limit: u64, 1138 + after: Option<String>, 1139 + filter_dids: &HashSet<Did>, 1140 + filter_to_targets: &HashSet<String>, 1141 + ) -> Result<PagedOrderedCollection<(RecordId, String), String>> { 1142 + // helper to resolve dids 1143 + let resolve_active_did = |did_id: &DidId| -> Option<Did> { 1144 + let Some(did) = self.did_id_table.get_val_from_id(&self.db, did_id.0).ok()? else { 1145 + eprintln!("failed to look up did from did_id {did_id:?}"); 1146 + return None; 1147 + }; 1148 + let Some(DidIdValue(_, active)) = self.did_id_table.get_id_val(&self.db, &did).ok()? 1149 + else { 1150 + eprintln!("failed to look up did_value from did_id {did_id:?}: {did:?}: data consistency bug?"); 1151 + return None; 1152 + }; 1153 + active.then_some(did) 1154 + }; 1155 + 1156 + // setup variables that we need later 1157 + let collection = Collection(collection.to_string()); 1158 + let path = RPath(path.to_string()); 1159 + 1160 + // extract parts form composite cursor 1161 + let (backward_idx, forward_idx) = match after { 1162 + Some(a) => { 1163 + eprintln!("a: {:#?}", a); 1164 + 1165 + let after_str = String::from_utf8(b64::URL_SAFE.decode(a)?)?; 1166 + 1167 + eprintln!("after_str: {:#?}", after_str); 1168 + let (b, f) = after_str 1169 + .split_once(',') 1170 + .ok_or_else(|| anyhow!("invalid cursor format"))?; 1171 + ( 1172 + (!b.is_empty()).then(|| b.parse::<u64>()).transpose()?, 1173 + (!f.is_empty()).then(|| f.parse::<u64>()).transpose()?, 1174 + ) 1175 + } 1176 + None => (None, None), 1177 + }; 1178 + 1179 + eprintln!("backward_idx: {:#?}", backward_idx); 1180 + eprintln!("forward_idx: {:#?}", forward_idx); 1181 + 1182 + // (__active__) did ids and filter targets 1183 + let filter_did_ids: HashMap<DidId, bool> = filter_dids 1184 + .iter() 1185 + .filter_map(|did| self.did_id_table.get_id_val(&self.db, did).transpose()) 1186 + .collect::<Result<Vec<DidIdValue>>>()? 1187 + .into_iter() 1188 + .map(|DidIdValue(id, active)| (id, active)) 1189 + .collect(); 1190 + let mut filter_to_target_ids: HashSet<TargetId> = HashSet::new(); 1191 + for t in filter_to_targets { 1192 + for (_, target_id) in self.iter_targets_for_target(&Target(t.to_string())) { 1193 + filter_to_target_ids.insert(target_id); 1194 + } 1195 + } 1196 + 1197 + let target_key = TargetKey(Target(target.to_string()), collection.clone(), path); 1198 + let Some(target_id) = self.target_id_table.get_id_val(&self.db, &target_key)? else { 1199 + eprintln!("Target not found for {target_key:?}"); 1200 + return Ok(PagedOrderedCollection::empty()); 1201 + }; 1202 + let linkers = self.get_target_linkers(&target_id)?; 1203 + 1204 + let mut items: Vec<(usize, usize, RecordId, String)> = Vec::new(); 1205 + 1206 + // iterate backwards (who linked to the target?) 1207 + for (linker_idx, (did_id, rkey)) in 1208 + linkers.0.iter().enumerate().skip_while(|(linker_idx, _)| { 1209 + backward_idx.is_some_and(|idx| match forward_idx { 1210 + Some(_) => *linker_idx < idx as usize, // inclusive: depend on link idx for skipping 1211 + None => *linker_idx <= idx as usize, // exclusive: skip right here 1212 + }) 1213 + }) 1214 + { 1215 + if did_id.is_empty() 1216 + || (!filter_did_ids.is_empty() && !filter_did_ids.contains_key(did_id)) 1217 + { 1218 + continue; 1219 + } 1220 + 1221 + let Some(links) = self.get_record_link_targets(&RecordLinkKey( 1222 + *did_id, 1223 + collection.clone(), 1224 + rkey.clone(), 1225 + ))? 1226 + else { 1227 + continue; 1228 + }; 1229 + 1230 + // iterate forward (which of these links point to the __other__ target?) 1231 + for (link_idx, RecordLinkTarget(_, fwd_target_id)) in links 1232 + .0 1233 + .into_iter() 1234 + .enumerate() 1235 + .filter(|(_, RecordLinkTarget(rpath, target_id))| { 1236 + eprintln!("rpath.0: {} vs. path_to_other: {path_to_other}", rpath.0); 1237 + rpath.0 == path_to_other 1238 + && (filter_to_target_ids.is_empty() 1239 + || filter_to_target_ids.contains(target_id)) 1240 + }) 1241 + .skip_while(|(link_idx, _)| { 1242 + backward_idx.is_some_and(|bl_idx| { 1243 + linker_idx == bl_idx as usize 1244 + && forward_idx.is_some_and(|fwd_idx| *link_idx <= fwd_idx as usize) 1245 + }) 1246 + }) 1247 + .take(limit as usize + 1 - items.len()) 1248 + { 1249 + // extract forward target did (target that links to the __other__ target) 1250 + let Some(did) = resolve_active_did(did_id) else { 1251 + continue; 1252 + }; 1253 + // resolve to target string 1254 + let Some(fwd_target_key) = self 1255 + .target_id_table 1256 + .get_val_from_id(&self.db, fwd_target_id.0) 1257 + .ok() 1258 + .flatten() 1259 + else { 1260 + continue; 1261 + }; 1262 + 1263 + // link to be added 1264 + let record_id = RecordId { 1265 + did, 1266 + collection: collection.0.clone(), 1267 + rkey: rkey.0.clone(), 1268 + }; 1269 + items.push((linker_idx, link_idx, record_id, fwd_target_key.0 .0)); 1270 + } 1271 + 1272 + // page full - eject 1273 + if items.len() > limit as usize { 1274 + break; 1275 + } 1276 + } 1277 + 1278 + // We collect up to limit + 1 fully-resolved items. If we got more than 1279 + // limit, there are more results beyond this page. We truncate to limit 1280 + // items (the actual page) and build a composite cursor from the last 1281 + // item on the page โ€” a base64-encoded pair of (backlink_vec_idx, 1282 + // forward_link_idx). On the next request, skip_while advances past 1283 + // this position: backlinks before backlink_vec_idx are skipped entirely, 1284 + // and at backlink_vec_idx itself, forward links at or before 1285 + // forward_link_idx are skipped. This correctly resumes mid-record when 1286 + // a single backlinker has multiple forward links at path_to_other. 1287 + let next = if items.len() as u64 > limit { 1288 + items.truncate(limit as usize); 1289 + items 1290 + .last() 1291 + .map(|(l, f, _, _)| b64::URL_SAFE.encode(format!("{},{}", *l as u64, *f as u64))) 1292 + } else { 1293 + None 1294 + }; 1295 + 1296 + let items = items.into_iter().map(|(_, _, rid, t)| (rid, t)).collect(); 1297 + 1298 + Ok(PagedOrderedCollection { items, next }) 1299 } 1300 1301 fn get_links( ··· 1636 } 1637 1638 // target ids 1639 + #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialOrd, Ord, PartialEq, Eq, Hash)] 1640 struct TargetId(u64); // key 1641 1642 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
+58
constellation/templates/get-many-to-many.html.j2
···
··· 1 + {% extends "base.html.j2" %} 2 + {% import "try-it-macros.html.j2" as try_it %} 3 + 4 + {% block title %}Many-to-Many Links{% endblock %} 5 + {% block description %}All {{ query.source }} records with many-to-many links to {{ query.subject }} joining through {{ query.path_to_other }}{% endblock %} 6 + 7 + {% block content %} 8 + 9 + {% call try_it::get_many_to_many(query.subject, query.source, query.path_to_other, query.did, query.other_subject, query.limit) %} 10 + 11 + <h2> 12 + Many-to-many links to <code>{{ query.subject }}</code> 13 + {% if let Some(browseable_uri) = query.subject|to_browseable %} 14 + <small style="font-weight: normal; font-size: 1rem"><a href="{{ browseable_uri }}">browse record</a></small> 15 + {% endif %} 16 + </h2> 17 + 18 + <p><strong>Many-to-many links</strong> from <code>{{ query.source }}</code> joining through <code>{{ query.path_to_other }}</code></p> 19 + 20 + <ul> 21 + <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> 22 + </ul> 23 + 24 + <h3>Many-to-many links, most recent first:</h3> 25 + 26 + {% for item in items %} 27 + <pre style="display: block; margin: 1em 2em" class="code"><strong>Subject</strong>: <a href="/links/all?target={{ item.subject|urlencode }}">{{ item.subject }}</a> 28 + <strong>DID</strong>: {{ item.link.did().0 }} 29 + <strong>Collection</strong>: {{ item.link.collection }} 30 + <strong>RKey</strong>: {{ item.link.rkey }} 31 + -> <a href="https://pdsls.dev/at://{{ item.link.did().0 }}/{{ item.link.collection }}/{{ item.link.rkey }}">browse record</a></pre> 32 + {% endfor %} 33 + 34 + {% if let Some(c) = cursor %} 35 + <form method="get" action="/xrpc/blue.microcosm.links.getManyToMany"> 36 + <input type="hidden" name="subject" value="{{ query.subject }}" /> 37 + <input type="hidden" name="source" value="{{ query.source }}" /> 38 + <input type="hidden" name="pathToOther" value="{{ query.path_to_other }}" /> 39 + {% for did in query.did %} 40 + <input type="hidden" name="did" value="{{ did }}" /> 41 + {% endfor %} 42 + {% for other in query.other_subject %} 43 + <input type="hidden" name="otherSubject" value="{{ other }}" /> 44 + {% endfor %} 45 + <input type="hidden" name="limit" value="{{ query.limit }}" /> 46 + <input type="hidden" name="cursor" value={{ c|json|safe }} /> 47 + <button type="submit">next page&hellip;</button> 48 + </form> 49 + {% else %} 50 + <button disabled><em>end of results</em></button> 51 + {% endif %} 52 + 53 + <details> 54 + <summary>Raw JSON response</summary> 55 + <pre class="code">{{ self|tojson }}</pre> 56 + </details> 57 + 58 + {% endblock %}
+19
constellation/templates/hello.html.j2
··· 83 ) %} 84 85 86 <h3 class="route"><code>GET /links</code></h3> 87 88 <p>A list of records linking to a target.</p>
··· 83 ) %} 84 85 86 + <h3 class="route"><code>GET /xrpc/blue.microcosm.links.getManyToMany</code></h3> 87 + 88 + <p>A list of many-to-many join records linking to a target and a secondary target.</p> 89 + 90 + <h4>Query parameters:</h4> 91 + 92 + <ul> 93 + <li><p><code>subject</code>: required, must url-encode. Example: <code>at://did:plc:vc7f4oafdgxsihk4cry2xpze/app.bsky.feed.post/3lgwdn7vd722r</code></p></li> 94 + <li><p><code>source</code>: required. Example: <code>app.bsky.feed.like:subject.uri</code></p></li> 95 + <li><p><code>pathToOther</code>: required. Path to the secondary link in the many-to-many record. Example: <code>otherThing.uri</code></p></li> 96 + <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> 97 + <li><p><code>otherSubject</code>: optional, filter secondary links to specific subjects. Include multiple times to filter by multiple subjects. Example: <code>at://did:plc:vc7f4oafdgxsihk4cry2xpze/app.bsky.feed.post/3lgwdn7vd722r</code></p></li> 98 + <li><p><code>limit</code>: optional. Default: <code>16</code>. Maximum: <code>100</code></p></li> 99 + </ul> 100 + 101 + <p style="margin-bottom: 0"><strong>Try it:</strong></p> 102 + {% call try_it::get_many_to_many("at://did:plc:a4pqq234yw7fqbddawjo7y35/app.bsky.feed.post/3m237ilwc372e", "app.bsky.feed.like:subject.uri", "reply.parent.uri", [""], [""], 16) %} 103 + 104 + 105 <h3 class="route"><code>GET /links</code></h3> 106 107 <p>A list of records linking to a target.</p>
+30
constellation/templates/try-it-macros.html.j2
··· 68 </script> 69 {% endmacro %} 70 71 {% macro links(target, collection, path, dids, limit) %} 72 <form method="get" action="/links"> 73 <pre class="code"><strong>GET</strong> /links
··· 68 </script> 69 {% endmacro %} 70 71 + {% macro get_many_to_many(subject, source, pathToOther, dids, otherSubjects, limit) %} 72 + <form method="get" action="/xrpc/blue.microcosm.links.getManyToMany"> 73 + <pre class="code"><strong>GET</strong> /xrpc/blue.microcosm.links.getManyToMany 74 + ?subject= <input type="text" name="subject" value="{{ subject }}" placeholder="at-uri, did, uri..." /> 75 + &source= <input type="text" name="source" value="{{ source }}" placeholder="app.bsky.feed.like:subject" /> 76 + &pathToOther= <input type="text" name="pathToOther" value="{{ pathToOther }}" placeholder="otherThing" /> 77 + {%- for did in dids %}{% if !did.is_empty() %} 78 + &did= <input type="text" name="did" value="{{ did }}" placeholder="did:plc:..." />{% endif %}{% endfor %} 79 + <span id="m2m-did-placeholder"></span> <button id="m2m-add-did">+ did filter</button> 80 + {%- for otherSubject in otherSubjects %}{% if !otherSubject.is_empty() %} 81 + &otherSubject= <input type="text" name="otherSubject" value="{{ otherSubject }}" placeholder="at-uri, did, uri..." />{% endif %}{% endfor %} 82 + <span id="m2m-other-placeholder"></span> <button id="m2m-add-other">+ other subject filter</button> 83 + &limit= <input type="number" name="limit" value="{{ limit }}" max="100" placeholder="100" /> <button type="submit">get many-to-many links</button></pre> 84 + </form> 85 + <script> 86 + const m2mAddDidButton = document.getElementById('m2m-add-did'); 87 + const m2mDidPlaceholder = document.getElementById('m2m-did-placeholder'); 88 + m2mAddDidButton.addEventListener('click', e => { 89 + e.preventDefault(); 90 + const i = document.createElement('input'); 91 + i.placeholder = 'did:plc:...'; 92 + i.name = "did" 93 + const p = m2mAddDidButton.parentNode; 94 + p.insertBefore(document.createTextNode('&did= '), m2mDidPlaceholder); 95 + p.insertBefore(i, m2mDidPlaceholder); 96 + p.insertBefore(document.createTextNode('\n '), m2mDidPlaceholder); 97 + }); 98 + </script> 99 + {% endmacro %} 100 + 101 {% macro links(target, collection, path, dids, limit) %} 102 <form method="get" action="/links"> 103 <pre class="code"><strong>GET</strong> /links
+104
lexicons/blue.microcosm/links/getManyToMany.json
···
··· 1 + { 2 + "lexicon": 1, 3 + "id": "blue.microcosm.links.getManyToMany", 4 + "defs": { 5 + "main": { 6 + "type": "query", 7 + "description": "Get records that link to a primary subject along with the secondary subjects they also reference", 8 + "parameters": { 9 + "type": "params", 10 + "required": ["subject", "source", "pathToOther"], 11 + "properties": { 12 + "subject": { 13 + "type": "string", 14 + "format": "uri", 15 + "description": "the primary target being linked to (at-uri, did, or uri)" 16 + }, 17 + "source": { 18 + "type": "string", 19 + "description": "collection and path specification for the primary link (e.g., 'app.bsky.feed.like:subject.uri')" 20 + }, 21 + "pathToOther": { 22 + "type": "string", 23 + "description": "path to the secondary link in the many-to-many record (e.g., 'otherThing.uri')" 24 + }, 25 + "did": { 26 + "type": "array", 27 + "description": "filter links to those from specific users", 28 + "items": { 29 + "type": "string", 30 + "format": "did" 31 + } 32 + }, 33 + "otherSubject": { 34 + "type": "array", 35 + "description": "filter secondary links to specific subjects", 36 + "items": { 37 + "type": "string" 38 + } 39 + }, 40 + "limit": { 41 + "type": "integer", 42 + "minimum": 1, 43 + "maximum": 100, 44 + "default": 16, 45 + "description": "number of results to return" 46 + } 47 + } 48 + }, 49 + "output": { 50 + "encoding": "application/json", 51 + "schema": { 52 + "type": "object", 53 + "required": ["items"], 54 + "properties": { 55 + "items": { 56 + "type": "array", 57 + "items": { 58 + "type": "ref", 59 + "ref": "#item" 60 + } 61 + }, 62 + "cursor": { 63 + "type": "string" 64 + } 65 + } 66 + } 67 + } 68 + }, 69 + "item": { 70 + "type": "object", 71 + "required": ["link", "subject"], 72 + "properties": { 73 + "link": { 74 + "type": "ref", 75 + "ref": "#linkRecord" 76 + }, 77 + "subject": { 78 + "type": "string" 79 + } 80 + } 81 + }, 82 + "linkRecord": { 83 + "type": "object", 84 + "required": ["did", "collection", "rkey"], 85 + "description": "A record identifier consisting of a DID, collection, and record key", 86 + "properties": { 87 + "did": { 88 + "type": "string", 89 + "format": "did", 90 + "description": "the DID of the linking record's repository" 91 + }, 92 + "collection": { 93 + "type": "string", 94 + "format": "nsid", 95 + "description": "the collection of the linking record" 96 + }, 97 + "rkey": { 98 + "type": "string", 99 + "format": "record-key" 100 + } 101 + } 102 + } 103 + } 104 + }

History

8 rounds 13 comments
sign up or login to add to the discussion
11 commits
expand
wip: m2m
Add tests for new get_many_to_many query handler
Fix get_m2m_empty test
Replace tuple with RecordsBySubject struct
Fix conflicts after rebasing on main
Use record_id/subject tuple as return type for get_many_to_many
Fix get_many_to_many pagination with composite cursor
Fix get_many_to_many_counts pagination with fetch N+1
wip
Fix rocks-store to match mem-store composite cursor
Address feedback from fig
expand 0 comments
pull request successfully merged
10 commits
expand
wip: m2m
Add tests for new get_many_to_many query handler
Fix get_m2m_empty test
Replace tuple with RecordsBySubject struct
Fix conflicts after rebasing on main
Use record_id/subject tuple as return type for get_many_to_many
Fix get_many_to_many pagination with composite cursor
Fix get_many_to_many_counts pagination with fetch N+1
wip
Fix rocks-store to match mem-store composite cursor
expand 0 comments
8 commits
expand
wip: m2m
Add tests for new get_many_to_many query handler
Fix get_m2m_empty test
Replace tuple with RecordsBySubject struct
Fix conflicts after rebasing on main
Use record_id/subject tuple as return type for get_many_to_many
Fix get_many_to_many pagination with composite cursor
Fix get_many_to_many_counts pagination with fetch N+1
expand 1 comment

Okay. I wrapped my head around the composite cursor you proposed and am working on refactoring both storage implementations towards that. I think I might re-submit another round tomorrow :)

6 commits
expand
wip: m2m
Add tests for new get_many_to_many query handler
Fix get_m2m_empty test
Replace tuple with RecordsBySubject struct
Fix conflicts after rebasing on main
Use record_id/subject tuple as return type for get_many_to_many
expand 3 comments

Found a bug in how we handle some of the pagination logic in cases where the number of items and the user selected limit are identical to very close too each other (already working on a fix)

thanks for the rebase! i tried to write things in the tiny text box but ended up needing to make a diagram: https://bsky.app/profile/did:plc:hdhoaan3xa3jiuq4fg4mefid/post/3mejuq44twc2t

key thing is that where the focus of getManyToManyCounts was the other subject (aggregation was against that, so grouping happened with it),

i think the focus of disagreggated many-to-many is on the linking records themselves

to me that takes me toward a few things

  • i don't think we should need to group the links by target (does the current code build up the full aggregation on every requested page? we should be able to avoid doing that)

  • i think the order of the response should actually be based on the linking record itself (since we have a row in the output), not the other subject, unlike with the aggregated/count version. this means you get eg. list items in order they were added instead of the order of the listed things being created. (i haven't fully wrapped my head around the grouping/ordering code here yet)

  • since any linking record can have a path_to_other with multiple links, i think a composite cursor could work here:

a 2-tuple of (backlink_vec_idx, forward_vec_idx).

for normal cases where the many-to-many record points to exactly one other subject, it would just be advancing backlink_vec_idx like normal backlinks

for cases where the many-to-many record actually has multiple foward links at the given path_to_other, the second part of the tuple would track progress through that list

i think that allows us to hold the necessary state between calls without needing to reconstruct too much in memory each time?

(also it's hard to write in this tiny tiny textbox and have a sense of whether what i'm saying makes sense)

Interesting approach! I have to think through this for a bit to be honest. Maybe I tried to follow the existing counts implementation too closely

Having said that, I added a new composite cursor to fix a couple of bugs that would arrive when hitting a couple of possible edge-cases in the pagination logic. This affects both the new get-many-to-many endpoint as well as the existing get-many-to-many-counts endpoint. As the changes are split over two distinct commits things should be straightforward to review.

Your assumption is still correct in the sense that we do indeed have to build up the aggregation again for every request. I have to double-check the get-backlinks endpoint to get a better sense of where you're going at.

Finally, I agree that the interface here doesn't necessarily make the whole thing easier to understand, unfortunately

6 commits
expand
wip: m2m
Add tests for new get_many_to_many query handler
Fix get_m2m_empty test
Replace tuple with RecordsBySubject struct
Fix conflicts after rebasing on main
Use record_id/subject tuple as return type for get_many_to_many
expand 2 comments

i think something got funky with a rebase or the way tangled is showing it -- some of my changes on main seem to be getting shown (reverted) in the diff.

i don't mind sorting it locally but will mostly get to it tomorrow, in case you want to see what's up before i do.

That's one on me, sorry! Rebased again on main and now everything seems fine

5 commits
expand
wip: m2m
Add tests for new get_many_to_many query handler
Fix get_m2m_empty test
Replace tuple with RecordsBySubject struct
Fix conflicts after rebasing on main
expand 5 comments

Rebased on main. As we discussed in the PR for the order query parameter, I didn't include this here as it's not a particular sensible fit.

i need to get into the code properly but my initial thought is that this endpoint should return a flat list of results, like

{
  "items": [
    {
      "link": { did, collection, rkey }, // the m2m link record
      "subject": "a.com"
    },
    {
      "link": { did, collection, rkey },
      "subject": "a.com"
    },
    {
      "link": { did, collection, rkey },
      "subject": "b.com"
    },
  ]
}

this will require a bit of tricks in the cursor to track pages across half-finished groups of links

(also this isn't an immediate change request, just getting it down for discussion!)

(and separately, i've also been wondering about moving more toward returning at-uris instead of broken-out did/collection/rkey objects. which isn't specifically about this PR, but if that happens then switching before releasing it is nice)

Hmm, I wonder how this would then work with the path_to_other parameter. Currently we have this nested grouping in order to show and disambiguate different relationships between different links.

For instance take the following query and it's results:

http://localhost:6789/xrpc/blue.microcosm.links.getManyToMany?subject=at://did:plc:2w45zyhuklwihpdc7oj3mi63/app.bsky.feed.post/3mdbbkuq6t32y&source=app.bsky.feed.post:reply.root.uri&pathToOther=reply.parent.uri&limit=16

This query asks: "Show me all posts in this thread, grouped by who they're responding to."

A flat list would just give us all the posts in the thread. The nested structure answers a richer question: who's talking to whom? Some posts are direct responses to the original article. Others are replies to other commenters, forming side conversations that branch off from the main thread.

The pathToOther grouping preserves that distinction. Without it, we'd lose the information about who's talking to whom.

{
  "linking_records": [
    {
      "subject": "at://did:plc:2w45zyhuklwihpdc7oj3mi63/app.bsky.feed.post/3mdbbkuq6t32y",
      "records": [
        {
          "did": "did:plc:lznqwrsbnyf6fdxohikqj6h3",
          "collection": "app.bsky.feed.post",
          "rkey": "3mdd27pja7s2y"
        },
        {
          "did": "did:plc:uffx77au6hoauuuumkbuvqdr",
          "collection": "app.bsky.feed.post",
          "rkey": "3mdd2tt5efc2a"
        },
        {
          "did": "did:plc:y7qyxzo7dns5m54dlq3youu3",
          "collection": "app.bsky.feed.post",
          "rkey": "3mdd2wtjxgc2d"
        },
        {
          "did": "did:plc:yaakslxyqydb76ybgkhrr4jk",
          "collection": "app.bsky.feed.post",
          "rkey": "3mdd35hyads22"
        },
        {
          "did": "did:plc:fia7w2kbnrdjwp6zvxywt7qv",
          "collection": "app.bsky.feed.post",
          "rkey": "3mdd37j3ldk2m"
        },
        {
          "did": "did:plc:xtecipifublblkomwau5x2ok",
          "collection": "app.bsky.feed.post",
          "rkey": "3mdd3dbtbz22n"
        },
        {
          "did": "did:plc:hl5lhiy2qr4nf5e4eefldvme",
          "collection": "app.bsky.feed.post",
          "rkey": "3mdd42hpw7c2e"
        },
        {
          "did": "did:plc:fgquypfh32pewivn3bcmzseb",
          "collection": "app.bsky.feed.post",
          "rkey": "3mdd46jteoc2m"
        }
      ]
    },
    {
      "subject": "at://did:plc:3rhjxwwui6wwfokh4at3q2dl/app.bsky.feed.post/3mdczc7c4gk2i",
      "records": [
        {
          "did": "did:plc:3rhjxwwui6wwfokh4at3q2dl",
          "collection": "app.bsky.feed.post",
          "rkey": "3mdczt7cwhk2i"
        }
      ]
    },
    {
      "subject": "at://did:plc:6buibzhkqr4vkqu75ezr2uv2/app.bsky.feed.post/3mdby25hbbk2v",
      "records": [
        {
          "did": "did:plc:fgeie2bmzlmx37iglj3xbzuj",
          "collection": "app.bsky.feed.post",
          "rkey": "3mdd26ulf4k2j"
        }
      ]
    },
    {
      "subject": "at://did:plc:lwgvv5oqh5stzb6dxa5d7z3n/app.bsky.feed.post/3mdcxqbkkfk2i",
      "records": [
        {
          "did": "did:plc:hl5lhiy2qr4nf5e4eefldvme",
          "collection": "app.bsky.feed.post",
          "rkey": "3mdd45u56sk2e"
        }
      ]
    }
  ],
  "cursor": null
}

Correct me if I'm somehow wrong here!

Regarding returning at-uris: I think this might be a nice idea as users might be able to split these up when they feel the need to any way and it feels conceptually more complete. But, it might be easier to do this in a different PR over all existing XRPC endpoints. This would allow us to add this new endpoint already while working on the updated return values in the meantime. I'd like to avoid doing too much distinct stuff in one PR. :)

at-uris: totally fair, holding off for a follow-up.

flat list: i might have messed it up in my example but i think what i meant is actually equivalent to the grouped version: flattened, with the subject ("group by") included with every item in the flatted list.

clients can collect the flat list and group on subject to get back to your structured example, if they want.

my motivations are probably part sql-brain, part flat-list-enjoyer, and part cursor-related. i'm trying to disregard the first two, and i'm curious about your thoughts about how to handle the cursor:

with a flat list it's easy (from the client perspective at least) -- just keep chasing the cursor for as much of the data as you need. (cursors can happen in the middle of a subject)

with nested results grouped by subject it's less obvious to me. correct me if i'm wrong (need another block of time to actually get into the code) but i think the grouped item sub-list is unbounded size in the proposed code here? so cursors are only limiting the number of groups.

if we go with the grouped nested response, i think maybe we'd want something like:

  • a cursor at the end for fetching more groups, and
  • a cursor for each group-list that lets you fetch more items from just that group-list.

(i think this kind of nested paging is pretty neat!)

Interesting. Now that you mention it I feel I kinda get where you're going at!

I think the whole cursor thing, albeit possible for sure, is kinda creating more unnecessary complexity so I'll probably go with your suggestion.

It seems easier to create custom groupings on their own for most users (having more freedom is always great) and I think from an ergonomic perspective the two cursors might create more friction.

4 commits
expand
wip: m2m
Add tests for new get_many_to_many query handler
Fix get_m2m_empty test
Replace tuple with RecordsBySubject struct
expand 1 comment

Added the missing lexicon entry for the new endpoint and changed the return type as well. Commented this wrongly at the other PR that I was working on. Sorry about that lol.

3 commits
expand
wip: m2m
Add tests for new get_many_to_many query handler
Fix get_m2m_empty test
expand 1 comment

I think the existing get_many_to_many_counts handler and the new get_many_to_many handler are similar enough that we might extract the bulk of their logic in a shared piece of logic. Maybe a method that takes the existing identical function parameters and a new additional callback parameter (that handles what we do with found matches, i.e. calculate counts or join URIs) might be one way to go for it.

I am not too sure yet though if this is indeed the right thing to do as the new shared implementation might be a bit complicated. But given the strong similarities between the two I think it's worth at least considering.