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