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