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
+805 -1
Diff #4
+1 -1
constellation/src/lib.rs
··· 31 } 32 } 33 34 - #[derive(Debug, PartialEq, Serialize, Deserialize)] 35 pub struct RecordId { 36 pub did: Did, 37 pub collection: String,
··· 31 } 32 } 33 34 + #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] 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 },
+98
constellation/src/storage/mem_store.rs
··· 234 .len() as u64) 235 } 236 237 fn get_links( 238 &self, 239 target: &str,
··· 234 .len() as u64) 235 } 236 237 + fn get_many_to_many( 238 + &self, 239 + target: &str, 240 + collection: &str, 241 + path: &str, 242 + path_to_other: &str, 243 + limit: u64, 244 + after: Option<String>, 245 + filter_dids: &HashSet<Did>, 246 + filter_to_targets: &HashSet<String>, 247 + ) -> Result<PagedOrderedCollection<(RecordId, String), String>> { 248 + let empty_res = Ok(PagedOrderedCollection { 249 + items: Vec::new(), 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 { 261 + return empty_res; 262 + }; 263 + let Some(linkers) = sources.get(&Source::new(collection, path)) else { 264 + return empty_res; 265 + }; 266 + let path_to_other = RecordPath::new(path_to_other); 267 + 268 + // Convert filter_to_targets to Target objects for comparison 269 + let filter_to_target_objs: HashSet<Target> = 270 + HashSet::from_iter(filter_to_targets.iter().map(|s| Target::new(s))); 271 + 272 + let mut grouped_links: HashMap<Target, Vec<RecordId>> = HashMap::new(); 273 + for (did, rkey) in linkers.iter().flatten().cloned() { 274 + // Filter by DID if filter is provided 275 + if !filter_dids.is_empty() && !filter_dids.contains(&did) { 276 + continue; 277 + } 278 + if let Some(fwd_target) = data 279 + .links 280 + .get(&did) 281 + .unwrap_or(&HashMap::new()) 282 + .get(&RepoId { 283 + collection: collection.to_string(), 284 + rkey: rkey.clone(), 285 + }) 286 + .unwrap_or(&Vec::new()) 287 + .iter() 288 + .find_map(|(path, target)| { 289 + if *path == path_to_other 290 + && (filter_to_target_objs.is_empty() 291 + || filter_to_target_objs.contains(target)) 292 + { 293 + Some(target) 294 + } else { 295 + None 296 + } 297 + }) 298 + { 299 + let record_ids = grouped_links.entry(fwd_target.clone()).or_default(); 300 + record_ids.push(RecordId { 301 + did, 302 + collection: collection.to_string(), 303 + rkey: rkey.0, 304 + }); 305 + } 306 + } 307 + 308 + let mut items = grouped_links 309 + .into_iter() 310 + .flat_map(|(target, records)| { 311 + records 312 + .iter() 313 + .map(move |r| (r.clone(), target.0.clone())) 314 + .collect::<Vec<_>>() 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 + }; 331 + 332 + Ok(PagedOrderedCollection { items, next }) 333 + } 334 + 335 fn get_links( 336 &self, 337 target: &str,
+234
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, ··· 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, ··· 1682 next: None, 1683 } 1684 ); 1685 + }); 1686 + 1687 + test_each_storage!(get_m2m_empty, |storage| { 1688 + assert_eq!( 1689 + storage.get_many_to_many( 1690 + "a.com", 1691 + "a.b.c", 1692 + ".d.e", 1693 + ".f.g", 1694 + 10, 1695 + None, 1696 + &HashSet::new(), 1697 + &HashSet::new(), 1698 + )?, 1699 + PagedOrderedCollection { 1700 + items: vec![], 1701 + next: None, 1702 + } 1703 + ); 1704 + }); 1705 + 1706 + test_each_storage!(get_m2m_single, |storage| { 1707 + storage.push( 1708 + &ActionableEvent::CreateLinks { 1709 + record_id: RecordId { 1710 + did: "did:plc:asdf".into(), 1711 + collection: "app.t.c".into(), 1712 + rkey: "asdf".into(), 1713 + }, 1714 + links: vec![ 1715 + CollectedLink { 1716 + target: Link::Uri("a.com".into()), 1717 + path: ".abc.uri".into(), 1718 + }, 1719 + CollectedLink { 1720 + target: Link::Uri("b.com".into()), 1721 + path: ".def.uri".into(), 1722 + }, 1723 + CollectedLink { 1724 + target: Link::Uri("b.com".into()), 1725 + path: ".ghi.uri".into(), 1726 + }, 1727 + ], 1728 + }, 1729 + 0, 1730 + )?; 1731 + assert_eq!( 1732 + storage.get_many_to_many( 1733 + "a.com", 1734 + "app.t.c", 1735 + ".abc.uri", 1736 + ".def.uri", 1737 + 10, 1738 + None, 1739 + &HashSet::new(), 1740 + &HashSet::new(), 1741 + )?, 1742 + PagedOrderedCollection { 1743 + items: vec![( 1744 + RecordId { 1745 + did: "did:plc:asdf".into(), 1746 + collection: "app.t.c".into(), 1747 + rkey: "asdf".into(), 1748 + }, 1749 + "b.com".to_string(), 1750 + )], 1751 + next: None, 1752 + } 1753 + ); 1754 + }); 1755 + 1756 + test_each_storage!(get_m2m_no_filters, |storage| { 1757 + storage.push( 1758 + &ActionableEvent::CreateLinks { 1759 + record_id: RecordId { 1760 + did: "did:plc:asdf".into(), 1761 + collection: "app.t.c".into(), 1762 + rkey: "asdf".into(), 1763 + }, 1764 + links: vec![ 1765 + CollectedLink { 1766 + target: Link::Uri("a.com".into()), 1767 + path: ".abc.uri".into(), 1768 + }, 1769 + CollectedLink { 1770 + target: Link::Uri("b.com".into()), 1771 + path: ".def.uri".into(), 1772 + }, 1773 + ], 1774 + }, 1775 + 0, 1776 + )?; 1777 + storage.push( 1778 + &ActionableEvent::CreateLinks { 1779 + record_id: RecordId { 1780 + did: "did:plc:asdf".into(), 1781 + collection: "app.t.c".into(), 1782 + rkey: "asdf2".into(), 1783 + }, 1784 + links: vec![ 1785 + CollectedLink { 1786 + target: Link::Uri("a.com".into()), 1787 + path: ".abc.uri".into(), 1788 + }, 1789 + CollectedLink { 1790 + target: Link::Uri("b.com".into()), 1791 + path: ".def.uri".into(), 1792 + }, 1793 + ], 1794 + }, 1795 + 1, 1796 + )?; 1797 + storage.push( 1798 + &ActionableEvent::CreateLinks { 1799 + record_id: RecordId { 1800 + did: "did:plc:fdsa".into(), 1801 + collection: "app.t.c".into(), 1802 + rkey: "fdsa".into(), 1803 + }, 1804 + links: vec![ 1805 + CollectedLink { 1806 + target: Link::Uri("a.com".into()), 1807 + path: ".abc.uri".into(), 1808 + }, 1809 + CollectedLink { 1810 + target: Link::Uri("c.com".into()), 1811 + path: ".def.uri".into(), 1812 + }, 1813 + ], 1814 + }, 1815 + 2, 1816 + )?; 1817 + storage.push( 1818 + &ActionableEvent::CreateLinks { 1819 + record_id: RecordId { 1820 + did: "did:plc:fdsa".into(), 1821 + collection: "app.t.c".into(), 1822 + rkey: "fdsa2".into(), 1823 + }, 1824 + links: vec![ 1825 + CollectedLink { 1826 + target: Link::Uri("a.com".into()), 1827 + path: ".abc.uri".into(), 1828 + }, 1829 + CollectedLink { 1830 + target: Link::Uri("c.com".into()), 1831 + path: ".def.uri".into(), 1832 + }, 1833 + ], 1834 + }, 1835 + 3, 1836 + )?; 1837 + 1838 + // Test without filters - should get all records as flat items 1839 + let result = storage.get_many_to_many( 1840 + "a.com", 1841 + "app.t.c", 1842 + ".abc.uri", 1843 + ".def.uri", 1844 + 10, 1845 + None, 1846 + &HashSet::new(), 1847 + &HashSet::new(), 1848 + )?; 1849 + assert_eq!(result.items.len(), 4); 1850 + assert_eq!(result.next, None); 1851 + // Check b.com items 1852 + let b_items: Vec<_> = result 1853 + .items 1854 + .iter() 1855 + .filter(|(_, subject)| subject == "b.com") 1856 + .collect(); 1857 + assert_eq!(b_items.len(), 2); 1858 + assert!(b_items 1859 + .iter() 1860 + .any(|(r, _)| r.did.0 == "did:plc:asdf" && r.rkey == "asdf")); 1861 + assert!(b_items 1862 + .iter() 1863 + .any(|(r, _)| r.did.0 == "did:plc:asdf" && r.rkey == "asdf2")); 1864 + // Check c.com items 1865 + let c_items: Vec<_> = result 1866 + .items 1867 + .iter() 1868 + .filter(|(_, subject)| subject == "c.com") 1869 + .collect(); 1870 + assert_eq!(c_items.len(), 2); 1871 + assert!(c_items 1872 + .iter() 1873 + .any(|(r, _)| r.did.0 == "did:plc:fdsa" && r.rkey == "fdsa")); 1874 + assert!(c_items 1875 + .iter() 1876 + .any(|(r, _)| r.did.0 == "did:plc:fdsa" && r.rkey == "fdsa2")); 1877 + 1878 + // Test with DID filter - should only get records from did:plc:fdsa 1879 + let result = storage.get_many_to_many( 1880 + "a.com", 1881 + "app.t.c", 1882 + ".abc.uri", 1883 + ".def.uri", 1884 + 10, 1885 + None, 1886 + &HashSet::from_iter([Did("did:plc:fdsa".to_string())]), 1887 + &HashSet::new(), 1888 + )?; 1889 + assert_eq!(result.items.len(), 2); 1890 + assert!(result.items.iter().all(|(_, subject)| subject == "c.com")); 1891 + assert!(result.items.iter().all(|(r, _)| r.did.0 == "did:plc:fdsa")); 1892 + 1893 + // Test with target filter - should only get records linking to b.com 1894 + let result = storage.get_many_to_many( 1895 + "a.com", 1896 + "app.t.c", 1897 + ".abc.uri", 1898 + ".def.uri", 1899 + 10, 1900 + None, 1901 + &HashSet::new(), 1902 + &HashSet::from_iter(["b.com".to_string()]), 1903 + )?; 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 }
+145
constellation/src/storage/rocks_store.rs
··· 1122 } 1123 } 1124 1125 fn get_links( 1126 &self, 1127 target: &str,
··· 1122 } 1123 } 1124 1125 + fn get_many_to_many( 1126 + &self, 1127 + target: &str, 1128 + collection: &str, 1129 + path: &str, 1130 + path_to_other: &str, 1131 + limit: u64, 1132 + after: Option<String>, 1133 + filter_dids: &HashSet<Did>, 1134 + filter_to_targets: &HashSet<String>, 1135 + ) -> Result<PagedOrderedCollection<(RecordId, String), String>> { 1136 + let collection = Collection(collection.to_string()); 1137 + let path = RPath(path.to_string()); 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:?}"); 1145 + return Ok(PagedOrderedCollection::empty()); 1146 + }; 1147 + 1148 + let filter_did_ids: HashMap<DidId, bool> = filter_dids 1149 + .iter() 1150 + .filter_map(|did| self.did_id_table.get_id_val(&self.db, did).transpose()) 1151 + .collect::<Result<Vec<DidIdValue>>>()? 1152 + .into_iter() 1153 + .map(|DidIdValue(id, active)| (id, active)) 1154 + .collect(); 1155 + 1156 + let mut filter_to_target_ids: HashSet<TargetId> = HashSet::new(); 1157 + for t in filter_to_targets { 1158 + for (_, target_id) in self.iter_targets_for_target(&Target(t.to_string())) { 1159 + filter_to_target_ids.insert(target_id); 1160 + } 1161 + } 1162 + 1163 + let linkers = self.get_target_linkers(&target_id)?; 1164 + 1165 + // we want to provide many to many which effectively means that we want to show a specific 1166 + // list of reords that is linked to by a specific number of linkers 1167 + let mut grouped_links: BTreeMap<TargetId, Vec<RecordId>> = BTreeMap::new(); 1168 + for (did_id, rkey) in linkers.0 { 1169 + if did_id.is_empty() { 1170 + continue; 1171 + } 1172 + 1173 + if !filter_did_ids.is_empty() && filter_did_ids.get(&did_id) != Some(&true) { 1174 + continue; 1175 + } 1176 + 1177 + // Make sure the current did is active 1178 + let Some(did) = self.did_id_table.get_val_from_id(&self.db, did_id.0)? else { 1179 + eprintln!("failed to look up did from did_id {did_id:?}"); 1180 + continue; 1181 + }; 1182 + let Some(DidIdValue(_, active)) = self.did_id_table.get_id_val(&self.db, &did)? else { 1183 + eprintln!("failed to look up did_value from did_id {did_id:?}: {did:?}: data consistency bug?"); 1184 + continue; 1185 + }; 1186 + if !active { 1187 + continue; 1188 + } 1189 + 1190 + let record_link_key = RecordLinkKey(did_id, collection.clone(), rkey.clone()); 1191 + let Some(targets) = self.get_record_link_targets(&record_link_key)? else { 1192 + continue; 1193 + }; 1194 + 1195 + let Some(fwd_target) = targets 1196 + .0 1197 + .into_iter() 1198 + .filter_map(|RecordLinkTarget(rpath, target_id)| { 1199 + if rpath.0 == path_to_other 1200 + && (filter_to_target_ids.is_empty() 1201 + || filter_to_target_ids.contains(&target_id)) 1202 + { 1203 + Some(target_id) 1204 + } else { 1205 + None 1206 + } 1207 + }) 1208 + .take(1) 1209 + .next() 1210 + else { 1211 + eprintln!("no forward match found."); 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(); 1222 + if fwd_target > *current_max { 1223 + continue; 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(); 1241 + } 1242 + } 1243 + 1244 + let mut items: Vec<(RecordId, String)> = Vec::with_capacity(grouped_links.len()); 1245 + for (fwd_target_id, records) in &grouped_links { 1246 + let Some(target_key) = self 1247 + .target_id_table 1248 + .get_val_from_id(&self.db, fwd_target_id.0)? 1249 + else { 1250 + eprintln!("failed to look up target from target_id {fwd_target_id:?}"); 1251 + continue; 1252 + }; 1253 + 1254 + let target_string = target_key.0 .0; 1255 + 1256 + records 1257 + .iter() 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 + }; 1266 + 1267 + Ok(PagedOrderedCollection { items, next }) 1268 + } 1269 + 1270 fn get_links( 1271 &self, 1272 target: &str,
+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.