Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 01b8af4757 | |||
| ef251ae339 | |||
| 3ae1097e1b | |||
| a1683415c1 | |||
| 90d048fdef | |||
| 20d3d3fc62 | |||
| c0b5455582 |
Generated
+26
-26
@@ -29,12 +29,30 @@ version = "0.2.22"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "57b212daf2e827b1ccdd778b7eb48ba433e58cb0e4f27b43cd6b7a608425a014"
|
||||
|
||||
[[package]]
|
||||
name = "app"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bot",
|
||||
"core",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"ureq",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.23.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
|
||||
|
||||
[[package]]
|
||||
name = "bot"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
version = "1.12.2"
|
||||
@@ -97,6 +115,14 @@ dependencies = [
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"jieba-rs",
|
||||
"unicode-normalization",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.6"
|
||||
@@ -811,32 +837,6 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "telefind-app"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"telefind-bot",
|
||||
"telefind-core",
|
||||
"ureq",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "telefind-bot"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"telefind-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "telefind-core"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"jieba-rs",
|
||||
"unicode-normalization",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time"
|
||||
version = "0.3.55"
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
[workspace]
|
||||
members = ["crates/telefind-core", "crates/telefind-bot", "crates/telefind-app"]
|
||||
members = ["crates/core", "crates/bot", "crates/app"]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
|
||||
@@ -7,7 +7,7 @@ Rust keyword search for public Telegram channels, groups, bots and posts. The ex
|
||||
From the workspace root:
|
||||
|
||||
```sh
|
||||
cargo run -p telefind-app -- query - '/search type:video 上海相机' <<'JSONL'
|
||||
cargo run -p app -- query - '/search type:video 上海相机' <<'JSONL'
|
||||
{"op":"upsert","kind":"post","id":-100501,"message_id":42,"username":"example_feed","title":"相机入门.mp4","body":"上海 摄影","media":"video"}
|
||||
JSONL
|
||||
```
|
||||
@@ -19,12 +19,12 @@ This prints the reply as JSON, including a button with the URL `https://t.me/exa
|
||||
Supply the bot token through the environment variable `TELEGRAM_BOT_TOKEN` and run:
|
||||
|
||||
```sh
|
||||
cargo run -p telefind-app -- bot events.jsonl
|
||||
cargo run -p 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.
|
||||
Use a leading `type:channel`, `type:group`, `type:bot`, `type:post`, `type:photo`, `type:video`, `type:audio` or `type:file` to filter. After the optional type filter, add `from:@username` to restrict the source, or `exclude:广告` to omit titles and bodies containing that normalized text fragment. Multiple exclusions are allowed. Follow the filters with search terms, for example `/search type:video from:@example_feed exclude:广告 相机`. 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
|
||||
|
||||
@@ -34,8 +34,10 @@ Pass an ordered UTF-8 JSONL stream in a file, or pass `-` to read standard input
|
||||
{"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`.
|
||||
The process keeps no database or history archive. Restarting loads whichever input the caller supplies. For a persistent or concurrent host, implement `search_core::index::IndexStore` and its snapshot reader, then use `Engine::new(store)`. Pass the resulting engine to `app::telegram::run` with a `app::telegram::Client` to reuse the same polling and reply logic. The JSONL reader `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.
|
||||
|
||||
For a host that needs independent indexing and query workers, see [queue integration and capacity estimates](docs/capacity.md).
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
[package]
|
||||
name = "telefind-app"
|
||||
name = "app"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
default-run = "telefind"
|
||||
@@ -9,8 +9,8 @@ name = "telefind"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
telefind-core = { path = "../telefind-core" }
|
||||
telefind-bot = { path = "../telefind-bot" }
|
||||
core = { path = "../core" }
|
||||
bot = { path = "../bot" }
|
||||
ureq = { version = "3", features = ["json"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Line-delimited public document changes supplied by the caller.
|
||||
use search_core::{Document, DocumentId, Media, PublicName, SearchIndex};
|
||||
use serde::Deserialize;
|
||||
use std::{error::Error, io::BufRead};
|
||||
use telefind_core::{Document, DocumentId, Media, PublicName, SearchIndex};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
@@ -1,3 +1,5 @@
|
||||
use app::{input, telegram};
|
||||
use search_core::MemoryIndex;
|
||||
use std::{
|
||||
env,
|
||||
error::Error,
|
||||
@@ -5,8 +7,6 @@ use std::{
|
||||
io::{self, BufReader},
|
||||
process::ExitCode,
|
||||
};
|
||||
use telefind_app::{input, telegram};
|
||||
use telefind_core::MemoryIndex;
|
||||
|
||||
const USAGE: &str = concat!(
|
||||
"telefind bot [events.jsonl|-]\n",
|
||||
@@ -36,7 +36,7 @@ fn run() -> Result<(), Box<dyn Error>> {
|
||||
}
|
||||
Some("query") if args.len() >= 3 => {
|
||||
load(&args[1], &mut index)?;
|
||||
let reply = telefind_bot::handle(&index, "telefind", &args[2..].join(" "))?;
|
||||
let reply = bot::handle(&index, "telefind", &args[2..].join(" "))?;
|
||||
println!("{}", serde_json::to_string(&telegram::render(reply))?);
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,14 +1,15 @@
|
||||
mod client;
|
||||
pub mod queue;
|
||||
mod update;
|
||||
use self::{
|
||||
client::Failure,
|
||||
update::{dispatch, Update},
|
||||
};
|
||||
pub use client::Client;
|
||||
use search_core::SearchIndex;
|
||||
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>(
|
||||
@@ -42,10 +43,17 @@ pub fn run<S: SearchIndex>(client: &Client, index: &mut S) -> Result<(), Box<dyn
|
||||
where
|
||||
S::Error: Error + 'static,
|
||||
{
|
||||
run_loop(client, |bot, offset| poll(client, index, bot, offset))
|
||||
}
|
||||
|
||||
fn run_loop(
|
||||
client: &Client,
|
||||
mut cycle: impl FnMut(&str, &mut Option<i64>) -> Result<(), Box<dyn Error>>,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
let bot: BotInfo = with_retry(|| Ok(client.call("getMe", &json!({}))?))?;
|
||||
let mut offset = None;
|
||||
loop {
|
||||
with_retry(|| poll(client, index, &bot.username, &mut offset))?;
|
||||
with_retry(|| cycle(&bot.username, &mut offset))?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,13 +66,21 @@ fn poll<S: SearchIndex>(
|
||||
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);
|
||||
receive(client, offset, |update| {
|
||||
process(client, index, bot, &update)
|
||||
})
|
||||
}
|
||||
let batch: Vec<Update> = client.call("getUpdates", &request)?;
|
||||
for update in batch {
|
||||
if let Some(payload) = dispatch(index, bot, &update)? {
|
||||
|
||||
fn process<S: SearchIndex>(
|
||||
client: &Client,
|
||||
index: &mut S,
|
||||
bot: &str,
|
||||
update: &Update,
|
||||
) -> Result<(), Box<dyn Error>>
|
||||
where
|
||||
S::Error: Error + 'static,
|
||||
{
|
||||
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.
|
||||
@@ -74,7 +90,23 @@ where
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
}
|
||||
*offset = Some(update.update_id + 1);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn receive(
|
||||
client: &Client,
|
||||
offset: &mut Option<i64>,
|
||||
mut accept: impl FnMut(Update) -> Result<(), Box<dyn Error>>,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
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 {
|
||||
let next = update.update_id + 1;
|
||||
accept(update)?;
|
||||
*offset = Some(next);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
//! Broker-neutral gateway and leased workers. Each adapter is scoped to one bot.
|
||||
use super::{client::Failure, process, receive, run_loop, Client, Update};
|
||||
use search_core::SearchIndex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{error::Error, time::Duration};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Lane {
|
||||
Index,
|
||||
Query,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct Job {
|
||||
bot_username: String,
|
||||
update: Update,
|
||||
}
|
||||
|
||||
impl Job {
|
||||
pub fn update_id(&self) -> i64 {
|
||||
self.update.update_id
|
||||
}
|
||||
}
|
||||
pub type QueueResult<T> = Result<T, Box<dyn Error>>;
|
||||
|
||||
/// Return success after durable acceptance or detection of a previously accepted
|
||||
/// update ID (including completed jobs). Bound the backlog. On saturation,
|
||||
/// block or return an error. Never acknowledge a dropped job.
|
||||
pub trait Publisher {
|
||||
fn publish(&mut self, lane: Lane, chat_id: i64, job: Job) -> QueueResult<()>;
|
||||
}
|
||||
|
||||
/// Bind a consumer to one lane. Deliver FIFO per chat with only one outstanding
|
||||
/// delivery per partition; reclaim expired leases, fence stale workers and retain
|
||||
/// deduplication keys across ack. Persistent retries/quarantine are adapter policy.
|
||||
pub trait Consumer {
|
||||
type Receipt;
|
||||
fn reserve(&mut self) -> QueueResult<Option<(Self::Receipt, Job)>>;
|
||||
fn ack(&mut self, receipt: Self::Receipt) -> QueueResult<()>;
|
||||
fn defer(&mut self, receipt: Self::Receipt, delay: Duration) -> QueueResult<()>;
|
||||
}
|
||||
|
||||
/// Single poller per token. A failed publication leaves the update unconfirmed.
|
||||
pub fn run_gateway(client: &Client, publisher: &mut impl Publisher) -> QueueResult<()> {
|
||||
run_loop(client, |bot, offset| {
|
||||
poll_into(client, bot, offset, publisher)
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn poll_into(
|
||||
client: &Client,
|
||||
bot: &str,
|
||||
offset: &mut Option<i64>,
|
||||
publisher: &mut impl Publisher,
|
||||
) -> QueueResult<()> {
|
||||
receive(client, offset, |mut update| {
|
||||
if let Some((lane, chat_id)) = update.route() {
|
||||
update.minimize();
|
||||
publisher.publish(
|
||||
lane,
|
||||
chat_id,
|
||||
Job {
|
||||
bot_username: bot.to_owned(),
|
||||
update,
|
||||
},
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Outcome {
|
||||
Idle,
|
||||
Completed,
|
||||
Deferred,
|
||||
}
|
||||
|
||||
/// Run separate workers per lane over the same backing index. Unacknowledged
|
||||
/// work is recoverable on lease expiry. Sending a Telegram reply is at-least-once.
|
||||
pub fn consume_one<S: SearchIndex>(
|
||||
client: &Client,
|
||||
index: &mut S,
|
||||
consumer: &mut impl Consumer,
|
||||
) -> QueueResult<Outcome>
|
||||
where
|
||||
S::Error: Error + 'static,
|
||||
{
|
||||
let Some((receipt, job)) = consumer.reserve()? else {
|
||||
return Ok(Outcome::Idle);
|
||||
};
|
||||
if let Err(err) = process(client, index, &job.bot_username, &job.update) {
|
||||
if let Some(failure) = err.downcast_ref::<Failure>().filter(|f| f.transient()) {
|
||||
consumer.defer(
|
||||
receipt,
|
||||
failure
|
||||
.retry_after
|
||||
.unwrap_or(Duration::from_secs(1))
|
||||
.max(Duration::from_secs(1)),
|
||||
)?;
|
||||
return Ok(Outcome::Deferred);
|
||||
}
|
||||
return Err(err);
|
||||
}
|
||||
consumer.ack(receipt)?;
|
||||
Ok(Outcome::Completed)
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
use super::*;
|
||||
use search_core::MemoryIndex;
|
||||
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();
|
||||
@@ -105,7 +105,7 @@ fn nonpublic_and_protected_updates_do_not_add_searchable_posts() {
|
||||
}
|
||||
assert_eq!(
|
||||
index
|
||||
.search(&telefind_core::Query::new("private"))
|
||||
.search(&search_core::Query::new("private"))
|
||||
.unwrap()
|
||||
.total,
|
||||
0
|
||||
@@ -156,3 +156,5 @@ fn flood_wait_keeps_failed_update_pending_and_preserves_prior_progress() {
|
||||
.contains("401"));
|
||||
peer.join().unwrap();
|
||||
}
|
||||
|
||||
mod queued;
|
||||
@@ -0,0 +1,117 @@
|
||||
use super::*;
|
||||
use queue::{Consumer, Job, Lane, Outcome, Publisher, QueueResult};
|
||||
use std::collections::VecDeque;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Broker {
|
||||
jobs: VecDeque<(Lane, i64, Value)>,
|
||||
full: bool,
|
||||
delay: Option<Duration>,
|
||||
}
|
||||
impl Publisher for Broker {
|
||||
fn publish(&mut self, lane: Lane, chat: i64, job: Job) -> QueueResult<()> {
|
||||
if self.full {
|
||||
return Err("queue full".into());
|
||||
}
|
||||
self.jobs
|
||||
.push_back((lane, chat, serde_json::to_value(job)?));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Consumer for Broker {
|
||||
type Receipt = i64;
|
||||
fn reserve(&mut self) -> QueueResult<Option<(i64, Job)>> {
|
||||
let Some((_, _, value)) = self.jobs.front() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let job: Job = serde_json::from_value(value.clone())?;
|
||||
Ok(Some((job.update_id(), job)))
|
||||
}
|
||||
fn ack(&mut self, receipt: i64) -> QueueResult<()> {
|
||||
let job = self.jobs.pop_front().unwrap();
|
||||
assert_eq!(job.2["update"]["update_id"], receipt);
|
||||
Ok(())
|
||||
}
|
||||
fn defer(&mut self, _: i64, delay: Duration) -> QueueResult<()> {
|
||||
self.delay = Some(delay);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn publish_failure_keeps_offset_then_workers_replay_and_defer_flooded_reply() {
|
||||
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 channel = json!({"type":"channel","id":-99,"username":"sample_feed"});
|
||||
let batch = json!([
|
||||
{"update_id":10,"channel_post":{"chat":channel,"message_id":1,"text":"tutorial"}},
|
||||
{"update_id":11,"message":{"chat":{"type":"private","id":2},"message_id":1,"text":"tutorial"}},
|
||||
{"update_id":12,"edited_channel_post":{"chat":channel,"message_id":1,"has_protected_content":true,"caption":"secret caption"}}
|
||||
]);
|
||||
for _ in 0..2 {
|
||||
respond(&server, |method, req| {
|
||||
assert!(method.contains("getUpdates"));
|
||||
assert_eq!(req["offset"], 10);
|
||||
(200, json!({"ok":true,"result":batch}).to_string())
|
||||
});
|
||||
}
|
||||
respond(&server, |method, reply| {
|
||||
assert!(method.contains("sendMessage"));
|
||||
assert_eq!(
|
||||
reply["reply_markup"]["inline_keyboard"][0][0]["url"],
|
||||
"https://t.me/sample_feed/1"
|
||||
);
|
||||
(
|
||||
429,
|
||||
json!({"ok":false,"error_code":429,"parameters":{"retry_after":8}}).to_string(),
|
||||
)
|
||||
});
|
||||
respond(&server, |_, _| {
|
||||
(200, json!({"ok":true,"result":{}}).to_string())
|
||||
});
|
||||
});
|
||||
let mut broker = Broker {
|
||||
full: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut offset = Some(10);
|
||||
assert!(queue::poll_into(&client, "mybot", &mut offset, &mut broker).is_err());
|
||||
assert_eq!(offset, Some(10));
|
||||
broker.full = false;
|
||||
queue::poll_into(&client, "mybot", &mut offset, &mut broker).unwrap();
|
||||
assert_eq!(offset, Some(13));
|
||||
assert_eq!(broker.jobs[0].0, Lane::Index);
|
||||
assert_eq!(broker.jobs[1].0, Lane::Query);
|
||||
assert_eq!(broker.jobs[2].1, -99);
|
||||
assert!(!broker.jobs[2].2.to_string().contains("secret caption"));
|
||||
let mut index = MemoryIndex::default();
|
||||
let (index_jobs, query_jobs) = broker
|
||||
.jobs
|
||||
.into_iter()
|
||||
.partition(|job| job.0 == Lane::Index);
|
||||
let mut writes = Broker {
|
||||
jobs: index_jobs,
|
||||
..Default::default()
|
||||
};
|
||||
let mut queries = Broker {
|
||||
jobs: query_jobs,
|
||||
..Default::default()
|
||||
};
|
||||
let mut step = |lane: &mut Broker| queue::consume_one(&client, &mut index, lane).unwrap();
|
||||
assert_eq!(step(&mut writes), Outcome::Completed);
|
||||
assert_eq!(step(&mut queries), Outcome::Deferred);
|
||||
assert_eq!(queries.delay, Some(Duration::from_secs(8)));
|
||||
// Index processing can advance during the query worker's flood wait.
|
||||
assert_eq!(step(&mut writes), Outcome::Completed);
|
||||
assert_eq!(step(&mut writes), Outcome::Idle);
|
||||
assert_eq!(step(&mut queries), Outcome::Completed);
|
||||
assert_eq!(
|
||||
index
|
||||
.search(&search_core::Query::new("tutorial"))
|
||||
.unwrap()
|
||||
.total,
|
||||
0
|
||||
);
|
||||
peer.join().unwrap();
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
use serde::Deserialize;
|
||||
use bot::{handle, Reply};
|
||||
use search_core::{Document, DocumentId, Media, PublicName, SearchIndex};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use telefind_bot::{handle, Reply};
|
||||
use telefind_core::{Document, DocumentId, Media, PublicName, SearchIndex};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct Update {
|
||||
pub update_id: i64,
|
||||
message: Option<Message>,
|
||||
@@ -11,7 +11,7 @@ pub struct Update {
|
||||
edited_channel_post: Option<Message>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct Chat {
|
||||
id: i64,
|
||||
#[serde(rename = "type")]
|
||||
@@ -19,11 +19,11 @@ struct Chat {
|
||||
username: Option<String>,
|
||||
title: Option<String>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct File {
|
||||
file_name: Option<String>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct Message {
|
||||
chat: Chat,
|
||||
message_id: u32,
|
||||
@@ -38,6 +38,63 @@ struct Message {
|
||||
message_thread_id: Option<i64>,
|
||||
}
|
||||
|
||||
impl Update {
|
||||
pub(super) fn route(&self) -> Option<(super::queue::Lane, i64)> {
|
||||
use super::queue::Lane;
|
||||
if let Some(post) = self
|
||||
.channel_post
|
||||
.as_ref()
|
||||
.or(self.edited_channel_post.as_ref())
|
||||
{
|
||||
return (post.chat.kind == "channel" && post.message_id > 0)
|
||||
.then_some((Lane::Index, post.chat.id));
|
||||
}
|
||||
let msg = self.message.as_ref()?;
|
||||
let text = msg.text.as_deref()?.trim();
|
||||
(!text.is_empty() && (msg.chat.kind == "private" || text.starts_with('/')))
|
||||
.then_some((Lane::Query, msg.chat.id))
|
||||
}
|
||||
|
||||
pub(super) fn minimize(&mut self) {
|
||||
for post in self
|
||||
.channel_post
|
||||
.iter_mut()
|
||||
.chain(self.edited_channel_post.iter_mut())
|
||||
{
|
||||
if post.has_protected_content
|
||||
|| post
|
||||
.chat
|
||||
.username
|
||||
.as_deref()
|
||||
.and_then(PublicName::new)
|
||||
.is_none()
|
||||
{
|
||||
post.text = None;
|
||||
post.caption = None;
|
||||
post.video = None;
|
||||
post.audio = None;
|
||||
post.document = None;
|
||||
post.photo = None;
|
||||
post.chat.title = None;
|
||||
} else if let Some(photos) = &mut post.photo {
|
||||
// Indexing only needs to know whether a photo exists.
|
||||
if !photos.is_empty() {
|
||||
*photos = vec![Value::Null];
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(msg) = self.message.as_mut() {
|
||||
msg.caption = None;
|
||||
msg.photo = None;
|
||||
msg.audio = None;
|
||||
msg.document = None;
|
||||
msg.video = None;
|
||||
msg.chat.title = None;
|
||||
msg.chat.username = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Message {
|
||||
fn attachment(&self) -> (Option<Media>, String) {
|
||||
for (media, file) in [
|
||||
@@ -101,7 +158,7 @@ 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 页码 关键词 翻页。"}),
|
||||
json!({"text":"发送关键词或 /search 关键词。可用 type:channel、group、bot、post、video、photo、audio、file 筛选;可在关键词前加 from:@频道名 限定来源,或 exclude:广告 排除含该文字的结果。用 /page 页码 关键词 翻页。"}),
|
||||
),
|
||||
Reply::Results { total, links } if links.is_empty() => Some(
|
||||
json!({"text":if total == 0 {"没有找到匹配结果。".into()} else {format!("本页没有结果,共 {total} 条。")}}),
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "telefind-bot"
|
||||
name = "bot"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[dependencies]
|
||||
telefind-core = { path = "../telefind-core" }
|
||||
core = { path = "../core" }
|
||||
@@ -1,4 +1,4 @@
|
||||
use telefind_core::{Kind, Media, Query};
|
||||
use search_core::{Kind, Media, Query};
|
||||
pub(crate) enum Input<'a> {
|
||||
Ignore,
|
||||
Help,
|
||||
@@ -1,7 +1,7 @@
|
||||
//! 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};
|
||||
use search_core::{Document, Kind, SearchIndex};
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub struct ResultLink {
|
||||
@@ -1,5 +1,5 @@
|
||||
use telefind_bot::{handle, Reply};
|
||||
use telefind_core::{Document, DocumentId, MemoryIndex, PublicName, SearchIndex};
|
||||
use bot::{handle, Reply};
|
||||
use search_core::{Document, DocumentId, MemoryIndex, PublicName, SearchIndex};
|
||||
|
||||
#[test]
|
||||
fn plain_and_addressed_search_return_public_post_link() {
|
||||
@@ -72,7 +72,7 @@ fn paging_is_stateless_and_rejects_invalid_numbers() {
|
||||
#[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))] {
|
||||
for (id, media) in [(1, None), (2, Some(search_core::Media::Video))] {
|
||||
index
|
||||
.upsert(Document {
|
||||
id: DocumentId::Post {
|
||||
@@ -102,3 +102,33 @@ fn type_filter_is_available_in_search_and_page_commands() {
|
||||
Reply::Help
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scoped_media_search_keeps_quoted_phrase_and_original_link() {
|
||||
let mut index = MemoryIndex::default();
|
||||
for (message, body) in [
|
||||
(1, "Rust search"),
|
||||
(2, "Rust search SALE"),
|
||||
(3, "search Rust"),
|
||||
] {
|
||||
index
|
||||
.upsert(Document {
|
||||
id: DocumentId::Post { chat: 3, message },
|
||||
username: PublicName::new("my_feed").unwrap(),
|
||||
title: String::new(),
|
||||
body: body.into(),
|
||||
media: Some(search_core::Media::Video),
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
let Reply::Results { total, links } = handle(
|
||||
&index,
|
||||
"me",
|
||||
r#"/page@me 1 type:video from:@My_Feed exclude:sale "rust search""#,
|
||||
)
|
||||
.unwrap() else {
|
||||
panic!("expected a search result")
|
||||
};
|
||||
assert_eq!(total, 1);
|
||||
assert_eq!(links[0].url, "https://t.me/my_feed/1");
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
[package]
|
||||
name = "telefind-core"
|
||||
name = "core"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[lib]
|
||||
name = "search_core"
|
||||
|
||||
[dependencies]
|
||||
jieba-rs = "0.8"
|
||||
unicode-normalization = "0.1"
|
||||
@@ -1,6 +1,7 @@
|
||||
pub(crate) mod analysis;
|
||||
pub(crate) mod rank;
|
||||
pub(crate) mod retrieve;
|
||||
mod scope;
|
||||
|
||||
use crate::{Document, Kind, Media};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{analysis, rank};
|
||||
use super::{analysis, rank, scope::Scope};
|
||||
use crate::{index::IndexReader, DocumentId, Kind, Query, SearchPage};
|
||||
use std::{
|
||||
cmp::{Ordering, Reverse},
|
||||
@@ -37,7 +37,10 @@ pub(crate) fn retrieve<R: IndexReader>(reader: &R, query: &Query) -> Result<Sear
|
||||
total: 0,
|
||||
hits: Vec::new(),
|
||||
};
|
||||
let text = analysis::normalize(query.text);
|
||||
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
|
||||
@@ -46,7 +49,7 @@ pub(crate) fn retrieve<R: IndexReader>(reader: &R, query: &Query) -> Result<Sear
|
||||
.filter(|phrase| !phrase.is_empty())
|
||||
.collect();
|
||||
let mut lists = Vec::new();
|
||||
for term in analysis::query_terms(&text) {
|
||||
for term in analysis::query_terms(text) {
|
||||
let Some(postings) = reader.postings(&term)? else {
|
||||
return Ok(empty());
|
||||
};
|
||||
@@ -66,7 +69,8 @@ pub(crate) fn retrieve<R: IndexReader>(reader: &R, query: &Query) -> Result<Sear
|
||||
continue;
|
||||
}
|
||||
let entry = reader.document(*id)?;
|
||||
if query.kind.is_some_and(|kind| kind != entry.document.kind())
|
||||
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)
|
||||
@@ -87,9 +91,9 @@ pub(crate) fn retrieve<R: IndexReader>(reader: &R, query: &Query) -> Result<Sear
|
||||
.iter()
|
||||
.map(|list| rank::term_score(list[id], entry.lengths, avg, n, list.len()))
|
||||
.sum();
|
||||
if entry.title.contains(&text) {
|
||||
if entry.title.contains(text) {
|
||||
score += 2.0;
|
||||
} else if entry.body.contains(&text) {
|
||||
} else if entry.body.contains(text) {
|
||||
score += 0.5;
|
||||
}
|
||||
let exact = entry.document.kind() != Kind::Post
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
use telefind_core::{
|
||||
Document, DocumentId, Kind, Media, MemoryIndex, PublicName, Query, SearchIndex,
|
||||
};
|
||||
use search_core::{Document, DocumentId, Kind, Media, MemoryIndex, PublicName, Query, SearchIndex};
|
||||
|
||||
fn post(chat: i64, message: u32, title: &str, body: &str) -> Document {
|
||||
Document {
|
||||
@@ -183,3 +181,31 @@ fn measure_ranked_queries_over_25000_posts() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
# Estimating intake and queue capacity
|
||||
|
||||
TGStat reports over 40 million new posts and messages daily from over 3.165 million channels and chats. Its callback documentation separately reports around 100,000 events per minute. Those figures measure different work. Neither is a traffic forecast for a single Telegram bot. [Monitoring figures](https://tgstat.ru/alerts) · [Callback documentation](https://api.tgstat.ru/docs/ru/callback/intro.html)
|
||||
|
||||
Telemetry advertises a searchable stock of over 4.45 billion messages. Its homepage does not give a daily intake series. A directory entry, an indexed post, an edit and a user query should be counted separately. [Telemetry](https://www.telemetryapp.io/)
|
||||
|
||||
Estimate new posts per day as the sum of reachable sources times posts per source per day for each source class. Measure edits, redeliveries and queries separately. As a planning scenario, 10,000 channels at 20 posts/day produce 200,000 posts/day. At an assumed 2 KiB per projected job this is 0.41 GB/day before queue overhead, indexes, replicas or media. A 10x peak is 23.1 posts/s. At that sustained peak, 15 minutes of stopped workers creates about 20,833 pending jobs; a consumer group processing 50/s takes about 13 minutes to catch up while peak traffic continues. Use measured byte and rate distributions before choosing a broker or retention period.
|
||||
|
||||
## Queue integration
|
||||
|
||||
The built-in CLI processes updates inline. Hosts can instead call `telegram::queue::run_gateway` with a durable `Publisher` and run `consume_one` against separate Index and Query consumers. Scope the broker namespace to the bot. Share the backing search index across workers. Queries read the latest committed snapshot; queued posts can take time to appear. Search calls themselves remain synchronous. Workers for separate lanes may run on different hosts. A full broker can still backpressure the single inbound poller.
|
||||
|
||||
Use bounded retention and high-water marks. Commit durable acceptance before returning from publish; enforce deduplication across delivery and completion for the Telegram retry horizon. Preserve per-chat order across retries and exclude concurrent stale owners, including when worker leases expire during index writes. Configure finite worker operation timeouts, lease renewal or fenced writes. On store or worker failure the receipt remains unacknowledged. On transient reply failures the worker defers delivery, honoring Telegram retry_after. Spread retries, cap attempts, quarantine poison jobs with a replay path and coordinate bot-wide send limits across query workers. A lost sendMessage acknowledgement can still cause duplicate replies.
|
||||
|
||||
Monitor oldest unprocessed age, ingress rate and bytes by lane, indexing lag, reply latency, retry and dead-letter counts, 429s and worker throughput. Telegram keeps pending updates for at most 24 hours; a local broker only covers work it has accepted. A Bot API token receives channel posts where the bot is a member. Wider coverage needs an upstream source. Index growth, query traffic and restart recovery require separate measurements. [Telegram Bot API](https://core.telegram.org/bots/api#getting-updates) · [Bot FAQ](https://core.telegram.org/bots/faq#what-messages-will-my-bot-get)
|
||||
Reference in New Issue
Block a user