Shorten workspace directory names to app, bot and core

This commit is contained in:
2026-12-03 04:26:31 +08:00
parent 3ae1097e1b
commit ef251ae339
28 changed files with 4 additions and 4 deletions
+8
View File
@@ -0,0 +1,8 @@
[package]
name = "telefind-core"
version.workspace = true
edition.workspace = true
[dependencies]
jieba-rs = "0.8"
unicode-normalization = "0.1"
+71
View File
@@ -0,0 +1,71 @@
/// Stable Telegram identity. A post number is scoped to its source.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum DocumentId {
Channel(i64),
Group(i64),
Bot(i64),
Post { chat: i64, message: u32 },
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Kind {
Channel,
Group,
Bot,
Post,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Media {
Photo,
Video,
Audio,
File,
}
/// A public username, validated for safe interpolation into a t.me path.
/// Existence and public accessibility are checked by the caller at ingestion.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PublicName(String);
impl PublicName {
pub fn new(value: &str) -> Option<Self> {
let name = value.strip_prefix('@').unwrap_or(value);
if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
return None;
}
Some(Self(name.to_ascii_lowercase()))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Clone, Debug)]
pub struct Document {
pub id: DocumentId,
pub username: PublicName,
/// For posts, use the post title or attachment filename, not the channel name.
pub title: String,
/// Directory description, post text or media caption.
pub body: String,
pub media: Option<Media>,
}
impl Document {
pub fn kind(&self) -> Kind {
match self.id {
DocumentId::Channel(_) => Kind::Channel,
DocumentId::Group(_) => Kind::Group,
DocumentId::Bot(_) => Kind::Bot,
DocumentId::Post { .. } => Kind::Post,
}
}
pub fn url(&self) -> String {
let base = format!("https://t.me/{}", self.username.as_str());
match self.id {
DocumentId::Post { message, .. } => format!("{base}/{message}"),
_ => base,
}
}
}
+63
View File
@@ -0,0 +1,63 @@
use super::{IndexReader, IndexStore, IndexedDocument, Postings};
use crate::DocumentId;
use std::{borrow::Cow, collections::HashMap, convert::Infallible};
#[derive(Default)]
pub struct MemoryStore {
docs: HashMap<DocumentId, IndexedDocument>,
postings: HashMap<String, Postings>,
lengths: [usize; 2],
}
impl IndexStore for MemoryStore {
type Error = Infallible;
type Reader<'a> = &'a Self;
fn snapshot(&self) -> Result<&Self, Infallible> {
Ok(self)
}
fn replace(&mut self, entry: IndexedDocument) -> Result<(), Infallible> {
let id = entry.document.id;
self.delete(id)?;
for (term, counts) in &entry.frequencies {
self.postings
.entry(term.clone())
.or_default()
.insert(id, *counts);
}
for (sum, count) in self.lengths.iter_mut().zip(entry.lengths) {
*sum += count;
}
self.docs.insert(id, entry);
Ok(())
}
fn delete(&mut self, id: DocumentId) -> Result<bool, Infallible> {
let Some(entry) = self.docs.remove(&id) else {
return Ok(false);
};
for (sum, count) in self.lengths.iter_mut().zip(entry.lengths) {
*sum -= count;
}
for term in entry.frequencies.keys() {
if let Some(list) = self.postings.get_mut(term) {
list.remove(&id);
if list.is_empty() {
self.postings.remove(term);
}
}
}
Ok(true)
}
}
impl IndexReader for &MemoryStore {
type Error = Infallible;
fn statistics(&self) -> Result<(usize, [usize; 2]), Infallible> {
Ok((self.docs.len(), self.lengths))
}
fn postings(&self, term: &str) -> Result<Option<Cow<'_, Postings>>, Infallible> {
Ok(self.postings.get(term).map(Cow::Borrowed))
}
fn document(&self, id: DocumentId) -> Result<Cow<'_, IndexedDocument>, Infallible> {
Ok(Cow::Borrowed(&self.docs[&id]))
}
}
+68
View File
@@ -0,0 +1,68 @@
mod memory;
mod store;
use crate::search::{analysis, retrieve::retrieve};
use crate::Kind;
use std::collections::BTreeMap;
pub use store::{IndexReader, IndexStore, IndexedDocument, Postings};
use crate::{Document, DocumentId, Query, SearchPage};
pub use memory::MemoryStore;
pub type MemoryIndex = Engine<MemoryStore>;
/// Port for a database-backed searchable index. Writes replace by stable ID.
/// Implementations must make document, token and statistics changes atomic.
/// Search requires all query terms, applies filters before paging and returns
/// a deterministic order for an unchanged snapshot. Errors reach the caller.
pub trait SearchIndex {
type Error;
fn upsert(&mut self, document: Document) -> Result<(), Self::Error>;
fn remove(&mut self, id: DocumentId) -> Result<bool, Self::Error>;
fn search(&self, query: &Query<'_>) -> Result<SearchPage, Self::Error>;
}
#[derive(Default)]
pub struct Engine<S> {
store: S,
}
impl<S> Engine<S> {
pub fn new(store: S) -> Self {
Self { store }
}
}
impl<S: IndexStore> SearchIndex for Engine<S> {
type Error = S::Error;
fn upsert(&mut self, doc: Document) -> Result<(), Self::Error> {
let title = analysis::normalize(&doc.title);
let body = analysis::normalize(&doc.body);
let mut short = analysis::index_tokens(&title);
if doc.kind() != Kind::Post {
short.push(doc.username.as_str().to_owned());
}
let mut counts: BTreeMap<String, [usize; 2]> = BTreeMap::new();
let mut lengths = [0; 2];
for (field, tokens) in [short, analysis::index_tokens(&body)]
.into_iter()
.enumerate()
{
lengths[field] = tokens.len();
for term in tokens {
counts.entry(term).or_default()[field] += 1;
}
}
self.store.replace(IndexedDocument {
document: doc,
title,
body,
lengths,
frequencies: counts,
})
}
fn remove(&mut self, id: DocumentId) -> Result<bool, Self::Error> {
self.store.delete(id)
}
fn search(&self, query: &Query) -> Result<SearchPage, Self::Error> {
retrieve(&self.store.snapshot()?, query)
}
}
+34
View File
@@ -0,0 +1,34 @@
//! Persistence boundary. A read view must represent a single committed revision.
use crate::{Document, DocumentId};
use std::{borrow::Cow, collections::BTreeMap};
pub type Postings = BTreeMap<DocumentId, [usize; 2]>;
#[derive(Clone, Debug)]
pub struct IndexedDocument {
pub document: Document,
pub title: String,
pub body: String,
pub lengths: [usize; 2],
pub frequencies: BTreeMap<String, [usize; 2]>,
}
pub trait IndexReader {
type Error;
/// Document count and total token counts in the short and body fields.
fn statistics(&self) -> Result<(usize, [usize; 2]), Self::Error>;
fn postings(&self, term: &str) -> Result<Option<Cow<'_, Postings>>, Self::Error>;
/// IDs come from this snapshot's posting lists and must resolve.
fn document(&self, id: DocumentId) -> Result<Cow<'_, IndexedDocument>, Self::Error>;
}
pub trait IndexStore {
type Error;
type Reader<'a>: IndexReader<Error = Self::Error>
where
Self: 'a;
fn snapshot(&self) -> Result<Self::Reader<'_>, Self::Error>;
/// Atomically replace the old document, its postings and field statistics.
fn replace(&mut self, entry: IndexedDocument) -> Result<(), Self::Error>;
fn delete(&mut self, id: DocumentId) -> Result<bool, Self::Error>;
}
+8
View File
@@ -0,0 +1,8 @@
//! Lexical retrieval over already-collected, public Telegram records.
mod document;
pub mod index;
pub mod search;
pub use document::{Document, DocumentId, Kind, Media, PublicName};
pub use index::{MemoryIndex, SearchIndex};
pub use search::{Query, SearchPage};
+77
View File
@@ -0,0 +1,77 @@
use jieba_rs::Jieba;
use std::{collections::BTreeSet, sync::OnceLock};
use unicode_normalization::UnicodeNormalization;
pub(crate) fn normalize(text: &str) -> String {
text.nfkc()
.flat_map(char::to_lowercase)
.collect::<String>()
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
}
fn han(c: char) -> bool {
matches!(c as u32, 0x3400..=0x4dbf | 0x4e00..=0x9fff | 0xf900..=0xfaff | 0x20000..=0x323af)
}
// Keep individual Han characters in the index for one-character queries;
// for longer Han runs query only the more selective overlapping bigrams.
fn tokens(text: &str, indexing: bool) -> Vec<String> {
let mut output = Vec::new();
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
if han(c) {
let mut previous = c;
let mut single = true;
if indexing {
output.push(c.to_string());
}
while let Some(next) = chars.next_if(|&n| han(n)) {
output.push(format!("{previous}{next}"));
if indexing {
output.push(next.to_string());
}
single = false;
previous = next;
}
if single && !indexing {
output.push(c.to_string());
}
} else if c.is_alphanumeric() || c == '_' {
let mut word = String::from(c);
while let Some(next) = chars.next_if(|&n| !han(n) && (n.is_alphanumeric() || n == '_'))
{
word.push(next);
}
output.push(word);
}
}
output
}
pub(crate) fn index_tokens(text: &str) -> Vec<String> {
tokens(text, true)
}
pub(crate) fn query_terms(text: &str) -> BTreeSet<String> {
static LEXICON: OnceLock<Jieba> = OnceLock::new();
let mut terms = BTreeSet::new();
let mut rest = text;
while let Some(first) = rest.chars().next() {
let is_han = han(first);
let end = rest.find(|c: char| han(c) != is_han).unwrap_or(rest.len());
let (run, tail) = rest.split_at(end);
if is_han {
// Segment only the query. The existing character/bigram postings can
// match each dictionary word even in names absent from the dictionary.
for word in LEXICON.get_or_init(Jieba::new).cut(run, false) {
terms.extend(tokens(word, false));
}
} else {
terms.extend(tokens(run, false));
}
rest = tail;
}
terms
}
+33
View File
@@ -0,0 +1,33 @@
pub(crate) mod analysis;
pub(crate) mod rank;
pub(crate) mod retrieve;
mod scope;
use crate::{Document, Kind, Media};
#[derive(Clone, Debug)]
pub struct Query<'a> {
pub text: &'a str,
pub kind: Option<Kind>,
pub media: Option<Media>,
pub offset: usize,
pub limit: usize,
}
impl<'a> Query<'a> {
pub fn new(text: &'a str) -> Self {
Self {
text,
kind: None,
media: None,
offset: 0,
limit: 10,
}
}
}
#[derive(Debug)]
pub struct SearchPage {
pub total: usize,
pub hits: Vec<Document>,
}
+18
View File
@@ -0,0 +1,18 @@
// BM25F: normalize field frequencies before saturation. Title/username share
// the short field. Corpus-wide document frequency is counted once per term.
pub(crate) fn term_score(
counts: [usize; 2],
lengths: [usize; 2],
averages: [f64; 2],
n: usize,
df: usize,
) -> f64 {
let weights = [3.0, 1.0];
let mut frequency = 0.0;
for field in 0..2 {
let norm = 0.25 + 0.75 * lengths[field] as f64 / averages[field].max(1.0);
frequency += weights[field] * counts[field] as f64 / norm;
}
let idf = (1.0 + ((n - df) as f64 + 0.5) / (df as f64 + 0.5)).ln();
idf * (2.2 * frequency) / (1.2 + frequency)
}
+122
View File
@@ -0,0 +1,122 @@
use super::{analysis, rank, scope::Scope};
use crate::{index::IndexReader, DocumentId, Kind, Query, SearchPage};
use std::{
cmp::{Ordering, Reverse},
collections::BinaryHeap,
};
#[derive(Debug)]
struct Hit {
exact: bool,
score: f64,
id: DocumentId,
}
impl Ord for Hit {
fn cmp(&self, other: &Self) -> Ordering {
self.exact
.cmp(&other.exact)
.then_with(|| self.score.total_cmp(&other.score))
.then_with(|| other.id.cmp(&self.id))
}
}
impl PartialOrd for Hit {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Hit {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for Hit {}
pub(crate) fn retrieve<R: IndexReader>(reader: &R, query: &Query) -> Result<SearchPage, R::Error> {
let empty = || SearchPage {
total: 0,
hits: Vec::new(),
};
let normalized = analysis::normalize(query.text);
let Some((scope, text)) = Scope::parse(&normalized) else {
return Ok(empty());
};
// Only closed quote pairs are operators; an unmatched trailing quote is punctuation.
let parts: Vec<_> = text.split('"').skip(1).collect();
let phrases: Vec<_> = parts
.chunks_exact(2)
.map(|pair| pair[0].trim())
.filter(|phrase| !phrase.is_empty())
.collect();
let mut lists = Vec::new();
for term in analysis::query_terms(text) {
let Some(postings) = reader.postings(&term)? else {
return Ok(empty());
};
lists.push(postings);
}
lists.sort_unstable_by_key(|list| list.len());
let Some(first) = lists.first() else {
return Ok(empty());
};
let (n, lengths) = reader.statistics()?;
let avg = lengths.map(|length| length as f64 / n.max(1) as f64);
let mut best = BinaryHeap::new();
let mut total = 0;
let window = query.offset.saturating_add(query.limit);
for id in first.keys() {
if !lists[1..].iter().all(|list| list.contains_key(id)) {
continue;
}
let entry = reader.document(*id)?;
if !scope.accepts(&entry)
|| query.kind.is_some_and(|kind| kind != entry.document.kind())
|| query
.media
.is_some_and(|media| Some(media) != entry.document.media)
{
continue;
}
if !phrases
.iter()
.all(|phrase| entry.title.contains(phrase) || entry.body.contains(phrase))
{
continue;
}
total += 1;
if query.limit == 0 || query.offset >= first.len() {
continue;
}
let mut score: f64 = lists
.iter()
.map(|list| rank::term_score(list[id], entry.lengths, avg, n, list.len()))
.sum();
if entry.title.contains(text) {
score += 2.0;
} else if entry.body.contains(text) {
score += 0.5;
}
let exact = entry.document.kind() != Kind::Post
&& (entry.title == text
|| entry.document.username.as_str() == text.trim_start_matches('@'));
let hit = Hit {
exact,
score,
id: *id,
};
if best.len() < window {
best.push(Reverse(hit));
} else if let Some(mut worst) = best.peek_mut() {
if hit > worst.0 {
*worst = Reverse(hit);
}
}
}
let hits = best
.into_sorted_vec()
.into_iter()
.skip(query.offset)
.map(|Reverse(hit)| reader.document(hit.id).map(|entry| entry.document.clone()))
.collect::<Result<Vec<_>, _>>()?;
Ok(SearchPage { total, hits })
}
+42
View File
@@ -0,0 +1,42 @@
//! Leading source and exclusion filters in normalized search text.
use crate::{index::IndexedDocument, PublicName};
#[derive(Default)]
pub(super) struct Scope<'a> {
source: Option<PublicName>,
excluded: Vec<&'a str>,
}
impl<'a> Scope<'a> {
pub fn parse(mut text: &'a str) -> Option<(Self, &'a str)> {
let mut scope = Self::default();
loop {
let (token, rest) = text.split_once(' ').unwrap_or((text, ""));
if let Some(source) = token.strip_prefix("from:") {
let name = PublicName::new(source)?;
if scope.source.as_ref().is_some_and(|s| s != &name) {
return None;
}
scope.source = Some(name);
} else if let Some(fragment) = token.strip_prefix("exclude:") {
if fragment.is_empty() {
return None;
}
scope.excluded.push(fragment);
} else {
return Some((scope, text));
}
text = rest;
}
}
pub fn accepts(&self, entry: &IndexedDocument) -> bool {
self.source
.as_ref()
.is_none_or(|s| s == &entry.document.username)
&& !self
.excluded
.iter()
.any(|f| entry.title.contains(f) || entry.body.contains(f))
}
}
+213
View File
@@ -0,0 +1,213 @@
use telefind_core::{
Document, DocumentId, Kind, Media, MemoryIndex, PublicName, Query, SearchIndex,
};
fn post(chat: i64, message: u32, title: &str, body: &str) -> Document {
Document {
id: DocumentId::Post { chat, message },
username: PublicName::new(&format!("chat{chat}")).unwrap(),
title: title.into(),
body: body.into(),
media: None,
}
}
fn ids(index: &MemoryIndex, q: &Query) -> Vec<DocumentId> {
index
.search(q)
.unwrap()
.hits
.into_iter()
.map(|doc| doc.id)
.collect()
}
#[test]
fn mixed_script_and_single_character_queries() {
let mut index = MemoryIndex::default();
let doc = post(1, 2, "深圳二手", "RTX 5090");
index.upsert(doc.clone()).unwrap();
for keyword in ["深圳 RTX 5090", "深", "5090 二手", "二手 二手"] {
assert_eq!(ids(&index, &Query::new(keyword)), vec![doc.id]);
}
for keyword in ["深圳 5080", "", "!!"] {
assert!(ids(&index, &Query::new(keyword)).is_empty());
}
}
#[test]
fn edits_and_deletes_remove_stale_postings_and_keep_other_chats() {
let mut index = MemoryIndex::default();
let first = post(1, 7, "旧标题", "");
let second = post(2, 7, "旧标题", "");
for doc in [&first, &second, &first] {
index.upsert(doc.clone()).unwrap();
}
assert_eq!(index.search(&Query::new("旧标题")).unwrap().total, 2);
index.upsert(post(1, 7, "新标题", "")).unwrap();
assert_eq!(ids(&index, &Query::new("旧标题")), vec![second.id]);
assert_eq!(ids(&index, &Query::new("新标题")), vec![first.id]);
assert!(index.remove(first.id).unwrap());
assert!(!index.remove(first.id).unwrap());
assert!(ids(&index, &Query::new("新标题")).is_empty());
}
#[test]
fn directory_identity_and_exact_title_rank_first() {
let mut index = MemoryIndex::default();
let mut channel = post(1, 1, "摄影", "");
channel.id = DocumentId::Channel(1);
channel.username = PublicName::new("@Photo_News").unwrap();
index.upsert(post(2, 3, "摄影", "photo_news")).unwrap();
index.upsert(channel.clone()).unwrap();
for term in ["摄影", "@PHOTO_NEWS"] {
assert_eq!(ids(&index, &Query::new(term))[0], channel.id);
}
assert_eq!(channel.url(), "https://t.me/photo_news");
assert!(PublicName::new("a/b?c").is_none());
}
#[test]
fn title_and_contiguous_phrase_outrank_scattered_words() {
let mut index = MemoryIndex::default();
let exact = post(1, 1, "rust search", "");
let separated = post(1, 2, "search rust", "");
let body = post(1, 3, "", "rust and search");
for doc in [&body, &separated, &exact] {
index.upsert(doc.clone()).unwrap();
}
assert_eq!(
ids(&index, &Query::new("rust search")),
vec![exact.id, separated.id, body.id]
);
}
#[test]
fn filtering_precedes_paging_and_ties_are_stable() {
let mut index = MemoryIndex::default();
for id in (1..=5).rev() {
let mut doc = post(1, id, "sample", "");
if id % 2 == 1 {
doc.media = Some(Media::Video);
}
index.upsert(doc).unwrap();
}
let mut query = Query {
kind: Some(Kind::Post),
media: Some(Media::Video),
offset: 1,
limit: 1,
..Query::new("sample")
};
let page = index.search(&query).unwrap();
assert_eq!(page.total, 3);
assert_eq!(page.hits[0].url(), "https://t.me/chat1/3");
query.offset = usize::MAX;
assert!(ids(&index, &query).is_empty());
query.offset = 0;
query.limit = 0;
assert_eq!(index.search(&query).unwrap().total, 3);
assert!(ids(&index, &query).is_empty());
query.kind = Some(Kind::Bot);
assert_eq!(index.search(&query).unwrap().total, 0);
}
#[test]
fn quoted_phrase_requires_adjacency_in_a_single_field() {
let mut index = MemoryIndex::default();
for doc in [
post(1, 1, "Rust Search", "入门"),
post(1, 2, "Rust", "Search 入门"),
post(1, 3, "Search Rust", "入门"),
] {
index.upsert(doc).unwrap();
}
assert_eq!(
ids(&index, &Query::new("\"rust search\" 入门")),
vec![DocumentId::Post {
chat: 1,
message: 1
}]
);
}
#[test]
fn unspaced_chinese_query_matches_words_across_fields_and_keeps_model_required() {
let mut index = MemoryIndex::default();
index
.upsert(post(1, 1, "上海", "二手 相机 RTX 5090"))
.unwrap();
index
.upsert(post(1, 2, "上海", "二手 相机 RTX 5080"))
.unwrap();
assert_eq!(
ids(&index, &Query::new("上海二手相机 5090")),
vec![DocumentId::Post {
chat: 1,
message: 1
}]
);
}
#[test]
#[ignore = "synthetic capacity measurement; run explicitly in release mode"]
fn measure_ranked_queries_over_25000_posts() {
use std::time::Instant;
let mut index = MemoryIndex::default();
let start = Instant::now();
for id in 1..=25_000 {
let title = format!("频道sku{} 相机 {}", id % 100, id % 50);
index.upsert(post(1, id, &title, "摄影教程与设备")).unwrap();
}
let ingest = start.elapsed();
let queries = ["相机", "sku3 3", "设备", "摄影教程 17"];
for text in queries {
let query = Query::new(text);
let page = index.search(&query).unwrap();
let expected = match text {
"sku3 3" => 250,
"摄影教程 17" => 500,
_ => 25_000,
};
assert_eq!(page.total, expected);
let mut times = Vec::new();
for _ in 0..30 {
let start = Instant::now();
let result = index.search(&query).unwrap();
assert_eq!(result.hits.len(), 10);
times.push(start.elapsed());
}
times.sort_unstable();
println!(
"records=25000 ingest={ingest:?} query={text:?} matches={expected} p50={:?} p95={:?}",
times[14], times[28]
);
}
}
#[test]
fn source_and_exclusions_apply_before_total_and_offset() {
let mut index = MemoryIndex::default();
for (chat, message, title, body) in [
(1, 1, "相机 广告", ""),
(1, 2, "相机", "转发"),
(1, 3, "相机", ""),
(1, 4, "相机", ""),
(2, 1, "相机", ""),
] {
index.upsert(post(chat, message, title, body)).unwrap();
}
let mut query = Query::new("exclude:广告 from:@CHAT1 exclude:转发 相机");
query.offset = 1;
query.limit = 1;
let page = index.search(&query).unwrap();
assert_eq!(page.total, 2);
assert_eq!(page.hits[0].url(), "https://t.me/chat1/4");
for invalid in [
"from:@x/y 相机",
"from:chat1 from:chat2 相机",
"exclude: 相机",
"from:chat1",
] {
assert_eq!(index.search(&Query::new(invalid)).unwrap().total, 0);
}
}