Skip to main content

tango_core/
search.rs

1//! Search across everything harvested, videos and playlists together.
2//!
3//! All the work happens in PostgreSQL: `ts_rank` over the generated `fts`
4//! columns, and `word_similarity` over trigram-indexed titles. Scoring in Rust
5//! would mean reading rows and ranking them in memory, throwing away the GIN
6//! indexes that make this fast.
7//!
8//! Results come back in two tiers. A full-text hit is stronger evidence than a
9//! fuzzy title match, so it always sorts above one - see the comment in
10//! `sql/0005_search.sql` for why those cannot share a single rank.
11
12use sea_orm::{ConnectionTrait, DatabaseConnection, DbBackend, QueryResult, Statement};
13
14#[derive(Debug, Clone)]
15pub struct SearchHit {
16    pub id: String,
17    pub channel_id: String,
18    pub title: String,
19    pub description: String,
20    pub thumbnail_url: String,
21    pub published_at: Option<chrono::DateTime<chrono::FixedOffset>>,
22    /// `video` or `playlist`.
23    pub source: String,
24    pub score: f32,
25    /// 2 for a title/description/tags full-text hit, 1 for a fuzzy title match,
26    /// 0 for a transcript hit. Separate tiers rather than one numeric scale,
27    /// because a title match and a transcript hit are different kinds of
28    /// evidence - see migration 0011.
29    pub match_tier: i32,
30    /// The mode that matched: `fts`, `fuzzy`, `substring` or `transcript`.
31    pub matched_by: String,
32    /// Which field it matched in: `title`, `description`, `tags` or
33    /// `transcript`. Null only for a fuzzy hit, which only ever looks at
34    /// titles and would otherwise be redundant with `matched_by`.
35    pub matched_field: Option<String>,
36    pub snippet: String,
37    /// Position of the best matching transcript cue, in milliseconds. `None`
38    /// for everything that is not a transcript.
39    ///
40    /// Seek with `player.seekTo(start_ms / 1000)`. This is the reason a
41    /// transcript hit is worth surfacing separately from a title match: it
42    /// answers *where*, not just *which video*.
43    pub start_ms: Option<i32>,
44}
45
46#[derive(Debug, Clone)]
47pub struct SearchQuery {
48    pub text: String,
49    pub page: u32,
50    pub page_size: u32,
51    /// Which text may match. `None` means every field, which is what the
52    /// database does with a NULL list.
53    pub search_in: Option<Vec<String>>,
54    /// Literal matching over `search_in`, rather than the text index.
55    pub substring: bool,
56    pub channel_id: Option<String>,
57    /// Postgres text search configuration, e.g. `english`, `spanish`, `simple`.
58    pub text_config: String,
59    /// Include the fuzzy trigram tier. See the note on the SQL: it matches
60    /// whole words, so it forgives a typo without matching a fragment of an
61    /// unrelated one, and a well-formed query may still want it off.
62    pub include_fuzzy: bool,
63    pub sort_by: SearchSort,
64    /// Descending. Meaningless for [`SearchSort::Relevance`], which is always
65    /// best-first; the database is told so explicitly rather than being handed
66    /// a flag it would honour and ignore.
67    pub desc: bool,
68}
69
70/// What a search is ordered by.
71///
72/// Serializable so a front-end can echo the order it applied, with the variant
73/// names matching what [`SearchSort::parse`] accepts — `published_at`, not
74/// `PublishedAt`.
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
76#[serde(rename_all = "snake_case")]
77pub enum SearchSort {
78    /// Tier, then field, then score. What a search has always returned.
79    #[default]
80    Relevance,
81    PublishedAt,
82    Title,
83}
84
85impl SearchSort {
86    /// The name the database takes.
87    pub fn as_str(&self) -> &'static str {
88        match self {
89            SearchSort::Relevance => "relevance",
90            SearchSort::PublishedAt => "published_at",
91            SearchSort::Title => "title",
92        }
93    }
94
95    /// Every accepted key, for an error message.
96    pub fn all() -> [&'static str; 3] {
97        ["relevance", "published_at", "title"]
98    }
99
100    /// Parses a sort key, or explains what was expected.
101    ///
102    /// An unknown key is refused rather than ignored, for the same reason an
103    /// unknown field is: a search that quietly ignored the sort it was asked
104    /// for looks exactly like one that honoured it. `score` is deliberately not
105    /// accepted — ts_rank is not comparable across tiers, which is the reason
106    /// the tiers exist.
107    pub fn parse(raw: &str) -> Result<Self, InvalidQuery> {
108        match raw.trim().to_lowercase().as_str() {
109            "relevance" | "relevance_score" | "best" => Ok(SearchSort::Relevance),
110            "published_at" | "published" | "date" | "newest" => Ok(SearchSort::PublishedAt),
111            "title" | "alphabetical" => Ok(SearchSort::Title),
112            other => Err(InvalidQuery(format!(
113                "unknown sort key {other:?}. Expected one of: {}",
114                SearchSort::all().join(", ")
115            ))),
116        }
117    }
118}
119
120impl std::str::FromStr for SearchSort {
121    type Err = InvalidQuery;
122
123    fn from_str(s: &str) -> Result<Self, Self::Err> {
124        SearchSort::parse(s)
125    }
126}
127
128/// Every field a search can be pointed at, in the order the help lists them.
129/// The text `search` may match, in the order they are ranked.
130///
131/// Metadata only. Transcripts are not here: they are a separate body of text
132/// with their own endpoint (`/transcripts/search`, `search_transcripts()`),
133/// their own ranking and their own seek positions. Leaving them reachable from
134/// `in` made a result depend on which videos happened to have been fetched -
135/// 40 of 8,748 on the dev corpus - which is not a property a search should
136/// have.
137pub const SEARCH_FIELDS: [&str; 3] = ["title", "description", "tags"];
138
139/// The text search configuration the generated tsvector columns are built with.
140///
141/// Advisory for videos and playlists, whose columns are generated at
142/// `'english'` and cannot be reconfigured without rewriting the table. It does
143/// apply to the query, so a differently-worded query parses differently — but
144/// the stored vectors will not have been stemmed that way, which is why the
145/// parameter exists and why the generated columns are the hard constraint.
146pub const DEFAULT_TEXT_CONFIG: &str = "english";
147
148/// A query that cannot be searched, and why.
149///
150/// A plain message rather than an error enum, because the two callers want
151/// different things from a refusal: the CLI prints it, the API turns it into a
152/// 400. Neither needs to match on which rule was broken.
153#[derive(Debug)]
154pub struct InvalidQuery(pub String);
155
156impl std::fmt::Display for InvalidQuery {
157    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
158        f.write_str(&self.0)
159    }
160}
161
162impl std::error::Error for InvalidQuery {}
163
164/// The longest query accepted, in characters.
165pub const MAX_QUERY_CHARS: usize = 100;
166
167/// The shortest. Two characters produce a tsquery that matches most of a
168/// corpus, which is a scan dressed up as a search.
169pub const MIN_QUERY_CHARS: usize = 3;
170
171/// Reduces a query to the text worth searching, or refuses it.
172///
173/// The character filter is not decoration. The search function is called twice
174/// per transcript hit: once for the AND that decides which documents match, and
175/// again to build an OR-ed variant that locates a cue. An unbalanced quote is
176/// absorbed by the first and is a parse error in the second, so the input is
177/// reduced to characters that mean something before it ever reaches SQL.
178///
179/// This lived only in the API, which meant the CLI could be handed a query that
180/// the same database would have rejected - and would fail on it with a
181/// Postgres parse error instead of a sentence saying what was wrong.
182pub fn validate_query(raw: &str) -> Result<String, InvalidQuery> {
183    let q = raw.trim();
184    if q.is_empty() {
185        return Err(InvalidQuery("q cannot be empty".into()));
186    }
187    if q.chars().count() < MIN_QUERY_CHARS {
188        return Err(InvalidQuery(format!(
189            "q must be at least {MIN_QUERY_CHARS} characters"
190        )));
191    }
192    if q.chars().count() > MAX_QUERY_CHARS {
193        return Err(InvalidQuery(format!(
194            "q must be {MAX_QUERY_CHARS} characters or less"
195        )));
196    }
197
198    let q: String = q
199        .chars()
200        .filter(|c| c.is_alphanumeric() || c.is_whitespace() || "-:'\"()".contains(*c))
201        .collect();
202    let q = q.trim().to_string();
203
204    if q.is_empty() {
205        return Err(InvalidQuery("q contains no searchable characters".into()));
206    }
207    Ok(q)
208}
209
210/// Parses `--in` into the list the database takes.
211///
212/// A comma-separated list rather than a repeated flag, so it reads the same in
213/// a shell as in a URL. Aliases exist because `desc` is what people type; the
214/// database is given the canonical name, so it never has to know either.
215///
216/// `transcript` and `transcripts` are no longer accepted here and are refused
217/// like any other unknown field, naming the three that are. Silently ignoring
218/// them would leave `?in=title,transcript` searching titles and looking like a
219/// query with no matches.
220///
221/// An unknown field is refused rather than ignored. A field this search does
222/// not understand is a typo, and a typo that silently narrows the result set
223/// looks exactly like a query with no matches - which is the same failure the
224/// fuzzy tier had, where a misspelled parameter quietly changed what was
225/// searched.
226pub fn parse_search_fields(raw: Option<&str>) -> anyhow::Result<Vec<String>> {
227    let Some(raw) = raw else {
228        return Ok(SEARCH_FIELDS.iter().map(|f| f.to_string()).collect());
229    };
230
231    let mut fields: Vec<String> = Vec::new();
232    for part in raw.split(',') {
233        let part = part.trim().to_lowercase();
234        if part.is_empty() {
235            continue;
236        }
237        let canonical = match part.as_str() {
238            "title" | "titles" => "title",
239            "description" | "desc" | "descriptions" => "description",
240            "tags" | "tag" => "tags",
241            other => anyhow::bail!(
242                "unknown search field {other:?}. Expected a comma-separated list of: {}",
243                SEARCH_FIELDS.join(", ")
244            ),
245        };
246        if !fields.iter().any(|f| f == canonical) {
247            fields.push(canonical.to_string());
248        }
249    }
250
251    if fields.is_empty() {
252        anyhow::bail!(
253            "--in named no fields. Expected a comma-separated list of: {}",
254            SEARCH_FIELDS.join(", ")
255        );
256    }
257    Ok(fields)
258}
259
260/// Deliberately not built with the query builder: the search is a call to
261/// `search_content`, and hand-rolling it in SeaQuery would only obscure what
262/// SQL actually runs. Values are still bound, never interpolated.
263///
264/// The `::int` and `::text[]` casts are required. Rust's `u32` arrives as
265/// PostgreSQL `bigint`, and function resolution will not narrow bigint to int
266/// implicitly, so the call fails to resolve without them - and the same applies
267/// to a `Vec<String>` arriving as an unknown-type array.
268const CALL: &str = "SELECT * FROM public.search_content(\
269     $1, $2::int, $3::int, $4::text[], $5, $6::regconfig, $7, $8, $9, $10)";
270
271/// The same call without the paging parameters or the sort, for a total.
272///
273/// It takes fewer arguments than [`CALL`] binds, which is why the two cannot
274/// share one value list: sqlx-postgres rejects a statement supplied with more
275/// parameters than it declares. Order cannot change how many rows match, so
276/// leaving the sort out is not leaving anything out of the answer.
277const COUNT: &str = "SELECT public.search_content_count(\
278     $1, $4::text[], $5, $6::regconfig, $7, $8)";
279
280/// The values the paged call binds, in the order it expects.
281///
282/// The sort is bound as text rather than interpolated: the key is a closed set
283/// validated in Rust, and a bound value cannot be a column name anyway.
284fn values(q: &SearchQuery, page: u32, page_size: u32) -> Vec<sea_orm::Value> {
285    vec![
286        q.text.clone().into(),
287        page.max(1).into(),
288        page_size.max(1).into(),
289        search_fields_value(q.search_in.as_deref()),
290        q.channel_id.clone().into(),
291        q.text_config.clone().into(),
292        q.include_fuzzy.into(),
293        q.substring.into(),
294        q.sort_by.as_str().into(),
295        q.desc.into(),
296    ]
297}
298
299/// The values the counting call binds: the same search, without the paging and
300/// without the sort, which are the last two arguments.
301fn count_values(q: &SearchQuery) -> Vec<sea_orm::Value> {
302    let mut values = values(q, 1, 1);
303    values.truncate(8);
304    values
305}
306
307/// How many results a search has in total.
308///
309/// Counts the same `search_all_hits` the page comes from, so a total and a page
310/// cannot describe different searches. A caller that wants a pager needs this
311/// and had no way to ask before.
312pub async fn count(db: &DatabaseConnection, q: &SearchQuery) -> anyhow::Result<u64> {
313    let statement = Statement::from_sql_and_values(DbBackend::Postgres, COUNT, count_values(q));
314
315    let row = db
316        .query_one_raw(statement)
317        .await
318        .map_err(|e| anyhow::anyhow!("search count failed: {e}"))?;
319
320    // `search_content_count` returns bigint, and sqlx-postgres has no u64
321    // codec - reading it as one fails at runtime.
322    Ok(row
323        .map(|row| row.try_get::<i64>("", "search_content_count"))
324        .transpose()?
325        .unwrap_or(0)
326        .max(0) as u64)
327}
328
329pub async fn search(db: &DatabaseConnection, q: &SearchQuery) -> anyhow::Result<Vec<SearchHit>> {
330    let statement =
331        Statement::from_sql_and_values(DbBackend::Postgres, CALL, values(q, q.page, q.page_size));
332
333    let rows = db
334        .query_all_raw(statement)
335        .await
336        .map_err(|e| anyhow::anyhow!("search failed: {e}"))?;
337
338    rows.iter().map(to_hit).collect()
339}
340
341/// The field list as a bound value, or SQL NULL for "every field".
342///
343/// NULL rather than an explicit four-element list so the database's default is
344/// the single definition of what an unqualified search covers, and a caller
345/// that passes nothing cannot drift from it.
346///
347/// Built by hand rather than through `Value::from`, which has no array
348/// conversion for strings. The `$4::text[]` cast in the call is what makes
349/// function resolution work; an untyped array parameter would not resolve.
350fn search_fields_value(fields: Option<&[String]>) -> sea_orm::Value {
351    match fields {
352        Some(fields) => sea_orm::Value::Array(
353            sea_orm::sea_query::ArrayType::String,
354            Some(Box::new(
355                fields
356                    .iter()
357                    .map(|f| sea_orm::Value::String(Some(f.clone())))
358                    .collect(),
359            )),
360        ),
361        None => sea_orm::Value::String(None),
362    }
363}
364
365fn to_hit(row: &QueryResult) -> anyhow::Result<SearchHit> {
366    // Read straight into the chrono type. The column is TIMESTAMPTZ, so
367    // pulling it out as text and re-parsing would both fail and lose the
368    // offset Postgres already resolved.
369    let published_at: Option<chrono::DateTime<chrono::FixedOffset>> =
370        row.try_get("", "published_at")?;
371    Ok(SearchHit {
372        id: row.try_get("", "id")?,
373        channel_id: row.try_get("", "channel_id")?,
374        title: row.try_get("", "title")?,
375        description: row.try_get("", "description")?,
376        thumbnail_url: row.try_get("", "thumbnail_url")?,
377        published_at,
378        source: row.try_get("", "source")?,
379        score: row.try_get("", "score")?,
380        match_tier: row.try_get("", "match_tier")?,
381        matched_by: row.try_get("", "matched_by")?,
382        matched_field: row.try_get("", "matched_field")?,
383        snippet: row.try_get("", "snippet")?,
384        start_ms: row.try_get("", "start_ms")?,
385    })
386}
387
388impl SearchHit {
389    /// A timestamped watch URL for a transcript hit, a plain one otherwise.
390    ///
391    /// The `&t=` parameter is seconds, which is why this divides. It is
392    /// YouTube's own convention, so the link works when pasted anywhere.
393    pub fn reference(&self) -> String {
394        match self.source.as_str() {
395            "playlist" => format!("https://www.youtube.com/playlist?list={}", self.id),
396            "transcript" => match self.start_ms {
397                Some(ms) => format!(
398                    "https://www.youtube.com/watch?v={}&t={}s",
399                    self.id,
400                    ms / 1000
401                ),
402                None => format!("https://www.youtube.com/watch?v={}", self.id),
403            },
404            _ => format!("https://www.youtube.com/watch?v={}", self.id),
405        }
406    }
407}
408
409#[cfg(test)]
410mod tests {
411    use super::*;
412
413    fn hit(source: &str) -> SearchHit {
414        SearchHit {
415            id: "abc".into(),
416            channel_id: "UC_x".into(),
417            title: "t".into(),
418            description: String::new(),
419            thumbnail_url: String::new(),
420            published_at: None,
421            source: source.into(),
422            score: 0.5,
423            match_tier: 1,
424            matched_by: "fts".into(),
425            matched_field: Some("title".into()),
426            snippet: String::new(),
427            start_ms: None,
428        }
429    }
430
431    #[test]
432    fn video_hits_reference_a_watch_url() {
433        assert_eq!(
434            hit("video").reference(),
435            "https://www.youtube.com/watch?v=abc"
436        );
437    }
438
439    #[test]
440    fn playlist_hits_reference_a_playlist_url() {
441        // The id is already a playlist id, so it is not wrapped in a watch URL.
442        assert_eq!(
443            hit("playlist").reference(),
444            "https://www.youtube.com/playlist?list=abc"
445        );
446    }
447
448    #[test]
449    fn a_transcript_hit_links_straight_to_the_moment() {
450        // The whole point of keeping transcripts in their own tier: the result
451        // answers *where*, not just which video.
452        let mut transcript = hit("transcript");
453        transcript.start_ms = Some(7_320);
454        assert_eq!(
455            transcript.reference(),
456            "https://www.youtube.com/watch?v=abc&t=7s"
457        );
458    }
459
460    #[test]
461    fn a_transcript_hit_without_a_position_is_still_linkable() {
462        // A document can match with no cue at all, if the phrase only survives
463        // deduplication. Better a working link than a broken one.
464        assert_eq!(
465            hit("transcript").reference(),
466            "https://www.youtube.com/watch?v=abc"
467        );
468    }
469
470    #[test]
471    fn the_seek_parameter_is_seconds_not_milliseconds() {
472        // `&t=` takes seconds. Passing milliseconds would seek to roughly
473        // 1000x the intended position - a plausible-looking link that lands
474        // somewhere else entirely.
475        let mut transcript = hit("transcript");
476        transcript.start_ms = Some(94_160);
477        assert!(transcript.reference().ends_with("&t=94s"));
478    }
479
480    // --- the field list ---
481
482    #[test]
483    fn no_list_means_every_field() {
484        // The database holds the definition of an unqualified search, so this
485        // is only about the explicit spelling. The two must agree; if a field
486        // is ever added, both lists grow together or the default quietly stops
487        // covering it.
488        assert_eq!(parse_search_fields(None).unwrap(), SEARCH_FIELDS.to_vec());
489    }
490
491    #[test]
492    fn a_list_is_split_and_trimmed() {
493        assert_eq!(
494            parse_search_fields(Some(" title , description ")).unwrap(),
495            vec!["title", "description"]
496        );
497    }
498
499    #[test]
500    fn aliases_resolve_to_the_canonical_name() {
501        // `desc` is what people type. The database only ever sees the canonical
502        // name, so it does not have to know either spelling.
503        assert_eq!(
504            parse_search_fields(Some("titles,desc,tag")).unwrap(),
505            vec!["title", "description", "tags"]
506        );
507    }
508
509    #[test]
510    fn transcripts_are_refused_as_a_field() {
511        // Transcripts moved to their own endpoint. Refusing the word is the
512        // point: ignoring it would leave `?in=title,transcript` searching
513        // titles and reporting no matches, which reads as "nothing says this"
514        // rather than "you asked the wrong endpoint".
515        let err = parse_search_fields(Some("title,transcript")).unwrap_err();
516        let message = err.to_string();
517        assert!(message.contains("transcript"), "{message}");
518        assert!(message.contains("title, description, tags"), "{message}");
519    }
520
521    #[test]
522    fn a_repeated_field_is_collapsed() {
523        assert_eq!(
524            parse_search_fields(Some("title,title,tags")).unwrap(),
525            vec!["title", "tags"]
526        );
527    }
528
529    #[test]
530    fn an_unknown_field_is_refused_rather_than_ignored() {
531        // A misspelled field that narrowed the search would look exactly like
532        // a query with no matches, which is indistinguishable from the truth.
533        let err = parse_search_fields(Some("title,descriptionsss")).unwrap_err();
534        let message = err.to_string();
535        assert!(message.contains("descriptionsss"), "{message}");
536        assert!(message.contains("title, description, tags"), "{message}");
537    }
538
539    #[test]
540    fn an_empty_list_is_refused() {
541        // It would otherwise reach the database as "match nothing" and return
542        // zero results, which reads as "nothing matched" rather than "nothing
543        // was asked for".
544        assert!(parse_search_fields(Some(" , ")).is_err());
545        assert!(parse_search_fields(Some("")).is_err());
546    }
547
548    #[test]
549    fn an_unqualified_search_binds_null_rather_than_the_full_list() {
550        // NULL, so the database default is the one definition of "everything"
551        // and a caller that passes nothing cannot drift from it.
552        assert!(matches!(
553            search_fields_value(None),
554            sea_orm::Value::String(None)
555        ));
556    }
557
558    // --- the sort ---
559
560    #[test]
561    fn relevance_is_the_default_sort() {
562        assert_eq!(SearchSort::default(), SearchSort::Relevance);
563    }
564
565    #[test]
566    fn the_three_sort_keys_parse_in_any_case() {
567        for (raw, expected) in [
568            ("relevance", SearchSort::Relevance),
569            ("Relevance", SearchSort::Relevance),
570            ("published_at", SearchSort::PublishedAt),
571            ("PUBLISHED_AT", SearchSort::PublishedAt),
572            ("  title ", SearchSort::Title),
573        ] {
574            assert_eq!(SearchSort::parse(raw).unwrap(), expected, "{raw}");
575        }
576    }
577
578    #[test]
579    fn the_aliases_are_the_spellings_people_type() {
580        assert_eq!(
581            SearchSort::parse("newest").unwrap(),
582            SearchSort::PublishedAt
583        );
584        assert_eq!(
585            SearchSort::parse("alphabetical").unwrap(),
586            SearchSort::Title
587        );
588    }
589
590    #[test]
591    fn score_is_not_a_sort_key() {
592        // Not an oversight: ts_rank is not comparable across tiers, which is the
593        // reason the tiers exist. Offering it would offer back the ordering 0005
594        // was written to fix.
595        let err = SearchSort::parse("score").unwrap_err().to_string();
596        assert!(err.contains("score"), "{err}");
597        assert!(err.contains("relevance, published_at, title"), "{err}");
598    }
599
600    #[test]
601    fn an_unknown_sort_key_is_refused_rather_than_ignored() {
602        // A search that silently ignored the sort it was asked for looks
603        // exactly like one that honoured it.
604        assert!(SearchSort::parse("relevances").is_err());
605    }
606}