This repository has no description
0

Configure Feed

Select the types of activity you want to include in your feed.

core / bobbin / crates / xrpc / src / lib.rs
90 kB 2778 lines
1use std::future::Future; 2use std::sync::Arc; 3 4use bobbin_resolver::{ 5 NormalizeRepoRefs, decode_canon_or_upgrade, normalize_record_fields, scrub_record_bytes, 6 upgrade_wire_bytes, 7}; 8 9use axum::{ 10 Router, 11 body::Body, 12 extract::{FromRequestParts, Query, RawQuery, State, rejection::QueryRejection}, 13 http::{ 14 HeaderMap, HeaderName, StatusCode, 15 header::{ 16 ACCEPT_RANGES, CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_ENCODING, CONTENT_LENGTH, 17 CONTENT_RANGE, CONTENT_TYPE, ETAG, IF_MODIFIED_SINCE, IF_NONE_MATCH, IF_RANGE, 18 LAST_MODIFIED, RANGE, 19 }, 20 request::Parts, 21 }, 22 response::{IntoResponse, Json, Response}, 23 routing::get, 24}; 25use bobbin_edge_index::{ 26 Coverage, CoverageWatch, CursorParseError, EdgeItem, EdgePage, EdgeStore, IssueStateKind, 27 PageCursor, PageLimit, PageToken, PullStatusKind, SortDir, StateIndex, StateKind, 28}; 29use bobbin_knot_proxy::{KnotHost, KnotProxy, KnotProxyError, ProxyResponse, RepoSlug}; 30use bobbin_record_lru::RecordStore; 31use bobbin_resolver::RepoIdResolver; 32use bobbin_search::{ 33 SearchCursor, SearchError, SearchFilters, SearchHit, SearchOffset, SearchReader, 34}; 35use bobbin_slingshot_client::{SlingshotClient, SlingshotError}; 36use bobbin_types::ids::{EdgeKey, SubjectRef, nsid_static}; 37use bobbin_types::knot_acl::{KnotOwnedSource, decode_knot_owned_source, knot_did_host}; 38use bobbin_types::record::RecordBody; 39use bobbin_types::search::SearchableRecord; 40use bobbin_types::sh_tangled::actor::profile::{Profile, ProfileGetRecordOutput, ProfileRecord}; 41use bobbin_types::sh_tangled::feed::comment::{ 42 Comment as FeedComment, CommentRecord as FeedCommentRecord, 43}; 44use bobbin_types::sh_tangled::feed::reaction::{Reaction, ReactionRecord}; 45use bobbin_types::sh_tangled::feed::star::{Star, StarRecord}; 46use bobbin_types::sh_tangled::git::ref_update::{RefUpdate, RefUpdateRecord}; 47use bobbin_types::sh_tangled::graph::follow::{Follow, FollowRecord}; 48use bobbin_types::sh_tangled::graph::vouch::{Vouch, VouchRecord}; 49use bobbin_types::sh_tangled::knot::member::{ 50 Member as KnotMember, MemberRecord as KnotMemberRecord, 51}; 52use bobbin_types::sh_tangled::knot::{Knot, KnotRecord}; 53use bobbin_types::sh_tangled::label::definition::{ 54 Definition as LabelDefinition, DefinitionRecord as LabelDefinitionRecord, 55}; 56use bobbin_types::sh_tangled::label::op::{Op as LabelOp, OpRecord as LabelOpRecord}; 57use bobbin_types::sh_tangled::pipeline::status::{ 58 Status as PipelineStatus, StatusRecord as PipelineStatusRecord, 59}; 60use bobbin_types::sh_tangled::pipeline::{Pipeline, PipelineRecord}; 61use bobbin_types::sh_tangled::public_key::{PublicKey, PublicKeyRecord}; 62use bobbin_types::sh_tangled::repo::artifact::{Artifact, ArtifactRecord}; 63use bobbin_types::sh_tangled::repo::collaborator::{Collaborator, CollaboratorRecord}; 64use bobbin_types::sh_tangled::repo::issue::state::{ 65 State as IssueState, StateRecord as IssueStateRecord, 66}; 67use bobbin_types::sh_tangled::repo::issue::{Issue, IssueGetRecordOutput, IssueRecord}; 68use bobbin_types::sh_tangled::repo::pull::status::{ 69 Status as PullStatus, StatusRecord as PullStatusRecord, 70}; 71use bobbin_types::sh_tangled::repo::pull::{Pull, PullGetRecordOutput, PullRecord}; 72use bobbin_types::sh_tangled::repo::{Repo, RepoGetRecordOutput, RepoRecord}; 73use bobbin_types::sh_tangled::spindle::member::{ 74 Member as SpindleMember, MemberRecord as SpindleMemberRecord, 75}; 76use bobbin_types::sh_tangled::spindle::{Spindle, SpindleRecord}; 77use bobbin_types::sh_tangled::string::{TangledString, TangledStringRecord}; 78use futures::Stream; 79use futures::stream::{self, StreamExt, TryStreamExt}; 80use jacquard_common::types::did::Did; 81use jacquard_common::types::ident::AtIdentifier; 82use jacquard_common::types::nsid::Nsid; 83use jacquard_common::types::recordkey::Rkey; 84use jacquard_common::types::string::{AtUri, Cid}; 85use jacquard_common::xrpc::XrpcResp; 86use jacquard_common::{DefaultStr, IntoStatic}; 87use serde::{Deserialize, Serialize}; 88use std::convert::Infallible; 89use std::time::Duration; 90use thiserror::Error; 91use url::form_urlencoded; 92 93use tower_http::classify::ServerErrorsFailureClass; 94use tower_http::trace::{DefaultMakeSpan, OnFailure, OnResponse, TraceLayer}; 95use tracing::{Level, Span}; 96 97mod backpressure; 98mod client_address; 99mod filter; 100 101pub use backpressure::{ 102 HeavyLimiter, HeavyPermit, MaxInFlight, PerRequestAnonBytes, PressureVerdict, ReservedFloor, 103}; 104use client_address::X_FORWARDED_FOR; 105pub use client_address::{ClientAddress, SocketPeer}; 106use filter::{IssueFilter, ListFilter, NoFilter, PullFilter}; 107use trusted_proxies::TrustedProxies; 108 109const DEFAULT_LIMIT: u32 = 50; 110const FETCH_CONCURRENCY: usize = 8; 111 112#[derive(Clone)] 113pub struct AppState { 114 pub records: Arc<dyn RecordStore>, 115 pub slingshot: SlingshotClient, 116 pub edges: Arc<EdgeStore>, 117 pub issue_states: Arc<StateIndex<IssueStateKind>>, 118 pub pull_statuses: Arc<StateIndex<PullStatusKind>>, 119 pub coverage: Arc<CoverageWatch>, 120 pub knots: Arc<KnotProxy>, 121 pub search: Arc<dyn SearchReader>, 122 pub resolver: Arc<RepoIdResolver>, 123 pub limiter: Option<Arc<HeavyLimiter>>, 124 pub client_address: Arc<ClientAddress>, 125} 126 127impl AppState { 128 #[allow(clippy::too_many_arguments)] 129 pub fn new( 130 records: Arc<dyn RecordStore>, 131 slingshot: SlingshotClient, 132 edges: Arc<EdgeStore>, 133 issue_states: Arc<StateIndex<IssueStateKind>>, 134 pull_statuses: Arc<StateIndex<PullStatusKind>>, 135 coverage: Arc<CoverageWatch>, 136 knots: Arc<KnotProxy>, 137 search: Arc<dyn SearchReader>, 138 resolver: Arc<RepoIdResolver>, 139 ) -> Self { 140 Self { 141 records, 142 slingshot, 143 edges, 144 issue_states, 145 pull_statuses, 146 coverage, 147 knots, 148 search, 149 resolver, 150 limiter: None, 151 client_address: Arc::new(ClientAddress::default()), 152 } 153 } 154 155 pub fn with_limiter(mut self, limiter: Option<Arc<HeavyLimiter>>) -> Self { 156 self.limiter = limiter; 157 self 158 } 159 160 pub fn with_proxies(mut self, proxies: TrustedProxies) -> Self { 161 self.client_address = Arc::new(ClientAddress::new(proxies)); 162 self 163 } 164 165 fn heavy_permit(&self) -> Result<Option<HeavyPermit>, XrpcError> { 166 self.limiter.as_ref().map(|l| l.try_enter()).transpose() 167 } 168} 169 170pub fn router(state: AppState) -> Router { 171 Router::new() 172 .route("/xrpc/sh.tangled.repo.getRepo", get(get_repo)) 173 .route("/xrpc/sh.tangled.repo.getRepos", get(get_repos)) 174 .route( 175 "/xrpc/sh.tangled.repo.getRepoByRepoDid", 176 get(get_repo_by_repo_did), 177 ) 178 .route("/xrpc/sh.tangled.actor.getProfile", get(get_profile)) 179 .route("/xrpc/sh.tangled.actor.getProfiles", get(get_profiles)) 180 .route("/xrpc/sh.tangled.repo.getIssue", get(get_issue)) 181 .route("/xrpc/sh.tangled.repo.getIssues", get(get_issues)) 182 .route("/xrpc/sh.tangled.repo.getPull", get(get_pull)) 183 .route("/xrpc/sh.tangled.repo.getPulls", get(get_pulls)) 184 .route("/xrpc/sh.tangled.feed.listStars", get(list_stars)) 185 .route("/xrpc/sh.tangled.feed.countStars", get(count_stars)) 186 .route("/xrpc/sh.tangled.graph.listFollows", get(list_follows)) 187 .route("/xrpc/sh.tangled.graph.countFollows", get(count_follows)) 188 .route("/xrpc/sh.tangled.repo.listIssues", get(list_issues)) 189 .route("/xrpc/sh.tangled.repo.countIssues", get(count_issues)) 190 .route("/xrpc/sh.tangled.repo.listPulls", get(list_pulls)) 191 .route("/xrpc/sh.tangled.repo.countPulls", get(count_pulls)) 192 .route( 193 "/xrpc/sh.tangled.feed.listComments", 194 get(list_feed_comments), 195 ) 196 .route( 197 "/xrpc/sh.tangled.feed.countComments", 198 get(count_feed_comments), 199 ) 200 .route("/xrpc/sh.tangled.feed.listReactions", get(list_reactions)) 201 .route("/xrpc/sh.tangled.feed.countReactions", get(count_reactions)) 202 .route("/xrpc/sh.tangled.git.listRefUpdates", get(list_ref_updates)) 203 .route( 204 "/xrpc/sh.tangled.git.countRefUpdates", 205 get(count_ref_updates), 206 ) 207 .route( 208 "/xrpc/sh.tangled.repo.listCollaborators", 209 get(list_collaborators), 210 ) 211 .route( 212 "/xrpc/sh.tangled.repo.countCollaborators", 213 get(count_collaborators), 214 ) 215 .route( 216 "/xrpc/sh.tangled.repo.issue.listStates", 217 get(list_issue_states), 218 ) 219 .route( 220 "/xrpc/sh.tangled.repo.issue.countStates", 221 get(count_issue_states), 222 ) 223 .route( 224 "/xrpc/sh.tangled.repo.pull.listStatuses", 225 get(list_pull_statuses), 226 ) 227 .route( 228 "/xrpc/sh.tangled.repo.pull.countStatuses", 229 get(count_pull_statuses), 230 ) 231 .route("/xrpc/sh.tangled.repo.listRepos", get(list_repos)) 232 .route("/xrpc/sh.tangled.repo.countRepos", get(count_repos)) 233 .route("/xrpc/sh.tangled.knot.listKnots", get(list_knots)) 234 .route("/xrpc/sh.tangled.knot.countKnots", get(count_knots)) 235 .route("/xrpc/sh.tangled.spindle.listSpindles", get(list_spindles)) 236 .route( 237 "/xrpc/sh.tangled.spindle.countSpindles", 238 get(count_spindles), 239 ) 240 .route("/xrpc/sh.tangled.publicKey.listKeys", get(list_public_keys)) 241 .route( 242 "/xrpc/sh.tangled.publicKey.countKeys", 243 get(count_public_keys), 244 ) 245 .route("/xrpc/sh.tangled.graph.listVouches", get(list_vouches)) 246 .route("/xrpc/sh.tangled.graph.countVouches", get(count_vouches)) 247 .route("/xrpc/sh.tangled.feed.listStarsBy", get(list_stars_by)) 248 .route("/xrpc/sh.tangled.feed.countStarsBy", get(count_stars_by)) 249 .route( 250 "/xrpc/sh.tangled.feed.listReactionsBy", 251 get(list_reactions_by), 252 ) 253 .route( 254 "/xrpc/sh.tangled.feed.countReactionsBy", 255 get(count_reactions_by), 256 ) 257 .route("/xrpc/sh.tangled.graph.listFollowsBy", get(list_follows_by)) 258 .route( 259 "/xrpc/sh.tangled.graph.countFollowsBy", 260 get(count_follows_by), 261 ) 262 .route("/xrpc/sh.tangled.graph.listVouchesBy", get(list_vouches_by)) 263 .route( 264 "/xrpc/sh.tangled.graph.countVouchesBy", 265 get(count_vouches_by), 266 ) 267 .route( 268 "/xrpc/sh.tangled.git.listRefUpdatesBy", 269 get(list_ref_updates_by), 270 ) 271 .route( 272 "/xrpc/sh.tangled.git.countRefUpdatesBy", 273 get(count_ref_updates_by), 274 ) 275 .route( 276 "/xrpc/sh.tangled.knot.listMembersBy", 277 get(list_knot_members_by), 278 ) 279 .route( 280 "/xrpc/sh.tangled.knot.countMembersBy", 281 get(count_knot_members_by), 282 ) 283 .route("/xrpc/sh.tangled.label.listOpsBy", get(list_label_ops_by)) 284 .route("/xrpc/sh.tangled.label.countOpsBy", get(count_label_ops_by)) 285 .route( 286 "/xrpc/sh.tangled.pipeline.listPipelinesBy", 287 get(list_pipelines_by), 288 ) 289 .route( 290 "/xrpc/sh.tangled.pipeline.countPipelinesBy", 291 get(count_pipelines_by), 292 ) 293 .route( 294 "/xrpc/sh.tangled.pipeline.listStatusesBy", 295 get(list_pipeline_statuses_by), 296 ) 297 .route( 298 "/xrpc/sh.tangled.pipeline.countStatusesBy", 299 get(count_pipeline_statuses_by), 300 ) 301 .route( 302 "/xrpc/sh.tangled.repo.listArtifactsBy", 303 get(list_artifacts_by), 304 ) 305 .route( 306 "/xrpc/sh.tangled.repo.countArtifactsBy", 307 get(count_artifacts_by), 308 ) 309 .route( 310 "/xrpc/sh.tangled.repo.listCollaboratorsBy", 311 get(list_collaborators_by), 312 ) 313 .route( 314 "/xrpc/sh.tangled.repo.countCollaboratorsBy", 315 get(count_collaborators_by), 316 ) 317 .route("/xrpc/sh.tangled.repo.listIssuesBy", get(list_issues_by)) 318 .route("/xrpc/sh.tangled.repo.countIssuesBy", get(count_issues_by)) 319 .route( 320 "/xrpc/sh.tangled.feed.listCommentsBy", 321 get(list_feed_comments_by), 322 ) 323 .route( 324 "/xrpc/sh.tangled.feed.countCommentsBy", 325 get(count_feed_comments_by), 326 ) 327 .route( 328 "/xrpc/sh.tangled.repo.issue.listStatesBy", 329 get(list_issue_states_by), 330 ) 331 .route( 332 "/xrpc/sh.tangled.repo.issue.countStatesBy", 333 get(count_issue_states_by), 334 ) 335 .route("/xrpc/sh.tangled.repo.listPullsBy", get(list_pulls_by)) 336 .route("/xrpc/sh.tangled.repo.countPullsBy", get(count_pulls_by)) 337 .route( 338 "/xrpc/sh.tangled.repo.pull.listStatusesBy", 339 get(list_pull_statuses_by), 340 ) 341 .route( 342 "/xrpc/sh.tangled.repo.pull.countStatusesBy", 343 get(count_pull_statuses_by), 344 ) 345 .route( 346 "/xrpc/sh.tangled.spindle.listMembersBy", 347 get(list_spindle_members_by), 348 ) 349 .route( 350 "/xrpc/sh.tangled.spindle.countMembersBy", 351 get(count_spindle_members_by), 352 ) 353 .route( 354 "/xrpc/sh.tangled.label.listDefinitions", 355 get(list_label_definitions), 356 ) 357 .route( 358 "/xrpc/sh.tangled.label.countDefinitions", 359 get(count_label_definitions), 360 ) 361 .route("/xrpc/sh.tangled.label.listOps", get(list_label_ops)) 362 .route("/xrpc/sh.tangled.label.countOps", get(count_label_ops)) 363 .route( 364 "/xrpc/sh.tangled.pipeline.listPipelines", 365 get(list_pipelines), 366 ) 367 .route( 368 "/xrpc/sh.tangled.pipeline.countPipelines", 369 get(count_pipelines), 370 ) 371 .route( 372 "/xrpc/sh.tangled.pipeline.listStatuses", 373 get(list_pipeline_statuses), 374 ) 375 .route( 376 "/xrpc/sh.tangled.pipeline.countStatuses", 377 get(count_pipeline_statuses), 378 ) 379 .route("/xrpc/sh.tangled.repo.listArtifacts", get(list_artifacts)) 380 .route("/xrpc/sh.tangled.repo.countArtifacts", get(count_artifacts)) 381 .route("/xrpc/sh.tangled.knot.listMembers", get(list_knot_members)) 382 .route( 383 "/xrpc/sh.tangled.knot.countMembers", 384 get(count_knot_members), 385 ) 386 .route( 387 "/xrpc/sh.tangled.spindle.listMembers", 388 get(list_spindle_members), 389 ) 390 .route( 391 "/xrpc/sh.tangled.spindle.countMembers", 392 get(count_spindle_members), 393 ) 394 .route("/xrpc/sh.tangled.string.listStrings", get(list_strings)) 395 .route("/xrpc/sh.tangled.string.countStrings", get(count_strings)) 396 .route("/xrpc/sh.tangled.search.query", get(search_query)) 397 .route("/xrpc/sh.tangled.bobbin.getCoverage", get(get_coverage)) 398 .route( 399 "/xrpc/com.bad-example.identity.resolveMiniDoc", 400 get(resolve_mini_doc), 401 ) 402 .merge(knot_proxied_routes()) 403 .layer( 404 TraceLayer::new_for_http() 405 .make_span_with(DefaultMakeSpan::new().level(Level::INFO)) 406 .on_request(()) 407 .on_response(LatencyFreeTrace) 408 .on_failure(LatencyFreeTrace), 409 ) 410 .with_state(state) 411} 412 413#[derive(Clone, Copy, Debug)] 414struct LatencyFreeTrace; 415 416impl<B> OnResponse<B> for LatencyFreeTrace { 417 fn on_response(self, response: &Response<B>, _latency: Duration, _span: &Span) { 418 tracing::event!( 419 target: "tower_http::trace::on_response", 420 Level::INFO, 421 status = response.status().as_u16(), 422 "request completed", 423 ); 424 } 425} 426 427impl OnFailure<ServerErrorsFailureClass> for LatencyFreeTrace { 428 fn on_failure(&mut self, error: ServerErrorsFailureClass, _latency: Duration, _span: &Span) { 429 tracing::event!( 430 target: "tower_http::trace::on_failure", 431 Level::WARN, 432 error = %error, 433 "request failed", 434 ); 435 } 436} 437 438const REPO_PROXIED_NSIDS: &[&str] = &[ 439 "sh.tangled.repo.archive", 440 "sh.tangled.repo.blob", 441 "sh.tangled.repo.branch", 442 "sh.tangled.repo.branches", 443 "sh.tangled.repo.compare", 444 "sh.tangled.repo.describeRepo", 445 "sh.tangled.repo.diff", 446 "sh.tangled.repo.getDefaultBranch", 447 "sh.tangled.repo.languages", 448 "sh.tangled.repo.listSecrets", 449 "sh.tangled.repo.log", 450 "sh.tangled.repo.tag", 451 "sh.tangled.repo.tags", 452 "sh.tangled.repo.tree", 453]; 454 455const KNOT_PROXIED_NSIDS: &[&str] = &[ 456 "sh.tangled.owner", 457 "sh.tangled.knot.version", 458 "sh.tangled.knot.listKeys", 459]; 460 461const PASSTHROUGH_HEADERS: &[&HeaderName] = &[ 462 &CONTENT_TYPE, 463 &CONTENT_LENGTH, 464 &CONTENT_ENCODING, 465 &ETAG, 466 &CACHE_CONTROL, 467 &LAST_MODIFIED, 468 &CONTENT_DISPOSITION, 469 &ACCEPT_RANGES, 470 &CONTENT_RANGE, 471]; 472 473const FORWARDED_REQUEST_HEADERS: &[&HeaderName] = 474 &[&RANGE, &IF_RANGE, &IF_NONE_MATCH, &IF_MODIFIED_SINCE]; 475 476const KNOT_HOST_PARAM: &str = "knot"; 477const REPO_PARAM: &str = "repo"; 478 479type ProxyParams = Vec<(String, String)>; 480 481fn knot_proxied_routes() -> Router<AppState> { 482 let with_repo = register_proxied(Router::new(), REPO_PROXIED_NSIDS, proxy_repo_handler); 483 register_proxied(with_repo, KNOT_PROXIED_NSIDS, proxy_knot_handler) 484} 485 486fn register_proxied<H, Fut>( 487 router: Router<AppState>, 488 nsids: &[&'static str], 489 handler: H, 490) -> Router<AppState> 491where 492 H: Fn(AppState, HeaderMap, SocketPeer, ProxyParams, Nsid<DefaultStr>) -> Fut 493 + Clone 494 + Send 495 + Sync 496 + 'static, 497 Fut: Future<Output = Result<Response, XrpcError>> + Send + 'static, 498{ 499 nsids.iter().fold(router, |router, &nsid_lit| { 500 let handler = handler.clone(); 501 let nsid = nsid_static(nsid_lit); 502 router.route( 503 &format!("/xrpc/{nsid_lit}"), 504 get( 505 move |State(state): State<AppState>, 506 headers: HeaderMap, 507 socket: SocketPeer, 508 Query(params): Query<ProxyParams>| { 509 handler(state, headers, socket, params, nsid.clone()) 510 }, 511 ), 512 ) 513 }) 514} 515 516#[derive(Clone, Debug)] 517pub enum SubjectQuery { 518 Did(Did<DefaultStr>), 519 Uri(AtUri<DefaultStr>), 520} 521 522impl<'de> Deserialize<'de> for SubjectQuery { 523 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> 524 where 525 D: serde::Deserializer<'de>, 526 { 527 let raw = String::deserialize(deserializer)?; 528 if let Ok(did) = Did::<DefaultStr>::new_owned(&raw) { 529 return Ok(Self::Did(did)); 530 } 531 AtUri::<DefaultStr>::new_owned(&raw) 532 .map(Self::Uri) 533 .map_err(serde::de::Error::custom) 534 } 535} 536 537#[derive(Clone, Debug, Eq, PartialEq)] 538pub struct ExpectedNsid { 539 canon: Nsid<DefaultStr>, 540 aliases: &'static [&'static str], 541} 542 543const FEED_COMMENT_LEGACY_ALIASES: &[&str] = &[ 544 "sh.tangled.repo.issue.comment", 545 "sh.tangled.repo.pull.comment", 546]; 547 548fn aliases_for(nsid: &str) -> &'static [&'static str] { 549 match nsid { 550 "sh.tangled.feed.comment" => FEED_COMMENT_LEGACY_ALIASES, 551 _ => &[], 552 } 553} 554 555impl ExpectedNsid { 556 pub fn new(nsid: Nsid<DefaultStr>) -> Self { 557 let aliases = aliases_for(nsid.as_ref()); 558 Self { 559 canon: nsid, 560 aliases, 561 } 562 } 563 564 pub fn from_static(s: &'static str) -> Self { 565 let canon = nsid_static(s); 566 let aliases = aliases_for(s); 567 Self { canon, aliases } 568 } 569 570 pub fn as_nsid(&self) -> &Nsid<DefaultStr> { 571 &self.canon 572 } 573 574 pub fn as_str(&self) -> &str { 575 self.canon.as_ref() 576 } 577 578 fn accepts(&self, other: &str) -> bool { 579 other == self.canon.as_ref() || self.aliases.contains(&other) 580 } 581} 582 583#[derive(Debug, Deserialize)] 584struct GetRepoQuery { 585 repo: AtUri<DefaultStr>, 586} 587 588#[derive(Debug, Deserialize)] 589struct GetRepoByRepoDidQuery { 590 #[serde(rename = "repoDid")] 591 repo_did: Did<DefaultStr>, 592} 593 594#[derive(Debug, Deserialize)] 595struct GetProfileQuery { 596 actor: AtUri<DefaultStr>, 597} 598 599#[derive(Debug, Deserialize)] 600struct GetIssueQuery { 601 issue: AtUri<DefaultStr>, 602} 603 604#[derive(Debug, Deserialize)] 605struct GetPullQuery { 606 pull: AtUri<DefaultStr>, 607} 608 609#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)] 610#[serde(rename_all = "lowercase")] 611enum Order { 612 Asc, 613 #[default] 614 Desc, 615} 616 617impl From<Order> for SortDir { 618 fn from(o: Order) -> Self { 619 match o { 620 Order::Asc => SortDir::Asc, 621 Order::Desc => SortDir::Desc, 622 } 623 } 624} 625 626#[derive(Debug, Deserialize)] 627struct TypedListQuery<F> { 628 subject: SubjectQuery, 629 cursor: Option<String>, 630 limit: Option<u32>, 631 #[serde(default)] 632 order: Order, 633 #[serde(flatten)] 634 filter: F, 635} 636 637impl<F> TypedListQuery<F> { 638 fn dir(&self) -> SortDir { 639 self.order.into() 640 } 641} 642 643#[derive(Debug, Deserialize)] 644struct CountQuery { 645 subject: SubjectQuery, 646} 647 648#[derive(Debug, Deserialize)] 649struct SearchQueryParams { 650 q: String, 651 nsid: Option<Nsid<DefaultStr>>, 652 author: Option<Did<DefaultStr>>, 653 repo: Option<Did<DefaultStr>>, 654 since: Option<String>, 655 until: Option<String>, 656 cursor: Option<String>, 657 limit: Option<u32>, 658} 659 660pub struct XrpcQuery<T>(pub T); 661 662impl<S, T> FromRequestParts<S> for XrpcQuery<T> 663where 664 S: Send + Sync, 665 T: serde::de::DeserializeOwned + Send + 'static, 666{ 667 type Rejection = XrpcError; 668 669 async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { 670 Query::<T>::from_request_parts(parts, state) 671 .await 672 .map(|Query(t)| Self(t)) 673 .map_err(|rej: QueryRejection| XrpcError::InvalidParams(rej.body_text())) 674 } 675} 676 677#[derive(Debug, Error)] 678pub enum XrpcError { 679 #[error("invalid request: {0}")] 680 InvalidParams(String), 681 #[error("record not found")] 682 NotFound, 683 #[error("upstream unavailable: {0}")] 684 UpstreamUnavailable(String), 685 #[error("upstream gone: {0}")] 686 UpstreamGone(String), 687 #[error("invalid record: {0}")] 688 InvalidRecord(String), 689 #[error("internal: {0}")] 690 Internal(String), 691 #[error("overloaded, shedding under memory pressure")] 692 Overloaded, 693} 694 695impl XrpcError { 696 pub fn overloaded() -> Self { 697 Self::Overloaded 698 } 699} 700 701#[derive(Serialize)] 702struct ErrorBody { 703 error: &'static str, 704 message: String, 705} 706 707impl IntoResponse for XrpcError { 708 fn into_response(self) -> Response { 709 let (status, error) = match &self { 710 Self::InvalidParams(_) => (StatusCode::BAD_REQUEST, "InvalidRequest"), 711 Self::NotFound => (StatusCode::NOT_FOUND, "RecordNotFound"), 712 Self::UpstreamUnavailable(_) => (StatusCode::BAD_GATEWAY, "UpstreamFailed"), 713 Self::UpstreamGone(_) => (StatusCode::BAD_GATEWAY, "UpstreamGone"), 714 Self::InvalidRecord(_) => (StatusCode::BAD_GATEWAY, "InvalidRecord"), 715 Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "InternalError"), 716 Self::Overloaded => (StatusCode::SERVICE_UNAVAILABLE, "Overloaded"), 717 }; 718 let body = ErrorBody { 719 error, 720 message: self.to_string(), 721 }; 722 (status, Json(body)).into_response() 723 } 724} 725 726#[derive(Serialize)] 727#[serde(rename_all = "camelCase")] 728struct CoverageEnvelope { 729 ready: bool, 730 events_processed: u64, 731 last_cursor: u64, 732} 733 734impl From<Coverage> for CoverageEnvelope { 735 fn from(c: Coverage) -> Self { 736 Self { 737 ready: c.is_ready(), 738 events_processed: c.events_processed(), 739 last_cursor: c.last_cursor().raw(), 740 } 741 } 742} 743 744struct Deduped<T>(T); 745 746impl<T: Serialize> Serialize for Deduped<T> { 747 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> 748 where 749 S: serde::Serializer, 750 { 751 serde_json::to_value(&self.0) 752 .map_err(serde::ser::Error::custom)? 753 .serialize(serializer) 754 } 755} 756 757#[derive(Serialize)] 758#[serde(rename_all = "camelCase")] 759struct RecordView<V> { 760 uri: AtUri<DefaultStr>, 761 cid: Option<Cid<DefaultStr>>, 762 value: V, 763} 764 765#[derive(Serialize)] 766#[serde(rename_all = "camelCase")] 767struct StatefulItem<V> { 768 #[serde(flatten)] 769 view: RecordView<V>, 770 state: &'static str, 771 #[serde(skip_serializing_if = "Option::is_none")] 772 state_updated_at: Option<String>, 773 comment_count: u64, 774} 775 776fn format_micros(micros: u64) -> String { 777 let signed = i64::try_from(micros).ok(); 778 let rfc = signed 779 .and_then(chrono::DateTime::<chrono::Utc>::from_timestamp_micros) 780 .map(|dt| dt.to_rfc3339_opts(chrono::SecondsFormat::Micros, true)); 781 rfc.unwrap_or_else(|| micros.to_string()) 782} 783 784pub(crate) fn source_authority_did(source: &AtUri<DefaultStr>) -> Option<Did<DefaultStr>> { 785 match source.authority() { 786 AtIdentifier::Did(d) => Some(d.clone().into_static()), 787 AtIdentifier::Handle(_) => None, 788 } 789} 790 791fn enrich_issue_view( 792 state: &AppState, 793 view: RecordView<Issue<DefaultStr>>, 794) -> StatefulItem<Issue<DefaultStr>> { 795 let issue_author = source_authority_did(&view.uri); 796 let repo_did = view.value.repo.clone(); 797 enrich_view( 798 &state.edges, 799 nsid_static("sh.tangled.feed.comment"), 800 &state.issue_states, 801 view, 802 move |src| accept_state_source(src, issue_author.as_ref(), &repo_did), 803 ) 804} 805 806fn enrich_pull_view( 807 state: &AppState, 808 view: RecordView<Pull<DefaultStr>>, 809) -> StatefulItem<Pull<DefaultStr>> { 810 let pull_author = source_authority_did(&view.uri); 811 let target_repo = view.value.target.repo.clone(); 812 enrich_view( 813 &state.edges, 814 nsid_static("sh.tangled.feed.comment"), 815 &state.pull_statuses, 816 view, 817 move |src| accept_state_source(src, pull_author.as_ref(), &target_repo), 818 ) 819} 820 821pub(crate) fn accept_state_source( 822 source: &AtUri<DefaultStr>, 823 entity_author: Option<&Did<DefaultStr>>, 824 repo_owner: &Did<DefaultStr>, 825) -> bool { 826 let Some(src) = source_authority_did(source) else { 827 return false; 828 }; 829 Some(&src) == entity_author || &src == repo_owner 830} 831 832fn enrich_view<V, K, F>( 833 edges: &EdgeStore, 834 comment_nsid: Nsid<DefaultStr>, 835 states: &StateIndex<K>, 836 view: RecordView<V>, 837 accept: F, 838) -> StatefulItem<V> 839where 840 K: StateKind + Default, 841 F: Fn(&AtUri<DefaultStr>) -> bool, 842{ 843 let comment_count = edges.count(&EdgeKey::new( 844 comment_nsid, 845 SubjectRef::Uri(view.uri.clone()), 846 )); 847 let (state, state_updated_at) = states 848 .latest_by(&view.uri, accept) 849 .map_or((K::default().wire(), None), |(kind, micros)| { 850 (kind.wire(), Some(format_micros(micros))) 851 }); 852 StatefulItem { 853 view, 854 state, 855 state_updated_at, 856 comment_count, 857 } 858} 859 860#[derive(Serialize)] 861#[serde(rename_all = "camelCase")] 862struct CountResponse { 863 count: u64, 864 distinct_authors: u64, 865} 866 867#[derive(Serialize)] 868#[serde(rename_all = "camelCase")] 869struct SearchHitView { 870 uri: AtUri<DefaultStr>, 871 cid: Option<Cid<DefaultStr>>, 872 nsid: Nsid<DefaultStr>, 873 score: f32, 874 value: SearchableRecord, 875} 876 877fn map_slingshot(err: SlingshotError) -> XrpcError { 878 use SlingshotError as E; 879 match err { 880 E::NotFound => XrpcError::NotFound, 881 e @ (E::Decode(_) 882 | E::MissingField(_) 883 | E::InvalidAtUri(_) 884 | E::InvalidCid(_) 885 | E::UriMismatch { .. }) => XrpcError::InvalidRecord(e.to_string()), 886 e @ (E::Network(_) 887 | E::Build(_) 888 | E::Upstream(_) 889 | E::BodyTooLarge { .. } 890 | E::BadScheme(_)) => XrpcError::UpstreamUnavailable(e.to_string()), 891 } 892} 893 894fn parse_uri(raw: &str) -> Result<AtUri<DefaultStr>, XrpcError> { 895 AtUri::<DefaultStr>::new_owned(raw).map_err(|e| XrpcError::InvalidParams(format!("uri: {e}"))) 896} 897 898#[derive(Clone, Copy, Debug, Eq, PartialEq)] 899pub enum SubjectShape { 900 BareDid, 901 Collection(&'static str), 902 BareDidOrOneOfCollections(&'static [&'static str]), 903 OneOfCollections(&'static [&'static str]), 904 AnyAtUri, 905} 906 907pub trait HasSubject { 908 const SHAPE: SubjectShape; 909} 910 911pub trait MirrorOf { 912 type Record: XrpcResp; 913 const EDGE_KIND: &'static str; 914 const SHAPE: SubjectShape; 915} 916 917pub struct StarBy; 918pub struct ReactionBy; 919pub struct FollowBy; 920pub struct VouchBy; 921pub struct RefUpdateBy; 922pub struct KnotMemberBy; 923pub struct LabelOpBy; 924pub struct PipelineBy; 925pub struct PipelineStatusBy; 926pub struct ArtifactBy; 927pub struct CollaboratorBy; 928pub struct FeedCommentBy; 929pub struct IssueBy; 930pub struct IssueStateBy; 931pub struct PullBy; 932pub struct PullStatusBy; 933pub struct SpindleMemberBy; 934 935impl MirrorOf for StarBy { 936 type Record = StarRecord; 937 const EDGE_KIND: &'static str = "sh.tangled.feed.star.by"; 938 const SHAPE: SubjectShape = SubjectShape::BareDid; 939} 940impl MirrorOf for ReactionBy { 941 type Record = ReactionRecord; 942 const EDGE_KIND: &'static str = "sh.tangled.feed.reaction.by"; 943 const SHAPE: SubjectShape = SubjectShape::BareDid; 944} 945impl MirrorOf for FollowBy { 946 type Record = FollowRecord; 947 const EDGE_KIND: &'static str = "sh.tangled.graph.follow.by"; 948 const SHAPE: SubjectShape = SubjectShape::BareDid; 949} 950impl MirrorOf for VouchBy { 951 type Record = VouchRecord; 952 const EDGE_KIND: &'static str = "sh.tangled.graph.vouch.by"; 953 const SHAPE: SubjectShape = SubjectShape::BareDid; 954} 955impl MirrorOf for RefUpdateBy { 956 type Record = RefUpdateRecord; 957 const EDGE_KIND: &'static str = "sh.tangled.git.refUpdate.by"; 958 const SHAPE: SubjectShape = SubjectShape::BareDid; 959} 960impl MirrorOf for KnotMemberBy { 961 type Record = KnotMemberRecord; 962 const EDGE_KIND: &'static str = "sh.tangled.knot.member.by"; 963 const SHAPE: SubjectShape = SubjectShape::BareDid; 964} 965impl MirrorOf for LabelOpBy { 966 type Record = LabelOpRecord; 967 const EDGE_KIND: &'static str = "sh.tangled.label.op.by"; 968 const SHAPE: SubjectShape = SubjectShape::BareDid; 969} 970impl MirrorOf for PipelineBy { 971 type Record = PipelineRecord; 972 const EDGE_KIND: &'static str = "sh.tangled.pipeline.by"; 973 const SHAPE: SubjectShape = SubjectShape::BareDid; 974} 975impl MirrorOf for PipelineStatusBy { 976 type Record = PipelineStatusRecord; 977 const EDGE_KIND: &'static str = "sh.tangled.pipeline.status.by"; 978 const SHAPE: SubjectShape = SubjectShape::BareDid; 979} 980impl MirrorOf for ArtifactBy { 981 type Record = ArtifactRecord; 982 const EDGE_KIND: &'static str = "sh.tangled.repo.artifact.by"; 983 const SHAPE: SubjectShape = SubjectShape::BareDid; 984} 985impl MirrorOf for CollaboratorBy { 986 type Record = CollaboratorRecord; 987 const EDGE_KIND: &'static str = "sh.tangled.repo.collaborator.by"; 988 const SHAPE: SubjectShape = SubjectShape::BareDid; 989} 990impl MirrorOf for FeedCommentBy { 991 type Record = FeedCommentRecord; 992 const EDGE_KIND: &'static str = "sh.tangled.feed.comment.by"; 993 const SHAPE: SubjectShape = SubjectShape::BareDid; 994} 995impl MirrorOf for IssueBy { 996 type Record = IssueRecord; 997 const EDGE_KIND: &'static str = "sh.tangled.repo.issue.by"; 998 const SHAPE: SubjectShape = SubjectShape::BareDid; 999} 1000impl MirrorOf for IssueStateBy { 1001 type Record = IssueStateRecord; 1002 const EDGE_KIND: &'static str = "sh.tangled.repo.issue.state.by"; 1003 const SHAPE: SubjectShape = SubjectShape::BareDid; 1004} 1005impl MirrorOf for PullBy { 1006 type Record = PullRecord; 1007 const EDGE_KIND: &'static str = "sh.tangled.repo.pull.by"; 1008 const SHAPE: SubjectShape = SubjectShape::BareDid; 1009} 1010impl MirrorOf for PullStatusBy { 1011 type Record = PullStatusRecord; 1012 const EDGE_KIND: &'static str = "sh.tangled.repo.pull.status.by"; 1013 const SHAPE: SubjectShape = SubjectShape::BareDid; 1014} 1015impl MirrorOf for SpindleMemberBy { 1016 type Record = SpindleMemberRecord; 1017 const EDGE_KIND: &'static str = "sh.tangled.spindle.member.by"; 1018 const SHAPE: SubjectShape = SubjectShape::BareDid; 1019} 1020 1021impl HasSubject for StarRecord { 1022 const SHAPE: SubjectShape = SubjectShape::BareDidOrOneOfCollections(&["sh.tangled.string"]); 1023} 1024impl HasSubject for FollowRecord { 1025 const SHAPE: SubjectShape = SubjectShape::BareDid; 1026} 1027impl HasSubject for IssueRecord { 1028 const SHAPE: SubjectShape = SubjectShape::BareDid; 1029} 1030impl HasSubject for PullRecord { 1031 const SHAPE: SubjectShape = SubjectShape::BareDid; 1032} 1033impl HasSubject for FeedCommentRecord { 1034 const SHAPE: SubjectShape = SubjectShape::OneOfCollections(&[ 1035 "sh.tangled.repo.issue", 1036 "sh.tangled.repo.pull", 1037 "sh.tangled.string", 1038 ]); 1039} 1040impl HasSubject for LabelDefinitionRecord { 1041 const SHAPE: SubjectShape = SubjectShape::BareDid; 1042} 1043impl HasSubject for LabelOpRecord { 1044 const SHAPE: SubjectShape = 1045 SubjectShape::OneOfCollections(&["sh.tangled.repo.issue", "sh.tangled.repo.pull"]); 1046} 1047impl HasSubject for PipelineRecord { 1048 const SHAPE: SubjectShape = SubjectShape::BareDid; 1049} 1050impl HasSubject for PipelineStatusRecord { 1051 const SHAPE: SubjectShape = SubjectShape::Collection("sh.tangled.pipeline"); 1052} 1053impl HasSubject for ArtifactRecord { 1054 const SHAPE: SubjectShape = SubjectShape::BareDid; 1055} 1056impl HasSubject for KnotMemberRecord { 1057 const SHAPE: SubjectShape = SubjectShape::BareDid; 1058} 1059impl HasSubject for SpindleMemberRecord { 1060 const SHAPE: SubjectShape = SubjectShape::BareDid; 1061} 1062impl HasSubject for TangledStringRecord { 1063 const SHAPE: SubjectShape = SubjectShape::BareDid; 1064} 1065impl HasSubject for ReactionRecord { 1066 const SHAPE: SubjectShape = SubjectShape::AnyAtUri; 1067} 1068impl HasSubject for RefUpdateRecord { 1069 const SHAPE: SubjectShape = SubjectShape::BareDid; 1070} 1071impl HasSubject for CollaboratorRecord { 1072 const SHAPE: SubjectShape = SubjectShape::BareDid; 1073} 1074impl HasSubject for IssueStateRecord { 1075 const SHAPE: SubjectShape = SubjectShape::Collection("sh.tangled.repo.issue"); 1076} 1077impl HasSubject for PullStatusRecord { 1078 const SHAPE: SubjectShape = SubjectShape::Collection("sh.tangled.repo.pull"); 1079} 1080impl HasSubject for KnotRecord { 1081 const SHAPE: SubjectShape = SubjectShape::BareDid; 1082} 1083impl HasSubject for SpindleRecord { 1084 const SHAPE: SubjectShape = SubjectShape::BareDid; 1085} 1086impl HasSubject for PublicKeyRecord { 1087 const SHAPE: SubjectShape = SubjectShape::BareDid; 1088} 1089impl HasSubject for RepoRecord { 1090 const SHAPE: SubjectShape = SubjectShape::BareDid; 1091} 1092impl HasSubject for VouchRecord { 1093 const SHAPE: SubjectShape = SubjectShape::BareDid; 1094} 1095 1096fn parse_subject(raw: &SubjectQuery, shape: SubjectShape) -> Result<SubjectRef, XrpcError> { 1097 let uri = match raw { 1098 SubjectQuery::Did(did) => { 1099 return match shape { 1100 SubjectShape::BareDid | SubjectShape::BareDidOrOneOfCollections(_) => { 1101 Ok(SubjectRef::Did(did.clone())) 1102 } 1103 SubjectShape::Collection(expected) => Err(XrpcError::InvalidParams(format!( 1104 "subject must be at://<did>/{expected}/<rkey>, got bare did" 1105 ))), 1106 SubjectShape::OneOfCollections(allowed) => Err(XrpcError::InvalidParams(format!( 1107 "subject must be at://<did>/<nsid>/<rkey> with nsid in [{}], got bare did", 1108 allowed.join(", "), 1109 ))), 1110 SubjectShape::AnyAtUri => Err(XrpcError::InvalidParams( 1111 "subject must be at-uri form, got bare did".into(), 1112 )), 1113 }; 1114 } 1115 SubjectQuery::Uri(uri) => uri, 1116 }; 1117 if matches!(uri.authority(), AtIdentifier::Handle(_)) { 1118 return Err(XrpcError::InvalidParams( 1119 "subject authority must be a did, not a handle".into(), 1120 )); 1121 } 1122 let Some(collection) = uri.collection() else { 1123 return Err(XrpcError::InvalidParams( 1124 "subject must be a bare did or full at://<did>/<nsid>/<rkey>".into(), 1125 )); 1126 }; 1127 let c = collection.as_ref(); 1128 match shape { 1129 SubjectShape::BareDid => Err(XrpcError::InvalidParams(format!( 1130 "subject must be a bare did, got at-uri with collection {c}" 1131 ))), 1132 SubjectShape::Collection(expected) if c == expected => { 1133 require_rkey(uri, expected)?; 1134 Ok(SubjectRef::Uri(uri.clone())) 1135 } 1136 SubjectShape::Collection(expected) => Err(XrpcError::InvalidParams(format!( 1137 "subject must be at://<did>/{expected}/<rkey>, got collection {c}" 1138 ))), 1139 SubjectShape::OneOfCollections(allowed) if allowed.contains(&c) => { 1140 require_rkey(uri, c)?; 1141 Ok(SubjectRef::Uri(uri.clone())) 1142 } 1143 SubjectShape::OneOfCollections(allowed) => Err(XrpcError::InvalidParams(format!( 1144 "subject must be at://<did>/<nsid>/<rkey> with nsid in [{}], got collection {c}", 1145 allowed.join(", "), 1146 ))), 1147 SubjectShape::BareDidOrOneOfCollections(allowed) if allowed.contains(&c) => { 1148 require_rkey(uri, c)?; 1149 Ok(SubjectRef::Uri(uri.clone())) 1150 } 1151 SubjectShape::BareDidOrOneOfCollections(allowed) => Err(XrpcError::InvalidParams(format!( 1152 "subject must be a bare did or at://<did>/<nsid>/<rkey> with nsid in [{}], got collection {c}", 1153 allowed.join(", "), 1154 ))), 1155 SubjectShape::AnyAtUri => Ok(SubjectRef::Uri(uri.clone())), 1156 } 1157} 1158 1159fn require_rkey(uri: &AtUri<DefaultStr>, expected: &str) -> Result<(), XrpcError> { 1160 uri.rkey().map(|_| ()).ok_or_else(|| { 1161 XrpcError::InvalidParams(format!( 1162 "subject must be at://<did>/{expected}/<rkey>; missing rkey" 1163 )) 1164 }) 1165} 1166 1167fn parse_cursor(raw: Option<&str>) -> Result<PageCursor, XrpcError> { 1168 PageCursor::from_token(raw) 1169 .map_err(|e: CursorParseError| XrpcError::InvalidParams(format!("cursor: {e}"))) 1170} 1171 1172fn parse_limit(raw: Option<u32>) -> Result<PageLimit, XrpcError> { 1173 PageLimit::new(raw.unwrap_or(DEFAULT_LIMIT)) 1174 .map_err(|e| XrpcError::InvalidParams(format!("limit: {e}"))) 1175} 1176 1177pub(crate) fn at_uri_owned_by(uri: &AtUri<DefaultStr>, author: &Did<DefaultStr>) -> bool { 1178 match uri.authority() { 1179 AtIdentifier::Did(d) => d.as_ref() == author.as_ref(), 1180 AtIdentifier::Handle(_) => false, 1181 } 1182} 1183 1184async fn resolve_for_view( 1185 state: &AppState, 1186 expected_nsid: &Nsid<DefaultStr>, 1187 uri: AtUri<DefaultStr>, 1188) -> Result<Arc<RecordBody>, XrpcError> { 1189 let raw = uri.as_ref().to_owned(); 1190 resolve(state, ExpectedNsid::new(expected_nsid.clone()), uri) 1191 .await 1192 .map(|(body, _did)| body) 1193 .map_err(|e| match e { 1194 XrpcError::NotFound => XrpcError::UpstreamGone(raw), 1195 other => other, 1196 }) 1197} 1198 1199async fn resolve( 1200 state: &AppState, 1201 expected: ExpectedNsid, 1202 uri: AtUri<DefaultStr>, 1203) -> Result<(Arc<RecordBody>, Did<DefaultStr>), XrpcError> { 1204 let collection = uri 1205 .collection() 1206 .ok_or_else(|| XrpcError::InvalidParams("uri missing collection".into()))?; 1207 if !expected.accepts(collection.as_ref()) { 1208 return Err(XrpcError::InvalidParams(format!( 1209 "collection mismatch: expected {}, got {}", 1210 expected.as_str(), 1211 collection.as_ref() 1212 ))); 1213 } 1214 let rkey = uri 1215 .rkey() 1216 .ok_or_else(|| XrpcError::InvalidParams("uri missing rkey".into()))?; 1217 let did_ref = match uri.authority() { 1218 AtIdentifier::Did(d) => d, 1219 AtIdentifier::Handle(_) => { 1220 return Err(XrpcError::InvalidParams( 1221 "uri authority must be a did, not a handle".into(), 1222 )); 1223 } 1224 }; 1225 let did: Did<DefaultStr> = did_ref.clone().into_static(); 1226 1227 if let Some(hit) = state.records.get(&uri) { 1228 return Ok((hit, did)); 1229 } 1230 let body = state 1231 .slingshot 1232 .get_record(&did_ref, &collection, &rkey) 1233 .await 1234 .map_err(map_slingshot)?; 1235 verify_type_tag(&body, &expected)?; 1236 state.records.put(uri, body.clone()); 1237 Ok((body, did)) 1238} 1239 1240#[derive(Deserialize)] 1241struct TypeTag<'a> { 1242 #[serde(rename = "$type", borrow)] 1243 ty: &'a str, 1244} 1245 1246fn verify_type_tag(body: &RecordBody, expected: &ExpectedNsid) -> Result<(), XrpcError> { 1247 let bytes = body.value.as_ref(); 1248 let ty: std::borrow::Cow<'_, str> = match serde_json::from_slice::<TypeTag>(bytes) { 1249 Ok(t) => std::borrow::Cow::Borrowed(t.ty), 1250 Err(_) => { 1251 let value: serde_json::Value = serde_json::from_slice(bytes) 1252 .map_err(|e| XrpcError::InvalidRecord(format!("$type peek: {e}")))?; 1253 value 1254 .as_object() 1255 .and_then(|m| m.get("$type")) 1256 .and_then(|v| v.as_str()) 1257 .map(|s| std::borrow::Cow::Owned(s.to_owned())) 1258 .ok_or_else(|| XrpcError::InvalidRecord("$type peek: missing $type field".into()))? 1259 } 1260 }; 1261 if !expected.accepts(ty.as_ref()) { 1262 return Err(XrpcError::InvalidRecord(format!( 1263 "$type mismatch: expected {}, got {}", 1264 expected.as_str(), 1265 ty 1266 ))); 1267 } 1268 Ok(()) 1269} 1270 1271fn wire_type_nsid(bytes: &[u8]) -> Option<Nsid<DefaultStr>> { 1272 let ty = serde_json::from_slice::<TypeTag>(bytes).ok()?.ty; 1273 Nsid::<DefaultStr>::new_owned(ty).ok() 1274} 1275 1276async fn deserialize_or_upgrade<V>( 1277 state: &AppState, 1278 nsid: &Nsid<DefaultStr>, 1279 bytes: &[u8], 1280) -> Result<V, XrpcError> 1281where 1282 V: serde::de::DeserializeOwned, 1283{ 1284 match serde_json::from_slice::<V>(bytes) { 1285 Ok(v) => Ok(v), 1286 Err(canon_err) => { 1287 let normalized = normalize_record_fields(bytes); 1288 let working: &[u8] = normalized.as_deref().unwrap_or(bytes); 1289 if normalized.is_some() 1290 && let Ok(v) = serde_json::from_slice::<V>(working) 1291 { 1292 return Ok(v); 1293 } 1294 let scrubbed = scrub_record_bytes(nsid, working); 1295 let retry_bytes: &[u8] = scrubbed.as_deref().unwrap_or(working); 1296 if scrubbed.is_some() 1297 && let Ok(v) = serde_json::from_slice::<V>(retry_bytes) 1298 { 1299 return Ok(v); 1300 } 1301 let wire_nsid = wire_type_nsid(retry_bytes).unwrap_or_else(|| nsid.clone()); 1302 match upgrade_wire_bytes(&wire_nsid, retry_bytes, &state.resolver).await { 1303 Ok(canon_bytes) => serde_json::from_slice(&canon_bytes) 1304 .map_err(|e| XrpcError::InvalidRecord(e.to_string())), 1305 Err(_) => Err(XrpcError::InvalidRecord(canon_err.to_string())), 1306 } 1307 } 1308 } 1309} 1310 1311async fn fetch_from_uri<R, V>( 1312 state: &AppState, 1313 uri: AtUri<DefaultStr>, 1314) -> Result<(Arc<RecordBody>, V), XrpcError> 1315where 1316 R: XrpcResp, 1317 V: serde::de::DeserializeOwned + NormalizeRepoRefs, 1318{ 1319 let raw = uri.as_str().to_owned(); 1320 let nsid = nsid_static(R::NSID); 1321 let (body, _did) = resolve(state, ExpectedNsid::new(nsid.clone()), uri).await?; 1322 let value: V = deserialize_or_upgrade(state, &nsid, &body.value).await?; 1323 let value = value 1324 .normalize(&state.resolver) 1325 .await 1326 .ok_or(XrpcError::UpstreamGone(raw))?; 1327 Ok((body, value)) 1328} 1329 1330async fn fetch<R, V>( 1331 state: &AppState, 1332 uri: &AtUri<DefaultStr>, 1333) -> Result<(Arc<RecordBody>, V), XrpcError> 1334where 1335 R: XrpcResp, 1336 V: serde::de::DeserializeOwned + NormalizeRepoRefs, 1337{ 1338 fetch_from_uri::<R, V>(state, uri.clone()).await 1339} 1340 1341async fn get_repo( 1342 State(state): State<AppState>, 1343 XrpcQuery(q): XrpcQuery<GetRepoQuery>, 1344) -> Result<Json<Deduped<RepoGetRecordOutput<DefaultStr>>>, XrpcError> { 1345 let (body, value) = fetch::<RepoRecord, Repo<DefaultStr>>(&state, &q.repo).await?; 1346 Ok(Json(Deduped(RepoGetRecordOutput { 1347 cid: Some(body.cid.clone()), 1348 uri: body.uri.clone(), 1349 value, 1350 }))) 1351} 1352 1353async fn get_repo_by_repo_did( 1354 State(state): State<AppState>, 1355 XrpcQuery(q): XrpcQuery<GetRepoByRepoDidQuery>, 1356) -> Result<Json<Deduped<RepoGetRecordOutput<DefaultStr>>>, XrpcError> { 1357 let ident = state 1358 .resolver 1359 .lookup_by_repo_did(&q.repo_did) 1360 .await 1361 .ok_or(XrpcError::NotFound)?; 1362 let uri = AtUri::<DefaultStr>::from_parts_owned( 1363 ident.owner.as_str(), 1364 RepoRecord::NSID, 1365 ident.rkey.as_str(), 1366 ) 1367 .expect("Did and Rkey newtypes already validated, at-uri assembly cannot fail"); 1368 let (body, value) = fetch_from_uri::<RepoRecord, Repo<DefaultStr>>(&state, uri).await?; 1369 Ok(Json(Deduped(RepoGetRecordOutput { 1370 cid: Some(body.cid.clone()), 1371 uri: body.uri.clone(), 1372 value, 1373 }))) 1374} 1375 1376async fn get_profile( 1377 State(state): State<AppState>, 1378 XrpcQuery(q): XrpcQuery<GetProfileQuery>, 1379) -> Result<Json<Deduped<ProfileGetRecordOutput<DefaultStr>>>, XrpcError> { 1380 let (body, value) = fetch::<ProfileRecord, Profile<DefaultStr>>(&state, &q.actor).await?; 1381 Ok(Json(Deduped(ProfileGetRecordOutput { 1382 cid: Some(body.cid.clone()), 1383 uri: body.uri.clone(), 1384 value, 1385 }))) 1386} 1387 1388async fn get_issue( 1389 State(state): State<AppState>, 1390 XrpcQuery(q): XrpcQuery<GetIssueQuery>, 1391) -> Result<Json<Deduped<IssueGetRecordOutput<DefaultStr>>>, XrpcError> { 1392 let (body, value) = fetch::<IssueRecord, Issue<DefaultStr>>(&state, &q.issue).await?; 1393 Ok(Json(Deduped(IssueGetRecordOutput { 1394 cid: Some(body.cid.clone()), 1395 uri: body.uri.clone(), 1396 value, 1397 }))) 1398} 1399 1400async fn get_pull( 1401 State(state): State<AppState>, 1402 XrpcQuery(q): XrpcQuery<GetPullQuery>, 1403) -> Result<Json<Deduped<PullGetRecordOutput<DefaultStr>>>, XrpcError> { 1404 let (body, value) = fetch::<PullRecord, Pull<DefaultStr>>(&state, &q.pull).await?; 1405 Ok(Json(Deduped(PullGetRecordOutput { 1406 cid: Some(body.cid.clone()), 1407 uri: body.uri.clone(), 1408 value, 1409 }))) 1410} 1411 1412async fn get_repos( 1413 State(state): State<AppState>, 1414 RawQuery(query): RawQuery, 1415) -> Result<Response, XrpcError> { 1416 let uris = collect_repeated(query.as_deref(), BULK_REPOS_KEY); 1417 bulk_fetch::<RepoRecord, Repo<DefaultStr>>(&state, uris).await 1418} 1419 1420async fn get_profiles( 1421 State(state): State<AppState>, 1422 RawQuery(query): RawQuery, 1423) -> Result<Response, XrpcError> { 1424 let uris = collect_repeated(query.as_deref(), BULK_PROFILES_KEY); 1425 bulk_fetch::<ProfileRecord, Profile<DefaultStr>>(&state, uris).await 1426} 1427 1428async fn get_issues( 1429 State(state): State<AppState>, 1430 RawQuery(query): RawQuery, 1431) -> Result<Response, XrpcError> { 1432 let uris = collect_repeated(query.as_deref(), BULK_ISSUES_KEY); 1433 bulk_fetch::<IssueRecord, Issue<DefaultStr>>(&state, uris).await 1434} 1435 1436async fn get_pulls( 1437 State(state): State<AppState>, 1438 RawQuery(query): RawQuery, 1439) -> Result<Response, XrpcError> { 1440 let uris = collect_repeated(query.as_deref(), BULK_PULLS_KEY); 1441 bulk_fetch::<PullRecord, Pull<DefaultStr>>(&state, uris).await 1442} 1443 1444const BULK_REPOS_KEY: &str = "repos"; 1445const BULK_PROFILES_KEY: &str = "actors"; 1446const BULK_ISSUES_KEY: &str = "issues"; 1447const BULK_PULLS_KEY: &str = "pulls"; 1448const BULK_LIMIT: usize = 50; 1449 1450fn collect_repeated(query: Option<&str>, key: &str) -> Vec<String> { 1451 let Some(q) = query else { 1452 return Vec::new(); 1453 }; 1454 form_urlencoded::parse(q.as_bytes()) 1455 .filter_map(|(k, v)| (k == key).then(|| v.into_owned())) 1456 .collect() 1457} 1458 1459async fn hydrate_record_view<V>( 1460 state: &AppState, 1461 nsid: &Nsid<DefaultStr>, 1462 uri: AtUri<DefaultStr>, 1463 sort_micros: u64, 1464) -> Result<Option<RecordView<V>>, XrpcError> 1465where 1466 V: serde::de::DeserializeOwned + NormalizeRepoRefs, 1467{ 1468 if let Some(source) = decode_knot_owned_source(&uri) { 1469 return synthesize_knot_owned_view::<V>(state, uri, source, sort_micros).await; 1470 } 1471 let body = resolve_for_view(state, nsid, uri).await?; 1472 let value: V = deserialize_or_upgrade::<V>(state, nsid, &body.value).await?; 1473 let Some(value) = value.normalize(&state.resolver).await else { 1474 return Ok(None); 1475 }; 1476 Ok(Some(RecordView { 1477 uri: body.uri.clone(), 1478 cid: Some(body.cid.clone()), 1479 value, 1480 })) 1481} 1482 1483async fn synthesize_knot_owned_view<V>( 1484 state: &AppState, 1485 uri: AtUri<DefaultStr>, 1486 source: KnotOwnedSource, 1487 sort_micros: u64, 1488) -> Result<Option<RecordView<V>>, XrpcError> 1489where 1490 V: serde::de::DeserializeOwned + NormalizeRepoRefs, 1491{ 1492 let Some(body) = synth_knot_owned_value(source, sort_micros) else { 1493 return Ok(None); 1494 }; 1495 let Ok(value) = serde_json::from_value::<V>(body) else { 1496 return Ok(None); 1497 }; 1498 let Some(value) = value.normalize(&state.resolver).await else { 1499 return Ok(None); 1500 }; 1501 Ok(Some(RecordView { 1502 uri, 1503 cid: None, 1504 value, 1505 })) 1506} 1507 1508fn synth_knot_owned_value(source: KnotOwnedSource, sort_micros: u64) -> Option<serde_json::Value> { 1509 let created_at = micros_to_rfc3339(sort_micros)?; 1510 match source { 1511 KnotOwnedSource::Member { knot, subject } => Some(serde_json::json!({ 1512 "domain": knot_did_host(&knot)?, 1513 "subject": subject.as_ref(), 1514 "createdAt": created_at, 1515 })), 1516 KnotOwnedSource::Collaborator { repo, subject } => Some(serde_json::json!({ 1517 "repo": repo.as_ref(), 1518 "subject": subject.as_ref(), 1519 "createdAt": created_at, 1520 })), 1521 } 1522} 1523 1524fn micros_to_rfc3339(micros: u64) -> Option<String> { 1525 let micros = i64::try_from(micros).ok()?; 1526 chrono::DateTime::from_timestamp_micros(micros) 1527 .map(|dt| dt.to_rfc3339_opts(chrono::SecondsFormat::Micros, true)) 1528} 1529 1530#[derive(Clone, Copy)] 1531enum HitProvenance { 1532 ClientSupplied, 1533 Indexed, 1534} 1535 1536fn is_index_evictable(err: &XrpcError) -> bool { 1537 matches!( 1538 err, 1539 XrpcError::NotFound 1540 | XrpcError::UpstreamGone(_) 1541 | XrpcError::InvalidRecord(_) 1542 | XrpcError::InvalidParams(_) 1543 ) 1544} 1545 1546fn drop_unhydratable<V>( 1547 provenance: HitProvenance, 1548 nsid: &Nsid<DefaultStr>, 1549 uri: &AtUri<DefaultStr>, 1550 result: Result<Option<V>, XrpcError>, 1551) -> Result<Option<V>, XrpcError> { 1552 match result { 1553 Ok(view) => Ok(view), 1554 Err(err @ (XrpcError::NotFound | XrpcError::UpstreamGone(_))) => { 1555 tracing::debug!( 1556 uri = %uri, 1557 nsid = %nsid.as_ref(), 1558 error = %err, 1559 "dropping gone hit during hydration", 1560 ); 1561 Ok(None) 1562 } 1563 Err(err @ XrpcError::UpstreamUnavailable(_)) => { 1564 tracing::warn!( 1565 uri = %uri, 1566 nsid = %nsid.as_ref(), 1567 error = %err, 1568 "dropping hit, upstream unavailable during hydration", 1569 ); 1570 Ok(None) 1571 } 1572 Err(err @ XrpcError::InvalidRecord(_)) => { 1573 tracing::warn!( 1574 uri = %uri, 1575 nsid = %nsid.as_ref(), 1576 error = %err, 1577 "dropping invalid hit during hydration", 1578 ); 1579 Ok(None) 1580 } 1581 Err(err @ XrpcError::InvalidParams(_)) => match provenance { 1582 HitProvenance::ClientSupplied => Err(err), 1583 HitProvenance::Indexed => { 1584 tracing::warn!( 1585 uri = %uri, 1586 nsid = %nsid.as_ref(), 1587 error = %err, 1588 "dropping malformed indexed hit during hydration", 1589 ); 1590 Ok(None) 1591 } 1592 }, 1593 Err(err @ (XrpcError::Internal(_) | XrpcError::Overloaded)) => Err(err), 1594 } 1595} 1596 1597fn hydrate_stream<T, Fut, V>( 1598 items: impl IntoIterator<Item = T>, 1599 produce: impl FnMut(T) -> Fut, 1600) -> impl Stream<Item = Result<V, XrpcError>> 1601where 1602 Fut: Future<Output = Result<Option<V>, XrpcError>>, 1603{ 1604 stream::iter(items) 1605 .map(produce) 1606 .buffered(FETCH_CONCURRENCY) 1607 .try_filter_map(|view| async move { Ok(view) }) 1608} 1609 1610fn hydrate_record_stream<V>( 1611 state: &AppState, 1612 nsid: Nsid<DefaultStr>, 1613 items: Vec<EdgeItem>, 1614 provenance: HitProvenance, 1615) -> impl Stream<Item = Result<RecordView<V>, XrpcError>> + Send + 'static 1616where 1617 V: serde::de::DeserializeOwned + Serialize + NormalizeRepoRefs + Send + 'static, 1618{ 1619 let owned = state.clone(); 1620 hydrate_stream(items, move |item| { 1621 let owned = owned.clone(); 1622 let nsid = nsid.clone(); 1623 async move { 1624 let EdgeItem { uri, sort_micros } = item; 1625 let result = hydrate_record_view::<V>(&owned, &nsid, uri.clone(), sort_micros).await; 1626 if matches!(provenance, HitProvenance::Indexed) 1627 && let Err(err) = &result 1628 && is_index_evictable(err) 1629 { 1630 owned.edges.remove_source(&uri); 1631 } 1632 drop_unhydratable(provenance, &nsid, &uri, result) 1633 } 1634 }) 1635} 1636 1637enum PagePhase { 1638 Head, 1639 Body { first: bool }, 1640 Done, 1641} 1642 1643struct PageState<S> { 1644 items: std::pin::Pin<Box<S>>, 1645 phase: PagePhase, 1646 array_key: &'static str, 1647 tail: Vec<u8>, 1648 permit: Option<HeavyPermit>, 1649} 1650 1651fn paged_tail(cursor: Option<String>) -> Vec<u8> { 1652 let encoded = serde_json::to_string(&cursor).unwrap_or_else(|_| "null".to_owned()); 1653 format!("],\"cursor\":{encoded}}}").into_bytes() 1654} 1655 1656fn unpaged_tail() -> Vec<u8> { 1657 b"]}".to_vec() 1658} 1659 1660fn json_stream<V, S>( 1661 array_key: &'static str, 1662 items: S, 1663 tail: Vec<u8>, 1664 permit: Option<HeavyPermit>, 1665) -> Response 1666where 1667 V: Serialize + Send + 'static, 1668 S: Stream<Item = Result<V, XrpcError>> + Send + 'static, 1669{ 1670 let init = PageState { 1671 items: Box::pin(items), 1672 phase: PagePhase::Head, 1673 array_key, 1674 tail, 1675 permit, 1676 }; 1677 let chunks = stream::unfold(init, |mut st| async move { 1678 match st.phase { 1679 PagePhase::Head => { 1680 let head = format!("{{\"{}\":[", st.array_key).into_bytes(); 1681 st.phase = PagePhase::Body { first: true }; 1682 Some((Ok::<Vec<u8>, Infallible>(head), st)) 1683 } 1684 PagePhase::Body { first } => match st.items.next().await { 1685 Some(Ok(view)) => match serde_json::to_vec(&Deduped(&view)) { 1686 Ok(encoded) => { 1687 let mut chunk = Vec::with_capacity(encoded.len() + 1); 1688 if !first { 1689 chunk.push(b','); 1690 } 1691 chunk.extend_from_slice(&encoded); 1692 st.phase = PagePhase::Body { first: false }; 1693 Some((Ok(chunk), st)) 1694 } 1695 Err(e) => { 1696 tracing::warn!(error = %e, "skipping hit, serialize failed mid-stream"); 1697 Some((Ok(Vec::new()), st)) 1698 } 1699 }, 1700 Some(Err(e)) => { 1701 tracing::warn!(error = %e, "ending page early, hydration failed mid-stream"); 1702 let tail = std::mem::take(&mut st.tail); 1703 st.phase = PagePhase::Done; 1704 Some((Ok(tail), st)) 1705 } 1706 None => { 1707 let tail = std::mem::take(&mut st.tail); 1708 st.phase = PagePhase::Done; 1709 Some((Ok(tail), st)) 1710 } 1711 }, 1712 PagePhase::Done => { 1713 drop(st.permit.take()); 1714 None 1715 } 1716 } 1717 }); 1718 ( 1719 [(CONTENT_TYPE, "application/json")], 1720 Body::from_stream(chunks), 1721 ) 1722 .into_response() 1723} 1724 1725async fn bulk_fetch<R, V>(state: &AppState, uris: Vec<String>) -> Result<Response, XrpcError> 1726where 1727 R: XrpcResp, 1728 V: serde::de::DeserializeOwned + Serialize + NormalizeRepoRefs + Send + 'static, 1729{ 1730 if uris.is_empty() { 1731 return Err(XrpcError::InvalidParams("at least one uri required".into())); 1732 } 1733 if uris.len() > BULK_LIMIT { 1734 return Err(XrpcError::InvalidParams(format!( 1735 "at most {BULK_LIMIT} uris per request" 1736 ))); 1737 } 1738 let parsed: Vec<AtUri<DefaultStr>> = uris 1739 .iter() 1740 .map(|s| parse_uri(s)) 1741 .collect::<Result<_, _>>()?; 1742 let nsid = nsid_static(R::NSID); 1743 if let Some(bad) = parsed 1744 .iter() 1745 .find(|uri| uri.collection().is_none_or(|c| c.as_ref() != nsid.as_ref())) 1746 { 1747 return Err(XrpcError::InvalidParams(format!( 1748 "uri collection must be {}, got {}", 1749 nsid.as_ref(), 1750 bad.as_ref() 1751 ))); 1752 } 1753 let permit = state.heavy_permit()?; 1754 let items = parsed 1755 .into_iter() 1756 .map(|uri| EdgeItem { 1757 uri, 1758 sort_micros: 0, 1759 }) 1760 .collect(); 1761 let views = hydrate_record_stream::<V>(state, nsid, items, HitProvenance::ClientSupplied); 1762 Ok(json_stream::<RecordView<V>, _>( 1763 "items", 1764 views, 1765 unpaged_tail(), 1766 permit, 1767 )) 1768} 1769 1770fn record_edge_page<R, F>( 1771 state: &AppState, 1772 q: &TypedListQuery<F>, 1773) -> Result<(EdgePage, Nsid<DefaultStr>), XrpcError> 1774where 1775 R: XrpcResp + HasSubject, 1776 F: ListFilter, 1777{ 1778 let subject = parse_subject(&q.subject, R::SHAPE)?; 1779 let cursor = parse_cursor(q.cursor.as_deref())?; 1780 let limit = parse_limit(q.limit)?; 1781 let dir = q.dir(); 1782 let nsid = nsid_static(R::NSID); 1783 let page = if q.filter.is_identity() { 1784 let key = EdgeKey::new(nsid.clone(), subject); 1785 state.edges.list(&key, cursor, limit, dir) 1786 } else { 1787 let pred = q.filter.predicate(state, &subject); 1788 let key = EdgeKey::new(nsid.clone(), subject); 1789 state.edges.list_filtered(&key, cursor, limit, dir, pred) 1790 }; 1791 Ok((page, nsid)) 1792} 1793 1794async fn list_records<R, V, F>( 1795 state: &AppState, 1796 q: TypedListQuery<F>, 1797) -> Result<Response, XrpcError> 1798where 1799 R: XrpcResp + HasSubject, 1800 V: serde::de::DeserializeOwned + Serialize + NormalizeRepoRefs + Send + 'static, 1801 F: ListFilter, 1802{ 1803 let (page, nsid) = record_edge_page::<R, F>(state, &q)?; 1804 let permit = state.heavy_permit()?; 1805 let views = hydrate_record_stream::<V>(state, nsid, page.items, HitProvenance::Indexed); 1806 Ok(json_stream::<RecordView<V>, _>( 1807 "items", 1808 views, 1809 paged_tail(page.next.map(PageToken::encode_token)), 1810 permit, 1811 )) 1812} 1813 1814fn count_for<R: XrpcResp + HasSubject>( 1815 state: &AppState, 1816 q: CountQuery, 1817) -> Result<CountResponse, XrpcError> { 1818 let subject = parse_subject(&q.subject, R::SHAPE)?; 1819 let key = EdgeKey::new(nsid_static(R::NSID), subject); 1820 Ok(CountResponse { 1821 count: state.edges.count(&key), 1822 distinct_authors: state.edges.count_distinct_authors(&key), 1823 }) 1824} 1825 1826fn mirror_edge_page<M, F>( 1827 state: &AppState, 1828 q: &TypedListQuery<F>, 1829) -> Result<(EdgePage, Nsid<DefaultStr>), XrpcError> 1830where 1831 M: MirrorOf, 1832 F: ListFilter, 1833{ 1834 let subject = parse_subject(&q.subject, M::SHAPE)?; 1835 let cursor = parse_cursor(q.cursor.as_deref())?; 1836 let limit = parse_limit(q.limit)?; 1837 let dir = q.dir(); 1838 let edge_nsid = nsid_static(M::EDGE_KIND); 1839 let page = if q.filter.is_identity() { 1840 let key = EdgeKey::new(edge_nsid, subject); 1841 state.edges.list(&key, cursor, limit, dir) 1842 } else { 1843 let pred = q.filter.predicate(state, &subject); 1844 let key = EdgeKey::new(edge_nsid, subject); 1845 state.edges.list_filtered(&key, cursor, limit, dir, pred) 1846 }; 1847 let record_nsid = nsid_static(<M::Record as XrpcResp>::NSID); 1848 Ok((page, record_nsid)) 1849} 1850 1851async fn list_mirror<M, V, F>(state: &AppState, q: TypedListQuery<F>) -> Result<Response, XrpcError> 1852where 1853 M: MirrorOf, 1854 V: serde::de::DeserializeOwned + Serialize + NormalizeRepoRefs + Send + 'static, 1855 F: ListFilter, 1856{ 1857 let (page, record_nsid) = mirror_edge_page::<M, F>(state, &q)?; 1858 let permit = state.heavy_permit()?; 1859 let views = hydrate_record_stream::<V>(state, record_nsid, page.items, HitProvenance::Indexed); 1860 Ok(json_stream::<RecordView<V>, _>( 1861 "items", 1862 views, 1863 paged_tail(page.next.map(PageToken::encode_token)), 1864 permit, 1865 )) 1866} 1867 1868fn count_mirror<M: MirrorOf>(state: &AppState, q: CountQuery) -> Result<CountResponse, XrpcError> { 1869 let subject = parse_subject(&q.subject, M::SHAPE)?; 1870 let key = EdgeKey::new(nsid_static(M::EDGE_KIND), subject); 1871 Ok(CountResponse { 1872 count: state.edges.count(&key), 1873 distinct_authors: state.edges.count_distinct_authors(&key), 1874 }) 1875} 1876 1877async fn list_stars( 1878 State(state): State<AppState>, 1879 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 1880) -> Result<Response, XrpcError> { 1881 list_records::<StarRecord, Star<DefaultStr>, _>(&state, q).await 1882} 1883 1884async fn count_stars( 1885 State(state): State<AppState>, 1886 XrpcQuery(q): XrpcQuery<CountQuery>, 1887) -> Result<Json<CountResponse>, XrpcError> { 1888 count_for::<StarRecord>(&state, q).map(Json) 1889} 1890 1891async fn list_follows( 1892 State(state): State<AppState>, 1893 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 1894) -> Result<Response, XrpcError> { 1895 list_records::<FollowRecord, Follow<DefaultStr>, _>(&state, q).await 1896} 1897 1898async fn count_follows( 1899 State(state): State<AppState>, 1900 XrpcQuery(q): XrpcQuery<CountQuery>, 1901) -> Result<Json<CountResponse>, XrpcError> { 1902 count_for::<FollowRecord>(&state, q).map(Json) 1903} 1904 1905async fn list_issues( 1906 State(state): State<AppState>, 1907 XrpcQuery(q): XrpcQuery<TypedListQuery<IssueFilter>>, 1908) -> Result<Response, XrpcError> { 1909 let (page, nsid) = record_edge_page::<IssueRecord, _>(&state, &q)?; 1910 let permit = state.heavy_permit()?; 1911 let owned = state.clone(); 1912 let items = hydrate_record_stream::<Issue<DefaultStr>>( 1913 &state, 1914 nsid, 1915 page.items, 1916 HitProvenance::Indexed, 1917 ) 1918 .map(move |view| view.map(|v| enrich_issue_view(&owned, v))); 1919 Ok(json_stream::<StatefulItem<Issue<DefaultStr>>, _>( 1920 "items", 1921 items, 1922 paged_tail(page.next.map(PageToken::encode_token)), 1923 permit, 1924 )) 1925} 1926 1927async fn count_issues( 1928 State(state): State<AppState>, 1929 XrpcQuery(q): XrpcQuery<CountQuery>, 1930) -> Result<Json<CountResponse>, XrpcError> { 1931 count_for::<IssueRecord>(&state, q).map(Json) 1932} 1933 1934async fn list_pulls( 1935 State(state): State<AppState>, 1936 XrpcQuery(q): XrpcQuery<TypedListQuery<PullFilter>>, 1937) -> Result<Response, XrpcError> { 1938 let (page, nsid) = record_edge_page::<PullRecord, _>(&state, &q)?; 1939 let permit = state.heavy_permit()?; 1940 let owned = state.clone(); 1941 let items = 1942 hydrate_record_stream::<Pull<DefaultStr>>(&state, nsid, page.items, HitProvenance::Indexed) 1943 .map(move |view| view.map(|v| enrich_pull_view(&owned, v))); 1944 Ok(json_stream::<StatefulItem<Pull<DefaultStr>>, _>( 1945 "items", 1946 items, 1947 paged_tail(page.next.map(PageToken::encode_token)), 1948 permit, 1949 )) 1950} 1951 1952async fn count_pulls( 1953 State(state): State<AppState>, 1954 XrpcQuery(q): XrpcQuery<CountQuery>, 1955) -> Result<Json<CountResponse>, XrpcError> { 1956 count_for::<PullRecord>(&state, q).map(Json) 1957} 1958 1959async fn list_feed_comments( 1960 State(state): State<AppState>, 1961 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 1962) -> Result<Response, XrpcError> { 1963 list_records::<FeedCommentRecord, FeedComment<DefaultStr>, _>(&state, q).await 1964} 1965 1966async fn count_feed_comments( 1967 State(state): State<AppState>, 1968 XrpcQuery(q): XrpcQuery<CountQuery>, 1969) -> Result<Json<CountResponse>, XrpcError> { 1970 count_for::<FeedCommentRecord>(&state, q).map(Json) 1971} 1972 1973async fn list_reactions( 1974 State(state): State<AppState>, 1975 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 1976) -> Result<Response, XrpcError> { 1977 list_records::<ReactionRecord, Reaction<DefaultStr>, _>(&state, q).await 1978} 1979 1980async fn count_reactions( 1981 State(state): State<AppState>, 1982 XrpcQuery(q): XrpcQuery<CountQuery>, 1983) -> Result<Json<CountResponse>, XrpcError> { 1984 count_for::<ReactionRecord>(&state, q).map(Json) 1985} 1986 1987async fn list_ref_updates( 1988 State(state): State<AppState>, 1989 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 1990) -> Result<Response, XrpcError> { 1991 list_records::<RefUpdateRecord, RefUpdate<DefaultStr>, _>(&state, q).await 1992} 1993 1994async fn count_ref_updates( 1995 State(state): State<AppState>, 1996 XrpcQuery(q): XrpcQuery<CountQuery>, 1997) -> Result<Json<CountResponse>, XrpcError> { 1998 count_for::<RefUpdateRecord>(&state, q).map(Json) 1999} 2000 2001async fn list_collaborators( 2002 State(state): State<AppState>, 2003 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2004) -> Result<Response, XrpcError> { 2005 list_records::<CollaboratorRecord, Collaborator<DefaultStr>, _>(&state, q).await 2006} 2007 2008async fn count_collaborators( 2009 State(state): State<AppState>, 2010 XrpcQuery(q): XrpcQuery<CountQuery>, 2011) -> Result<Json<CountResponse>, XrpcError> { 2012 count_for::<CollaboratorRecord>(&state, q).map(Json) 2013} 2014 2015async fn list_issue_states( 2016 State(state): State<AppState>, 2017 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2018) -> Result<Response, XrpcError> { 2019 list_records::<IssueStateRecord, IssueState<DefaultStr>, _>(&state, q).await 2020} 2021 2022async fn count_issue_states( 2023 State(state): State<AppState>, 2024 XrpcQuery(q): XrpcQuery<CountQuery>, 2025) -> Result<Json<CountResponse>, XrpcError> { 2026 count_for::<IssueStateRecord>(&state, q).map(Json) 2027} 2028 2029async fn list_pull_statuses( 2030 State(state): State<AppState>, 2031 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2032) -> Result<Response, XrpcError> { 2033 list_records::<PullStatusRecord, PullStatus<DefaultStr>, _>(&state, q).await 2034} 2035 2036async fn count_pull_statuses( 2037 State(state): State<AppState>, 2038 XrpcQuery(q): XrpcQuery<CountQuery>, 2039) -> Result<Json<CountResponse>, XrpcError> { 2040 count_for::<PullStatusRecord>(&state, q).map(Json) 2041} 2042 2043async fn list_repos( 2044 State(state): State<AppState>, 2045 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2046) -> Result<Response, XrpcError> { 2047 list_records::<RepoRecord, Repo<DefaultStr>, _>(&state, q).await 2048} 2049 2050async fn count_repos( 2051 State(state): State<AppState>, 2052 XrpcQuery(q): XrpcQuery<CountQuery>, 2053) -> Result<Json<CountResponse>, XrpcError> { 2054 count_for::<RepoRecord>(&state, q).map(Json) 2055} 2056 2057async fn list_knots( 2058 State(state): State<AppState>, 2059 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2060) -> Result<Response, XrpcError> { 2061 list_records::<KnotRecord, Knot<DefaultStr>, _>(&state, q).await 2062} 2063 2064async fn count_knots( 2065 State(state): State<AppState>, 2066 XrpcQuery(q): XrpcQuery<CountQuery>, 2067) -> Result<Json<CountResponse>, XrpcError> { 2068 count_for::<KnotRecord>(&state, q).map(Json) 2069} 2070 2071async fn list_spindles( 2072 State(state): State<AppState>, 2073 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2074) -> Result<Response, XrpcError> { 2075 list_records::<SpindleRecord, Spindle<DefaultStr>, _>(&state, q).await 2076} 2077 2078async fn count_spindles( 2079 State(state): State<AppState>, 2080 XrpcQuery(q): XrpcQuery<CountQuery>, 2081) -> Result<Json<CountResponse>, XrpcError> { 2082 count_for::<SpindleRecord>(&state, q).map(Json) 2083} 2084 2085async fn list_public_keys( 2086 State(state): State<AppState>, 2087 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2088) -> Result<Response, XrpcError> { 2089 list_records::<PublicKeyRecord, PublicKey<DefaultStr>, _>(&state, q).await 2090} 2091 2092async fn count_public_keys( 2093 State(state): State<AppState>, 2094 XrpcQuery(q): XrpcQuery<CountQuery>, 2095) -> Result<Json<CountResponse>, XrpcError> { 2096 count_for::<PublicKeyRecord>(&state, q).map(Json) 2097} 2098 2099async fn list_vouches( 2100 State(state): State<AppState>, 2101 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2102) -> Result<Response, XrpcError> { 2103 list_records::<VouchRecord, Vouch<DefaultStr>, _>(&state, q).await 2104} 2105 2106async fn count_vouches( 2107 State(state): State<AppState>, 2108 XrpcQuery(q): XrpcQuery<CountQuery>, 2109) -> Result<Json<CountResponse>, XrpcError> { 2110 count_for::<VouchRecord>(&state, q).map(Json) 2111} 2112 2113async fn list_stars_by( 2114 State(state): State<AppState>, 2115 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2116) -> Result<Response, XrpcError> { 2117 list_mirror::<StarBy, Star<DefaultStr>, _>(&state, q).await 2118} 2119async fn count_stars_by( 2120 State(state): State<AppState>, 2121 XrpcQuery(q): XrpcQuery<CountQuery>, 2122) -> Result<Json<CountResponse>, XrpcError> { 2123 count_mirror::<StarBy>(&state, q).map(Json) 2124} 2125 2126async fn list_reactions_by( 2127 State(state): State<AppState>, 2128 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2129) -> Result<Response, XrpcError> { 2130 list_mirror::<ReactionBy, Reaction<DefaultStr>, _>(&state, q).await 2131} 2132async fn count_reactions_by( 2133 State(state): State<AppState>, 2134 XrpcQuery(q): XrpcQuery<CountQuery>, 2135) -> Result<Json<CountResponse>, XrpcError> { 2136 count_mirror::<ReactionBy>(&state, q).map(Json) 2137} 2138 2139async fn list_follows_by( 2140 State(state): State<AppState>, 2141 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2142) -> Result<Response, XrpcError> { 2143 list_mirror::<FollowBy, Follow<DefaultStr>, _>(&state, q).await 2144} 2145async fn count_follows_by( 2146 State(state): State<AppState>, 2147 XrpcQuery(q): XrpcQuery<CountQuery>, 2148) -> Result<Json<CountResponse>, XrpcError> { 2149 count_mirror::<FollowBy>(&state, q).map(Json) 2150} 2151 2152async fn list_vouches_by( 2153 State(state): State<AppState>, 2154 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2155) -> Result<Response, XrpcError> { 2156 list_mirror::<VouchBy, Vouch<DefaultStr>, _>(&state, q).await 2157} 2158async fn count_vouches_by( 2159 State(state): State<AppState>, 2160 XrpcQuery(q): XrpcQuery<CountQuery>, 2161) -> Result<Json<CountResponse>, XrpcError> { 2162 count_mirror::<VouchBy>(&state, q).map(Json) 2163} 2164 2165async fn list_ref_updates_by( 2166 State(state): State<AppState>, 2167 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2168) -> Result<Response, XrpcError> { 2169 list_mirror::<RefUpdateBy, RefUpdate<DefaultStr>, _>(&state, q).await 2170} 2171async fn count_ref_updates_by( 2172 State(state): State<AppState>, 2173 XrpcQuery(q): XrpcQuery<CountQuery>, 2174) -> Result<Json<CountResponse>, XrpcError> { 2175 count_mirror::<RefUpdateBy>(&state, q).map(Json) 2176} 2177 2178async fn list_knot_members_by( 2179 State(state): State<AppState>, 2180 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2181) -> Result<Response, XrpcError> { 2182 list_mirror::<KnotMemberBy, KnotMember<DefaultStr>, _>(&state, q).await 2183} 2184async fn count_knot_members_by( 2185 State(state): State<AppState>, 2186 XrpcQuery(q): XrpcQuery<CountQuery>, 2187) -> Result<Json<CountResponse>, XrpcError> { 2188 count_mirror::<KnotMemberBy>(&state, q).map(Json) 2189} 2190 2191async fn list_label_ops_by( 2192 State(state): State<AppState>, 2193 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2194) -> Result<Response, XrpcError> { 2195 list_mirror::<LabelOpBy, LabelOp<DefaultStr>, _>(&state, q).await 2196} 2197async fn count_label_ops_by( 2198 State(state): State<AppState>, 2199 XrpcQuery(q): XrpcQuery<CountQuery>, 2200) -> Result<Json<CountResponse>, XrpcError> { 2201 count_mirror::<LabelOpBy>(&state, q).map(Json) 2202} 2203 2204async fn list_pipelines_by( 2205 State(state): State<AppState>, 2206 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2207) -> Result<Response, XrpcError> { 2208 list_mirror::<PipelineBy, Pipeline<DefaultStr>, _>(&state, q).await 2209} 2210async fn count_pipelines_by( 2211 State(state): State<AppState>, 2212 XrpcQuery(q): XrpcQuery<CountQuery>, 2213) -> Result<Json<CountResponse>, XrpcError> { 2214 count_mirror::<PipelineBy>(&state, q).map(Json) 2215} 2216 2217async fn list_pipeline_statuses_by( 2218 State(state): State<AppState>, 2219 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2220) -> Result<Response, XrpcError> { 2221 list_mirror::<PipelineStatusBy, PipelineStatus<DefaultStr>, _>(&state, q).await 2222} 2223async fn count_pipeline_statuses_by( 2224 State(state): State<AppState>, 2225 XrpcQuery(q): XrpcQuery<CountQuery>, 2226) -> Result<Json<CountResponse>, XrpcError> { 2227 count_mirror::<PipelineStatusBy>(&state, q).map(Json) 2228} 2229 2230async fn list_artifacts_by( 2231 State(state): State<AppState>, 2232 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2233) -> Result<Response, XrpcError> { 2234 list_mirror::<ArtifactBy, Artifact<DefaultStr>, _>(&state, q).await 2235} 2236async fn count_artifacts_by( 2237 State(state): State<AppState>, 2238 XrpcQuery(q): XrpcQuery<CountQuery>, 2239) -> Result<Json<CountResponse>, XrpcError> { 2240 count_mirror::<ArtifactBy>(&state, q).map(Json) 2241} 2242 2243async fn list_collaborators_by( 2244 State(state): State<AppState>, 2245 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2246) -> Result<Response, XrpcError> { 2247 list_mirror::<CollaboratorBy, Collaborator<DefaultStr>, _>(&state, q).await 2248} 2249async fn count_collaborators_by( 2250 State(state): State<AppState>, 2251 XrpcQuery(q): XrpcQuery<CountQuery>, 2252) -> Result<Json<CountResponse>, XrpcError> { 2253 count_mirror::<CollaboratorBy>(&state, q).map(Json) 2254} 2255 2256async fn list_issues_by( 2257 State(state): State<AppState>, 2258 XrpcQuery(q): XrpcQuery<TypedListQuery<IssueFilter>>, 2259) -> Result<Response, XrpcError> { 2260 let (page, nsid) = mirror_edge_page::<IssueBy, _>(&state, &q)?; 2261 let permit = state.heavy_permit()?; 2262 let owned = state.clone(); 2263 let items = hydrate_record_stream::<Issue<DefaultStr>>( 2264 &state, 2265 nsid, 2266 page.items, 2267 HitProvenance::Indexed, 2268 ) 2269 .map(move |view| view.map(|v| enrich_issue_view(&owned, v))); 2270 Ok(json_stream::<StatefulItem<Issue<DefaultStr>>, _>( 2271 "items", 2272 items, 2273 paged_tail(page.next.map(PageToken::encode_token)), 2274 permit, 2275 )) 2276} 2277async fn count_issues_by( 2278 State(state): State<AppState>, 2279 XrpcQuery(q): XrpcQuery<CountQuery>, 2280) -> Result<Json<CountResponse>, XrpcError> { 2281 count_mirror::<IssueBy>(&state, q).map(Json) 2282} 2283 2284async fn list_feed_comments_by( 2285 State(state): State<AppState>, 2286 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2287) -> Result<Response, XrpcError> { 2288 list_mirror::<FeedCommentBy, FeedComment<DefaultStr>, _>(&state, q).await 2289} 2290async fn count_feed_comments_by( 2291 State(state): State<AppState>, 2292 XrpcQuery(q): XrpcQuery<CountQuery>, 2293) -> Result<Json<CountResponse>, XrpcError> { 2294 count_mirror::<FeedCommentBy>(&state, q).map(Json) 2295} 2296 2297async fn list_issue_states_by( 2298 State(state): State<AppState>, 2299 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2300) -> Result<Response, XrpcError> { 2301 list_mirror::<IssueStateBy, IssueState<DefaultStr>, _>(&state, q).await 2302} 2303async fn count_issue_states_by( 2304 State(state): State<AppState>, 2305 XrpcQuery(q): XrpcQuery<CountQuery>, 2306) -> Result<Json<CountResponse>, XrpcError> { 2307 count_mirror::<IssueStateBy>(&state, q).map(Json) 2308} 2309 2310async fn list_pulls_by( 2311 State(state): State<AppState>, 2312 XrpcQuery(q): XrpcQuery<TypedListQuery<PullFilter>>, 2313) -> Result<Response, XrpcError> { 2314 let (page, nsid) = mirror_edge_page::<PullBy, _>(&state, &q)?; 2315 let permit = state.heavy_permit()?; 2316 let owned = state.clone(); 2317 let items = 2318 hydrate_record_stream::<Pull<DefaultStr>>(&state, nsid, page.items, HitProvenance::Indexed) 2319 .map(move |view| view.map(|v| enrich_pull_view(&owned, v))); 2320 Ok(json_stream::<StatefulItem<Pull<DefaultStr>>, _>( 2321 "items", 2322 items, 2323 paged_tail(page.next.map(PageToken::encode_token)), 2324 permit, 2325 )) 2326} 2327async fn count_pulls_by( 2328 State(state): State<AppState>, 2329 XrpcQuery(q): XrpcQuery<CountQuery>, 2330) -> Result<Json<CountResponse>, XrpcError> { 2331 count_mirror::<PullBy>(&state, q).map(Json) 2332} 2333 2334async fn list_pull_statuses_by( 2335 State(state): State<AppState>, 2336 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2337) -> Result<Response, XrpcError> { 2338 list_mirror::<PullStatusBy, PullStatus<DefaultStr>, _>(&state, q).await 2339} 2340async fn count_pull_statuses_by( 2341 State(state): State<AppState>, 2342 XrpcQuery(q): XrpcQuery<CountQuery>, 2343) -> Result<Json<CountResponse>, XrpcError> { 2344 count_mirror::<PullStatusBy>(&state, q).map(Json) 2345} 2346 2347async fn list_spindle_members_by( 2348 State(state): State<AppState>, 2349 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2350) -> Result<Response, XrpcError> { 2351 list_mirror::<SpindleMemberBy, SpindleMember<DefaultStr>, _>(&state, q).await 2352} 2353async fn count_spindle_members_by( 2354 State(state): State<AppState>, 2355 XrpcQuery(q): XrpcQuery<CountQuery>, 2356) -> Result<Json<CountResponse>, XrpcError> { 2357 count_mirror::<SpindleMemberBy>(&state, q).map(Json) 2358} 2359 2360async fn list_label_definitions( 2361 State(state): State<AppState>, 2362 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2363) -> Result<Response, XrpcError> { 2364 list_records::<LabelDefinitionRecord, LabelDefinition<DefaultStr>, _>(&state, q).await 2365} 2366 2367async fn count_label_definitions( 2368 State(state): State<AppState>, 2369 XrpcQuery(q): XrpcQuery<CountQuery>, 2370) -> Result<Json<CountResponse>, XrpcError> { 2371 count_for::<LabelDefinitionRecord>(&state, q).map(Json) 2372} 2373 2374async fn list_label_ops( 2375 State(state): State<AppState>, 2376 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2377) -> Result<Response, XrpcError> { 2378 list_records::<LabelOpRecord, LabelOp<DefaultStr>, _>(&state, q).await 2379} 2380 2381async fn count_label_ops( 2382 State(state): State<AppState>, 2383 XrpcQuery(q): XrpcQuery<CountQuery>, 2384) -> Result<Json<CountResponse>, XrpcError> { 2385 count_for::<LabelOpRecord>(&state, q).map(Json) 2386} 2387 2388async fn list_pipelines( 2389 State(state): State<AppState>, 2390 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2391) -> Result<Response, XrpcError> { 2392 list_records::<PipelineRecord, Pipeline<DefaultStr>, _>(&state, q).await 2393} 2394 2395async fn count_pipelines( 2396 State(state): State<AppState>, 2397 XrpcQuery(q): XrpcQuery<CountQuery>, 2398) -> Result<Json<CountResponse>, XrpcError> { 2399 count_for::<PipelineRecord>(&state, q).map(Json) 2400} 2401 2402async fn list_pipeline_statuses( 2403 State(state): State<AppState>, 2404 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2405) -> Result<Response, XrpcError> { 2406 list_records::<PipelineStatusRecord, PipelineStatus<DefaultStr>, _>(&state, q).await 2407} 2408 2409async fn count_pipeline_statuses( 2410 State(state): State<AppState>, 2411 XrpcQuery(q): XrpcQuery<CountQuery>, 2412) -> Result<Json<CountResponse>, XrpcError> { 2413 count_for::<PipelineStatusRecord>(&state, q).map(Json) 2414} 2415 2416async fn list_artifacts( 2417 State(state): State<AppState>, 2418 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2419) -> Result<Response, XrpcError> { 2420 list_records::<ArtifactRecord, Artifact<DefaultStr>, _>(&state, q).await 2421} 2422 2423async fn count_artifacts( 2424 State(state): State<AppState>, 2425 XrpcQuery(q): XrpcQuery<CountQuery>, 2426) -> Result<Json<CountResponse>, XrpcError> { 2427 count_for::<ArtifactRecord>(&state, q).map(Json) 2428} 2429 2430async fn list_knot_members( 2431 State(state): State<AppState>, 2432 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2433) -> Result<Response, XrpcError> { 2434 list_records::<KnotMemberRecord, KnotMember<DefaultStr>, _>(&state, q).await 2435} 2436 2437async fn count_knot_members( 2438 State(state): State<AppState>, 2439 XrpcQuery(q): XrpcQuery<CountQuery>, 2440) -> Result<Json<CountResponse>, XrpcError> { 2441 count_for::<KnotMemberRecord>(&state, q).map(Json) 2442} 2443 2444async fn list_spindle_members( 2445 State(state): State<AppState>, 2446 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2447) -> Result<Response, XrpcError> { 2448 list_records::<SpindleMemberRecord, SpindleMember<DefaultStr>, _>(&state, q).await 2449} 2450 2451async fn count_spindle_members( 2452 State(state): State<AppState>, 2453 XrpcQuery(q): XrpcQuery<CountQuery>, 2454) -> Result<Json<CountResponse>, XrpcError> { 2455 count_for::<SpindleMemberRecord>(&state, q).map(Json) 2456} 2457 2458async fn list_strings( 2459 State(state): State<AppState>, 2460 XrpcQuery(q): XrpcQuery<TypedListQuery<NoFilter>>, 2461) -> Result<Response, XrpcError> { 2462 list_records::<TangledStringRecord, TangledString<DefaultStr>, _>(&state, q).await 2463} 2464 2465async fn count_strings( 2466 State(state): State<AppState>, 2467 XrpcQuery(q): XrpcQuery<CountQuery>, 2468) -> Result<Json<CountResponse>, XrpcError> { 2469 count_for::<TangledStringRecord>(&state, q).map(Json) 2470} 2471 2472#[derive(Deserialize)] 2473struct ResolveMiniDocParams { 2474 identifier: AtIdentifier<DefaultStr>, 2475} 2476 2477async fn resolve_mini_doc( 2478 State(state): State<AppState>, 2479 XrpcQuery(q): XrpcQuery<ResolveMiniDocParams>, 2480) -> Result<Response, XrpcError> { 2481 let body = state 2482 .slingshot 2483 .resolve_mini_doc(&q.identifier) 2484 .await 2485 .map_err(map_slingshot)?; 2486 Ok((StatusCode::OK, [(CONTENT_TYPE, "application/json")], body).into_response()) 2487} 2488 2489async fn get_coverage(State(state): State<AppState>) -> Json<CoverageEnvelope> { 2490 Json(state.coverage.snapshot().into()) 2491} 2492 2493async fn search_query( 2494 State(state): State<AppState>, 2495 XrpcQuery(q): XrpcQuery<SearchQueryParams>, 2496) -> Result<Response, XrpcError> { 2497 if q.q.trim().is_empty() { 2498 return Err(XrpcError::InvalidParams("q must not be empty".into())); 2499 } 2500 let cursor = SearchCursor::from_token(q.cursor.as_deref()) 2501 .map_err(|e| XrpcError::InvalidParams(format!("cursor: {e}")))?; 2502 let limit = parse_limit(q.limit)?; 2503 let filters = build_search_filters(&q)?; 2504 let permit = state.heavy_permit()?; 2505 let page = state 2506 .search 2507 .search(&q.q, filters, cursor, limit.get()) 2508 .await 2509 .map_err(map_search_err)?; 2510 let next = page.next.map(SearchOffset::encode_token); 2511 let owned = state.clone(); 2512 let hits = hydrate_stream(page.hits, move |hit| { 2513 let owned = owned.clone(); 2514 let uri = hit.uri.clone(); 2515 let nsid = hit.nsid.clone(); 2516 async move { 2517 let result = hydrate_search_hit(&owned, hit).await; 2518 drop_unhydratable(HitProvenance::Indexed, &nsid, &uri, result) 2519 } 2520 }); 2521 Ok(json_stream::<SearchHitView, _>( 2522 "hits", 2523 hits, 2524 paged_tail(next), 2525 permit, 2526 )) 2527} 2528 2529fn build_search_filters(q: &SearchQueryParams) -> Result<SearchFilters, XrpcError> { 2530 let since = q 2531 .since 2532 .as_deref() 2533 .map(parse_rfc3339_seconds) 2534 .transpose() 2535 .map_err(|e| XrpcError::InvalidParams(format!("since: {e}")))?; 2536 let until = q 2537 .until 2538 .as_deref() 2539 .map(parse_rfc3339_seconds) 2540 .transpose() 2541 .map_err(|e| XrpcError::InvalidParams(format!("until: {e}")))?; 2542 if let (Some(s), Some(u)) = (since, until) 2543 && s > u 2544 { 2545 return Err(XrpcError::InvalidParams("since must be <= until".into())); 2546 } 2547 Ok(SearchFilters { 2548 nsid: q.nsid.clone(), 2549 author: q.author.clone(), 2550 repo: q.repo.clone(), 2551 since, 2552 until, 2553 }) 2554} 2555 2556fn parse_rfc3339_seconds(raw: &str) -> Result<i64, String> { 2557 chrono::DateTime::parse_from_rfc3339(raw) 2558 .map(|dt| dt.timestamp()) 2559 .map_err(|e| format!("expected RFC3339, got {raw}: {e}")) 2560} 2561 2562async fn hydrate_search_hit( 2563 state: &AppState, 2564 hit: SearchHit, 2565) -> Result<Option<SearchHitView>, XrpcError> { 2566 let SearchHit { uri, nsid, score } = hit; 2567 let body = resolve_for_view(state, &nsid, uri).await?; 2568 let record = decode_canon_or_upgrade(&nsid, &body.value, &state.resolver) 2569 .await 2570 .map_err(|err| XrpcError::InvalidRecord(err.to_string()))?; 2571 let Some(value) = SearchableRecord::try_from_record(record) else { 2572 return Ok(None); 2573 }; 2574 let Some(value) = value.normalize(&state.resolver).await else { 2575 return Ok(None); 2576 }; 2577 Ok(Some(SearchHitView { 2578 uri: body.uri.clone(), 2579 cid: Some(body.cid.clone()), 2580 nsid, 2581 score, 2582 value, 2583 })) 2584} 2585 2586fn map_search_err(err: SearchError) -> XrpcError { 2587 use SearchError as E; 2588 match err { 2589 E::Query(e) => XrpcError::InvalidParams(format!("query: {e}")), 2590 e @ (E::Tantivy(_) 2591 | E::InvalidUri(_) 2592 | E::InvalidNsid(_) 2593 | E::MissingField(_) 2594 | E::Cancelled(_)) => XrpcError::Internal(format!("search: {e}")), 2595 } 2596} 2597 2598fn map_proxy_error(err: KnotProxyError) -> XrpcError { 2599 match err { 2600 KnotProxyError::CircuitOpen => { 2601 XrpcError::UpstreamUnavailable("knot circuit breaker open".into()) 2602 } 2603 KnotProxyError::BlockedHost { host, reason } => { 2604 XrpcError::InvalidRecord(format!("knot host {host} is {reason} address space")) 2605 } 2606 KnotProxyError::PlaintextHttp { host } => { 2607 XrpcError::InvalidRecord(format!("knot host {host} requires https")) 2608 } 2609 KnotProxyError::Connect(e) => XrpcError::UpstreamUnavailable(format!("connect: {e}")), 2610 KnotProxyError::Timeout(e) => { 2611 XrpcError::UpstreamUnavailable(format!("upstream timeout: {e}")) 2612 } 2613 KnotProxyError::Redirect(e) => XrpcError::UpstreamUnavailable(format!("redirect: {e}")), 2614 KnotProxyError::Transport(e) => XrpcError::UpstreamUnavailable(format!("transport: {e}")), 2615 KnotProxyError::Upstream(s) => XrpcError::UpstreamUnavailable(format!("status {s}")), 2616 } 2617} 2618 2619fn validate_client_supplied_knot(state: &AppState, host: &KnotHost) -> Result<(), XrpcError> { 2620 let host_str = || host.url().host_str().unwrap_or_default().to_owned(); 2621 if state.knots.requires_https() && host.url().scheme() != "https" { 2622 return Err(XrpcError::InvalidParams(format!( 2623 "knot host {} must be https", 2624 host_str(), 2625 ))); 2626 } 2627 if state.knots.allows_private_hosts() { 2628 return Ok(()); 2629 } 2630 match host.private_literal_reason() { 2631 None => Ok(()), 2632 Some(reason) => Err(XrpcError::InvalidParams(format!( 2633 "knot host {} blocked: {} address space", 2634 host_str(), 2635 reason, 2636 ))), 2637 } 2638} 2639 2640async fn resolve_knot_target( 2641 state: &AppState, 2642 repo_uri: AtUri<DefaultStr>, 2643) -> Result<(KnotHost, RepoSlug), XrpcError> { 2644 let rkey: Option<Rkey<DefaultStr>> = repo_uri.rkey().map(|r| r.clone().into_static()); 2645 let (body, did) = resolve(state, ExpectedNsid::from_static(RepoRecord::NSID), repo_uri).await?; 2646 let value: Repo<DefaultStr> = serde_json::from_slice(&body.value) 2647 .map_err(|e| XrpcError::InvalidRecord(format!("decode repo record: {e}")))?; 2648 let host = KnotHost::parse(value.knot.as_ref()) 2649 .map_err(|e| XrpcError::InvalidRecord(format!("knot field: {e}")))?; 2650 let name = pick_human_slug(rkey.as_ref(), value.name.as_deref()).ok_or_else(|| { 2651 XrpcError::InvalidRecord("at-uri missing rkey and record missing name".to_string()) 2652 })?; 2653 let slug = RepoSlug::new(&did, &name) 2654 .map_err(|e| XrpcError::InvalidRecord(format!("repo slug: {e}")))?; 2655 Ok((host, slug)) 2656} 2657 2658fn pick_human_slug(rkey: Option<&Rkey<DefaultStr>>, name: Option<&str>) -> Option<String> { 2659 match rkey { 2660 Some(r) if jacquard_common::types::tid::Tid::new(r.as_ref()).is_ok() => { 2661 Some(name.unwrap_or(r.as_ref()).to_owned()) 2662 } 2663 Some(r) => Some(r.as_ref().to_owned()), 2664 None => name.map(str::to_owned), 2665 } 2666} 2667 2668fn filter_request_headers( 2669 client: &HeaderMap, 2670 socket: SocketPeer, 2671 address: &ClientAddress, 2672) -> HeaderMap { 2673 let forwarded = FORWARDED_REQUEST_HEADERS 2674 .iter() 2675 .fold(HeaderMap::new(), |mut acc, name| { 2676 if let Some(value) = client.get(*name) { 2677 acc.insert((*name).clone(), value.clone()); 2678 } 2679 acc 2680 }); 2681 address 2682 .of(client, socket) 2683 .into_iter() 2684 .fold(forwarded, |mut acc, address| { 2685 acc.insert(X_FORWARDED_FOR.clone(), address); 2686 acc 2687 }) 2688} 2689 2690fn upstream_to_axum(resp: ProxyResponse) -> Response { 2691 let status = resp.status(); 2692 let upstream_headers = resp.headers().clone(); 2693 let body = Body::from_stream(resp.into_body_stream()); 2694 let mut response = Response::builder() 2695 .status(status) 2696 .body(body) 2697 .expect("response body construction must succeed"); 2698 let response_headers = response.headers_mut(); 2699 PASSTHROUGH_HEADERS.iter().for_each(|name| { 2700 if let Some(value) = upstream_headers.get(*name) { 2701 response_headers.insert((*name).clone(), value.clone()); 2702 } 2703 }); 2704 response 2705} 2706 2707async fn dispatch_proxy( 2708 state: AppState, 2709 headers: HeaderMap, 2710 socket: SocketPeer, 2711 nsid: Nsid<DefaultStr>, 2712 host: KnotHost, 2713 params: ProxyParams, 2714) -> Result<Response, XrpcError> { 2715 let forward: Vec<(&str, &str)> = params 2716 .iter() 2717 .map(|(k, v)| (k.as_str(), v.as_str())) 2718 .collect(); 2719 let allowed = filter_request_headers(&headers, socket, &state.client_address); 2720 let upstream = state 2721 .knots 2722 .forward(&host, &nsid, &forward, allowed) 2723 .await 2724 .map_err(map_proxy_error)?; 2725 Ok(upstream_to_axum(upstream)) 2726} 2727 2728fn extract_param( 2729 params: ProxyParams, 2730 key: &str, 2731) -> Result<Option<(String, ProxyParams)>, XrpcError> { 2732 let (matching, rest): (ProxyParams, ProxyParams) = 2733 params.into_iter().partition(|(k, _)| k == key); 2734 match matching.as_slice() { 2735 [] => Ok(None), 2736 [_] => Ok(matching.into_iter().next().map(|(_, v)| (v, rest))), 2737 _ => Err(XrpcError::InvalidParams(format!( 2738 "{key} parameter must appear at most once, got {}", 2739 matching.len(), 2740 ))), 2741 } 2742} 2743 2744async fn proxy_repo_handler( 2745 state: AppState, 2746 headers: HeaderMap, 2747 socket: SocketPeer, 2748 params: ProxyParams, 2749 nsid: Nsid<DefaultStr>, 2750) -> Result<Response, XrpcError> { 2751 let (repo_raw, rest) = extract_param(params, REPO_PARAM)? 2752 .ok_or_else(|| XrpcError::InvalidParams("missing repo".into()))?; 2753 let repo_uri = parse_uri(&repo_raw)?; 2754 let (host, slug) = resolve_knot_target(&state, repo_uri).await?; 2755 let forward = rest 2756 .into_iter() 2757 .chain(std::iter::once(( 2758 REPO_PARAM.to_owned(), 2759 slug.as_str().to_owned(), 2760 ))) 2761 .collect(); 2762 dispatch_proxy(state, headers, socket, nsid, host, forward).await 2763} 2764 2765async fn proxy_knot_handler( 2766 state: AppState, 2767 headers: HeaderMap, 2768 socket: SocketPeer, 2769 params: ProxyParams, 2770 nsid: Nsid<DefaultStr>, 2771) -> Result<Response, XrpcError> { 2772 let (knot_raw, forward) = extract_param(params, KNOT_HOST_PARAM)? 2773 .ok_or_else(|| XrpcError::InvalidParams("missing knot".into()))?; 2774 let host = 2775 KnotHost::parse(&knot_raw).map_err(|e| XrpcError::InvalidParams(format!("knot: {e}")))?; 2776 validate_client_supplied_knot(&state, &host)?; 2777 dispatch_proxy(state, headers, socket, nsid, host, forward).await 2778}