tango-core 0.3.0

The tango schema, entities, migrations, and search contract
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
//! Search across everything harvested, videos and playlists together.
//!
//! All the work happens in PostgreSQL: `ts_rank` over the generated `fts`
//! columns, and `word_similarity` over trigram-indexed titles. Scoring in Rust
//! would mean reading rows and ranking them in memory, throwing away the GIN
//! indexes that make this fast.
//!
//! Results come back in two tiers. A full-text hit is stronger evidence than a
//! fuzzy title match, so it always sorts above one - see the comment in
//! `sql/0005_search.sql` for why those cannot share a single rank.

use sea_orm::{ConnectionTrait, DatabaseConnection, DbBackend, QueryResult, Statement};

#[derive(Debug, Clone)]
pub struct SearchHit {
    pub id: String,
    pub channel_id: String,
    pub title: String,
    pub description: String,
    pub thumbnail_url: String,
    pub published_at: Option<chrono::DateTime<chrono::FixedOffset>>,
    /// `video` or `playlist`.
    pub source: String,
    pub score: f32,
    /// 2 for a title/description/tags full-text hit, 1 for a fuzzy title match,
    /// 0 for a transcript hit. Separate tiers rather than one numeric scale,
    /// because a title match and a transcript hit are different kinds of
    /// evidence - see migration 0011.
    pub match_tier: i32,
    /// The mode that matched: `fts`, `fuzzy`, `substring` or `transcript`.
    pub matched_by: String,
    /// Which field it matched in: `title`, `description`, `tags` or
    /// `transcript`. Null only for a fuzzy hit, which only ever looks at
    /// titles and would otherwise be redundant with `matched_by`.
    pub matched_field: Option<String>,
    pub snippet: String,
    /// Position of the best matching transcript cue, in milliseconds. `None`
    /// for everything that is not a transcript.
    ///
    /// Seek with `player.seekTo(start_ms / 1000)`. This is the reason a
    /// transcript hit is worth surfacing separately from a title match: it
    /// answers *where*, not just *which video*.
    pub start_ms: Option<i32>,
}

#[derive(Debug, Clone)]
pub struct SearchQuery {
    pub text: String,
    pub page: u32,
    pub page_size: u32,
    /// Which text may match. `None` means every field, which is what the
    /// database does with a NULL list.
    pub search_in: Option<Vec<String>>,
    /// Literal matching over `search_in`, rather than the text index.
    pub substring: bool,
    pub channel_id: Option<String>,
    /// Postgres text search configuration, e.g. `english`, `spanish`, `simple`.
    pub text_config: String,
    /// Include the fuzzy trigram tier. See the note on the SQL: it matches
    /// whole words, so it forgives a typo without matching a fragment of an
    /// unrelated one, and a well-formed query may still want it off.
    pub include_fuzzy: bool,
    pub sort_by: SearchSort,
    /// Descending. Meaningless for [`SearchSort::Relevance`], which is always
    /// best-first; the database is told so explicitly rather than being handed
    /// a flag it would honour and ignore.
    pub desc: bool,
}

/// What a search is ordered by.
///
/// Serializable so a front-end can echo the order it applied, with the variant
/// names matching what [`SearchSort::parse`] accepts — `published_at`, not
/// `PublishedAt`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SearchSort {
    /// Tier, then field, then score. What a search has always returned.
    #[default]
    Relevance,
    PublishedAt,
    Title,
}

impl SearchSort {
    /// The name the database takes.
    pub fn as_str(&self) -> &'static str {
        match self {
            SearchSort::Relevance => "relevance",
            SearchSort::PublishedAt => "published_at",
            SearchSort::Title => "title",
        }
    }

    /// Every accepted key, for an error message.
    pub fn all() -> [&'static str; 3] {
        ["relevance", "published_at", "title"]
    }

    /// Parses a sort key, or explains what was expected.
    ///
    /// An unknown key is refused rather than ignored, for the same reason an
    /// unknown field is: a search that quietly ignored the sort it was asked
    /// for looks exactly like one that honoured it. `score` is deliberately not
    /// accepted — ts_rank is not comparable across tiers, which is the reason
    /// the tiers exist.
    pub fn parse(raw: &str) -> Result<Self, InvalidQuery> {
        match raw.trim().to_lowercase().as_str() {
            "relevance" | "relevance_score" | "best" => Ok(SearchSort::Relevance),
            "published_at" | "published" | "date" | "newest" => Ok(SearchSort::PublishedAt),
            "title" | "alphabetical" => Ok(SearchSort::Title),
            other => Err(InvalidQuery(format!(
                "unknown sort key {other:?}. Expected one of: {}",
                SearchSort::all().join(", ")
            ))),
        }
    }
}

