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