use std::future::Future; use std::sync::Arc; use bobbin_resolver::{ NormalizeRepoRefs, decode_canon_or_upgrade, normalize_record_fields, scrub_record_bytes, upgrade_wire_bytes, }; use axum::{ Router, body::Body, extract::{FromRequestParts, Query, RawQuery, State, rejection::QueryRejection}, http::{ HeaderMap, HeaderName, StatusCode, header::{ ACCEPT_RANGES, CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_RANGE, CONTENT_TYPE, ETAG, IF_MODIFIED_SINCE, IF_NONE_MATCH, IF_RANGE, LAST_MODIFIED, RANGE, }, request::Parts, }, response::{IntoResponse, Json, Response}, routing::get, }; use bobbin_edge_index::{ Coverage, CoverageWatch, CursorParseError, EdgeItem, EdgePage, EdgeStore, IssueStateKind, PageCursor, PageLimit, PageToken, PullStatusKind, SortDir, StateIndex, StateKind, }; use bobbin_knot_proxy::{KnotHost, KnotProxy, KnotProxyError, ProxyResponse, RepoSlug}; use bobbin_record_lru::RecordStore; use bobbin_resolver::{IdentityResolveError, IdentityResolver, RepoIdResolver}; use bobbin_runtime::ReqwestHttp; use bobbin_search::{ SearchCursor, SearchError, SearchFilters, SearchHit, SearchOffset, SearchReader, }; use bobbin_slingshot_client::{SlingshotClient, SlingshotError}; use bobbin_types::edges::REPO_SOURCE_EDGE_KIND; use bobbin_types::ids::{EdgeKey, SubjectRef, nsid_static}; use bobbin_types::knot_acl::{KnotOwnedSource, decode_knot_owned_source, knot_did_host}; use bobbin_types::record::RecordBody; use bobbin_types::search::SearchableRecord; use bobbin_types::sh_tangled::actor::profile::{Profile, ProfileGetRecordOutput, ProfileRecord}; use bobbin_types::sh_tangled::feed::comment::{ Comment as FeedComment, CommentRecord as FeedCommentRecord, }; use bobbin_types::sh_tangled::feed::reaction::{Reaction, ReactionRecord}; use bobbin_types::sh_tangled::feed::star::{Star, StarRecord}; use bobbin_types::sh_tangled::git::ref_update::{RefUpdate, RefUpdateRecord}; use bobbin_types::sh_tangled::graph::follow::{Follow, FollowRecord}; use bobbin_types::sh_tangled::graph::vouch::{Vouch, VouchRecord}; use bobbin_types::sh_tangled::knot::member::{ Member as KnotMember, MemberRecord as KnotMemberRecord, }; use bobbin_types::sh_tangled::knot::{Knot, KnotRecord}; use bobbin_types::sh_tangled::label::definition::{ Definition as LabelDefinition, DefinitionRecord as LabelDefinitionRecord, }; use bobbin_types::sh_tangled::label::op::{Op as LabelOp, OpRecord as LabelOpRecord}; use bobbin_types::sh_tangled::pipeline::status::{ Status as PipelineStatus, StatusRecord as PipelineStatusRecord, }; use bobbin_types::sh_tangled::pipeline::{Pipeline, PipelineRecord}; use bobbin_types::sh_tangled::public_key::{PublicKey, PublicKeyGetRecordOutput, PublicKeyRecord}; use bobbin_types::sh_tangled::repo::artifact::{Artifact, ArtifactRecord}; use bobbin_types::sh_tangled::repo::collaborator::{Collaborator, CollaboratorRecord}; use bobbin_types::sh_tangled::repo::issue::state::{ State as IssueState, StateRecord as IssueStateRecord, }; use bobbin_types::sh_tangled::repo::issue::{Issue, IssueGetRecordOutput, IssueRecord}; use bobbin_types::sh_tangled::repo::pull::status::{ Status as PullStatus, StatusRecord as PullStatusRecord, }; use bobbin_types::sh_tangled::repo::pull::{Pull, PullGetRecordOutput, PullRecord}; use bobbin_types::sh_tangled::repo::{Repo, RepoGetRecordOutput, RepoRecord}; use bobbin_types::sh_tangled::spindle::member::{ Member as SpindleMember, MemberRecord as SpindleMemberRecord, }; use bobbin_types::sh_tangled::spindle::{Spindle, SpindleRecord}; use bobbin_types::sh_tangled::string::{ TangledString, TangledStringGetRecordOutput, TangledStringRecord, }; use futures::Stream; use futures::stream::{self, StreamExt, TryStreamExt}; use jacquard_common::types::did::Did; use jacquard_common::types::ident::AtIdentifier; use jacquard_common::types::nsid::Nsid; use jacquard_common::types::recordkey::Rkey; use jacquard_common::types::string::{AtUri, Cid}; use jacquard_common::xrpc::XrpcResp; use jacquard_common::{DefaultStr, IntoStatic}; use jacquard_identity::JacquardResolver; use serde::{Deserialize, Serialize}; use std::convert::Infallible; use std::time::Duration; use thiserror::Error; use url::form_urlencoded; use tower_http::classify::ServerErrorsFailureClass; use tower_http::trace::{DefaultMakeSpan, OnFailure, OnResponse, TraceLayer}; use tracing::{Level, Span}; mod backpressure; mod client_address; mod enrich; mod feed; mod filter; mod recordpath; pub use backpressure::{ HeavyLimiter, HeavyPermit, MaxInFlight, PerRequestAnonBytes, PressureVerdict, ReservedFloor, }; use client_address::X_FORWARDED_FOR; pub use client_address::{ClientAddress, SocketPeer}; use filter::{CountFilter, IssueFilter, ListFilter, NoFilter, PullFilter}; use trusted_proxies::TrustedProxies; const DEFAULT_LIMIT: u32 = 50; const FETCH_CONCURRENCY: usize = 8; pub type Directory = JacquardResolver; pub fn default_directory() -> Directory { JacquardResolver::new(ReqwestHttp::new(reqwest::Client::new()), Default::default()) } #[derive(Clone)] pub struct AppState { pub records: Arc, pub slingshot: SlingshotClient, pub edges: Arc, pub issue_states: Arc>, pub pull_statuses: Arc>, pub coverage: Arc, pub knots: Arc, pub search: Arc, pub resolver: Arc, pub identity: Arc, pub directory: Arc, pub limiter: Option>, pub client_address: Arc, enrich_router: Arc>, } impl AppState { #[allow(clippy::too_many_arguments)] pub fn new( records: Arc, slingshot: SlingshotClient, edges: Arc, issue_states: Arc>, pull_statuses: Arc>, coverage: Arc, knots: Arc, search: Arc, resolver: Arc, directory: Arc, ) -> Self { let identity = Arc::new(IdentityResolver::with_slingshot( slingshot.clone(), bobbin_runtime::RuntimeHasher::default(), )); Self { records, slingshot, edges, issue_states, pull_statuses, coverage, knots, search, resolver, identity, directory, limiter: None, client_address: Arc::new(ClientAddress::default()), enrich_router: Arc::new(std::sync::OnceLock::new()), } } pub fn with_limiter(mut self, limiter: Option>) -> Self { self.limiter = limiter; self } pub fn with_identity(mut self, identity: Arc) -> Self { self.identity = identity; self } pub fn with_proxies(mut self, proxies: TrustedProxies) -> Self { self.client_address = Arc::new(ClientAddress::new(proxies)); self } /// for internal xrpc dispatch [`enrich`] pub fn self_router(&self) -> Router { self.enrich_router .get_or_init(|| router(self.clone())) .clone() } pub(crate) fn heavy_permit(&self) -> Result, XrpcError> { self.limiter.as_ref().map(|l| l.try_enter()).transpose() } } pub fn router(state: AppState) -> Router { Router::new() .route("/xrpc/sh.tangled.repo.getRepo", get(get_repo)) .route("/xrpc/sh.tangled.repo.getRepos", get(get_repos)) .route( "/xrpc/sh.tangled.repo.getRepoByRepoDid", get(get_repo_by_repo_did), ) .route( "/xrpc/sh.tangled.repo.getReposByRepoDids", get(get_repos_by_repo_dids), ) .route("/xrpc/sh.tangled.repo.getRepoByName", get(get_repo_by_name)) .route("/xrpc/sh.tangled.actor.getProfile", get(get_profile)) .route("/xrpc/sh.tangled.actor.getProfiles", get(get_profiles)) .route("/xrpc/sh.tangled.repo.getIssue", get(get_issue)) .route("/xrpc/sh.tangled.repo.getIssues", get(get_issues)) .route("/xrpc/sh.tangled.repo.getPull", get(get_pull)) .route("/xrpc/sh.tangled.repo.getPulls", get(get_pulls)) .route("/xrpc/sh.tangled.feed.listStars", get(list_stars)) .route("/xrpc/sh.tangled.feed.countStars", get(count_stars)) .route("/xrpc/sh.tangled.feed.getStar", get(get_star)) .route("/xrpc/sh.tangled.graph.listFollows", get(list_follows)) .route("/xrpc/sh.tangled.graph.countFollows", get(count_follows)) .route("/xrpc/sh.tangled.graph.getFollow", get(get_follow)) .route("/xrpc/sh.tangled.repo.listIssues", get(list_issues)) .route("/xrpc/sh.tangled.repo.countIssues", get(count_issues)) .route("/xrpc/sh.tangled.repo.listPulls", get(list_pulls)) .route("/xrpc/sh.tangled.repo.countPulls", get(count_pulls)) .route( "/xrpc/sh.tangled.feed.listComments", get(list_feed_comments), ) .route( "/xrpc/sh.tangled.feed.countComments", get(count_feed_comments), ) .route("/xrpc/sh.tangled.feed.listReactions", get(list_reactions)) .route("/xrpc/sh.tangled.feed.countReactions", get(count_reactions)) .route("/xrpc/sh.tangled.git.listRefUpdates", get(list_ref_updates)) .route( "/xrpc/sh.tangled.git.countRefUpdates", get(count_ref_updates), ) .route( "/xrpc/sh.tangled.repo.listCollaborators", get(list_collaborators), ) .route( "/xrpc/sh.tangled.repo.countCollaborators", get(count_collaborators), ) .route( "/xrpc/sh.tangled.repo.issue.listStates", get(list_issue_states), ) .route( "/xrpc/sh.tangled.repo.issue.countStates", get(count_issue_states), ) .route( "/xrpc/sh.tangled.repo.pull.listStatuses", get(list_pull_statuses), ) .route( "/xrpc/sh.tangled.repo.pull.countStatuses", get(count_pull_statuses), ) .route("/xrpc/sh.tangled.repo.listRepos", get(list_repos)) .route("/xrpc/sh.tangled.repo.countRepos", get(count_repos)) .route("/xrpc/sh.tangled.repo.countForks", get(count_forks)) .route("/xrpc/sh.tangled.knot.listKnots", get(list_knots)) .route("/xrpc/sh.tangled.knot.countKnots", get(count_knots)) .route("/xrpc/sh.tangled.spindle.listSpindles", get(list_spindles)) .route( "/xrpc/sh.tangled.spindle.countSpindles", get(count_spindles), ) .route( "/xrpc/sh.tangled.publicKey.getPublicKey", get(get_public_key), ) .route("/xrpc/sh.tangled.publicKey.listKeys", get(list_public_keys)) .route( "/xrpc/sh.tangled.publicKey.countKeys", get(count_public_keys), ) .route("/xrpc/sh.tangled.graph.listVouches", get(list_vouches)) .route("/xrpc/sh.tangled.graph.countVouches", get(count_vouches)) .route("/xrpc/sh.tangled.feed.getTimeline", get(feed::get_timeline)) .route("/xrpc/sh.tangled.feed.listStarsBy", get(list_stars_by)) .route("/xrpc/sh.tangled.feed.countStarsBy", get(count_stars_by)) .route( "/xrpc/sh.tangled.feed.listReactionsBy", get(list_reactions_by), ) .route( "/xrpc/sh.tangled.feed.countReactionsBy", get(count_reactions_by), ) .route("/xrpc/sh.tangled.graph.listFollowsBy", get(list_follows_by)) .route( "/xrpc/sh.tangled.graph.countFollowsBy", get(count_follows_by), ) .route("/xrpc/sh.tangled.graph.listVouchesBy", get(list_vouches_by)) .route( "/xrpc/sh.tangled.graph.countVouchesBy", get(count_vouches_by), ) .route( "/xrpc/sh.tangled.git.listRefUpdatesBy", get(list_ref_updates_by), ) .route( "/xrpc/sh.tangled.git.countRefUpdatesBy", get(count_ref_updates_by), ) .route( "/xrpc/sh.tangled.knot.listMembersBy", get(list_knot_members_by), ) .route( "/xrpc/sh.tangled.knot.countMembersBy", get(count_knot_members_by), ) .route("/xrpc/sh.tangled.label.listOpsBy", get(list_label_ops_by)) .route("/xrpc/sh.tangled.label.countOpsBy", get(count_label_ops_by)) .route( "/xrpc/sh.tangled.pipeline.listPipelinesBy", get(list_pipelines_by), ) .route( "/xrpc/sh.tangled.pipeline.countPipelinesBy", get(count_pipelines_by), ) .route( "/xrpc/sh.tangled.pipeline.listStatusesBy", get(list_pipeline_statuses_by), ) .route( "/xrpc/sh.tangled.pipeline.countStatusesBy", get(count_pipeline_statuses_by), ) .route( "/xrpc/sh.tangled.repo.listArtifactsBy", get(list_artifacts_by), ) .route( "/xrpc/sh.tangled.repo.countArtifactsBy", get(count_artifacts_by), ) .route( "/xrpc/sh.tangled.repo.listCollaboratorsBy", get(list_collaborators_by), ) .route( "/xrpc/sh.tangled.repo.countCollaboratorsBy", get(count_collaborators_by), ) .route("/xrpc/sh.tangled.repo.listIssuesBy", get(list_issues_by)) .route("/xrpc/sh.tangled.repo.countIssuesBy", get(count_issues_by)) .route( "/xrpc/sh.tangled.feed.listCommentsBy", get(list_feed_comments_by), ) .route( "/xrpc/sh.tangled.feed.countCommentsBy", get(count_feed_comments_by), ) .route( "/xrpc/sh.tangled.repo.issue.listStatesBy", get(list_issue_states_by), ) .route( "/xrpc/sh.tangled.repo.issue.countStatesBy", get(count_issue_states_by), ) .route("/xrpc/sh.tangled.repo.listPullsBy", get(list_pulls_by)) .route("/xrpc/sh.tangled.repo.countPullsBy", get(count_pulls_by)) .route( "/xrpc/sh.tangled.repo.pull.listStatusesBy", get(list_pull_statuses_by), ) .route( "/xrpc/sh.tangled.repo.pull.countStatusesBy", get(count_pull_statuses_by), ) .route( "/xrpc/sh.tangled.spindle.listMembersBy", get(list_spindle_members_by), ) .route( "/xrpc/sh.tangled.spindle.countMembersBy", get(count_spindle_members_by), ) .route( "/xrpc/sh.tangled.label.listDefinitions", get(list_label_definitions), ) .route( "/xrpc/sh.tangled.label.countDefinitions", get(count_label_definitions), ) .route("/xrpc/sh.tangled.label.listOps", get(list_label_ops)) .route("/xrpc/sh.tangled.label.countOps", get(count_label_ops)) .route( "/xrpc/sh.tangled.pipeline.listPipelines", get(list_pipelines), ) .route( "/xrpc/sh.tangled.pipeline.countPipelines", get(count_pipelines), ) .route( "/xrpc/sh.tangled.pipeline.listStatuses", get(list_pipeline_statuses), ) .route( "/xrpc/sh.tangled.pipeline.countStatuses", get(count_pipeline_statuses), ) .route("/xrpc/sh.tangled.repo.listArtifacts", get(list_artifacts)) .route("/xrpc/sh.tangled.repo.countArtifacts", get(count_artifacts)) .route("/xrpc/sh.tangled.knot.listMembers", get(list_knot_members)) .route( "/xrpc/sh.tangled.knot.countMembers", get(count_knot_members), ) .route( "/xrpc/sh.tangled.spindle.listMembers", get(list_spindle_members), ) .route( "/xrpc/sh.tangled.spindle.countMembers", get(count_spindle_members), ) .route("/xrpc/sh.tangled.string.getString", get(get_string)) .route("/xrpc/sh.tangled.string.listStrings", get(list_strings)) .route("/xrpc/sh.tangled.string.countStrings", get(count_strings)) .route("/xrpc/sh.tangled.search.query", get(search_query)) .route( "/xrpc/sh.tangled.query.enrichResponse", axum::routing::post(enrich::enrich), ) .route("/xrpc/sh.tangled.bobbin.getCoverage", get(get_coverage)) .route( "/xrpc/com.bad-example.identity.resolveMiniDoc", get(resolve_mini_doc), ) .merge(knot_proxied_routes()) .layer( TraceLayer::new_for_http() .make_span_with(DefaultMakeSpan::new().level(Level::INFO)) .on_request(()) .on_response(LatencyFreeTrace) .on_failure(LatencyFreeTrace), ) .with_state(state) } #[derive(Clone, Copy, Debug)] struct LatencyFreeTrace; impl OnResponse for LatencyFreeTrace { fn on_response(self, response: &Response, _latency: Duration, _span: &Span) { tracing::event!( target: "tower_http::trace::on_response", Level::INFO, status = response.status().as_u16(), "request completed", ); } } impl OnFailure for LatencyFreeTrace { fn on_failure(&mut self, error: ServerErrorsFailureClass, _latency: Duration, _span: &Span) { tracing::event!( target: "tower_http::trace::on_failure", Level::WARN, error = %error, "request failed", ); } } const REPO_PROXIED_NSIDS: &[&str] = &[ "sh.tangled.repo.archive", "sh.tangled.repo.blob", "sh.tangled.repo.branch", "sh.tangled.repo.branches", "sh.tangled.repo.compare", "sh.tangled.repo.describeRepo", "sh.tangled.repo.diff", "sh.tangled.repo.getDefaultBranch", "sh.tangled.repo.languages", "sh.tangled.repo.listSecrets", "sh.tangled.repo.log", "sh.tangled.repo.tag", "sh.tangled.repo.tags", "sh.tangled.repo.tree", ]; const KNOT_PROXIED_NSIDS: &[&str] = &[ "sh.tangled.owner", "sh.tangled.knot.version", "sh.tangled.knot.listKeys", ]; const PASSTHROUGH_HEADERS: &[&HeaderName] = &[ &CONTENT_TYPE, &CONTENT_LENGTH, &CONTENT_ENCODING, &ETAG, &CACHE_CONTROL, &LAST_MODIFIED, &CONTENT_DISPOSITION, &ACCEPT_RANGES, &CONTENT_RANGE, ]; const FORWARDED_REQUEST_HEADERS: &[&HeaderName] = &[&RANGE, &IF_RANGE, &IF_NONE_MATCH, &IF_MODIFIED_SINCE]; const KNOT_HOST_PARAM: &str = "knot"; const REPO_PARAM: &str = "repo"; type ProxyParams = Vec<(String, String)>; fn knot_proxied_routes() -> Router { let with_repo = register_proxied(Router::new(), REPO_PROXIED_NSIDS, proxy_repo_handler); register_proxied(with_repo, KNOT_PROXIED_NSIDS, proxy_knot_handler) } fn register_proxied( router: Router, nsids: &[&'static str], handler: H, ) -> Router where H: Fn(AppState, HeaderMap, SocketPeer, ProxyParams, Nsid) -> Fut + Clone + Send + Sync + 'static, Fut: Future> + Send + 'static, { nsids.iter().fold(router, |router, &nsid_lit| { let handler = handler.clone(); let nsid = nsid_static(nsid_lit); router.route( &format!("/xrpc/{nsid_lit}"), get( move |State(state): State, headers: HeaderMap, socket: SocketPeer, Query(params): Query| { handler(state, headers, socket, params, nsid.clone()) }, ), ) }) } #[derive(Clone, Debug)] pub enum SubjectQuery { Did(Did), Uri(AtUri), } impl<'de> Deserialize<'de> for SubjectQuery { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de>, { let raw = String::deserialize(deserializer)?; if let Ok(did) = Did::::new_owned(&raw) { return Ok(Self::Did(did)); } AtUri::::new_owned(&raw) .map(Self::Uri) .map_err(serde::de::Error::custom) } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct ExpectedNsid { canon: Nsid, aliases: &'static [&'static str], } const FEED_COMMENT_LEGACY_ALIASES: &[&str] = &[ "sh.tangled.repo.issue.comment", "sh.tangled.repo.pull.comment", ]; fn aliases_for(nsid: &str) -> &'static [&'static str] { match nsid { "sh.tangled.feed.comment" => FEED_COMMENT_LEGACY_ALIASES, _ => &[], } } impl ExpectedNsid { pub fn new(nsid: Nsid) -> Self { let aliases = aliases_for(nsid.as_ref()); Self { canon: nsid, aliases, } } pub fn from_static(s: &'static str) -> Self { let canon = nsid_static(s); let aliases = aliases_for(s); Self { canon, aliases } } pub fn as_nsid(&self) -> &Nsid { &self.canon } pub fn as_str(&self) -> &str { self.canon.as_ref() } fn accepts(&self, other: &str) -> bool { other == self.canon.as_ref() || self.aliases.contains(&other) } } #[derive(Debug, Deserialize)] struct GetRepoQuery { repo: AtUri, } #[derive(Debug, Deserialize)] struct GetRepoByRepoDidQuery { #[serde(rename = "repoDid")] repo_did: Did, } #[derive(Debug, Deserialize)] struct GetRepoByNameQuery { owner: Did, name: String, } #[derive(Debug, Deserialize)] struct GetProfileQuery { actor: AtUri, } #[derive(Debug, Deserialize)] struct GetIssueQuery { issue: AtUri, } #[derive(Debug, Deserialize)] struct GetPullQuery { pull: AtUri, } #[derive(Debug, Deserialize)] struct GetStringQuery { string: AtUri, } #[derive(Debug, Deserialize)] struct GetPublicKeyQuery { #[serde(rename = "publicKey")] public_key: AtUri, } #[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)] #[serde(rename_all = "lowercase")] enum Order { Asc, #[default] Desc, } impl From for SortDir { fn from(o: Order) -> Self { match o { Order::Asc => SortDir::Asc, Order::Desc => SortDir::Desc, } } } #[derive(Debug, Deserialize)] struct TypedListQuery { subject: SubjectQuery, cursor: Option, limit: Option, #[serde(default)] order: Order, #[serde(flatten)] filter: F, } impl TypedListQuery { fn dir(&self) -> SortDir { self.order.into() } } #[derive(Debug, Deserialize)] struct CountQuery { subject: SubjectQuery, } #[derive(Debug, Deserialize)] struct TypedCountQuery { subject: SubjectQuery, #[serde(flatten)] filter: F, } #[derive(Debug, Deserialize)] struct GetEdgeQuery { actor: Did, subject: SubjectQuery, } #[derive(Debug, Deserialize)] struct SearchQueryParams { q: String, nsid: Option>, author: Option>, repo: Option>, since: Option, until: Option, cursor: Option, limit: Option, } pub struct XrpcQuery(pub T); impl FromRequestParts for XrpcQuery where S: Send + Sync, T: serde::de::DeserializeOwned + Send + 'static, { type Rejection = XrpcError; async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { Query::::from_request_parts(parts, state) .await .map(|Query(t)| Self(t)) .map_err(|rej: QueryRejection| XrpcError::InvalidParams(rej.body_text())) } } #[derive(Debug, Error)] pub enum XrpcError { #[error("invalid request: {0}")] InvalidParams(String), #[error("record not found")] NotFound, #[error("upstream unavailable: {0}")] UpstreamUnavailable(String), #[error("upstream gone: {0}")] UpstreamGone(String), #[error("invalid record: {0}")] InvalidRecord(String), #[error("internal: {0}")] Internal(String), #[error("overloaded, shedding under memory pressure")] Overloaded, } impl XrpcError { pub fn overloaded() -> Self { Self::Overloaded } } #[derive(Serialize)] struct ErrorBody { error: &'static str, message: String, } impl IntoResponse for XrpcError { fn into_response(self) -> Response { let (status, error) = match &self { Self::InvalidParams(_) => (StatusCode::BAD_REQUEST, "InvalidRequest"), Self::NotFound => (StatusCode::NOT_FOUND, "RecordNotFound"), Self::UpstreamUnavailable(_) => (StatusCode::BAD_GATEWAY, "UpstreamFailed"), Self::UpstreamGone(_) => (StatusCode::BAD_GATEWAY, "UpstreamGone"), Self::InvalidRecord(_) => (StatusCode::BAD_GATEWAY, "InvalidRecord"), Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "InternalError"), Self::Overloaded => (StatusCode::SERVICE_UNAVAILABLE, "Overloaded"), }; let body = ErrorBody { error, message: self.to_string(), }; (status, Json(body)).into_response() } } #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct CoverageEnvelope { ready: bool, events_processed: u64, last_cursor: u64, } impl From for CoverageEnvelope { fn from(c: Coverage) -> Self { Self { ready: c.is_ready(), events_processed: c.events_processed(), last_cursor: c.last_cursor().raw(), } } } struct Deduped(T); impl Serialize for Deduped { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer, { serde_json::to_value(&self.0) .map_err(serde::ser::Error::custom)? .serialize(serializer) } } #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct RecordView { uri: AtUri, cid: Option>, value: V, } #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct StatefulItem { #[serde(flatten)] view: RecordView, state: &'static str, #[serde(skip_serializing_if = "Option::is_none")] state_updated_at: Option, comment_count: u64, } fn format_micros(micros: u64) -> String { let signed = i64::try_from(micros).ok(); let rfc = signed .and_then(chrono::DateTime::::from_timestamp_micros) .map(|dt| dt.to_rfc3339_opts(chrono::SecondsFormat::Micros, true)); rfc.unwrap_or_else(|| micros.to_string()) } pub(crate) fn source_authority_did(source: &AtUri) -> Option> { match source.authority() { AtIdentifier::Did(d) => Some(d.clone().into_static()), AtIdentifier::Handle(_) => None, } } fn enrich_issue_view( state: &AppState, view: RecordView>, ) -> StatefulItem> { let issue_author = source_authority_did(&view.uri); let repo_did = view.value.repo.clone(); enrich_view( &state.edges, nsid_static("sh.tangled.feed.comment"), &state.issue_states, view, move |src| accept_state_source(src, issue_author.as_ref(), &repo_did), ) } fn enrich_pull_view( state: &AppState, view: RecordView>, ) -> StatefulItem> { let pull_author = source_authority_did(&view.uri); let target_repo = view.value.target.repo.clone(); enrich_view( &state.edges, nsid_static("sh.tangled.feed.comment"), &state.pull_statuses, view, move |src| accept_state_source(src, pull_author.as_ref(), &target_repo), ) } pub(crate) fn accept_state_source( source: &AtUri, entity_author: Option<&Did>, repo_owner: &Did, ) -> bool { let Some(src) = source_authority_did(source) else { return false; }; Some(&src) == entity_author || &src == repo_owner } fn enrich_view( edges: &EdgeStore, comment_nsid: Nsid, states: &StateIndex, view: RecordView, accept: F, ) -> StatefulItem where K: StateKind + Default, F: Fn(&AtUri) -> bool, { let comment_count = edges.count(&EdgeKey::new( comment_nsid, SubjectRef::Uri(view.uri.clone()), )); let (state, state_updated_at) = states .latest_by(&view.uri, accept) .map_or((K::default().wire(), None), |(kind, micros)| { (kind.wire(), Some(format_micros(micros))) }); StatefulItem { view, state, state_updated_at, comment_count, } } #[derive(Clone, Copy, Debug, Serialize)] #[serde(rename_all = "camelCase")] struct CountResponse { count: u64, distinct_authors: u64, } #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct EdgeUriResponse { uri: AtUri, } #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct SearchHitView { uri: AtUri, cid: Option>, nsid: Nsid, score: f32, value: SearchableRecord, } fn map_slingshot(err: SlingshotError) -> XrpcError { use SlingshotError as E; match err { E::NotFound => XrpcError::NotFound, e @ (E::Decode(_) | E::MissingField(_) | E::InvalidAtUri(_) | E::InvalidCid(_) | E::UriMismatch { .. }) => XrpcError::InvalidRecord(e.to_string()), e @ (E::Network(_) | E::Build(_) | E::Upstream(_) | E::BodyTooLarge { .. } | E::BadScheme(_)) => XrpcError::UpstreamUnavailable(e.to_string()), } } fn parse_uri(raw: &str) -> Result, XrpcError> { AtUri::::new_owned(raw).map_err(|e| XrpcError::InvalidParams(format!("uri: {e}"))) } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum SubjectShape { BareDid, Collection(&'static str), BareDidOrOneOfCollections(&'static [&'static str]), OneOfCollections(&'static [&'static str]), AnyAtUri, } pub trait HasSubject { const SHAPE: SubjectShape; } pub trait MirrorOf { type Record: XrpcResp; const EDGE_KIND: &'static str; const SHAPE: SubjectShape; } macro_rules! edge_kinds { ($($collection:literal => $record:ty, $shape:expr $(, mirror $by:ident)? ;)*) => { $( impl HasSubject for $record { const SHAPE: SubjectShape = $shape; } )* $($( pub struct $by; impl MirrorOf for $by { type Record = $record; const EDGE_KIND: &'static str = concat!($collection, ".by"); const SHAPE: SubjectShape = SubjectShape::BareDid; } )?)* pub(crate) fn subject_shape(collection: &str) -> Option<(&'static str, SubjectShape)> { Some(match collection { $($collection => ($collection, <$record as HasSubject>::SHAPE),)* _ => return None, }) } pub(crate) fn mirror_kind(collection: &str) -> Option<&'static str> { Some(match collection { $($($collection => <$by as MirrorOf>::EDGE_KIND,)?)* _ => return None, }) } }; } edge_kinds! { "sh.tangled.feed.star" => StarRecord, SubjectShape::BareDidOrOneOfCollections(&["sh.tangled.string"]), mirror StarBy; "sh.tangled.feed.comment" => FeedCommentRecord, SubjectShape::OneOfCollections(&["sh.tangled.repo.issue", "sh.tangled.repo.pull", "sh.tangled.string"]), mirror FeedCommentBy; "sh.tangled.feed.reaction" => ReactionRecord, SubjectShape::AnyAtUri, mirror ReactionBy; "sh.tangled.graph.follow" => FollowRecord, SubjectShape::BareDid, mirror FollowBy; "sh.tangled.graph.vouch" => VouchRecord, SubjectShape::BareDid, mirror VouchBy; "sh.tangled.git.refUpdate" => RefUpdateRecord, SubjectShape::BareDid, mirror RefUpdateBy; "sh.tangled.knot" => KnotRecord, SubjectShape::BareDid; "sh.tangled.knot.member" => KnotMemberRecord, SubjectShape::BareDid, mirror KnotMemberBy; "sh.tangled.label.definition" => LabelDefinitionRecord, SubjectShape::BareDid; "sh.tangled.label.op" => LabelOpRecord, SubjectShape::OneOfCollections(&["sh.tangled.repo.issue", "sh.tangled.repo.pull"]), mirror LabelOpBy; "sh.tangled.pipeline" => PipelineRecord, SubjectShape::BareDid, mirror PipelineBy; "sh.tangled.pipeline.status" => PipelineStatusRecord, SubjectShape::Collection("sh.tangled.pipeline"), mirror PipelineStatusBy; "sh.tangled.publicKey" => PublicKeyRecord, SubjectShape::BareDid; "sh.tangled.repo" => RepoRecord, SubjectShape::BareDid; "sh.tangled.repo.artifact" => ArtifactRecord, SubjectShape::BareDid, mirror ArtifactBy; "sh.tangled.repo.collaborator" => CollaboratorRecord, SubjectShape::BareDid, mirror CollaboratorBy; "sh.tangled.repo.issue" => IssueRecord, SubjectShape::BareDid, mirror IssueBy; "sh.tangled.repo.issue.state" => IssueStateRecord, SubjectShape::Collection("sh.tangled.repo.issue"), mirror IssueStateBy; "sh.tangled.repo.pull" => PullRecord, SubjectShape::BareDid, mirror PullBy; "sh.tangled.repo.pull.status" => PullStatusRecord, SubjectShape::Collection("sh.tangled.repo.pull"), mirror PullStatusBy; "sh.tangled.spindle" => SpindleRecord, SubjectShape::BareDid; "sh.tangled.spindle.member" => SpindleMemberRecord, SubjectShape::BareDid, mirror SpindleMemberBy; "sh.tangled.string" => TangledStringRecord, SubjectShape::BareDid; } // the fork edge is not a collection so it is not in the table above const FORK_SUBJECT_SHAPE: SubjectShape = SubjectShape::BareDid; fn parse_subject(raw: &SubjectQuery, shape: SubjectShape) -> Result { let uri = match raw { SubjectQuery::Did(did) => { return match shape { SubjectShape::BareDid | SubjectShape::BareDidOrOneOfCollections(_) => { Ok(SubjectRef::Did(did.clone())) } SubjectShape::Collection(expected) => Err(XrpcError::InvalidParams(format!( "subject must be at:///{expected}/, got bare did" ))), SubjectShape::OneOfCollections(allowed) => Err(XrpcError::InvalidParams(format!( "subject must be at://// with nsid in [{}], got bare did", allowed.join(", "), ))), SubjectShape::AnyAtUri => Err(XrpcError::InvalidParams( "subject must be at-uri form, got bare did".into(), )), }; } SubjectQuery::Uri(uri) => uri, }; if matches!(uri.authority(), AtIdentifier::Handle(_)) { return Err(XrpcError::InvalidParams( "subject authority must be a did, not a handle".into(), )); } let Some(collection) = uri.collection() else { return Err(XrpcError::InvalidParams( "subject must be a bare did or full at:////".into(), )); }; let c = collection.as_ref(); match shape { SubjectShape::BareDid => Err(XrpcError::InvalidParams(format!( "subject must be a bare did, got at-uri with collection {c}" ))), SubjectShape::Collection(expected) if c == expected => { require_rkey(uri, expected)?; Ok(SubjectRef::Uri(uri.clone())) } SubjectShape::Collection(expected) => Err(XrpcError::InvalidParams(format!( "subject must be at:///{expected}/, got collection {c}" ))), SubjectShape::OneOfCollections(allowed) if allowed.contains(&c) => { require_rkey(uri, c)?; Ok(SubjectRef::Uri(uri.clone())) } SubjectShape::OneOfCollections(allowed) => Err(XrpcError::InvalidParams(format!( "subject must be at://// with nsid in [{}], got collection {c}", allowed.join(", "), ))), SubjectShape::BareDidOrOneOfCollections(allowed) if allowed.contains(&c) => { require_rkey(uri, c)?; Ok(SubjectRef::Uri(uri.clone())) } SubjectShape::BareDidOrOneOfCollections(allowed) => Err(XrpcError::InvalidParams(format!( "subject must be a bare did or at://// with nsid in [{}], got collection {c}", allowed.join(", "), ))), SubjectShape::AnyAtUri => Ok(SubjectRef::Uri(uri.clone())), } } fn require_rkey(uri: &AtUri, expected: &str) -> Result<(), XrpcError> { uri.rkey().map(|_| ()).ok_or_else(|| { XrpcError::InvalidParams(format!( "subject must be at:///{expected}/; missing rkey" )) }) } pub(crate) fn parse_cursor(raw: Option<&str>) -> Result { PageCursor::from_token(raw) .map_err(|e: CursorParseError| XrpcError::InvalidParams(format!("cursor: {e}"))) } pub(crate) fn parse_limit(raw: Option) -> Result { PageLimit::new(raw.unwrap_or(DEFAULT_LIMIT)) .map_err(|e| XrpcError::InvalidParams(format!("limit: {e}"))) } pub(crate) fn at_uri_owned_by(uri: &AtUri, author: &Did) -> bool { match uri.authority() { AtIdentifier::Did(d) => d.as_ref() == author.as_ref(), AtIdentifier::Handle(_) => false, } } async fn resolve_for_view( state: &AppState, expected_nsid: &Nsid, uri: AtUri, ) -> Result, XrpcError> { let raw = uri.as_ref().to_owned(); resolve(state, ExpectedNsid::new(expected_nsid.clone()), uri) .await .map(|(body, _did)| body) .map_err(|e| match e { XrpcError::NotFound => XrpcError::UpstreamGone(raw), other => other, }) } async fn resolve( state: &AppState, expected: ExpectedNsid, uri: AtUri, ) -> Result<(Arc, Did), XrpcError> { let collection = uri .collection() .ok_or_else(|| XrpcError::InvalidParams("uri missing collection".into()))?; if !expected.accepts(collection.as_ref()) { return Err(XrpcError::InvalidParams(format!( "collection mismatch: expected {}, got {}", expected.as_str(), collection.as_ref() ))); } let rkey = uri .rkey() .ok_or_else(|| XrpcError::InvalidParams("uri missing rkey".into()))?; let did_ref = match uri.authority() { AtIdentifier::Did(d) => d, AtIdentifier::Handle(_) => { return Err(XrpcError::InvalidParams( "uri authority must be a did, not a handle".into(), )); } }; let did: Did = did_ref.clone().into_static(); if let Some(hit) = state.records.get(&uri) { return Ok((hit, did)); } let body = state .slingshot .get_record(&did_ref, &collection, &rkey) .await .map_err(map_slingshot)?; verify_type_tag(&body, &expected)?; state.records.put(uri, body.clone()); Ok((body, did)) } #[derive(Deserialize)] struct TypeTag<'a> { #[serde(rename = "$type", borrow)] ty: &'a str, } fn verify_type_tag(body: &RecordBody, expected: &ExpectedNsid) -> Result<(), XrpcError> { let bytes = body.value.as_ref(); let ty: std::borrow::Cow<'_, str> = match serde_json::from_slice::(bytes) { Ok(t) => std::borrow::Cow::Borrowed(t.ty), Err(_) => { let value: serde_json::Value = serde_json::from_slice(bytes) .map_err(|e| XrpcError::InvalidRecord(format!("$type peek: {e}")))?; value .as_object() .and_then(|m| m.get("$type")) .and_then(|v| v.as_str()) .map(|s| std::borrow::Cow::Owned(s.to_owned())) .ok_or_else(|| XrpcError::InvalidRecord("$type peek: missing $type field".into()))? } }; if !expected.accepts(ty.as_ref()) { return Err(XrpcError::InvalidRecord(format!( "$type mismatch: expected {}, got {}", expected.as_str(), ty ))); } Ok(()) } fn wire_type_nsid(bytes: &[u8]) -> Option> { let ty = serde_json::from_slice::(bytes).ok()?.ty; Nsid::::new_owned(ty).ok() } async fn deserialize_or_upgrade( state: &AppState, nsid: &Nsid, bytes: &[u8], ) -> Result where V: serde::de::DeserializeOwned, { match serde_json::from_slice::(bytes) { Ok(v) => Ok(v), Err(canon_err) => { let normalized = normalize_record_fields(bytes); let working: &[u8] = normalized.as_deref().unwrap_or(bytes); if normalized.is_some() && let Ok(v) = serde_json::from_slice::(working) { return Ok(v); } let scrubbed = scrub_record_bytes(nsid, working); let retry_bytes: &[u8] = scrubbed.as_deref().unwrap_or(working); if scrubbed.is_some() && let Ok(v) = serde_json::from_slice::(retry_bytes) { return Ok(v); } let wire_nsid = wire_type_nsid(retry_bytes).unwrap_or_else(|| nsid.clone()); match upgrade_wire_bytes(&wire_nsid, retry_bytes, &state.resolver).await { Ok(canon_bytes) => serde_json::from_slice(&canon_bytes) .map_err(|e| XrpcError::InvalidRecord(e.to_string())), Err(_) => Err(XrpcError::InvalidRecord(canon_err.to_string())), } } } } async fn fetch_from_uri( state: &AppState, uri: AtUri, ) -> Result<(Arc, V), XrpcError> where R: XrpcResp, V: serde::de::DeserializeOwned + NormalizeRepoRefs, { let raw = uri.as_str().to_owned(); let nsid = nsid_static(R::NSID); let (body, _did) = resolve(state, ExpectedNsid::new(nsid.clone()), uri).await?; let value: V = deserialize_or_upgrade(state, &nsid, &body.value).await?; let value = value .normalize(&state.resolver) .await .ok_or(XrpcError::UpstreamGone(raw))?; Ok((body, value)) } pub(crate) async fn fetch( state: &AppState, uri: &AtUri, ) -> Result<(Arc, V), XrpcError> where R: XrpcResp, V: serde::de::DeserializeOwned + NormalizeRepoRefs, { fetch_from_uri::(state, uri.clone()).await } async fn get_repo( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result>>, XrpcError> { let (body, value) = fetch::>(&state, &q.repo).await?; Ok(Json(Deduped(RepoGetRecordOutput { cid: Some(body.cid.clone()), uri: body.uri.clone(), value, }))) } async fn get_repo_by_repo_did( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result>>, XrpcError> { let ident = state .resolver .lookup_by_repo_did(&q.repo_did) .await .ok_or(XrpcError::NotFound)?; let uri = AtUri::::from_parts_owned( ident.owner.as_str(), RepoRecord::NSID, ident.rkey.as_str(), ) .expect("Did and Rkey newtypes already validated, at-uri assembly cannot fail"); let (body, value) = fetch_from_uri::>(&state, uri).await?; Ok(Json(Deduped(RepoGetRecordOutput { cid: Some(body.cid.clone()), uri: body.uri.clone(), value, }))) } async fn get_repo_by_name( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result>>, XrpcError> { let ident = state .resolver .lookup_by_name(&q.owner, &q.name) .await .ok_or(XrpcError::NotFound)?; let uri = AtUri::::from_parts_owned( ident.owner.as_str(), RepoRecord::NSID, ident.rkey.as_str(), ) .expect("Did and Rkey newtypes already validated, at-uri assembly cannot fail"); let (body, value) = fetch_from_uri::>(&state, uri).await?; Ok(Json(Deduped(RepoGetRecordOutput { cid: Some(body.cid.clone()), uri: body.uri.clone(), value, }))) } async fn get_profile( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result>>, XrpcError> { let (body, value) = fetch::>(&state, &q.actor).await?; Ok(Json(Deduped(ProfileGetRecordOutput { cid: Some(body.cid.clone()), uri: body.uri.clone(), value, }))) } async fn get_issue( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result>>, XrpcError> { let (body, value) = fetch::>(&state, &q.issue).await?; Ok(Json(Deduped(IssueGetRecordOutput { cid: Some(body.cid.clone()), uri: body.uri.clone(), value, }))) } async fn get_pull( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result>>, XrpcError> { let (body, value) = fetch::>(&state, &q.pull).await?; Ok(Json(Deduped(PullGetRecordOutput { cid: Some(body.cid.clone()), uri: body.uri.clone(), value, }))) } async fn get_string( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result>>, XrpcError> { let (body, value) = fetch::>(&state, &q.string).await?; Ok(Json(Deduped(TangledStringGetRecordOutput { cid: Some(body.cid.clone()), uri: body.uri.clone(), value, }))) } async fn get_public_key( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result>>, XrpcError> { let (body, value) = fetch::>(&state, &q.public_key).await?; Ok(Json(Deduped(PublicKeyGetRecordOutput { cid: Some(body.cid.clone()), uri: body.uri.clone(), value, }))) } async fn get_repos( State(state): State, RawQuery(query): RawQuery, ) -> Result { let uris = collect_repeated(query.as_deref(), BULK_REPOS_KEY); bulk_fetch::>(&state, uris).await } async fn get_repos_by_repo_dids( State(state): State, RawQuery(query): RawQuery, ) -> Result { let dids = collect_repeated(query.as_deref(), BULK_REPO_DIDS_KEY); if dids.is_empty() { return Err(XrpcError::InvalidParams("at least one did required".into())); } if dids.len() > BULK_LIMIT { return Err(XrpcError::InvalidParams(format!( "at most {BULK_LIMIT} dids per request" ))); } let dids = dids .iter() .map(|s| { Did::::new_owned(s) .map_err(|_| XrpcError::InvalidParams(format!("invalid did: {s}"))) }) .collect::, _>>()?; let mut uris: Vec> = Vec::new(); for did in &dids { if let Some(ident) = state.resolver.lookup_by_repo_did(did).await { uris.push( AtUri::::from_parts_owned( ident.owner.as_str(), RepoRecord::NSID, ident.rkey.as_str(), ) .expect("Did and Rkey newtypes already validated, at-uri assembly cannot fail"), ); } } bulk_stream::>(&state, uris) } async fn get_profiles( State(state): State, RawQuery(query): RawQuery, ) -> Result { let uris = collect_repeated(query.as_deref(), BULK_PROFILES_KEY); bulk_fetch::>(&state, uris).await } async fn get_issues( State(state): State, RawQuery(query): RawQuery, ) -> Result { let uris = collect_repeated(query.as_deref(), BULK_ISSUES_KEY); bulk_fetch::>(&state, uris).await } async fn get_pulls( State(state): State, RawQuery(query): RawQuery, ) -> Result { let uris = collect_repeated(query.as_deref(), BULK_PULLS_KEY); bulk_fetch::>(&state, uris).await } const BULK_REPOS_KEY: &str = "repos"; const BULK_REPO_DIDS_KEY: &str = "dids"; const BULK_PROFILES_KEY: &str = "actors"; const BULK_ISSUES_KEY: &str = "issues"; const BULK_PULLS_KEY: &str = "pulls"; const BULK_LIMIT: usize = 50; fn collect_repeated(query: Option<&str>, key: &str) -> Vec { let Some(q) = query else { return Vec::new(); }; form_urlencoded::parse(q.as_bytes()) .filter_map(|(k, v)| (k == key).then(|| v.into_owned())) .collect() } async fn hydrate_record_view( state: &AppState, nsid: &Nsid, uri: AtUri, sort_micros: u64, ) -> Result>, XrpcError> where V: serde::de::DeserializeOwned + NormalizeRepoRefs, { if let Some(source) = decode_knot_owned_source(&uri) { return synthesize_knot_owned_view::(state, uri, source, sort_micros).await; } let body = resolve_for_view(state, nsid, uri).await?; let value: V = deserialize_or_upgrade::(state, nsid, &body.value).await?; let Some(value) = value.normalize(&state.resolver).await else { return Ok(None); }; Ok(Some(RecordView { uri: body.uri.clone(), cid: Some(body.cid.clone()), value, })) } async fn synthesize_knot_owned_view( state: &AppState, uri: AtUri, source: KnotOwnedSource, sort_micros: u64, ) -> Result>, XrpcError> where V: serde::de::DeserializeOwned + NormalizeRepoRefs, { let Some(body) = synth_knot_owned_value(source, sort_micros) else { return Ok(None); }; let Ok(value) = serde_json::from_value::(body) else { return Ok(None); }; let Some(value) = value.normalize(&state.resolver).await else { return Ok(None); }; Ok(Some(RecordView { uri, cid: None, value, })) } fn synth_knot_owned_value(source: KnotOwnedSource, sort_micros: u64) -> Option { let created_at = micros_to_rfc3339(sort_micros)?; match source { KnotOwnedSource::Member { knot, subject } => Some(serde_json::json!({ "domain": knot_did_host(&knot)?, "subject": subject.as_ref(), "createdAt": created_at, })), KnotOwnedSource::Collaborator { repo, subject } => Some(serde_json::json!({ "repo": repo.as_ref(), "subject": subject.as_ref(), "createdAt": created_at, })), } } fn micros_to_rfc3339(micros: u64) -> Option { let micros = i64::try_from(micros).ok()?; chrono::DateTime::from_timestamp_micros(micros) .map(|dt| dt.to_rfc3339_opts(chrono::SecondsFormat::Micros, true)) } #[derive(Clone, Copy)] enum HitProvenance { ClientSupplied, Indexed, } fn is_index_evictable(err: &XrpcError) -> bool { matches!( err, XrpcError::NotFound | XrpcError::UpstreamGone(_) | XrpcError::InvalidRecord(_) | XrpcError::InvalidParams(_) ) } fn drop_unhydratable( provenance: HitProvenance, nsid: &Nsid, uri: &AtUri, result: Result, XrpcError>, ) -> Result, XrpcError> { match result { Ok(view) => Ok(view), Err(err @ (XrpcError::NotFound | XrpcError::UpstreamGone(_))) => { tracing::debug!( uri = %uri, nsid = %nsid.as_ref(), error = %err, "dropping gone hit during hydration", ); Ok(None) } Err(err @ XrpcError::UpstreamUnavailable(_)) => { tracing::warn!( uri = %uri, nsid = %nsid.as_ref(), error = %err, "dropping hit, upstream unavailable during hydration", ); Ok(None) } Err(err @ XrpcError::InvalidRecord(_)) => { tracing::warn!( uri = %uri, nsid = %nsid.as_ref(), error = %err, "dropping invalid hit during hydration", ); Ok(None) } Err(err @ XrpcError::InvalidParams(_)) => match provenance { HitProvenance::ClientSupplied => Err(err), HitProvenance::Indexed => { tracing::warn!( uri = %uri, nsid = %nsid.as_ref(), error = %err, "dropping malformed indexed hit during hydration", ); Ok(None) } }, Err(err @ (XrpcError::Internal(_) | XrpcError::Overloaded)) => Err(err), } } fn hydrate_stream( items: impl IntoIterator, produce: impl FnMut(T) -> Fut, ) -> impl Stream> where Fut: Future, XrpcError>>, { stream::iter(items) .map(produce) .buffered(FETCH_CONCURRENCY) .try_filter_map(|view| async move { Ok(view) }) } fn hydrate_record_stream( state: &AppState, nsid: Nsid, items: Vec, provenance: HitProvenance, ) -> impl Stream, XrpcError>> + Send + 'static where V: serde::de::DeserializeOwned + Serialize + NormalizeRepoRefs + Send + 'static, { let owned = state.clone(); hydrate_stream(items, move |item| { let owned = owned.clone(); let nsid = nsid.clone(); async move { let EdgeItem { uri, sort_micros } = item; let result = hydrate_record_view::(&owned, &nsid, uri.clone(), sort_micros).await; if matches!(provenance, HitProvenance::Indexed) && let Err(err) = &result && is_index_evictable(err) { owned.edges.remove_source(&uri); } drop_unhydratable(provenance, &nsid, &uri, result) } }) } enum PagePhase { Head, Body { first: bool }, Done, } struct PageState { items: std::pin::Pin>, phase: PagePhase, array_key: &'static str, tail: Vec, permit: Option, } pub(crate) fn paged_tail(cursor: Option) -> Vec { let encoded = serde_json::to_string(&cursor).unwrap_or_else(|_| "null".to_owned()); format!("],\"cursor\":{encoded}}}").into_bytes() } fn unpaged_tail() -> Vec { b"]}".to_vec() } pub(crate) fn json_stream( array_key: &'static str, items: S, tail: Vec, permit: Option, ) -> Response where V: Serialize + Send + 'static, S: Stream> + Send + 'static, { let init = PageState { items: Box::pin(items), phase: PagePhase::Head, array_key, tail, permit, }; let chunks = stream::unfold(init, |mut st| async move { match st.phase { PagePhase::Head => { let head = format!("{{\"{}\":[", st.array_key).into_bytes(); st.phase = PagePhase::Body { first: true }; Some((Ok::, Infallible>(head), st)) } PagePhase::Body { first } => match st.items.next().await { Some(Ok(view)) => match serde_json::to_vec(&Deduped(&view)) { Ok(encoded) => { let mut chunk = Vec::with_capacity(encoded.len() + 1); if !first { chunk.push(b','); } chunk.extend_from_slice(&encoded); st.phase = PagePhase::Body { first: false }; Some((Ok(chunk), st)) } Err(e) => { tracing::warn!(error = %e, "skipping hit, serialize failed mid-stream"); Some((Ok(Vec::new()), st)) } }, Some(Err(e)) => { tracing::warn!(error = %e, "ending page early, hydration failed mid-stream"); let tail = std::mem::take(&mut st.tail); st.phase = PagePhase::Done; Some((Ok(tail), st)) } None => { let tail = std::mem::take(&mut st.tail); st.phase = PagePhase::Done; Some((Ok(tail), st)) } }, PagePhase::Done => { drop(st.permit.take()); None } } }); ( [(CONTENT_TYPE, "application/json")], Body::from_stream(chunks), ) .into_response() } async fn bulk_fetch(state: &AppState, uris: Vec) -> Result where R: XrpcResp, V: serde::de::DeserializeOwned + Serialize + NormalizeRepoRefs + Send + 'static, { if uris.is_empty() { return Err(XrpcError::InvalidParams("at least one uri required".into())); } if uris.len() > BULK_LIMIT { return Err(XrpcError::InvalidParams(format!( "at most {BULK_LIMIT} uris per request" ))); } let parsed: Vec> = uris .iter() .map(|s| parse_uri(s)) .collect::>()?; let nsid = nsid_static(R::NSID); if let Some(bad) = parsed .iter() .find(|uri| uri.collection().is_none_or(|c| c.as_ref() != nsid.as_ref())) { return Err(XrpcError::InvalidParams(format!( "uri collection must be {}, got {}", nsid.as_ref(), bad.as_ref() ))); } bulk_stream::(state, parsed) } fn bulk_stream( state: &AppState, parsed: Vec>, ) -> Result where R: XrpcResp, V: serde::de::DeserializeOwned + Serialize + NormalizeRepoRefs + Send + 'static, { let nsid = nsid_static(R::NSID); let permit = state.heavy_permit()?; let items = parsed .into_iter() .map(|uri| EdgeItem { uri, sort_micros: 0, }) .collect(); let views = hydrate_record_stream::(state, nsid, items, HitProvenance::ClientSupplied); Ok(json_stream::, _>( "items", views, unpaged_tail(), permit, )) } fn record_edge_page( state: &AppState, q: &TypedListQuery, ) -> Result<(EdgePage, Nsid), XrpcError> where R: XrpcResp + HasSubject, F: ListFilter, { let subject = parse_subject(&q.subject, R::SHAPE)?; let cursor = parse_cursor(q.cursor.as_deref())?; let limit = parse_limit(q.limit)?; let dir = q.dir(); let nsid = nsid_static(R::NSID); let page = if q.filter.is_identity() { let key = EdgeKey::new(nsid.clone(), subject); state.edges.list(&key, cursor, limit, dir) } else { let pred = q.filter.predicate(state, &subject); let key = EdgeKey::new(nsid.clone(), subject); state.edges.list_filtered(&key, cursor, limit, dir, pred) }; Ok((page, nsid)) } async fn list_records( state: &AppState, q: TypedListQuery, ) -> Result where R: XrpcResp + HasSubject, V: serde::de::DeserializeOwned + Serialize + NormalizeRepoRefs + Send + 'static, F: ListFilter, { let (page, nsid) = record_edge_page::(state, &q)?; let permit = state.heavy_permit()?; let views = hydrate_record_stream::(state, nsid, page.items, HitProvenance::Indexed); Ok(json_stream::, _>( "items", views, paged_tail(page.next.map(PageToken::encode_token)), permit, )) } fn count_for( state: &AppState, q: CountQuery, ) -> Result { let subject = parse_subject(&q.subject, R::SHAPE)?; let key = EdgeKey::new(nsid_static(R::NSID), subject); Ok(CountResponse { count: state.edges.count(&key), distinct_authors: state.edges.count_distinct_authors(&key), }) } fn count_typed_for( state: &AppState, q: TypedCountQuery, ) -> Result where R: XrpcResp + HasSubject, F: CountFilter, { let subject = parse_subject(&q.subject, R::SHAPE)?; let key = EdgeKey::new(nsid_static(R::NSID), subject); let counted = q.filter.count(state, &key); Ok(CountResponse { count: counted.count.get(), distinct_authors: counted.distinct_authors.get(), }) } // does `actor` have an edge of this kind pointing at `subject`, returns its own uri fn get_for( state: &AppState, q: GetEdgeQuery, ) -> Result { let subject = parse_subject(&q.subject, R::SHAPE)?; let key = EdgeKey::new(nsid_static(R::NSID), subject); let uri = state .edges .viewer_source(&key, q.actor.as_str()) .ok_or(XrpcError::NotFound)?; Ok(EdgeUriResponse { uri }) } fn mirror_edge_page( state: &AppState, q: &TypedListQuery, ) -> Result<(EdgePage, Nsid), XrpcError> where M: MirrorOf, F: ListFilter, { let subject = parse_subject(&q.subject, M::SHAPE)?; let cursor = parse_cursor(q.cursor.as_deref())?; let limit = parse_limit(q.limit)?; let dir = q.dir(); let edge_nsid = nsid_static(M::EDGE_KIND); let page = if q.filter.is_identity() { let key = EdgeKey::new(edge_nsid, subject); state.edges.list(&key, cursor, limit, dir) } else { let pred = q.filter.predicate(state, &subject); let key = EdgeKey::new(edge_nsid, subject); state.edges.list_filtered(&key, cursor, limit, dir, pred) }; let record_nsid = nsid_static(::NSID); Ok((page, record_nsid)) } async fn list_mirror(state: &AppState, q: TypedListQuery) -> Result where M: MirrorOf, V: serde::de::DeserializeOwned + Serialize + NormalizeRepoRefs + Send + 'static, F: ListFilter, { let (page, record_nsid) = mirror_edge_page::(state, &q)?; let permit = state.heavy_permit()?; let views = hydrate_record_stream::(state, record_nsid, page.items, HitProvenance::Indexed); Ok(json_stream::, _>( "items", views, paged_tail(page.next.map(PageToken::encode_token)), permit, )) } fn count_mirror(state: &AppState, q: CountQuery) -> Result { let subject = parse_subject(&q.subject, M::SHAPE)?; let key = EdgeKey::new(nsid_static(M::EDGE_KIND), subject); Ok(CountResponse { count: state.edges.count(&key), distinct_authors: state.edges.count_distinct_authors(&key), }) } async fn list_stars( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_records::, _>(&state, q).await } async fn count_stars( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_for::(&state, q).map(Json) } async fn get_star( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { get_for::(&state, q).map(Json) } async fn list_follows( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_records::, _>(&state, q).await } async fn count_follows( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_for::(&state, q).map(Json) } async fn get_follow( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { get_for::(&state, q).map(Json) } async fn list_issues( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { let (page, nsid) = record_edge_page::(&state, &q)?; let permit = state.heavy_permit()?; let owned = state.clone(); let items = hydrate_record_stream::>( &state, nsid, page.items, HitProvenance::Indexed, ) .map(move |view| view.map(|v| enrich_issue_view(&owned, v))); Ok(json_stream::>, _>( "items", items, paged_tail(page.next.map(PageToken::encode_token)), permit, )) } async fn count_issues( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result, XrpcError> { count_typed_for::(&state, q).map(Json) } async fn list_pulls( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { let (page, nsid) = record_edge_page::(&state, &q)?; let permit = state.heavy_permit()?; let owned = state.clone(); let items = hydrate_record_stream::>(&state, nsid, page.items, HitProvenance::Indexed) .map(move |view| view.map(|v| enrich_pull_view(&owned, v))); Ok(json_stream::>, _>( "items", items, paged_tail(page.next.map(PageToken::encode_token)), permit, )) } async fn count_pulls( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result, XrpcError> { count_typed_for::(&state, q).map(Json) } async fn list_feed_comments( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_records::, _>(&state, q).await } async fn count_feed_comments( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_for::(&state, q).map(Json) } async fn list_reactions( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_records::, _>(&state, q).await } async fn count_reactions( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_for::(&state, q).map(Json) } async fn list_ref_updates( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_records::, _>(&state, q).await } async fn count_ref_updates( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_for::(&state, q).map(Json) } async fn list_collaborators( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_records::, _>(&state, q).await } async fn count_collaborators( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_for::(&state, q).map(Json) } async fn list_issue_states( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_records::, _>(&state, q).await } async fn count_issue_states( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_for::(&state, q).map(Json) } async fn list_pull_statuses( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_records::, _>(&state, q).await } async fn count_pull_statuses( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_for::(&state, q).map(Json) } async fn list_repos( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_records::, _>(&state, q).await } async fn count_repos( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_for::(&state, q).map(Json) } // forks are repo records pointing back at a repo, so they get their own edge // kind instead of a collection async fn count_forks( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { let subject = parse_subject(&q.subject, FORK_SUBJECT_SHAPE)?; let key = EdgeKey::new(nsid_static(REPO_SOURCE_EDGE_KIND), subject); Ok(Json(CountResponse { count: state.edges.count(&key), distinct_authors: state.edges.count_distinct_authors(&key), })) } async fn list_knots( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_records::, _>(&state, q).await } async fn count_knots( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_for::(&state, q).map(Json) } async fn list_spindles( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_records::, _>(&state, q).await } async fn count_spindles( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_for::(&state, q).map(Json) } async fn list_public_keys( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_records::, _>(&state, q).await } async fn count_public_keys( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_for::(&state, q).map(Json) } async fn list_vouches( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_records::, _>(&state, q).await } async fn count_vouches( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_for::(&state, q).map(Json) } async fn list_stars_by( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_mirror::, _>(&state, q).await } async fn count_stars_by( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_mirror::(&state, q).map(Json) } async fn list_reactions_by( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_mirror::, _>(&state, q).await } async fn count_reactions_by( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_mirror::(&state, q).map(Json) } async fn list_follows_by( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_mirror::, _>(&state, q).await } async fn count_follows_by( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_mirror::(&state, q).map(Json) } async fn list_vouches_by( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_mirror::, _>(&state, q).await } async fn count_vouches_by( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_mirror::(&state, q).map(Json) } async fn list_ref_updates_by( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_mirror::, _>(&state, q).await } async fn count_ref_updates_by( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_mirror::(&state, q).map(Json) } async fn list_knot_members_by( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_mirror::, _>(&state, q).await } async fn count_knot_members_by( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_mirror::(&state, q).map(Json) } async fn list_label_ops_by( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_mirror::, _>(&state, q).await } async fn count_label_ops_by( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_mirror::(&state, q).map(Json) } async fn list_pipelines_by( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_mirror::, _>(&state, q).await } async fn count_pipelines_by( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_mirror::(&state, q).map(Json) } async fn list_pipeline_statuses_by( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_mirror::, _>(&state, q).await } async fn count_pipeline_statuses_by( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_mirror::(&state, q).map(Json) } async fn list_artifacts_by( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_mirror::, _>(&state, q).await } async fn count_artifacts_by( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_mirror::(&state, q).map(Json) } async fn list_collaborators_by( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_mirror::, _>(&state, q).await } async fn count_collaborators_by( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_mirror::(&state, q).map(Json) } async fn list_issues_by( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { let (page, nsid) = mirror_edge_page::(&state, &q)?; let permit = state.heavy_permit()?; let owned = state.clone(); let items = hydrate_record_stream::>( &state, nsid, page.items, HitProvenance::Indexed, ) .map(move |view| view.map(|v| enrich_issue_view(&owned, v))); Ok(json_stream::>, _>( "items", items, paged_tail(page.next.map(PageToken::encode_token)), permit, )) } async fn count_issues_by( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_mirror::(&state, q).map(Json) } async fn list_feed_comments_by( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_mirror::, _>(&state, q).await } async fn count_feed_comments_by( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_mirror::(&state, q).map(Json) } async fn list_issue_states_by( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_mirror::, _>(&state, q).await } async fn count_issue_states_by( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_mirror::(&state, q).map(Json) } async fn list_pulls_by( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { let (page, nsid) = mirror_edge_page::(&state, &q)?; let permit = state.heavy_permit()?; let owned = state.clone(); let items = hydrate_record_stream::>(&state, nsid, page.items, HitProvenance::Indexed) .map(move |view| view.map(|v| enrich_pull_view(&owned, v))); Ok(json_stream::>, _>( "items", items, paged_tail(page.next.map(PageToken::encode_token)), permit, )) } async fn count_pulls_by( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_mirror::(&state, q).map(Json) } async fn list_pull_statuses_by( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_mirror::, _>(&state, q).await } async fn count_pull_statuses_by( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_mirror::(&state, q).map(Json) } async fn list_spindle_members_by( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_mirror::, _>(&state, q).await } async fn count_spindle_members_by( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_mirror::(&state, q).map(Json) } async fn list_label_definitions( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_records::, _>(&state, q).await } async fn count_label_definitions( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_for::(&state, q).map(Json) } async fn list_label_ops( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_records::, _>(&state, q).await } async fn count_label_ops( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_for::(&state, q).map(Json) } async fn list_pipelines( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_records::, _>(&state, q).await } async fn count_pipelines( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_for::(&state, q).map(Json) } async fn list_pipeline_statuses( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_records::, _>(&state, q).await } async fn count_pipeline_statuses( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_for::(&state, q).map(Json) } async fn list_artifacts( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_records::, _>(&state, q).await } async fn count_artifacts( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_for::(&state, q).map(Json) } async fn list_knot_members( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_records::, _>(&state, q).await } async fn count_knot_members( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_for::(&state, q).map(Json) } async fn list_spindle_members( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_records::, _>(&state, q).await } async fn count_spindle_members( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_for::(&state, q).map(Json) } async fn list_strings( State(state): State, XrpcQuery(q): XrpcQuery>, ) -> Result { list_records::, _>(&state, q).await } async fn count_strings( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result, XrpcError> { count_for::(&state, q).map(Json) } #[derive(Deserialize)] struct ResolveMiniDocParams { identifier: AtIdentifier, } async fn resolve_mini_doc( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result { let doc = state .identity .resolve_minidoc(&q.identifier) .await .map_err(|error| match error { IdentityResolveError::NotFound => XrpcError::NotFound, IdentityResolveError::Upstream(message) => XrpcError::UpstreamUnavailable(message), IdentityResolveError::Decode(message) => XrpcError::InvalidRecord(message), })?; Ok(Json(doc).into_response()) } async fn get_coverage(State(state): State) -> Json { Json(state.coverage.snapshot().into()) } async fn search_query( State(state): State, XrpcQuery(q): XrpcQuery, ) -> Result { if q.q.trim().is_empty() { return Err(XrpcError::InvalidParams("q must not be empty".into())); } let cursor = SearchCursor::from_token(q.cursor.as_deref()) .map_err(|e| XrpcError::InvalidParams(format!("cursor: {e}")))?; let limit = parse_limit(q.limit)?; let filters = build_search_filters(&q)?; let permit = state.heavy_permit()?; let page = state .search .search(&q.q, filters, cursor, limit.get()) .await .map_err(map_search_err)?; let next = page.next.map(SearchOffset::encode_token); let owned = state.clone(); let hits = hydrate_stream(page.hits, move |hit| { let owned = owned.clone(); let uri = hit.uri.clone(); let nsid = hit.nsid.clone(); async move { let result = hydrate_search_hit(&owned, hit).await; drop_unhydratable(HitProvenance::Indexed, &nsid, &uri, result) } }); Ok(json_stream::( "hits", hits, paged_tail(next), permit, )) } fn build_search_filters(q: &SearchQueryParams) -> Result { let since = q .since .as_deref() .map(parse_rfc3339_seconds) .transpose() .map_err(|e| XrpcError::InvalidParams(format!("since: {e}")))?; let until = q .until .as_deref() .map(parse_rfc3339_seconds) .transpose() .map_err(|e| XrpcError::InvalidParams(format!("until: {e}")))?; if let (Some(s), Some(u)) = (since, until) && s > u { return Err(XrpcError::InvalidParams("since must be <= until".into())); } Ok(SearchFilters { nsid: q.nsid.clone(), author: q.author.clone(), repo: q.repo.clone(), since, until, }) } fn parse_rfc3339_seconds(raw: &str) -> Result { chrono::DateTime::parse_from_rfc3339(raw) .map(|dt| dt.timestamp()) .map_err(|e| format!("expected RFC3339, got {raw}: {e}")) } async fn hydrate_search_hit( state: &AppState, hit: SearchHit, ) -> Result, XrpcError> { let SearchHit { uri, nsid, score } = hit; let body = resolve_for_view(state, &nsid, uri).await?; let record = decode_canon_or_upgrade(&nsid, &body.value, &state.resolver) .await .map_err(|err| XrpcError::InvalidRecord(err.to_string()))?; let Some(value) = SearchableRecord::try_from_record(record) else { return Ok(None); }; let Some(value) = value.normalize(&state.resolver).await else { return Ok(None); }; Ok(Some(SearchHitView { uri: body.uri.clone(), cid: Some(body.cid.clone()), nsid, score, value, })) } fn map_search_err(err: SearchError) -> XrpcError { use SearchError as E; match err { E::Query(e) => XrpcError::InvalidParams(format!("query: {e}")), e @ (E::Tantivy(_) | E::InvalidUri(_) | E::InvalidNsid(_) | E::MissingField(_) | E::Cancelled(_)) => XrpcError::Internal(format!("search: {e}")), } } fn map_proxy_error(err: KnotProxyError) -> XrpcError { match err { KnotProxyError::CircuitOpen => { XrpcError::UpstreamUnavailable("knot circuit breaker open".into()) } KnotProxyError::BlockedHost { host, reason } => { XrpcError::InvalidRecord(format!("knot host {host} is {reason} address space")) } KnotProxyError::PlaintextHttp { host } => { XrpcError::InvalidRecord(format!("knot host {host} requires https")) } KnotProxyError::Connect(e) => XrpcError::UpstreamUnavailable(format!("connect: {e}")), KnotProxyError::Timeout(e) => { XrpcError::UpstreamUnavailable(format!("upstream timeout: {e}")) } KnotProxyError::Redirect(e) => XrpcError::UpstreamUnavailable(format!("redirect: {e}")), KnotProxyError::Transport(e) => XrpcError::UpstreamUnavailable(format!("transport: {e}")), KnotProxyError::Upstream(s) => XrpcError::UpstreamUnavailable(format!("status {s}")), } } fn validate_client_supplied_knot(state: &AppState, host: &KnotHost) -> Result<(), XrpcError> { let host_str = || host.url().host_str().unwrap_or_default().to_owned(); if state.knots.requires_https() && host.url().scheme() != "https" { return Err(XrpcError::InvalidParams(format!( "knot host {} must be https", host_str(), ))); } if state.knots.allows_private_hosts() { return Ok(()); } match host.private_literal_reason() { None => Ok(()), Some(reason) => Err(XrpcError::InvalidParams(format!( "knot host {} blocked: {} address space", host_str(), reason, ))), } } async fn resolve_knot_target( state: &AppState, repo_uri: AtUri, ) -> Result<(KnotHost, RepoSlug), XrpcError> { let rkey: Option> = repo_uri.rkey().map(|r| r.clone().into_static()); let (body, did) = resolve(state, ExpectedNsid::from_static(RepoRecord::NSID), repo_uri).await?; let value: Repo = serde_json::from_slice(&body.value) .map_err(|e| XrpcError::InvalidRecord(format!("decode repo record: {e}")))?; let host = KnotHost::parse(value.knot.as_ref()) .map_err(|e| XrpcError::InvalidRecord(format!("knot field: {e}")))?; let name = pick_human_slug(rkey.as_ref(), value.name.as_deref()).ok_or_else(|| { XrpcError::InvalidRecord("at-uri missing rkey and record missing name".to_string()) })?; let slug = RepoSlug::new(&did, &name) .map_err(|e| XrpcError::InvalidRecord(format!("repo slug: {e}")))?; Ok((host, slug)) } fn pick_human_slug(rkey: Option<&Rkey>, name: Option<&str>) -> Option { match rkey { Some(r) if jacquard_common::types::tid::Tid::new(r.as_ref()).is_ok() => { Some(name.unwrap_or(r.as_ref()).to_owned()) } Some(r) => Some(r.as_ref().to_owned()), None => name.map(str::to_owned), } } fn filter_request_headers( client: &HeaderMap, socket: SocketPeer, address: &ClientAddress, ) -> HeaderMap { let forwarded = FORWARDED_REQUEST_HEADERS .iter() .fold(HeaderMap::new(), |mut acc, name| { if let Some(value) = client.get(*name) { acc.insert((*name).clone(), value.clone()); } acc }); address .of(client, socket) .into_iter() .fold(forwarded, |mut acc, address| { acc.insert(X_FORWARDED_FOR.clone(), address); acc }) } fn upstream_to_axum(resp: ProxyResponse) -> Response { let status = resp.status(); let upstream_headers = resp.headers().clone(); let body = Body::from_stream(resp.into_body_stream()); let mut response = Response::builder() .status(status) .body(body) .expect("response body construction must succeed"); let response_headers = response.headers_mut(); PASSTHROUGH_HEADERS.iter().for_each(|name| { if let Some(value) = upstream_headers.get(*name) { response_headers.insert((*name).clone(), value.clone()); } }); response } async fn dispatch_proxy( state: AppState, headers: HeaderMap, socket: SocketPeer, nsid: Nsid, host: KnotHost, params: ProxyParams, ) -> Result { let forward: Vec<(&str, &str)> = params .iter() .map(|(k, v)| (k.as_str(), v.as_str())) .collect(); let allowed = filter_request_headers(&headers, socket, &state.client_address); let upstream = state .knots .forward(&host, &nsid, &forward, allowed) .await .map_err(map_proxy_error)?; Ok(upstream_to_axum(upstream)) } fn extract_param( params: ProxyParams, key: &str, ) -> Result, XrpcError> { let (matching, rest): (ProxyParams, ProxyParams) = params.into_iter().partition(|(k, _)| k == key); match matching.as_slice() { [] => Ok(None), [_] => Ok(matching.into_iter().next().map(|(_, v)| (v, rest))), _ => Err(XrpcError::InvalidParams(format!( "{key} parameter must appear at most once, got {}", matching.len(), ))), } } async fn proxy_repo_handler( state: AppState, headers: HeaderMap, socket: SocketPeer, params: ProxyParams, nsid: Nsid, ) -> Result { let (repo_raw, rest) = extract_param(params, REPO_PARAM)? .ok_or_else(|| XrpcError::InvalidParams("missing repo".into()))?; let repo_uri = parse_uri(&repo_raw)?; let (host, slug) = resolve_knot_target(&state, repo_uri).await?; let forward = rest .into_iter() .chain(std::iter::once(( REPO_PARAM.to_owned(), slug.as_str().to_owned(), ))) .collect(); dispatch_proxy(state, headers, socket, nsid, host, forward).await } async fn proxy_knot_handler( state: AppState, headers: HeaderMap, socket: SocketPeer, params: ProxyParams, nsid: Nsid, ) -> Result { let (knot_raw, forward) = extract_param(params, KNOT_HOST_PARAM)? .ok_or_else(|| XrpcError::InvalidParams("missing knot".into()))?; let host = KnotHost::parse(&knot_raw).map_err(|e| XrpcError::InvalidParams(format!("knot: {e}")))?; validate_client_supplied_knot(&state, &host)?; dispatch_proxy(state, headers, socket, nsid, host, forward).await }