impl std::str::FromStr for SearchSort {
    type Err = InvalidQuery;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        SearchSort::parse(s)
    }
}

/// Every field a search can be pointed at, in the order the help lists them.
/// The text `search` may match, in the order they are ranked.
///
/// Metadata only. Transcripts are not here: they are a separate body of text
/// with their own endpoint (`/transcripts/search`, `search_transcripts()`),
/// their own ranking and their own seek positions. Leaving them reachable from
/// `in` made a result depend on which videos happened to have been fetched -
/// 40 of 8,748 on the dev corpus - which is not a property a search should
/// have.
pub const SEARCH_FIELDS: [&str; 3] = ["title", "description", "tags"];

/// The text search configuration the generated tsvector columns are built with.
///
/// Advisory for videos and playlists, whose columns are generated at
/// `'english'` and cannot be reconfigured without rewriting the table. It does
/// apply to the query, so a differently-worded query parses differently — but
/// the stored vectors will not have been stemmed that way, which is why the
/// parameter exists and why the generated columns are the hard constraint.
pub const DEFAULT_TEXT_CONFIG: &str = "english";

/// A query that cannot be searched, and why.
///
/// A plain message rather than an error enum, because the two callers want
/// different things from a refusal: the CLI prints it, the API turns it into a
/// 400. Neither needs to match on which rule was broken.
#[derive(Debug)]
pub struct InvalidQuery(pub String);

