Merge pull request '实现 Telegram 中文词法搜索核心与 Bot 查询逻辑' (#1) from codex/01-search-engine into main
Reviewed-on: #1
This commit was merged in pull request #1.
This commit is contained in:
@@ -0,0 +1 @@
|
|||||||
|
/target/
|
||||||
Generated
+1193
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,7 @@
|
|||||||
|
[workspace]
|
||||||
|
members = ["crates/telefind-core", "crates/telefind-bot", "crates/telefind-app"]
|
||||||
|
resolver = "2"
|
||||||
|
|
||||||
|
[workspace.package]
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
# telefind-rs
|
||||||
|
|
||||||
|
Rust keyword search for public Telegram channels, groups, bots and posts. The executable runs with an in-memory index. It accepts records from the caller and new channel updates delivered to the bot.
|
||||||
|
|
||||||
|
## Try a query locally
|
||||||
|
|
||||||
|
From the workspace root:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo run -p telefind-app -- query - '/search type:video 上海相机' <<'JSONL'
|
||||||
|
{"op":"upsert","kind":"post","id":-100501,"message_id":42,"username":"example_feed","title":"相机入门.mp4","body":"上海 摄影","media":"video"}
|
||||||
|
JSONL
|
||||||
|
```
|
||||||
|
|
||||||
|
This prints the reply as JSON, including a button with the URL `https://t.me/example_feed/42`. The example uses a fictional record.
|
||||||
|
|
||||||
|
## Telegram bot
|
||||||
|
|
||||||
|
Supply the bot token through the environment variable `TELEGRAM_BOT_TOKEN` and run:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo run -p telefind-app -- bot events.jsonl
|
||||||
|
```
|
||||||
|
|
||||||
|
The input file is optional. The process identifies its username via `getMe`, then long-polls for incoming messages and sends search results with URL buttons. Type keywords in private chat or use `/search@YourBot keywords` in a group. In a public channel where the bot receives posts, incoming posts and edits update the in-memory index. For channels without a public username, protected posts and unsupported content, the bot skips indexing the message. Telegram does not send ordinary post-deletion notifications via this update stream. An upstream source can supply deletion events. If a reply reached Telegram but its HTTP acknowledgement was lost, retrying an update can send the reply twice.
|
||||||
|
|
||||||
|
Use a leading `type:channel`, `type:group`, `type:bot`, `type:post`, `type:photo`, `type:video`, `type:audio` or `type:file` to filter. Double quotes require a contiguous phrase in one field. Use `/page 2 type:video 摄影` to repeat a query on another page.
|
||||||
|
|
||||||
|
## Document input and storage
|
||||||
|
|
||||||
|
Pass an ordered UTF-8 JSONL stream in a file, or pass `-` to read standard input until EOF. The executable replays it before processing queries. A directory record uses its Telegram numeric ID. A post uses its chat ID and positive message ID. An upsert replaces the previous version with the same identity. Run a delete with the same key, for example:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"op":"delete","kind":"post","id":-100501,"message_id":42}
|
||||||
|
```
|
||||||
|
|
||||||
|
The process keeps no database or history archive. Restarting loads whichever input the caller supplies. For a persistent or concurrent host, implement `telefind_core::index::IndexStore` and its snapshot reader, then use `Engine::new(store)`. Pass the resulting engine to `telefind_app::telegram::run` with a `telefind_app::telegram::Client` to reuse the same polling and reply logic. The JSONL reader `telefind_app::input::load` also accepts any implementation of `SearchIndex`.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
`cargo test --workspace --locked` exercises the index, the executable with piped input, and Telegram Bot API requests against a loopback HTTP fixture. These tests use synthetic records.
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
[package]
|
||||||
|
name = "telefind-app"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
default-run = "telefind"
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "telefind"
|
||||||
|
path = "src/main.rs"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
telefind-core = { path = "../telefind-core" }
|
||||||
|
telefind-bot = { path = "../telefind-bot" }
|
||||||
|
ureq = { version = "3", features = ["json"] }
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
serde_json = "1"
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
//! Line-delimited public document changes supplied by the caller.
|
||||||
|
use serde::Deserialize;
|
||||||
|
use std::{error::Error, io::BufRead};
|
||||||
|
use telefind_core::{Document, DocumentId, Media, PublicName, SearchIndex};
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
enum Kind {
|
||||||
|
Channel,
|
||||||
|
Group,
|
||||||
|
Bot,
|
||||||
|
Post,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
enum Attachment {
|
||||||
|
Photo,
|
||||||
|
Video,
|
||||||
|
Audio,
|
||||||
|
File,
|
||||||
|
}
|
||||||
|
impl From<Attachment> for Media {
|
||||||
|
fn from(media: Attachment) -> Self {
|
||||||
|
match media {
|
||||||
|
Attachment::Photo => Media::Photo,
|
||||||
|
Attachment::Video => Media::Video,
|
||||||
|
Attachment::Audio => Media::Audio,
|
||||||
|
Attachment::File => Media::File,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Key {
|
||||||
|
kind: Kind,
|
||||||
|
id: i64,
|
||||||
|
message_id: Option<u32>,
|
||||||
|
}
|
||||||
|
impl Key {
|
||||||
|
fn resolve(&self) -> Result<DocumentId, &'static str> {
|
||||||
|
match (&self.kind, self.message_id) {
|
||||||
|
(Kind::Channel, None) => Ok(DocumentId::Channel(self.id)),
|
||||||
|
(Kind::Group, None) => Ok(DocumentId::Group(self.id)),
|
||||||
|
(Kind::Bot, None) => Ok(DocumentId::Bot(self.id)),
|
||||||
|
(Kind::Post, Some(n)) if n > 0 => Ok(DocumentId::Post {
|
||||||
|
chat: self.id,
|
||||||
|
message: n,
|
||||||
|
}),
|
||||||
|
_ => Err("message_id must be positive for a post and absent for a directory record"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(tag = "op", rename_all = "lowercase")]
|
||||||
|
enum Change {
|
||||||
|
Upsert {
|
||||||
|
#[serde(flatten)]
|
||||||
|
key: Key,
|
||||||
|
username: String,
|
||||||
|
#[serde(default)]
|
||||||
|
title: String,
|
||||||
|
#[serde(default)]
|
||||||
|
body: String,
|
||||||
|
media: Option<Attachment>,
|
||||||
|
},
|
||||||
|
Delete {
|
||||||
|
#[serde(flatten)]
|
||||||
|
key: Key,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load<R: BufRead, S: SearchIndex>(reader: R, index: &mut S) -> Result<(), Box<dyn Error>>
|
||||||
|
where
|
||||||
|
S::Error: Error + 'static,
|
||||||
|
{
|
||||||
|
for (number, line) in reader.lines().enumerate() {
|
||||||
|
let line = line?;
|
||||||
|
if line.trim().is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let context = |err: &str| format!("input line {}: {}", number + 1, err);
|
||||||
|
let change: Change = serde_json::from_str(&line).map_err(|e| context(&e.to_string()))?;
|
||||||
|
match change {
|
||||||
|
Change::Delete { key } => {
|
||||||
|
index.remove(key.resolve().map_err(context)?)?;
|
||||||
|
}
|
||||||
|
Change::Upsert {
|
||||||
|
key,
|
||||||
|
username,
|
||||||
|
title,
|
||||||
|
body,
|
||||||
|
media,
|
||||||
|
} => {
|
||||||
|
index.upsert(Document {
|
||||||
|
id: key.resolve().map_err(context)?,
|
||||||
|
username: PublicName::new(&username)
|
||||||
|
.ok_or_else(|| context("invalid public username"))?,
|
||||||
|
title,
|
||||||
|
body,
|
||||||
|
media: media.map(Into::into),
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
//! Integration entry points for hosts supplying their own search index.
|
||||||
|
pub mod input;
|
||||||
|
pub mod telegram;
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
use std::{
|
||||||
|
env,
|
||||||
|
error::Error,
|
||||||
|
fs::File,
|
||||||
|
io::{self, BufReader},
|
||||||
|
process::ExitCode,
|
||||||
|
};
|
||||||
|
use telefind_app::{input, telegram};
|
||||||
|
use telefind_core::MemoryIndex;
|
||||||
|
|
||||||
|
const USAGE: &str = concat!(
|
||||||
|
"telefind bot [events.jsonl|-]\n",
|
||||||
|
"telefind query <events.jsonl|-> <search text>\n",
|
||||||
|
"Bot mode reads TELEGRAM_BOT_TOKEN. An optional JSONL input is consumed before polling."
|
||||||
|
);
|
||||||
|
|
||||||
|
fn load(path: &str, index: &mut MemoryIndex) -> Result<(), Box<dyn Error>> {
|
||||||
|
if path == "-" {
|
||||||
|
input::load(io::stdin().lock(), index)
|
||||||
|
} else {
|
||||||
|
input::load(BufReader::new(File::open(path)?), index)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn run() -> Result<(), Box<dyn Error>> {
|
||||||
|
let args: Vec<_> = env::args().skip(1).collect();
|
||||||
|
let mut index = MemoryIndex::default();
|
||||||
|
match args.first().map(String::as_str) {
|
||||||
|
Some("bot") if args.len() <= 2 => {
|
||||||
|
let token =
|
||||||
|
env::var("TELEGRAM_BOT_TOKEN").map_err(|_| "TELEGRAM_BOT_TOKEN is required")?;
|
||||||
|
let client = telegram::Client::new(&token)?;
|
||||||
|
if let Some(path) = args.get(1) {
|
||||||
|
load(path, &mut index)?;
|
||||||
|
}
|
||||||
|
telegram::run(&client, &mut index)
|
||||||
|
}
|
||||||
|
Some("query") if args.len() >= 3 => {
|
||||||
|
load(&args[1], &mut index)?;
|
||||||
|
let reply = telefind_bot::handle(&index, "telefind", &args[2..].join(" "))?;
|
||||||
|
println!("{}", serde_json::to_string(&telegram::render(reply))?);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Some("--help" | "-h") => {
|
||||||
|
println!("{USAGE}");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
_ => Err(USAGE.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn main() -> ExitCode {
|
||||||
|
match run() {
|
||||||
|
Ok(()) => ExitCode::SUCCESS,
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("{err}");
|
||||||
|
ExitCode::FAILURE
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
use serde::{de::DeserializeOwned, Deserialize};
|
||||||
|
use serde_json::Value;
|
||||||
|
use std::{fmt, time::Duration};
|
||||||
|
use ureq::Agent;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Failure {
|
||||||
|
pub code: u16,
|
||||||
|
pub retry_after: Option<Duration>,
|
||||||
|
}
|
||||||
|
impl Failure {
|
||||||
|
pub fn transient(&self) -> bool {
|
||||||
|
self.code == 0 || self.code == 429 || self.code >= 500
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl fmt::Display for Failure {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match self.code {
|
||||||
|
0 => f.write_str("Telegram connection failed"),
|
||||||
|
200..=299 => f.write_str("invalid Telegram API response"),
|
||||||
|
code => write!(f, "Telegram API failure (code {code})"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl std::error::Error for Failure {}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Response<T> {
|
||||||
|
ok: bool,
|
||||||
|
result: Option<T>,
|
||||||
|
error_code: Option<u16>,
|
||||||
|
parameters: Option<Parameters>,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Parameters {
|
||||||
|
retry_after: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Client {
|
||||||
|
agent: Agent,
|
||||||
|
endpoint: String,
|
||||||
|
}
|
||||||
|
impl Client {
|
||||||
|
pub fn new(token: &str) -> Result<Self, &'static str> {
|
||||||
|
let Some((id, secret)) = token.split_once(':') else {
|
||||||
|
return Err("invalid TELEGRAM_BOT_TOKEN");
|
||||||
|
};
|
||||||
|
if id.is_empty()
|
||||||
|
|| secret.is_empty()
|
||||||
|
|| !id.bytes().all(|b| b.is_ascii_digit())
|
||||||
|
|| !secret
|
||||||
|
.bytes()
|
||||||
|
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
|
||||||
|
{
|
||||||
|
return Err("invalid TELEGRAM_BOT_TOKEN");
|
||||||
|
}
|
||||||
|
Ok(Self::at(format!("https://api.telegram.org/bot{token}")))
|
||||||
|
}
|
||||||
|
pub(super) fn at(endpoint: String) -> Self {
|
||||||
|
let config = Agent::config_builder()
|
||||||
|
.timeout_global(Some(Duration::from_secs(50)))
|
||||||
|
.max_redirects(0)
|
||||||
|
.http_status_as_error(false)
|
||||||
|
.build();
|
||||||
|
Self {
|
||||||
|
agent: config.into(),
|
||||||
|
endpoint,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn call<T: DeserializeOwned>(&self, method: &str, payload: &Value) -> Result<T, Failure> {
|
||||||
|
// Transport errors may include the request URL, which contains the token.
|
||||||
|
let mut response = self
|
||||||
|
.agent
|
||||||
|
.post(format!("{}/{method}", self.endpoint))
|
||||||
|
.send_json(payload)
|
||||||
|
.map_err(|_| Failure {
|
||||||
|
code: 0,
|
||||||
|
retry_after: None,
|
||||||
|
})?;
|
||||||
|
let status = response.status().as_u16();
|
||||||
|
let envelope: Response<T> = response.body_mut().read_json().map_err(|_| Failure {
|
||||||
|
code: status,
|
||||||
|
retry_after: None,
|
||||||
|
})?;
|
||||||
|
if envelope.ok {
|
||||||
|
return envelope.result.ok_or(Failure {
|
||||||
|
code: status,
|
||||||
|
retry_after: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Err(Failure {
|
||||||
|
code: envelope.error_code.unwrap_or(status),
|
||||||
|
retry_after: envelope
|
||||||
|
.parameters
|
||||||
|
.and_then(|p| p.retry_after)
|
||||||
|
.map(Duration::from_secs),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
mod client;
|
||||||
|
mod update;
|
||||||
|
use self::{
|
||||||
|
client::Failure,
|
||||||
|
update::{dispatch, Update},
|
||||||
|
};
|
||||||
|
pub use client::Client;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
use std::{error::Error, thread, time::Duration};
|
||||||
|
use telefind_core::SearchIndex;
|
||||||
|
pub use update::render;
|
||||||
|
|
||||||
|
fn with_retry<T>(
|
||||||
|
mut operation: impl FnMut() -> Result<T, Box<dyn Error>>,
|
||||||
|
) -> Result<T, Box<dyn Error>> {
|
||||||
|
let mut delay = Duration::from_secs(1);
|
||||||
|
loop {
|
||||||
|
match operation() {
|
||||||
|
Err(err) => {
|
||||||
|
let Some(failure) = err.downcast_ref::<Failure>().filter(|e| e.transient()) else {
|
||||||
|
return Err(err);
|
||||||
|
};
|
||||||
|
let wait = failure
|
||||||
|
.retry_after
|
||||||
|
.unwrap_or(delay)
|
||||||
|
.max(Duration::from_secs(1));
|
||||||
|
eprintln!("{failure}; retrying in {}s", wait.as_secs());
|
||||||
|
thread::sleep(wait);
|
||||||
|
delay = (delay * 2).min(Duration::from_secs(60));
|
||||||
|
}
|
||||||
|
Ok(value) => return Ok(value),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct BotInfo {
|
||||||
|
username: String,
|
||||||
|
}
|
||||||
|
pub fn run<S: SearchIndex>(client: &Client, index: &mut S) -> Result<(), Box<dyn Error>>
|
||||||
|
where
|
||||||
|
S::Error: Error + 'static,
|
||||||
|
{
|
||||||
|
let bot: BotInfo = with_retry(|| Ok(client.call("getMe", &json!({}))?))?;
|
||||||
|
let mut offset = None;
|
||||||
|
loop {
|
||||||
|
with_retry(|| poll(client, index, &bot.username, &mut offset))?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll<S: SearchIndex>(
|
||||||
|
client: &Client,
|
||||||
|
index: &mut S,
|
||||||
|
bot: &str,
|
||||||
|
offset: &mut Option<i64>,
|
||||||
|
) -> Result<(), Box<dyn Error>>
|
||||||
|
where
|
||||||
|
S::Error: Error + 'static,
|
||||||
|
{
|
||||||
|
let mut request = json!({"timeout":25,"limit":32,"allowed_updates":["message","channel_post","edited_channel_post"]});
|
||||||
|
if let Some(next) = offset {
|
||||||
|
request["offset"] = json!(next);
|
||||||
|
}
|
||||||
|
let batch: Vec<Update> = client.call("getUpdates", &request)?;
|
||||||
|
for update in batch {
|
||||||
|
if let Some(payload) = dispatch(index, bot, &update)? {
|
||||||
|
match client.call::<Value>("sendMessage", &payload) {
|
||||||
|
Ok(_) => (),
|
||||||
|
// Deleted chats and blocked bots must not stall the rest of the batch.
|
||||||
|
Err(err) if matches!(err.code, 400 | 403) => {
|
||||||
|
eprintln!("sendMessage for update {}: {err}", update.update_id)
|
||||||
|
}
|
||||||
|
Err(err) => return Err(err.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
*offset = Some(update.update_id + 1);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
use super::*;
|
||||||
|
use std::{
|
||||||
|
io::{BufRead, BufReader, Read, Write},
|
||||||
|
net::TcpListener,
|
||||||
|
};
|
||||||
|
use telefind_core::MemoryIndex;
|
||||||
|
|
||||||
|
fn respond(server: &TcpListener, reply: impl FnOnce(&str, Value) -> (u16, String)) {
|
||||||
|
let (mut socket, _) = server.accept().unwrap();
|
||||||
|
let mut reader = BufReader::new(&socket);
|
||||||
|
let mut first = String::new();
|
||||||
|
reader.read_line(&mut first).unwrap();
|
||||||
|
let mut size = 0;
|
||||||
|
loop {
|
||||||
|
let mut line = String::new();
|
||||||
|
reader.read_line(&mut line).unwrap();
|
||||||
|
assert!(!line.is_empty(), "unexpected end of headers");
|
||||||
|
if line == "\r\n" {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if let Some((_, n)) = line
|
||||||
|
.to_lowercase()
|
||||||
|
.strip_prefix("content-length")
|
||||||
|
.and_then(|s| s.split_once(':'))
|
||||||
|
{
|
||||||
|
size = n.trim().parse().unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut bytes = vec![0; size];
|
||||||
|
reader.read_exact(&mut bytes).unwrap();
|
||||||
|
let req: Value = serde_json::from_slice(&bytes).unwrap();
|
||||||
|
let (status, body) = reply(&first, req);
|
||||||
|
write!(
|
||||||
|
socket,
|
||||||
|
"HTTP/1.1 {status} Response\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
|
||||||
|
body.len(),
|
||||||
|
body
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn actual_http_client_handles_live_edit_and_returns_keyboard_and_offset() {
|
||||||
|
// Loopback only. Exercise real HTTP serialization in both directions.
|
||||||
|
let server = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let address = server.local_addr().unwrap();
|
||||||
|
let peer = thread::spawn(move || {
|
||||||
|
let channel = json!({"id":-123,"type":"channel","username":"photofeed","title":"摄影频道"});
|
||||||
|
let user = json!({"id":9,"type":"private"});
|
||||||
|
let batch = json!([
|
||||||
|
{"update_id":1,"channel_post":{"message_id":11,"chat":channel,"text":"旧教程"}},
|
||||||
|
{"update_id":2,"edited_channel_post":{"message_id":11,"chat":channel,"caption":"摄影 新教程","video":{"file_name":"入门.mp4"}}},
|
||||||
|
{"update_id":3,"message":{"message_id":1,"chat":user,"text":"/search type:video 新教程"}},
|
||||||
|
{"update_id":4,"message":{"message_id":2,"chat":user,"text":"旧教程"}}
|
||||||
|
]);
|
||||||
|
for step in 0..4 {
|
||||||
|
respond(&server, |first, req| {
|
||||||
|
let result = match step {
|
||||||
|
0 => {
|
||||||
|
assert!(first.contains("/getUpdates "));
|
||||||
|
assert!(req.get("offset").is_none());
|
||||||
|
batch.clone()
|
||||||
|
}
|
||||||
|
1 => {
|
||||||
|
assert!(first.contains("/sendMessage "));
|
||||||
|
assert_eq!(req["chat_id"], 9);
|
||||||
|
assert_eq!(
|
||||||
|
req["reply_markup"]["inline_keyboard"][0][0]["url"],
|
||||||
|
"https://t.me/photofeed/11"
|
||||||
|
);
|
||||||
|
json!({})
|
||||||
|
}
|
||||||
|
2 => {
|
||||||
|
assert_eq!(req["text"], "没有找到匹配结果。");
|
||||||
|
json!({})
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
assert_eq!(req["offset"], 5);
|
||||||
|
json!([])
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let body = json!({"ok":true,"result":result}).to_string();
|
||||||
|
(200, body)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let client = Client::at(format!("http://{address}/botTest"));
|
||||||
|
let mut offset = None;
|
||||||
|
let mut index = MemoryIndex::default();
|
||||||
|
poll(&client, &mut index, "searchbot", &mut offset).unwrap();
|
||||||
|
poll(&client, &mut index, "searchbot", &mut offset).unwrap();
|
||||||
|
peer.join().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn nonpublic_and_protected_updates_do_not_add_searchable_posts() {
|
||||||
|
let mut index = MemoryIndex::default();
|
||||||
|
for (name, protected) in [(Value::Null, false), (json!("demo_channel"), true)] {
|
||||||
|
let update = serde_json::from_value(json!({"update_id":1,"channel_post":{
|
||||||
|
"message_id":2,"chat":{"id":9,"type":"channel","username":name},
|
||||||
|
"text":"private phrase","has_protected_content":protected
|
||||||
|
}}))
|
||||||
|
.unwrap();
|
||||||
|
assert!(dispatch(&mut index, "mybot", &update).unwrap().is_none());
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
index
|
||||||
|
.search(&telefind_core::Query::new("private"))
|
||||||
|
.unwrap()
|
||||||
|
.total,
|
||||||
|
0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn flood_wait_keeps_failed_update_pending_and_preserves_prior_progress() {
|
||||||
|
let server = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let client = Client::at(format!("http://{}/botTest", server.local_addr().unwrap()));
|
||||||
|
let peer = thread::spawn(move || {
|
||||||
|
let query = json!({"update_id":22,"message":{"message_id":1,"chat":{"id":9,"type":"private"},"text":"example"}});
|
||||||
|
respond(&server, |_, _| {
|
||||||
|
(
|
||||||
|
200,
|
||||||
|
json!({"ok":true,"result":[{"update_id":21},query]}).to_string(),
|
||||||
|
)
|
||||||
|
});
|
||||||
|
respond(&server, |_, _| {
|
||||||
|
(
|
||||||
|
429,
|
||||||
|
json!({"ok":false,"error_code":429,"parameters":{"retry_after":7}}).to_string(),
|
||||||
|
)
|
||||||
|
});
|
||||||
|
respond(&server, |_, request| {
|
||||||
|
assert_eq!(request["offset"], 22);
|
||||||
|
(200, json!({"ok":true,"result":[query]}).to_string())
|
||||||
|
});
|
||||||
|
respond(&server, |_, _| {
|
||||||
|
(403, json!({"ok":false,"error_code":403}).to_string())
|
||||||
|
});
|
||||||
|
respond(&server, |_, _| {
|
||||||
|
(401, json!({"ok":false,"error_code":401}).to_string())
|
||||||
|
});
|
||||||
|
});
|
||||||
|
let mut offset = None;
|
||||||
|
let mut index = MemoryIndex::default();
|
||||||
|
let err = poll(&client, &mut index, "searchbot", &mut offset).unwrap_err();
|
||||||
|
let flood = err.downcast_ref::<Failure>().unwrap();
|
||||||
|
assert!(flood.transient());
|
||||||
|
assert_eq!(flood.retry_after, Some(Duration::from_secs(7)));
|
||||||
|
assert_eq!(offset, Some(22));
|
||||||
|
poll(&client, &mut index, "searchbot", &mut offset).unwrap();
|
||||||
|
assert_eq!(offset, Some(23));
|
||||||
|
assert!(run(&client, &mut index)
|
||||||
|
.unwrap_err()
|
||||||
|
.to_string()
|
||||||
|
.contains("401"));
|
||||||
|
peer.join().unwrap();
|
||||||
|
}
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
use telefind_bot::{handle, Reply};
|
||||||
|
use telefind_core::{Document, DocumentId, Media, PublicName, SearchIndex};
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct Update {
|
||||||
|
pub update_id: i64,
|
||||||
|
message: Option<Message>,
|
||||||
|
channel_post: Option<Message>,
|
||||||
|
edited_channel_post: Option<Message>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Chat {
|
||||||
|
id: i64,
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
kind: String,
|
||||||
|
username: Option<String>,
|
||||||
|
title: Option<String>,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct File {
|
||||||
|
file_name: Option<String>,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Message {
|
||||||
|
chat: Chat,
|
||||||
|
message_id: u32,
|
||||||
|
text: Option<String>,
|
||||||
|
caption: Option<String>,
|
||||||
|
video: Option<File>,
|
||||||
|
audio: Option<File>,
|
||||||
|
document: Option<File>,
|
||||||
|
photo: Option<Vec<Value>>,
|
||||||
|
#[serde(default)]
|
||||||
|
has_protected_content: bool,
|
||||||
|
message_thread_id: Option<i64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Message {
|
||||||
|
fn attachment(&self) -> (Option<Media>, String) {
|
||||||
|
for (media, file) in [
|
||||||
|
(Media::Video, &self.video),
|
||||||
|
(Media::Audio, &self.audio),
|
||||||
|
(Media::File, &self.document),
|
||||||
|
] {
|
||||||
|
if let Some(file) = file {
|
||||||
|
return (Some(media), file.file_name.clone().unwrap_or_default());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(
|
||||||
|
self.photo
|
||||||
|
.as_ref()
|
||||||
|
.filter(|p| !p.is_empty())
|
||||||
|
.map(|_| Media::Photo),
|
||||||
|
String::new(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
fn index_post<S: SearchIndex>(&self, index: &mut S) -> Result<(), S::Error> {
|
||||||
|
if self.chat.kind != "channel" || self.message_id == 0 {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let id = DocumentId::Post {
|
||||||
|
chat: self.chat.id,
|
||||||
|
message: self.message_id,
|
||||||
|
};
|
||||||
|
let Some(username) = self.chat.username.as_deref().and_then(PublicName::new) else {
|
||||||
|
index.remove(id)?;
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
let (media, title) = self.attachment();
|
||||||
|
let body = self
|
||||||
|
.text
|
||||||
|
.as_ref()
|
||||||
|
.or(self.caption.as_ref())
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_default();
|
||||||
|
if self.has_protected_content || (body.is_empty() && title.is_empty() && media.is_none()) {
|
||||||
|
index.remove(id)?;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
index.upsert(Document {
|
||||||
|
id: DocumentId::Channel(self.chat.id),
|
||||||
|
username: username.clone(),
|
||||||
|
title: self.chat.title.clone().unwrap_or_default(),
|
||||||
|
body: String::new(),
|
||||||
|
media: None,
|
||||||
|
})?;
|
||||||
|
index.upsert(Document {
|
||||||
|
id,
|
||||||
|
username,
|
||||||
|
title,
|
||||||
|
body,
|
||||||
|
media,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn render(reply: Reply) -> Option<Value> {
|
||||||
|
match reply {
|
||||||
|
Reply::Ignored => None,
|
||||||
|
Reply::Help => Some(
|
||||||
|
json!({"text":"发送关键词或 /search 关键词。可用 type:channel、group、bot、post、video、photo、audio、file 筛选;用 /page 页码 关键词 翻页。"}),
|
||||||
|
),
|
||||||
|
Reply::Results { total, links } if links.is_empty() => Some(
|
||||||
|
json!({"text":if total == 0 {"没有找到匹配结果。".into()} else {format!("本页没有结果,共 {total} 条。")}}),
|
||||||
|
),
|
||||||
|
Reply::Results { total, links } => {
|
||||||
|
let rows: Vec<_> = links
|
||||||
|
.into_iter()
|
||||||
|
.map(|link| json!([{"text":link.label,"url":link.url}]))
|
||||||
|
.collect();
|
||||||
|
Some(
|
||||||
|
json!({"text":format!("共 {total} 条结果"),"reply_markup":{"inline_keyboard":rows}}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn dispatch<S: SearchIndex>(
|
||||||
|
index: &mut S,
|
||||||
|
bot: &str,
|
||||||
|
update: &Update,
|
||||||
|
) -> Result<Option<Value>, S::Error> {
|
||||||
|
if let Some(post) = update
|
||||||
|
.channel_post
|
||||||
|
.as_ref()
|
||||||
|
.or(update.edited_channel_post.as_ref())
|
||||||
|
{
|
||||||
|
post.index_post(index)?;
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
let Some(message) = update.message.as_ref() else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let Some(text) = message.text.as_deref() else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
if message.chat.kind != "private" && !text.trim_start().starts_with('/') {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
Ok(render(handle(index, bot, text)?).map(|mut payload| {
|
||||||
|
payload["chat_id"] = json!(message.chat.id);
|
||||||
|
if let Some(thread) = message.message_thread_id {
|
||||||
|
payload["message_thread_id"] = json!(thread);
|
||||||
|
}
|
||||||
|
payload
|
||||||
|
}))
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
use serde_json::{json, Value};
|
||||||
|
use std::{
|
||||||
|
io::Write,
|
||||||
|
process::{Command, Stdio},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn executable_replays_external_changes_and_returns_a_public_link() {
|
||||||
|
let mut child = Command::new(env!("CARGO_BIN_EXE_telefind"))
|
||||||
|
.args(["query", "-", "相机"])
|
||||||
|
.stdin(Stdio::piped())
|
||||||
|
.stdout(Stdio::piped())
|
||||||
|
.spawn()
|
||||||
|
.unwrap();
|
||||||
|
{
|
||||||
|
let mut input = child.stdin.take().unwrap();
|
||||||
|
for row in [
|
||||||
|
json!({"op":"upsert","kind":"channel","id":9,"username":"photocn","title":"相机"}),
|
||||||
|
json!({"op":"upsert","kind":"post","id":9,"message_id":4,"username":"photocn","body":"相机"}),
|
||||||
|
json!({"op":"delete","kind":"channel","id":9}),
|
||||||
|
] {
|
||||||
|
writeln!(input, "{row}").unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let response = child.wait_with_output().unwrap();
|
||||||
|
assert!(response.status.success());
|
||||||
|
let result: Value = serde_json::from_slice(&response.stdout).unwrap();
|
||||||
|
assert_eq!(result["text"], "共 1 条结果");
|
||||||
|
assert_eq!(
|
||||||
|
result["reply_markup"]["inline_keyboard"][0][0]["url"],
|
||||||
|
"https://t.me/photocn/4"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn invalid_record_reports_its_line_and_fails_before_search() {
|
||||||
|
let mut child = Command::new(env!("CARGO_BIN_EXE_telefind"))
|
||||||
|
.args(["query", "-", "demo"])
|
||||||
|
.stdin(Stdio::piped())
|
||||||
|
.stdout(Stdio::piped())
|
||||||
|
.stderr(Stdio::piped())
|
||||||
|
.spawn()
|
||||||
|
.unwrap();
|
||||||
|
child
|
||||||
|
.stdin
|
||||||
|
.take()
|
||||||
|
.unwrap()
|
||||||
|
.write_all(b"\n{\"op\":\"delete\",\"kind\":\"post\",\"id\":5}\n")
|
||||||
|
.unwrap();
|
||||||
|
let output = child.wait_with_output().unwrap();
|
||||||
|
assert!(!output.status.success());
|
||||||
|
assert!(output.stdout.is_empty());
|
||||||
|
assert!(String::from_utf8(output.stderr)
|
||||||
|
.unwrap()
|
||||||
|
.contains("input line 2"));
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
[package]
|
||||||
|
name = "telefind-bot"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
telefind-core = { path = "../telefind-core" }
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
use telefind_core::{Kind, Media, Query};
|
||||||
|
pub(crate) enum Input<'a> {
|
||||||
|
Ignore,
|
||||||
|
Help,
|
||||||
|
Search(Query<'a>),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn parse<'a>(bot: &str, text: &'a str) -> Input<'a> {
|
||||||
|
let text = text.trim();
|
||||||
|
if text.is_empty() {
|
||||||
|
return Input::Ignore;
|
||||||
|
}
|
||||||
|
if !text.starts_with('/') {
|
||||||
|
return search(text, 1);
|
||||||
|
}
|
||||||
|
let (command, args) = text.split_once(char::is_whitespace).unwrap_or((text, ""));
|
||||||
|
let (command, target) = command
|
||||||
|
.split_once('@')
|
||||||
|
.map_or((command, None), |(cmd, target)| (cmd, Some(target)));
|
||||||
|
if target.is_some_and(|name| !name.eq_ignore_ascii_case(bot.trim_start_matches('@'))) {
|
||||||
|
return Input::Ignore;
|
||||||
|
}
|
||||||
|
match (command, args.trim()) {
|
||||||
|
("/search", "") | ("/help" | "/start", _) => Input::Help,
|
||||||
|
("/search", query) => search(query, 1),
|
||||||
|
("/page", args) => {
|
||||||
|
let Some((number, text)) = args.split_once(char::is_whitespace) else {
|
||||||
|
return Input::Help;
|
||||||
|
};
|
||||||
|
number
|
||||||
|
.parse()
|
||||||
|
.map_or(Input::Help, |page| search(text.trim(), page))
|
||||||
|
}
|
||||||
|
_ => Input::Ignore,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn search(text: &str, page: usize) -> Input<'_> {
|
||||||
|
let mut q = Query::new(text);
|
||||||
|
if let Some(filter) = text.strip_prefix("type:") {
|
||||||
|
let Some((kind, rest)) = filter.split_once(char::is_whitespace) else {
|
||||||
|
return Input::Help;
|
||||||
|
};
|
||||||
|
q.text = rest.trim();
|
||||||
|
match kind {
|
||||||
|
"channel" => q.kind = Some(Kind::Channel),
|
||||||
|
"group" => q.kind = Some(Kind::Group),
|
||||||
|
"bot" => q.kind = Some(Kind::Bot),
|
||||||
|
"post" => q.kind = Some(Kind::Post),
|
||||||
|
"photo" => q.media = Some(Media::Photo),
|
||||||
|
"video" => q.media = Some(Media::Video),
|
||||||
|
"audio" => q.media = Some(Media::Audio),
|
||||||
|
"file" => q.media = Some(Media::File),
|
||||||
|
_ => return Input::Help,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let Some(offset) = page.checked_sub(1).and_then(|p| p.checked_mul(q.limit)) else {
|
||||||
|
return Input::Help;
|
||||||
|
};
|
||||||
|
q.offset = offset;
|
||||||
|
Input::Search(q)
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
//! Transport-independent Telegram search interaction. The host supplies
|
||||||
|
//! incoming text and sends the returned plain-text labels and URL buttons.
|
||||||
|
mod command;
|
||||||
|
use telefind_core::{Document, Kind, SearchIndex};
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq)]
|
||||||
|
pub struct ResultLink {
|
||||||
|
pub label: String,
|
||||||
|
pub url: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq)]
|
||||||
|
pub enum Reply {
|
||||||
|
Ignored,
|
||||||
|
Help,
|
||||||
|
Results {
|
||||||
|
total: usize,
|
||||||
|
links: Vec<ResultLink>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Accept a keyword message or /search. The bot username is needed for
|
||||||
|
/// commands addressed to a particular bot in a group. Use /page N keywords
|
||||||
|
/// to fetch a later page without storing per-user sessions.
|
||||||
|
pub fn handle<S: SearchIndex>(index: &S, bot: &str, text: &str) -> Result<Reply, S::Error> {
|
||||||
|
let request = match command::parse(bot, text) {
|
||||||
|
command::Input::Ignore => return Ok(Reply::Ignored),
|
||||||
|
command::Input::Help => return Ok(Reply::Help),
|
||||||
|
command::Input::Search(query) => query,
|
||||||
|
};
|
||||||
|
let page = index.search(&request)?;
|
||||||
|
Ok(Reply::Results {
|
||||||
|
total: page.total,
|
||||||
|
links: page.hits.iter().map(link).collect(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn link(doc: &Document) -> ResultLink {
|
||||||
|
let kind = match doc.kind() {
|
||||||
|
Kind::Channel => "频道",
|
||||||
|
Kind::Group => "群组",
|
||||||
|
Kind::Bot => "Bot",
|
||||||
|
Kind::Post => "帖子",
|
||||||
|
};
|
||||||
|
let name = [&doc.title[..], &doc.body[..], doc.username.as_str()]
|
||||||
|
.into_iter()
|
||||||
|
.map(str::trim)
|
||||||
|
.find(|s| !s.is_empty())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let compact: String = name
|
||||||
|
.split_whitespace()
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(" ")
|
||||||
|
.chars()
|
||||||
|
.take(60)
|
||||||
|
.collect();
|
||||||
|
ResultLink {
|
||||||
|
label: format!("{kind} · {compact}"),
|
||||||
|
url: doc.url(),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
use telefind_bot::{handle, Reply};
|
||||||
|
use telefind_core::{Document, DocumentId, MemoryIndex, PublicName, SearchIndex};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn plain_and_addressed_search_return_public_post_link() {
|
||||||
|
let mut index = MemoryIndex::default();
|
||||||
|
index
|
||||||
|
.upsert(Document {
|
||||||
|
id: DocumentId::Post {
|
||||||
|
chat: 9,
|
||||||
|
message: 4,
|
||||||
|
},
|
||||||
|
username: PublicName::new("techfeed").unwrap(),
|
||||||
|
title: "".into(),
|
||||||
|
body: "Rust 教程".into(),
|
||||||
|
media: None,
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
for text in ["rust", "/search@MyBot RUST", "/search 教程"] {
|
||||||
|
let Reply::Results { total, links } = handle(&index, "mybot", text).unwrap() else {
|
||||||
|
panic!("expected results")
|
||||||
|
};
|
||||||
|
assert_eq!(total, 1);
|
||||||
|
assert_eq!(links[0].url, "https://t.me/techfeed/4");
|
||||||
|
assert_eq!(links[0].label, "帖子 · Rust 教程");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn missing_queries_and_foreign_commands_are_distinct() {
|
||||||
|
let index = MemoryIndex::default();
|
||||||
|
for text in ["/start", "/search@me ", "/help"] {
|
||||||
|
assert_eq!(handle(&index, "me", text).unwrap(), Reply::Help);
|
||||||
|
}
|
||||||
|
for text in [" ", "/search@another x", "/status"] {
|
||||||
|
assert_eq!(handle(&index, "me", text).unwrap(), Reply::Ignored);
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
handle(&index, "me", "中文").unwrap(),
|
||||||
|
Reply::Results {
|
||||||
|
total: 0,
|
||||||
|
links: vec![]
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn paging_is_stateless_and_rejects_invalid_numbers() {
|
||||||
|
let mut index = MemoryIndex::default();
|
||||||
|
for message in 1..=11 {
|
||||||
|
index
|
||||||
|
.upsert(Document {
|
||||||
|
id: DocumentId::Post { chat: 1, message },
|
||||||
|
username: PublicName::new("books").unwrap(),
|
||||||
|
title: "book".into(),
|
||||||
|
body: String::new(),
|
||||||
|
media: None,
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
let Reply::Results { total, links } = handle(&index, "me", "/page@me 2 book").unwrap() else {
|
||||||
|
panic!("expected page")
|
||||||
|
};
|
||||||
|
assert_eq!(total, 11);
|
||||||
|
assert_eq!(links.len(), 1);
|
||||||
|
assert_eq!(links[0].url, "https://t.me/books/11");
|
||||||
|
for text in ["/page 0 book", "/page x book", "/page 2"] {
|
||||||
|
assert_eq!(handle(&index, "me", text).unwrap(), Reply::Help);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn type_filter_is_available_in_search_and_page_commands() {
|
||||||
|
let mut index = MemoryIndex::default();
|
||||||
|
for (id, media) in [(1, None), (2, Some(telefind_core::Media::Video))] {
|
||||||
|
index
|
||||||
|
.upsert(Document {
|
||||||
|
id: DocumentId::Post {
|
||||||
|
chat: 1,
|
||||||
|
message: id,
|
||||||
|
},
|
||||||
|
username: PublicName::new("demo_feed").unwrap(),
|
||||||
|
title: "教程".into(),
|
||||||
|
body: String::new(),
|
||||||
|
media,
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
for query in [
|
||||||
|
"type:video 教程",
|
||||||
|
"/search type:video 教程",
|
||||||
|
"/page 1 type:video 教程",
|
||||||
|
] {
|
||||||
|
let Reply::Results { links, total } = handle(&index, "me", query).unwrap() else {
|
||||||
|
panic!("expected results")
|
||||||
|
};
|
||||||
|
assert_eq!(total, 1);
|
||||||
|
assert_eq!(links[0].url, "https://t.me/demo_feed/2");
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
handle(&index, "me", "/search type:unknown 教程").unwrap(),
|
||||||
|
Reply::Help
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
[package]
|
||||||
|
name = "telefind-core"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
jieba-rs = "0.8"
|
||||||
|
unicode-normalization = "0.1"
|
||||||
@@ -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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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]))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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>;
|
||||||
|
}
|
||||||
@@ -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};
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
pub(crate) mod analysis;
|
||||||
|
pub(crate) mod rank;
|
||||||
|
pub(crate) mod retrieve;
|
||||||
|
|
||||||
|
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>,
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
use super::{analysis, rank};
|
||||||
|
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 text = analysis::normalize(query.text);
|
||||||
|
// 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 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 })
|
||||||
|
}
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
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]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user