Skip to main content

rustango_cms/
search_promotion.rs

1//! Search query log + editor-pinned results.
2//!
3//! Two tables:
4//! - `cms_search_query` — one row per normalized query string, with
5//!   a rolling hit counter. Logged best-effort from the admin search
6//!   handler.
7//! - `cms_search_promotion` — editor-pinned `(query, page)` pairs that
8//!   surface at the top of matching search responses.
9
10use chrono::{DateTime, Utc};
11use rustango::sql::Auto;
12use rustango::Model;
13use serde::{Deserialize, Serialize};
14
15#[derive(Model, Debug, Clone, Serialize, Deserialize)]
16#[rustango(
17    table = "cms_search_query",
18    app = "cms",
19    display = "raw",
20    admin(
21        list_display = "normalized, raw, hits, last_seen_at",
22        ordering = "-hits, -last_seen_at",
23        search_fields = "normalized, raw",
24    )
25)]
26pub struct SearchQuery {
27    #[rustango(primary_key)]
28    pub id: Auto<i64>,
29
30    /// Trimmed + lowercased + whitespace-collapsed form. Indexed for
31    /// upsert lookups; the canonical key the rest of the system uses.
32    #[rustango(max_length = 200, index)]
33    pub normalized: String,
34
35    /// First-seen original casing — used as the friendly display in
36    /// the analytics report.
37    #[rustango(max_length = 200)]
38    pub raw: String,
39
40    /// Total number of times this query has been logged.
41    pub hits: i64,
42
43    #[rustango(auto_now_add)]
44    pub first_seen_at: Auto<DateTime<Utc>>,
45
46    #[rustango(auto_now)]
47    pub last_seen_at: Auto<DateTime<Utc>>,
48}
49
50#[derive(Model, Debug, Clone, Serialize, Deserialize)]
51#[rustango(
52    table = "cms_search_promotion",
53    app = "cms",
54    display = "id",
55    admin(
56        list_display = "query_id, page_id, sort_order",
57        ordering = "query_id, sort_order",
58    )
59)]
60pub struct SearchPromotion {
61    #[rustango(primary_key)]
62    pub id: Auto<i64>,
63
64    #[rustango(fk = "cms_search_query", on = "id", index)]
65    pub query_id: i64,
66
67    #[rustango(fk = "cms_page", on = "id", index)]
68    pub page_id: i64,
69
70    /// Ordering among pinned pages for this query.
71    pub sort_order: i32,
72
73    /// Editor's optional note explaining why this result is pinned.
74    /// Surfaces in the admin promotions list, not on the public side.
75    #[rustango(max_length = 200)]
76    pub description: String,
77
78    #[rustango(auto_now_add)]
79    pub created_at: Auto<DateTime<Utc>>,
80}
81
82/// Normalize a user-typed query: trim + collapse whitespace +
83/// lowercase. The normalized form drives both the dedup key and the
84/// promotion-match lookup.
85#[must_use]
86pub fn normalize_query(raw: &str) -> String {
87    raw.split_whitespace()
88        .map(str::to_lowercase)
89        .collect::<Vec<_>>()
90        .join(" ")
91}
92
93/// Longest visitor query that is logged; longer ones are noise or abuse.
94const MAX_LOGGED_QUERY: usize = 100;
95
96/// Log a visitor's search from the public API, so the search report
97/// shows what visitors look for, not only admin searches. First page only
98/// (paging through results isn't a new search), capped in length, run in
99/// the background, and errors only logged: it never slows or fails the
100/// search itself.
101pub fn log_public_query(pool: &rustango::sql::Pool, raw: &str, offset: usize) {
102    if offset != 0 {
103        return;
104    }
105    let query = normalize_query(raw);
106    if query.is_empty() || query.chars().count() > MAX_LOGGED_QUERY {
107        return;
108    }
109    let pool = pool.clone();
110    rustango::__private_runtime::tokio::spawn(async move {
111        if let Err(e) = log_query(&pool, &query).await {
112            tracing::warn!(target: "rustango_cms::search", error = %e, "visitor search not logged");
113        }
114    });
115}
116
117/// Increment the hit count for `raw` (upserting a new row when this
118/// is the first time it's been logged). Best-effort — caller should
119/// ignore the `Result` if logging shouldn't gate the request path.
120///
121/// # Errors
122/// Driver / query failures.
123pub async fn log_query(
124    pool: &rustango::sql::Pool,
125    raw: &str,
126) -> Result<SearchQuery, rustango::sql::ExecError> {
127    use rustango::core::Column as _;
128    use rustango::sql::FetcherPool as _;
129    let normalized = normalize_query(raw);
130    if normalized.is_empty() {
131        // Defensive — empty queries shouldn't pollute the table.
132        // Return a synthetic row caller can discard.
133        return Ok(SearchQuery {
134            id: Auto::Unset,
135            normalized: String::new(),
136            raw: String::new(),
137            hits: 0,
138            first_seen_at: Auto::Unset,
139            last_seen_at: Auto::Unset,
140        });
141    }
142    let existing: Vec<SearchQuery> = SearchQuery::objects()
143        .where_(SearchQuery::normalized.eq(normalized.clone()))
144        .fetch(pool)
145        .await?;
146    if let Some(mut row) = existing.into_iter().next() {
147        row.hits += 1;
148        row.save(pool).await?;
149        return Ok(row);
150    }
151    let mut row = SearchQuery {
152        id: Auto::Unset,
153        normalized,
154        raw: raw.trim().to_owned(),
155        hits: 1,
156        first_seen_at: Auto::Unset,
157        last_seen_at: Auto::Unset,
158    };
159    row.insert(pool).await?;
160    Ok(row)
161}
162
163/// Look up the SearchQuery row whose `normalized` form matches.
164/// Returns `None` if the query has never been logged.
165///
166/// # Errors
167/// Driver / query failures.
168pub async fn find_by_query(
169    pool: &rustango::sql::Pool,
170    raw: &str,
171) -> Result<Option<SearchQuery>, rustango::sql::ExecError> {
172    use rustango::core::Column as _;
173    use rustango::sql::FetcherPool as _;
174    let normalized = normalize_query(raw);
175    if normalized.is_empty() {
176        return Ok(None);
177    }
178    let mut rows: Vec<SearchQuery> = SearchQuery::objects()
179        .where_(SearchQuery::normalized.eq(normalized))
180        .fetch(pool)
181        .await?;
182    Ok(rows.pop())
183}
184
185/// Every pinned promotion for `query_id`, sorted by `sort_order`.
186///
187/// # Errors
188/// Driver / query failures.
189pub async fn promotions_for_query(
190    pool: &rustango::sql::Pool,
191    query_id: i64,
192) -> Result<Vec<SearchPromotion>, rustango::sql::ExecError> {
193    use rustango::core::Column as _;
194    use rustango::sql::FetcherPool as _;
195    SearchPromotion::objects()
196        .where_(SearchPromotion::query_id.eq(query_id))
197        .order_by(&[("sort_order", false)])
198        .fetch(pool)
199        .await
200}
201
202/// Top N queries by hit count, newest-tie-breaker on `last_seen_at`.
203///
204/// # Errors
205/// Driver / query failures.
206pub async fn top_queries(
207    pool: &rustango::sql::Pool,
208    limit: usize,
209) -> Result<Vec<SearchQuery>, rustango::sql::ExecError> {
210    use rustango::sql::FetcherPool as _;
211    let mut rows: Vec<SearchQuery> = SearchQuery::objects().fetch(pool).await?;
212    rows.sort_by(|a, b| {
213        b.hits
214            .cmp(&a.hits)
215            .then_with(|| b.last_seen_at.get().cmp(&a.last_seen_at.get()))
216    });
217    rows.truncate(limit);
218    Ok(rows)
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224
225    #[test]
226    fn normalize_lowercases_and_collapses() {
227        assert_eq!(normalize_query("  Hello   WORLD "), "hello world");
228    }
229
230    #[test]
231    fn normalize_drops_empty() {
232        assert_eq!(normalize_query("   "), "");
233    }
234
235    #[test]
236    fn normalize_idempotent() {
237        let once = normalize_query("Foo Bar");
238        let twice = normalize_query(&once);
239        assert_eq!(once, twice);
240    }
241}