1use std::sync::{Arc, OnceLock};
23
24#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
27pub struct SearchDoc {
28 pub page_id: i64,
29 pub title: String,
30 pub seo_title: String,
31 pub seo_description: String,
32 pub url_path: String,
33 #[serde(default = "default_published_status")]
37 pub status: String,
38}
39
40fn default_published_status() -> String {
41 crate::page::PageStatus::Published.as_str().to_owned()
42}
43
44#[async_trait::async_trait]
49pub trait SearchBackend: Send + Sync + 'static {
50 async fn search(&self, tenant_slug: &str, query: &str, limit: i64) -> Vec<i64>;
52 async fn index(&self, tenant_slug: &str, doc: &SearchDoc);
54 async fn delete(&self, tenant_slug: &str, page_id: i64);
56}
57
58static BACKEND: OnceLock<Arc<dyn SearchBackend>> = OnceLock::new();
59
60pub fn set_backend(backend: Arc<dyn SearchBackend>) {
64 if BACKEND.set(backend).is_err() {
66 tracing::error!(target: "rustango_cms", "set_backend: a search backend is already installed; this one is ignored");
67 }
68}
69
70#[must_use]
72pub fn backend() -> Option<&'static Arc<dyn SearchBackend>> {
73 BACKEND.get()
74}
75
76#[cfg(feature = "postgres")]
80const DOC_SQL: &str =
81 "coalesce(title,'') || ' ' || coalesce(seo_title,'') || ' ' || coalesce(seo_description,'')";
82
83pub async fn search_page_ids(
90 pool: &rustango::sql::Pool,
91 query: &str,
92 limit: i64,
93) -> Option<Vec<i64>> {
94 fts_page_ids(pool, query, limit, true).await
95}
96
97pub async fn ranked_public_page_ids(
101 pool: &rustango::sql::Pool,
102 tenant_slug: &str,
103 query: &str,
104 limit: i64,
105) -> Option<Vec<i64>> {
106 match backend() {
107 Some(b) => Some(b.search(tenant_slug, query, limit).await),
108 None => search_page_ids(pool, query, limit).await,
109 }
110}
111
112pub async fn search_page_ids_all_statuses(
117 pool: &rustango::sql::Pool,
118 query: &str,
119 limit: i64,
120) -> Option<Vec<i64>> {
121 fts_page_ids(pool, query, limit, false).await
122}
123
124async fn fts_page_ids(
125 pool: &rustango::sql::Pool,
126 query: &str,
127 limit: i64,
128 public_only: bool,
129) -> Option<Vec<i64>> {
130 #[cfg(feature = "postgres")]
134 {
135 let pg = pool.as_postgres()?;
136 let status_clause = if public_only {
139 "status IN ('published','archived') AND "
140 } else {
141 ""
142 };
143 let sql = format!(
144 "SELECT id FROM cms_page, websearch_to_tsquery('english', $1) AS q \
145 WHERE {status_clause}to_tsvector('english', {DOC_SQL}) @@ q \
146 ORDER BY ts_rank(to_tsvector('english', {DOC_SQL}), q) DESC, id ASC \
147 LIMIT $2"
148 );
149 match rustango::sql::sqlx::query_scalar::<_, i64>(&sql)
150 .bind(query)
151 .bind(limit)
152 .fetch_all(pg)
153 .await
154 {
155 Ok(ids) => Some(ids),
156 Err(e) => {
157 tracing::warn!(
158 target: "rustango_cms::search",
159 error = %e,
160 "postgres FTS query failed; falling back to substring search",
161 );
162 None
163 }
164 }
165 }
166 #[cfg(not(feature = "postgres"))]
167 {
168 let _ = (pool, query, limit, public_only);
169 None
170 }
171}
172
173pub async fn did_you_mean(
182 pool: &rustango::sql::Pool,
183 query: &str,
184 threshold: f32,
185) -> Option<String> {
186 #[cfg(feature = "postgres")]
187 {
188 let pg = pool.as_postgres()?;
189 let sql = "SELECT title FROM cms_page \
191 WHERE status IN ('published','archived') AND similarity(title, $1) > $2 \
192 ORDER BY similarity(title, $1) DESC, title ASC \
193 LIMIT 1";
194 let title: Option<String> = rustango::sql::sqlx::query_scalar(sql)
195 .bind(query)
196 .bind(threshold)
197 .fetch_optional(pg)
198 .await
199 .ok()
200 .flatten();
201 title.filter(|t| !t.eq_ignore_ascii_case(query.trim()))
202 }
203 #[cfg(not(feature = "postgres"))]
204 {
205 let _ = (pool, query, threshold);
206 None
207 }
208}
209
210#[cfg(feature = "postgres")]
212const FTS_INDEX: &str = "cms_page_fts_idx";
213
214pub async fn ensure_pg_fts_index(
223 pool: &rustango::sql::Pool,
224) -> Result<(), rustango::sql::sqlx::Error> {
225 #[cfg(feature = "postgres")]
226 {
227 let Some(pg) = pool.as_postgres() else {
228 return Ok(());
229 };
230 let sql = format!(
232 "CREATE INDEX IF NOT EXISTS {FTS_INDEX} ON cms_page \
233 USING GIN (to_tsvector('english', {DOC_SQL}))"
234 );
235 rustango::sql::sqlx::query(&sql)
236 .execute(pg)
237 .await
238 .map(|_| ())
239 }
240 #[cfg(not(feature = "postgres"))]
241 {
242 let _ = pool;
243 Ok(())
244 }
245}
246
247#[cfg(all(test, feature = "postgres"))]
248mod tests {
249 use rustango::sql::sqlx;
250
251 struct Scratch {
260 pool: rustango::sql::Pool,
261 admin: sqlx::PgPool,
262 schema: String,
263 }
264
265 impl Scratch {
266 async fn new() -> Self {
267 use std::sync::atomic::{AtomicUsize, Ordering};
268 static N: AtomicUsize = AtomicUsize::new(0);
269 let url = std::env::var("RCMS_TEST_PG_URL")
270 .expect("set RCMS_TEST_PG_URL to a throwaway Postgres database to run these");
271 let schema = format!(
272 "rcms_test_{}_{}",
273 std::process::id(),
274 N.fetch_add(1, Ordering::Relaxed)
275 );
276 let admin = sqlx::PgPool::connect(&url).await.expect("connect");
277 sqlx::query(&format!("CREATE SCHEMA {schema}"))
278 .execute(&admin)
279 .await
280 .expect("create schema");
281 let sep = if url.contains('?') { '&' } else { '?' };
283 let scoped = format!("{url}{sep}options=-c%20search_path%3D{schema},public");
284 let pool = rustango::sql::Pool::connect(&scoped).await.expect("connect scoped");
285 sqlx::query(
286 "CREATE TABLE cms_page (\
287 id BIGINT PRIMARY KEY, title TEXT, seo_title TEXT, \
288 seo_description TEXT, status TEXT)",
289 )
290 .execute(pool.as_postgres().expect("postgres pool"))
291 .await
292 .expect("create cms_page");
293 Self { pool, admin, schema }
294 }
295
296 fn pg(&self) -> &sqlx::PgPool {
297 self.pool.as_postgres().expect("postgres pool")
298 }
299
300 async fn drop(self) {
301 sqlx::query(&format!("DROP SCHEMA {} CASCADE", self.schema))
302 .execute(&self.admin)
303 .await
304 .expect("drop schema");
305 }
306 }
307
308 #[tokio::test]
315 #[ignore = "needs RCMS_TEST_PG_URL"]
316 async fn pg_fts_ranks_and_filters() {
317 let scratch = Scratch::new().await;
318 let (pool, pg) = (&scratch.pool, scratch.pg());
319
320 for (id, title, desc) in [
321 (9001_i64, "Rust web framework guide", ""),
322 (
323 9002,
324 "Cooking with cast iron",
325 "a rust-free skillet, mostly",
326 ),
327 (9003, "Knitting patterns", "wool and yarn"),
328 ] {
329 sqlx::query(
330 "INSERT INTO cms_page (id,title,seo_title,seo_description,status) \
331 VALUES ($1,$2,'',$3,'published')",
332 )
333 .bind(id)
334 .bind(title)
335 .bind(desc)
336 .execute(pg)
337 .await
338 .expect("insert");
339 }
340
341 let ids = super::search_page_ids(pool, "rust", 10)
342 .await
343 .expect("Some on postgres");
344
345 scratch.drop().await;
348 assert!(ids.contains(&9001), "title match present: {ids:?}");
349 assert!(ids.contains(&9002), "description match present: {ids:?}");
350 assert!(!ids.contains(&9003), "non-match excluded: {ids:?}");
351 let pos = |id| ids.iter().position(|x| *x == id);
352 assert!(pos(9001) < pos(9002), "title match ranks first: {ids:?}");
353 }
354
355 #[tokio::test]
359 #[ignore = "needs RCMS_TEST_PG_URL"]
360 async fn pg_did_you_mean_suggests_near_title() {
361 let scratch = Scratch::new().await;
362 let (pool, pg) = (&scratch.pool, scratch.pg());
363 sqlx::query("CREATE EXTENSION IF NOT EXISTS pg_trgm")
364 .execute(pg)
365 .await
366 .ok();
367 sqlx::query(
368 "INSERT INTO cms_page (id,title,seo_title,seo_description,status) \
369 VALUES (9101,'Accessibility checklist','','','published')",
370 )
371 .execute(pg)
372 .await
373 .expect("insert");
374
375 let hit = super::did_you_mean(pool, "accessibilty checklist", 0.3).await;
377 let none = super::did_you_mean(pool, "zxqw nonsense", 0.3).await;
378
379 scratch.drop().await;
380 assert_eq!(
381 hit.as_deref(),
382 Some("Accessibility checklist"),
383 "got {hit:?}"
384 );
385 assert_eq!(none, None, "no near match → no suggestion");
386 }
387
388 #[tokio::test]
391 #[ignore = "needs RCMS_TEST_PG_URL"]
392 async fn pg_fts_index_created_idempotently() {
393 let scratch = Scratch::new().await;
394 let (pool, pg) = (&scratch.pool, scratch.pg());
395
396 super::ensure_pg_fts_index(pool)
397 .await
398 .expect("create index");
399 super::ensure_pg_fts_index(pool).await.expect("idempotent");
401
402 let name: Option<String> = sqlx::query_scalar(
403 "SELECT indexname FROM pg_indexes WHERE schemaname = $1 AND indexname = $2",
404 )
405 .bind(&scratch.schema)
406 .bind(super::FTS_INDEX)
407 .fetch_optional(pg)
408 .await
409 .expect("query pg_indexes");
410 scratch.drop().await;
411 assert_eq!(name.as_deref(), Some(super::FTS_INDEX));
412 }
413
414 #[tokio::test]
417 #[ignore = "needs RCMS_TEST_PG_URL"]
418 async fn pg_all_statuses_includes_drafts() {
419 let scratch = Scratch::new().await;
420 let (pool, pg) = (&scratch.pool, scratch.pg());
421 sqlx::query(
422 "INSERT INTO cms_page (id,title,seo_title,seo_description,status) VALUES \
423 (9201,'Draft rust note','','','draft'),\
424 (9202,'Published rust post','','','published')",
425 )
426 .execute(pg)
427 .await
428 .expect("insert");
429
430 let published = super::search_page_ids(pool, "rust", 10).await.unwrap();
431 let all = super::search_page_ids_all_statuses(pool, "rust", 10)
432 .await
433 .unwrap();
434
435 scratch.drop().await;
436 assert!(
437 published.contains(&9202),
438 "published query has the published post"
439 );
440 assert!(
441 !published.contains(&9201),
442 "published query excludes the draft"
443 );
444 assert!(
445 all.contains(&9201) && all.contains(&9202),
446 "all-status has both: {all:?}"
447 );
448 }
449}