impl std::fmt::Display for InvalidQuery {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for InvalidQuery {}

/// The longest query accepted, in characters.
pub const MAX_QUERY_CHARS: usize = 100;

/// The shortest. Two characters produce a tsquery that matches most of a
/// corpus, which is a scan dressed up as a search.
pub const MIN_QUERY_CHARS: usize = 3;

/// Reduces a query to the text worth searching, or refuses it.
///
/// The character filter is not decoration. The search function is called twice
/// per transcript hit: once for the AND that decides which documents match, and
/// again to build an OR-ed variant that locates a cue. An unbalanced quote is
/// absorbed by the first and is a parse error in the second, so the input is
/// reduced to characters that mean something before it ever reaches SQL.
///
/// This lived only in the API, which meant the CLI could be handed a query that
/// the same database would have rejected - and would fail on it with a
/// Postgres parse error instead of a sentence saying what was wrong.
pub fn validate_query(raw: &str) -> Result<String, InvalidQuery> {
    let q = raw.trim();
    if q.is_empty() {
        return Err(InvalidQuery("q cannot be empty".into()));
    }
    if q.chars().count() < MIN_QUERY_CHARS {
        return Err(InvalidQuery(format!(
            "q must be at least {MIN_QUERY_CHARS} characters"
        )));
    }
    if q.chars().count() > MAX_QUERY_CHARS {
        return Err(InvalidQuery(format!(
            "q must be {MAX_QUERY_CHARS} characters or less"
        )));
    }

    let q: String = q
        .chars()
        .filter(|c| c.is_alphanumeric() || c.is_whitespace() || "-:'\"()".contains(*c))
        .collect();
    let q = q.trim().to_string();

    if q.is_empty() {
        return Err(InvalidQuery("q contains no searchable characters".into()));
    }
    Ok(q)
}

/// Parses `--in` into the list the database takes.
///
/// A comma-separated list rather than a repeated flag, so it reads the same in
/// a shell as in a URL. Aliases exist because `desc` is what people type; the
/// database is given the canonical name, so it never has to know either.
///
/// `transcript` and `transcripts` are no longer accepted here and are refused
/// like any other unknown field, naming the three that are. Silently ignoring
/// them would leave `?in=title,transcript` searching titles and looking like a
/// query with no matches.
///
/// An unknown field is refused rather than ignored. A field this search does
/// not understand is a typo, and a typo that silently narrows the result set
/// looks exactly like a query with no matches - which is the same failure the
/// fuzzy tier had, where a misspelled parameter quietly changed what was
/// searched.
pub fn parse_search_fields(raw: Option<&str>) -> anyhow::Result<Vec<String>> {
    let Some(raw) = raw else {
        return Ok(SEARCH_FIELDS.iter().map(|f| f.to_string()).collect());
    };

    let mut fields: Vec<String> = Vec::new();
    for part in raw.split(',') {
        let part = part.trim().to_lowercase();
        if part.is_empty() {
            continue;
        }
        let canonical = match part.as_str() {
            "title" | "titles" => "title",
            "description" | "desc" | "descriptions" => "description",
            "tags" | "tag" => "tags",
            other => anyhow::bail!(
                "unknown search field {other:?}. Expected a comma-separated list of: {}",
                SEARCH_FIELDS.join(", ")
            ),
        };
        if !fields.iter().any(|f| f == canonical) {
            fields.push(canonical.to_string());
        }
    }

    if fields.is_empty() {
        anyhow::bail!(
            "--in named no fields. Expected a comma-separated list of: {}",
            SEARCH_FIELDS.join(", ")
        );
    }
    Ok(fields)
}

/// Deliberately not built with the query builder: the search is a call to
/// `search_content`, and hand-rolling it in SeaQuery would only obscure what
/// SQL actually runs. Values are still bound, never interpolated.
///
/// The `::int` and `::text[]` casts are required. Rust's `u32` arrives as
/// PostgreSQL `bigint`, and function resolution will not narrow bigint to int
/// implicitly, so the call fails to resolve without them - and the same applies
/// to a `Vec<String>` arriving as an unknown-type array.
const CALL: &str = "SELECT * FROM public.search_content(\
     $1, $2::int, $3::int, $4::text[], $5, $6::regconfig, $7, $8, $9, $10)";

/// The same call without the paging parameters or the sort, for a total.
///
/// It takes fewer arguments than [`CALL`] binds, which is why the two cannot
/// share one value list: sqlx-postgres rejects a statement supplied with more
/// parameters than it declares. Order cannot change how many rows match, so
/// leaving the sort out is not leaving anything out of the answer.
const COUNT: &str = "SELECT public.search_content_count(\
     $1, $4::text[], $5, $6::regconfig, $7, $8)";

/// The values the paged call binds, in the order it expects.
///
/// The sort is bound as text rather than interpolated: the key is a closed set
/// validated in Rust, and a bound value cannot be a column name anyway.
fn values(q: &SearchQuery, page: u32, page_size: u32) -> Vec<sea_orm::Value> {
    vec![
        q.text.clone().into(),
        page.max(1).into(),
        page_size.max(1).into(),
        search_fields_value(q.search_in.as_deref()),
        q.channel_id.clone().into(),
        q.text_config.clone().into(),
        q.include_fuzzy.into(),
        q.substring.into(),
        q.sort_by.as_str().into(),
        q.desc.into(),
    ]
}

/// The values the counting call binds: the same search, without the paging and
/// without the sort, which are the last two arguments.
fn count_values(q: &SearchQuery) -> Vec<sea_orm::Value> {
    let mut values = values(q, 1, 1);
    values.truncate(8);
    values
}

/// How many results a search has in total.
///
/// Counts the same `search_all_hits` the page comes from, so a total and a page
/// cannot describe different searches. A caller that wants a pager needs this
/// and had no way to ask before.
pub async fn count(db: &DatabaseConnection, q: &SearchQuery) -> anyhow::Result<u64> {
    let statement = Statement::from_sql_and_values(DbBackend::Postgres, COUNT, count_values(q));

    let row = db
        .query_one_raw(statement)
        .await
        .map_err(|e| anyhow::anyhow!("search count failed: {e}"))?;

    // `search_content_count` returns bigint, and sqlx-postgres has no u64
    // codec - reading it as one fails at runtime.
    Ok(row
        .map(|row| row.try_get::<i64>("", "search_content_count"))
        .transpose()?
        .unwrap_or(0)
        .max(0) as u64)
}

pub async fn search(db: &DatabaseConnection, q: &SearchQuery) -> anyhow::Result<Vec<SearchHit>> {
    let statement =
        Statement::from_sql_and_values(DbBackend::Postgres, CALL, values(q, q.page, q.page_size));

    let rows = db
        .query_all_raw(statement)
        .await
        .map_err(|e| anyhow::anyhow!("search failed: {e}"))?;

    rows.iter().map(to_hit).collect()
}

/// The field list as a bound value, or SQL NULL for "every field".
///
/// NULL rather than an explicit four-element list so the database's default is
/// the single definition of what an unqualified search covers, and a caller
/// that passes nothing cannot drift from it.
///
/// Built by hand rather than through `Value::from`, which has no array
/// conversion for strings. The `$4::text[]` cast in the call is what makes
/// function resolution work; an untyped array parameter would not resolve.
fn search_fields_value(fields: Option<&[String]>) -> sea_orm::Value {
    match fields {
        Some(fields) => sea_orm::Value::Array(
            sea_orm::sea_query::ArrayType::String,
            Some(Box::new(
                fields
                    .iter()
                    .map(|f| sea_orm::Value::String(Some(f.clone())))
                    .collect(),
            )),
        ),
        None => sea_orm::Value::String(None),
    }
}

fn to_hit(row: &QueryResult) -> anyhow::Result<SearchHit> {
    // Read straight into the chrono type. The column is TIMESTAMPTZ, so
    // pulling it out as text and re-parsing would both fail and lose the
    // offset Postgres already resolved.
    let published_at: Option<chrono::DateTime<chrono::FixedOffset>> =
        row.try_get("", "published_at")?;
    Ok(SearchHit {
        id: row.try_get("", "id")?,
        channel_id: row.try_get("", "channel_id")?,
        title: row.try_get("", "title")?,
        description: row.try_get("", "description")?,
        thumbnail_url: row.try_get("", "thumbnail_url")?,
        published_at,
        source: row.try_get("", "source")?,
        score: row.try_get("", "score")?,
        match_tier: row.try_get("", "match_tier")?,
        matched_by: row.try_get("", "matched_by")?,
        matched_field: row.try_get("", "matched_field")?,
        snippet: row.try_get("", "snippet")?,
        start_ms: row.try_get("", "start_ms")?,
    })
}

impl SearchHit {
    /// A timestamped watch URL for a transcript hit, a plain one otherwise.
    ///
    /// The `&t=` parameter is seconds, which is why this divides. It is
    /// YouTube's own convention, so the link works when pasted anywhere.
    pub fn reference(&self) -> String {
        match self.source.as_str() {
            "playlist" => format!("https://www.youtube.com/playlist?list={}", self.id),
            "transcript" => match self.start_ms {
                Some(ms) => format!(
                    "https://www.youtube.com/watch?v={}&t={}s",
                    self.id,
                    ms / 1000
                ),
                None => format!("https://www.youtube.com/watch?v={}", self.id),
            },
            _ => format!("https://www.youtube.com/watch?v={}", self.id),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn hit(source: &str) -> SearchHit {
        SearchHit {
            id: "abc".into(),
            channel_id: "UC_x".into(),
            title: "t".into(),
            description: String::new(),
            thumbnail_url: String::new(),
            published_at: None,
            source: source.into(),
            score: 0.5,
            match_tier: 1,
            matched_by: "fts".into(),
            matched_field: Some("title".into()),
            snippet: String::new(),
            start_ms: None,
        }
    }

    #[test]
    fn video_hits_reference_a_watch_url() {
        assert_eq!(
            hit("video").reference(),
            "https://www.youtube.com/watch?v=abc"
        );
    }

    #[test]
    fn playlist_hits_reference_a_playlist_url() {
        // The id is already a playlist id, so it is not wrapped in a watch URL.
        assert_eq!(
            hit("playlist").reference(),
            "https://www.youtube.com/playlist?list=abc"
        );
    }

    #[test]
    fn a_transcript_hit_links_straight_to_the_moment() {
        // The whole point of keeping transcripts in their own tier: the result
        // answers *where*, not just which video.
        let mut transcript = hit("transcript");
        transcript.start_ms = Some(7_320);
        assert_eq!(
            transcript.reference(),
            "https://www.youtube.com/watch?v=abc&t=7s"
        );
    }

    #[test]
    fn a_transcript_hit_without_a_position_is_still_linkable() {
        // A document can match with no cue at all, if the phrase only survives
        // deduplication. Better a working link than a broken one.
        assert_eq!(
            hit("transcript").reference(),
            "https://www.youtube.com/watch?v=abc"
        );
    }

    #[test]
    fn the_seek_parameter_is_seconds_not_milliseconds() {
        // `&t=` takes seconds. Passing milliseconds would seek to roughly
        // 1000x the intended position - a plausible-looking link that lands
        // somewhere else entirely.
        let mut transcript = hit("transcript");
        transcript.start_ms = Some(94_160);
        assert!(transcript.reference().ends_with("&t=94s"));
    }

    // --- the field list ---

    #[test]
    fn no_list_means_every_field() {
        // The database holds the definition of an unqualified search, so this
        // is only about the explicit spelling. The two must agree; if a field
        // is ever added, both lists grow together or the default quietly stops
        // covering it.
        assert_eq!(parse_search_fields(None).unwrap(), SEARCH_FIELDS.to_vec());
    }

    #[test]
    fn a_list_is_split_and_trimmed() {
        assert_eq!(
            parse_search_fields(Some(" title , description ")).unwrap(),
            vec!["title", "description"]
        );
    }

    #[test]
    fn aliases_resolve_to_the_canonical_name() {
        // `desc` is what people type. The database only ever sees the canonical
        // name, so it does not have to know either spelling.
        assert_eq!(
            parse_search_fields(Some("titles,desc,tag")).unwrap(),
            vec!["title", "description", "tags"]
        );
    }

    #[test]
    fn transcripts_are_refused_as_a_field() {
        // Transcripts moved to their own endpoint. Refusing the word is the
        // point: ignoring it would leave `?in=title,transcript` searching
        // titles and reporting no matches, which reads as "nothing says this"
        // rather than "you asked the wrong endpoint".
        let err = parse_search_fields(Some("title,transcript")).unwrap_err();
        let message = err.to_string();
        assert!(message.contains("transcript"), "{message}");
        assert!(message.contains("title, description, tags"), "{message}");
    }

    #[test]
    fn a_repeated_field_is_collapsed() {
        assert_eq!(
            parse_search_fields(Some("title,title,tags")).unwrap(),
            vec!["title", "tags"]
        );
    }

    #[test]
    fn an_unknown_field_is_refused_rather_than_ignored() {
        // A misspelled field that narrowed the search would look exactly like
        // a query with no matches, which is indistinguishable from the truth.
        let err = parse_search_fields(Some("title,descriptionsss")).unwrap_err();
        let message = err.to_string();
        assert!(message.contains("descriptionsss"), "{message}");
        assert!(message.contains("title, description, tags"), "{message}");
    }

    #[test]
    fn an_empty_list_is_refused() {
        // It would otherwise reach the database as "match nothing" and return
        // zero results, which reads as "nothing matched" rather than "nothing
        // was asked for".
        assert!(parse_search_fields(Some(" , ")).is_err());
        assert!(parse_search_fields(Some("")).is_err());
    }

    #[test]
    fn an_unqualified_search_binds_null_rather_than_the_full_list() {
        // NULL, so the database default is the one definition of "everything"
        // and a caller that passes nothing cannot drift from it.
        assert!(matches!(
            search_fields_value(None),
            sea_orm::Value::String(None)
        ));
    }

    // --- the sort ---

    #[test]
    fn relevance_is_the_default_sort() {
        assert_eq!(SearchSort::default(), SearchSort::Relevance);
    }

    #[test]
    fn the_three_sort_keys_parse_in_any_case() {
        for (raw, expected) in [
            ("relevance", SearchSort::Relevance),
            ("Relevance", SearchSort::Relevance),
            ("published_at", SearchSort::PublishedAt),
            ("PUBLISHED_AT", SearchSort::PublishedAt),
            ("  title ", SearchSort::Title),
        ] {
            assert_eq!(SearchSort::parse(raw).unwrap(), expected, "{raw}");
        }
    }

    #[test]
    fn the_aliases_are_the_spellings_people_type() {
        assert_eq!(
            SearchSort::parse("newest").unwrap(),
            SearchSort::PublishedAt
        );
        assert_eq!(
            SearchSort::parse("alphabetical").unwrap(),
            SearchSort::Title
        );
    }

    #[test]
    fn score_is_not_a_sort_key() {
        // Not an oversight: ts_rank is not comparable across tiers, which is the
        // reason the tiers exist. Offering it would offer back the ordering 0005
        // was written to fix.
        let err = SearchSort::parse("score").unwrap_err().to_string();
        assert!(err.contains("score"), "{err}");
        assert!(err.contains("relevance, published_at, title"), "{err}");
    }

    #[test]
    fn an_unknown_sort_key_is_refused_rather_than_ignored() {
        // A search that silently ignored the sort it was asked for looks
        // exactly like one that honoured it.
        assert!(SearchSort::parse("relevances").is_err());
    }
}