Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 8.5 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Discovery: explore, search, topics and profiles (section 16).
5//!
6//! Explore and search list public repositories that landed something, of
7//! owners established on the hub. A query is at most [`MAX_QUERY`]
8//! characters, in at most [`MAX_TERMS`] terms, and each term matches the
9//! start of a word of a repository's owner, name, description or topics:
10//! [`terms`] says which queries a hub takes, so that a client can check
11//! one before it sends it. Lists come a page at a time, at most
12//! [`MAX_PAGES`] pages of one query.
13
14use std::fmt;
15
16use serde::{Deserialize, Serialize};
17
18/// The most characters of a query.
19pub const MAX_QUERY: usize = 100;
20
21/// The most terms of a query.
22pub const MAX_TERMS: usize = 10;
23
24/// The most pages of one query of explore, search or topics: past them,
25/// a page answers no `next`.
26pub const MAX_PAGES: usize = 50;
27
28/// The order of best matches first: the default with a query.
29pub const MATCH: &str = "match";
30
31/// The order of the latest landing first: the default without a query.
32pub const RECENT: &str = "recent";
33
34/// The order of the most stars first.
35pub const STARS: &str = "stars";
36
37/// The order of the newest repositories first.
38pub const NEW: &str = "new";
39
40/// The orders of explore and search.
41pub const SORTS: [&str; 4] = [MATCH, RECENT, STARS, NEW];
42
43/// Every repository of an account the caller may read: the default `type`.
44pub const ALL: &str = "all";
45
46/// Its public repositories only.
47pub const PUBLIC: &str = "public";
48
49/// Its private repositories only, of those the caller may read.
50pub const PRIVATE: &str = "private";
51
52/// Its repositories that are not forks.
53pub const SOURCES: &str = "sources";
54
55/// Its forks.
56pub const FORKS: &str = "forks";
57
58/// The kinds of an account's repositories a list holds (`type`).
59pub const REPO_TYPES: [&str; 5] = [ALL, PUBLIC, PRIVATE, SOURCES, FORKS];
60
61/// An account's repositories by their latest landing, newest first, those
62/// that never landed last: the default `sort`.
63pub const PUSHED: &str = "pushed";
64
65/// By name.
66pub const NAME: &str = "name";
67
68/// By when they were made, newest first.
69pub const CREATED: &str = "created";
70
71/// The orders of an account's repositories (`sort`).
72pub const REPO_SORTS: [&str; 3] = [PUSHED, NAME, CREATED];
73
74/// Why a query is refused.
75#[derive(Clone, Debug, PartialEq, Eq)]
76pub enum QueryError {
77 /// It holds more than [`MAX_QUERY`] characters.
78 TooLong,
79 /// It holds more than [`MAX_TERMS`] terms.
80 TooManyTerms,
81 /// It holds a character no term takes.
82 Character(char),
83}
84
85impl fmt::Display for QueryError {
86 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87 match self {
88 QueryError::TooLong => write!(f, "a query holds at most {MAX_QUERY} characters"),
89 QueryError::TooManyTerms => write!(f, "a query holds at most {MAX_TERMS} terms"),
90 QueryError::Character(c) => write!(
91 f,
92 "a query holds terms of letters, digits, '.', '_' and '-', between spaces or '/', not {c:?}"
93 ),
94 }
95 }
96}
97
98impl std::error::Error for QueryError {}
99
100/// Whether a term may hold `c`: a letter, a digit, `.`, `_` or `-`.
101pub fn is_term_char(c: char) -> bool {
102 c.is_alphanumeric() || matches!(c, '.' | '_' | '-')
103}
104
105/// The terms of the query `query`: its words between spaces and `/`, so
106/// that `owner/name` finds a repository by both. A word of `.`, `_` and
107/// `-` alone matches nothing, and is left out; a query left with no term
108/// lists what a query-less one lists.
109pub fn terms(query: &str) -> Result<Vec<String>, QueryError> {
110 if query.chars().count() > MAX_QUERY {
111 return Err(QueryError::TooLong);
112 }
113 let mut terms = Vec::new();
114 for word in query.split(|c: char| c.is_whitespace() || c == '/') {
115 if let Some(bad) = word.chars().find(|c| !is_term_char(*c)) {
116 return Err(QueryError::Character(bad));
117 }
118 if word.chars().any(char::is_alphanumeric) {
119 terms.push(word.to_owned());
120 }
121 }
122 if terms.len() > MAX_TERMS {
123 return Err(QueryError::TooManyTerms);
124 }
125 Ok(terms)
126}
127
128/// A topic, and how many listed repositories have it.
129#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
130pub struct TopicCount {
131 /// The topic: lowercase letters, digits and `-`.
132 pub name: String,
133 /// How many public repositories of established owners have it, forks
134 /// left out.
135 pub repos: u64,
136}
137
138/// `GET /v1/topics`: topics, the most used first.
139#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
140pub struct Topics {
141 /// The topics.
142 pub topics: Vec<TopicCount>,
143 /// The cursor of the next page, or `None` on the last one.
144 #[serde(default)]
145 pub next: Option<String>,
146}
147
148/// `GET /v1/users/{login}`: an account, as the caller may see it.
149#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
150pub struct Profile {
151 /// Its login, lowercase.
152 pub login: String,
153 /// Its display name, if any.
154 #[serde(default)]
155 pub name: Option<String>,
156 /// When the account was made.
157 pub created: String,
158 /// The accounts that follow it.
159 #[serde(default)]
160 pub followers: u64,
161 /// The accounts it follows.
162 #[serde(default)]
163 pub following: u64,
164 /// Its repositories the caller may read.
165 #[serde(default)]
166 pub repos: u64,
167 /// Its stars of repositories the caller may read, or `None` when it
168 /// keeps its stars from the caller.
169 #[serde(default)]
170 pub stars: Option<u64>,
171 /// What the caller itself does with the account, for a signed-in
172 /// caller.
173 #[serde(default, skip_serializing_if = "Option::is_none")]
174 pub viewer: Option<ProfileViewer>,
175}
176
177/// What the caller does with an account.
178#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
179pub struct ProfileViewer {
180 /// Whether it follows it.
181 pub follows: bool,
182}
183
184#[cfg(test)]
185mod tests {
186 use super::*;
187
188 #[test]
189 fn queries_split_into_terms() {
190 assert_eq!(terms("").unwrap(), Vec::<String>::new());
191 assert_eq!(terms(" rust cli ").unwrap(), ["rust", "cli"]);
192 assert_eq!(terms("ada/demo").unwrap(), ["ada", "demo"]);
193 assert_eq!(
194 terms("my-project v1.2 a_b").unwrap(),
195 ["my-project", "v1.2", "a_b"]
196 );
197 assert_eq!(terms("café\tNEAR OR").unwrap(), ["café", "NEAR", "OR"]);
198 // Punctuation alone is no term.
199 assert_eq!(terms("- . _ x").unwrap(), ["x"]);
200 assert_eq!(terms("---").unwrap(), Vec::<String>::new());
201 for (bad, c) in [
202 ("\"rust\"", '"'),
203 ("rust*", '*'),
204 ("(a)", '('),
205 ("a:b", ':'),
206 ("a^b", '^'),
207 ("a\0b", '\0'),
208 ("%_", '%'),
209 ] {
210 assert_eq!(terms(bad), Err(QueryError::Character(c)), "{bad:?}");
211 }
212 let long = "a".repeat(MAX_QUERY + 1);
213 assert_eq!(terms(&long), Err(QueryError::TooLong));
214 // Characters, not bytes.
215 assert!(terms(&"é".repeat(MAX_QUERY)).is_ok());
216 let many = ["a"; MAX_TERMS + 1].join(" ");
217 assert_eq!(terms(&many), Err(QueryError::TooManyTerms));
218 assert!(terms(&["a"; MAX_TERMS].join(" ")).is_ok());
219 assert!(
220 QueryError::Character('\u{7}')
221 .to_string()
222 .contains("\\u{7}")
223 );
224 }
225
226 #[test]
227 fn discovery_on_the_wire() {
228 let hidden = Profile {
229 login: "ada".into(),
230 created: "2026-01-01T00:00:00Z".into(),
231 repos: 2,
232 ..Profile::default()
233 };
234 let text = serde_json::to_string(&hidden).unwrap();
235 // Stars kept private are null, not left out; a viewer is.
236 assert!(text.contains(r#""stars":null"#), "{text}");
237 assert!(!text.contains("viewer"), "{text}");
238 assert_eq!(serde_json::from_str::<Profile>(&text).unwrap(), hidden);
239 let seen = Profile {
240 stars: Some(3),
241 viewer: Some(ProfileViewer { follows: true }),
242 ..hidden
243 };
244 let text = serde_json::to_string(&seen).unwrap();
245 assert!(text.contains(r#""viewer":{"follows":true}"#), "{text}");
246 let topics: Topics =
247 serde_json::from_str(r#"{"topics":[{"name":"rust","repos":4}]}"#).unwrap();
248 assert_eq!(topics.topics[0].repos, 4);
249 assert_eq!(topics.next, None);
250 for sort in SORTS {
251 assert!(!sort.is_empty());
252 }
253 assert_eq!(REPO_TYPES.len(), 5);
254 assert_eq!(REPO_SORTS[0], PUSHED);
255 }
256}