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
+289 -39
Interdiff #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, Clone)] 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,
constellation/src/server/mod.rs

This file has not been changed.

+41 -12
constellation/src/storage/mem_store.rs
··· 1 use super::{ 2 LinkReader, LinkStorage, Order, PagedAppendingCollection, PagedOrderedCollection, StorageStats, 3 }; 4 use crate::{ActionableEvent, CountsByCount, Did, RecordId}; 5 use anyhow::Result; 6 use links::CollectedLink; ··· 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 ··· 250 next: None, 251 }); 252 253 - // struct MemStorageData { 254 - // dids: HashMap<Did, bool>, 255 - // targets: HashMap<Target, HashMap<Source, Linkers>>, 256 - // links: HashMap<Did, HashMap<RepoId, Vec<(RecordPath, Target)>>>, 257 - // } 258 let data = self.0.lock().unwrap(); 259 260 let Some(sources) = data.targets.get(&Target::new(target)) else { ··· 315 }) 316 .collect::<Vec<_>>(); 317 318 - items.sort_by(|a: &(RecordId, String), b| a.1.cmp(&b.1)); 319 320 items = items 321 .into_iter() 322 - .skip_while(|item| after.as_ref().map(|a| &item.1 <= a).unwrap_or(false)) 323 - .take(limit as usize) 324 .collect(); 325 326 - let next = if items.len() as u64 >= limit { 327 - items.last().map(|item| item.1.clone()) 328 } else { 329 None 330 };
··· 1 use super::{ 2 LinkReader, LinkStorage, Order, PagedAppendingCollection, PagedOrderedCollection, StorageStats, 3 }; 4 + use crate::storage::{decode_m2m_cursor, encode_m2m_cursor}; 5 use crate::{ActionableEvent, CountsByCount, Did, RecordId}; 6 use anyhow::Result; 7 use links::CollectedLink; ··· 198 items = items 199 .into_iter() 200 .skip_while(|(t, _, _)| after.as_ref().map(|a| t <= a).unwrap_or(false)) 201 + .take(limit as usize + 1) 202 .collect(); 203 + let next = if items.len() as u64 > limit { 204 + items.truncate(limit as usize); 205 items.last().map(|(t, _, _)| t.clone()) 206 } else { 207 None ··· 252 next: None, 253 }); 254 255 let data = self.0.lock().unwrap(); 256 257 let Some(sources) = data.targets.get(&Target::new(target)) else { ··· 312 }) 313 .collect::<Vec<_>>(); 314 315 + // first try to sort by subject, then by did, collection and finally rkey 316 + items.sort_by(|a, b| { 317 + if a.1 == b.1 { 318 + a.0.cmp(&b.0) 319 + } else { 320 + a.1.cmp(&b.1) 321 + } 322 + }); 323 324 + // Parse cursor if provided (malformed cursor silently ignored) 325 + let after_cursor = after.and_then(|a| decode_m2m_cursor(&a).ok()); 326 + 327 + // Apply cursor: skip everything up to and including the cursor position 328 items = items 329 .into_iter() 330 + .skip_while(|item| { 331 + let Some((after_did, after_rkey, after_subject)) = &after_cursor else { 332 + return false; 333 + }; 334 + 335 + if &item.1 == after_subject { 336 + // Same subject โ€” compare by RecordId to find our position 337 + let cursor_id = RecordId { 338 + did: Did(after_did.clone()), 339 + collection: collection.to_string(), 340 + rkey: after_rkey.clone(), 341 + }; 342 + item.0.cmp(&cursor_id).is_le() 343 + } else { 344 + // Different subject โ€” compare subjects directly 345 + item.1.cmp(after_subject).is_le() 346 + } 347 + }) 348 + .take(limit as usize + 1) 349 .collect(); 350 351 + // Build the new cursor from last item, if needed 352 + let next = if items.len() as u64 > limit { 353 + items.truncate(limit as usize); 354 + items 355 + .last() 356 + .map(|item| encode_m2m_cursor(&item.0.did.0, &item.0.rkey, &item.1)) 357 } else { 358 None 359 };
+180 -1
constellation/src/storage/mod.rs
··· 6 pub mod mem_store; 7 pub use mem_store::MemStorage; 8 9 #[cfg(feature = "rocks")] 10 pub mod rocks_store; 11 #[cfg(feature = "rocks")] ··· 156 fn get_stats(&self) -> Result<StorageStats>; 157 } 158 159 #[cfg(test)] 160 161 ··· 1682 next: None, 1683 } 1684 ); 1685 }); 1686 1687 test_each_storage!(get_m2m_empty, |storage| { ··· 1753 ); 1754 }); 1755 1756 - test_each_storage!(get_m2m_no_filters, |storage| { 1757 storage.push( 1758 &ActionableEvent::CreateLinks { 1759 record_id: RecordId { ··· 1904 assert_eq!(result.items.len(), 2); 1905 assert!(result.items.iter().all(|(_, subject)| subject == "b.com")); 1906 assert!(result.items.iter().all(|(r, _)| r.did.0 == "did:plc:asdf")); 1907 }); 1908 }
··· 6 pub mod mem_store; 7 pub use mem_store::MemStorage; 8 9 + use anyhow::anyhow; 10 + 11 + use base64::engine::general_purpose as b64; 12 + use base64::Engine as _; 13 + 14 #[cfg(feature = "rocks")] 15 pub mod rocks_store; 16 #[cfg(feature = "rocks")] ··· 161 fn get_stats(&self) -> Result<StorageStats>; 162 } 163 164 + // Shared helpers 165 + 166 + /// Decode a base64 cursor into its component parts (did, rkey, subject). 167 + /// The subject is placed last because it may contain '|' characters. 168 + pub(crate) fn decode_m2m_cursor(cursor: &str) -> Result<(String, String, String)> { 169 + let decoded = String::from_utf8(b64::URL_SAFE.decode(cursor)?)?; 170 + let mut parts = decoded.splitn(3, '|').map(String::from); 171 + 172 + // Using .next() to pull each part out of the iterator in order. 173 + // This avoids collecting into a Vec just to index and clone back out. 174 + let did = parts 175 + .next() 176 + .ok_or_else(|| anyhow!("missing did in cursor"))?; 177 + let rkey = parts 178 + .next() 179 + .ok_or_else(|| anyhow!("missing rkey in cursor"))?; 180 + let subject = parts 181 + .next() 182 + .ok_or_else(|| anyhow!("missing subject in cursor"))?; 183 + 184 + Ok((did, rkey, subject)) 185 + } 186 + 187 + /// Encode cursor components into a base64 string. 188 + pub(crate) fn encode_m2m_cursor(did: &str, rkey: &str, subject: &str) -> String { 189 + let raw = format!("{did}|{rkey}|{subject}"); 190 + b64::URL_SAFE.encode(&raw) 191 + } 192 + 193 #[cfg(test)] 194 195 ··· 1716 next: None, 1717 } 1718 ); 1719 + 1720 + // Pagination edge cases: we have 2 grouped results (b.com and c.com) 1721 + 1722 + // Case 1: limit > items (limit=10, items=2) -> next should be None 1723 + let result = storage.get_many_to_many_counts( 1724 + "a.com", 1725 + "app.t.c", 1726 + ".abc.uri", 1727 + ".def.uri", 1728 + 10, 1729 + None, 1730 + &HashSet::new(), 1731 + &HashSet::new(), 1732 + )?; 1733 + assert_eq!(result.items.len(), 2); 1734 + assert_eq!(result.next, None, "next should be None when items < limit"); 1735 + 1736 + // Case 2: limit == items (limit=2, items=2) -> next should be None 1737 + let result = storage.get_many_to_many_counts( 1738 + "a.com", 1739 + "app.t.c", 1740 + ".abc.uri", 1741 + ".def.uri", 1742 + 2, 1743 + None, 1744 + &HashSet::new(), 1745 + &HashSet::new(), 1746 + )?; 1747 + assert_eq!(result.items.len(), 2); 1748 + assert_eq!( 1749 + result.next, None, 1750 + "next should be None when items == limit (no more pages)" 1751 + ); 1752 + 1753 + // Case 3: limit < items (limit=1, items=2) -> next should be Some 1754 + let result = storage.get_many_to_many_counts( 1755 + "a.com", 1756 + "app.t.c", 1757 + ".abc.uri", 1758 + ".def.uri", 1759 + 1, 1760 + None, 1761 + &HashSet::new(), 1762 + &HashSet::new(), 1763 + )?; 1764 + assert_eq!(result.items.len(), 1); 1765 + assert!( 1766 + result.next.is_some(), 1767 + "next should be Some when items > limit" 1768 + ); 1769 + 1770 + // Verify second page returns remaining item with no cursor 1771 + let result2 = storage.get_many_to_many_counts( 1772 + "a.com", 1773 + "app.t.c", 1774 + ".abc.uri", 1775 + ".def.uri", 1776 + 1, 1777 + result.next, 1778 + &HashSet::new(), 1779 + &HashSet::new(), 1780 + )?; 1781 + assert_eq!(result2.items.len(), 1); 1782 + assert_eq!(result2.next, None, "next should be None on final page"); 1783 }); 1784 1785 test_each_storage!(get_m2m_empty, |storage| { ··· 1851 ); 1852 }); 1853 1854 + test_each_storage!(get_m2m_filters, |storage| { 1855 storage.push( 1856 &ActionableEvent::CreateLinks { 1857 record_id: RecordId { ··· 2002 assert_eq!(result.items.len(), 2); 2003 assert!(result.items.iter().all(|(_, subject)| subject == "b.com")); 2004 assert!(result.items.iter().all(|(r, _)| r.did.0 == "did:plc:asdf")); 2005 + 2006 + // Pagination edge cases: we have 4 flat items 2007 + 2008 + // Case 1: limit > items (limit=10, items=4) -> next should be None 2009 + let result = storage.get_many_to_many( 2010 + "a.com", 2011 + "app.t.c", 2012 + ".abc.uri", 2013 + ".def.uri", 2014 + 10, 2015 + None, 2016 + &HashSet::new(), 2017 + &HashSet::new(), 2018 + )?; 2019 + assert_eq!(result.items.len(), 4); 2020 + assert_eq!(result.next, None, "next should be None when items < limit"); 2021 + 2022 + // Case 2: limit == items (limit=4, items=4) -> next should be None 2023 + let result = storage.get_many_to_many( 2024 + "a.com", 2025 + "app.t.c", 2026 + ".abc.uri", 2027 + ".def.uri", 2028 + 4, 2029 + None, 2030 + &HashSet::new(), 2031 + &HashSet::new(), 2032 + )?; 2033 + assert_eq!(result.items.len(), 4); 2034 + assert_eq!( 2035 + result.next, None, 2036 + "next should be None when items == limit (no more pages)" 2037 + ); 2038 + 2039 + // Case 3: limit < items (limit=3, items=4) -> next should be Some 2040 + let result = storage.get_many_to_many( 2041 + "a.com", 2042 + "app.t.c", 2043 + ".abc.uri", 2044 + ".def.uri", 2045 + 3, 2046 + None, 2047 + &HashSet::new(), 2048 + &HashSet::new(), 2049 + )?; 2050 + assert_eq!(result.items.len(), 3); 2051 + assert!( 2052 + result.next.is_some(), 2053 + "next should be Some when items > limit" 2054 + ); 2055 + 2056 + // Verify second page returns remaining item with no cursor. 2057 + // This now works correctly because we use a composite cursor that includes 2058 + // (target, did, rkey), allowing pagination even when multiple records share 2059 + // the same target string. 2060 + let result2 = storage.get_many_to_many( 2061 + "a.com", 2062 + "app.t.c", 2063 + ".abc.uri", 2064 + ".def.uri", 2065 + 3, 2066 + result.next, 2067 + &HashSet::new(), 2068 + &HashSet::new(), 2069 + )?; 2070 + assert_eq!( 2071 + result2.items.len(), 2072 + 1, 2073 + "second page should have 1 remaining item" 2074 + ); 2075 + assert_eq!(result2.next, None, "next should be None on final page"); 2076 + 2077 + // Verify we got all 4 unique items across both pages (no duplicates, no gaps) 2078 + let mut all_rkeys: Vec<_> = result.items.iter().map(|(r, _)| r.rkey.clone()).collect(); 2079 + all_rkeys.extend(result2.items.iter().map(|(r, _)| r.rkey.clone())); 2080 + all_rkeys.sort(); 2081 + assert_eq!( 2082 + all_rkeys, 2083 + vec!["asdf", "asdf2", "fdsa", "fdsa2"], 2084 + "should have all 4 records across both pages" 2085 + ); 2086 }); 2087 }
+64 -24
constellation/src/storage/rocks_store.rs
··· 2 ActionableEvent, LinkReader, LinkStorage, Order, PagedAppendingCollection, 3 PagedOrderedCollection, StorageStats, 4 }; 5 use crate::{CountsByCount, Did, RecordId}; 6 use anyhow::{bail, Result}; 7 use bincode::Options as BincodeOptions; ··· 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 ··· 1138 1139 let target_key = TargetKey(Target(target.to_string()), collection.clone(), path); 1140 1141 - let after = after.map(|s| s.parse::<u64>().map(TargetId)).transpose()?; 1142 1143 let Some(target_id) = self.target_id_table.get_id_val(&self.db, &target_key)? else { 1144 eprintln!("Target not found for {target_key:?}"); ··· 1212 continue; 1213 }; 1214 1215 - // pagination logic mirrors what is currently done in get_many_to_many_counts 1216 - if after.as_ref().map(|a| fwd_target <= *a).unwrap_or(false) { 1217 - continue; 1218 - } 1219 let page_is_full = grouped_links.len() as u64 >= limit; 1220 if page_is_full { 1221 let current_max = grouped_links.keys().next_back().unwrap(); ··· 1224 } 1225 } 1226 1227 // pagination, continued 1228 let mut should_evict = false; 1229 let entry = grouped_links.entry(fwd_target.clone()).or_insert_with(|| { 1230 should_evict = page_is_full; 1231 Vec::default() 1232 }); 1233 - entry.push(RecordId { 1234 - did, 1235 - collection: collection.0.clone(), 1236 - rkey: rkey.0, 1237 - }); 1238 1239 if should_evict { 1240 grouped_links.pop_last(); ··· 1258 .for_each(|r| items.push((r.clone(), target_string.clone()))); 1259 } 1260 1261 - let next = if grouped_links.len() as u64 >= limit { 1262 - grouped_links.keys().next_back().map(|k| format!("{}", k.0)) 1263 } else { 1264 None 1265 };
··· 2 ActionableEvent, LinkReader, LinkStorage, Order, PagedAppendingCollection, 3 PagedOrderedCollection, StorageStats, 4 }; 5 + use crate::storage::{decode_m2m_cursor, encode_m2m_cursor}; 6 use crate::{CountsByCount, Did, RecordId}; 7 use anyhow::{bail, Result}; 8 use bincode::Options as BincodeOptions; ··· 1033 1034 // aand we can skip target ids that must be on future pages 1035 // (this check continues after the did-lookup, which we have to do) 1036 + let page_is_full = grouped_counts.len() as u64 > limit; 1037 if page_is_full { 1038 + let current_max = grouped_counts.keys().next_back().unwrap(); 1039 if fwd_target > *current_max { 1040 continue; 1041 } ··· 1071 } 1072 } 1073 1074 + // If we accumulated more than limit groups, there's another page. 1075 + // Pop the extra before building items so it doesn't appear in results. 1076 + let next = if grouped_counts.len() as u64 > limit { 1077 + grouped_counts.pop_last(); 1078 + grouped_counts 1079 + .keys() 1080 + .next_back() 1081 + .map(|k| format!("{}", k.0)) 1082 + } else { 1083 + None 1084 + }; 1085 + 1086 let mut items: Vec<(String, u64, u64)> = Vec::with_capacity(grouped_counts.len()); 1087 for (target_id, (n, dids)) in &grouped_counts { 1088 let Some(target) = self ··· 1095 items.push((target.0 .0, *n, dids.len() as u64)); 1096 } 1097 1098 Ok(PagedOrderedCollection { items, next }) 1099 } 1100 ··· 1141 1142 let target_key = TargetKey(Target(target.to_string()), collection.clone(), path); 1143 1144 + // Parse cursor if provided (malformed cursor silently ignored) 1145 + let after_cursor = after.and_then(|a| decode_m2m_cursor(&a).ok()); 1146 1147 let Some(target_id) = self.target_id_table.get_id_val(&self.db, &target_key)? else { 1148 eprintln!("Target not found for {target_key:?}"); ··· 1216 continue; 1217 }; 1218 1219 let page_is_full = grouped_links.len() as u64 >= limit; 1220 if page_is_full { 1221 let current_max = grouped_links.keys().next_back().unwrap(); ··· 1224 } 1225 } 1226 1227 + // link to be added 1228 + let record_id = RecordId { 1229 + did, 1230 + collection: collection.0.clone(), 1231 + rkey: rkey.0, 1232 + }; 1233 + 1234 + // pagination: 1235 + if after_cursor.is_some() { 1236 + // extract composite-cursor parts 1237 + let Some((after_did, after_rkey, after_subject)) = &after_cursor else { 1238 + continue; 1239 + }; 1240 + 1241 + let Some(fwd_target_key) = self 1242 + .target_id_table 1243 + .get_val_from_id(&self.db, fwd_target.0)? 1244 + else { 1245 + eprintln!("failed to look up target from target_id {fwd_target:?}"); 1246 + continue; 1247 + }; 1248 + 1249 + // first try and compare by subject only 1250 + if &fwd_target_key.0 .0 != after_subject 1251 + && fwd_target_key.0 .0.cmp(after_subject).is_le() 1252 + { 1253 + continue; 1254 + } 1255 + 1256 + // then, if needed, we compare by record id 1257 + let cursor_id = RecordId { 1258 + did: Did(after_did.clone()), 1259 + collection: collection.0.clone(), 1260 + rkey: after_rkey.clone(), 1261 + }; 1262 + if record_id.cmp(&cursor_id).is_le() { 1263 + continue; 1264 + } 1265 + } 1266 + 1267 // pagination, continued 1268 let mut should_evict = false; 1269 let entry = grouped_links.entry(fwd_target.clone()).or_insert_with(|| { 1270 should_evict = page_is_full; 1271 Vec::default() 1272 }); 1273 + entry.push(record_id); 1274 1275 if should_evict { 1276 grouped_links.pop_last(); ··· 1294 .for_each(|r| items.push((r.clone(), target_string.clone()))); 1295 } 1296 1297 + // Build new cursor from last the item, if needed 1298 + let next = if items.len() as u64 > limit { 1299 + items.truncate(limit as usize); 1300 + items 1301 + .last() 1302 + .map(|item| encode_m2m_cursor(&item.0.did.0, &item.0.rkey, &item.1)) 1303 } else { 1304 None 1305 };
constellation/templates/get-many-to-many.html.j2

This file has not been changed.

constellation/templates/hello.html.j2

This file has not been changed.

constellation/templates/try-it-macros.html.j2

This file has not been changed.

lexicons/blue.microcosm/links/getManyToMany.json

This file has not been changed.

+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"

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.