From a1683415c1f15369a07da4c02ff0fea4a82db561 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Thu, 3 Dec 2026 04:01:39 +0800 Subject: [PATCH] Route Telegram updates to independently consumable index and query queues --- README.md | 2 + crates/telefind-app/src/telegram/mod.rs | 56 +++++++-- crates/telefind-app/src/telegram/queue.rs | 107 ++++++++++++++++ crates/telefind-app/src/telegram/tests.rs | 2 + .../telefind-app/src/telegram/tests/queued.rs | 117 ++++++++++++++++++ crates/telefind-app/src/telegram/update.rs | 67 +++++++++- docs/capacity.md | 15 +++ 7 files changed, 349 insertions(+), 17 deletions(-) create mode 100644 crates/telefind-app/src/telegram/queue.rs create mode 100644 crates/telefind-app/src/telegram/tests/queued.rs create mode 100644 docs/capacity.md diff --git a/README.md b/README.md index 7abf211..368ac57 100644 --- a/README.md +++ b/README.md @@ -39,3 +39,5 @@ The process keeps no database or history archive. Restarting loads whichever inp ## 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). diff --git a/crates/telefind-app/src/telegram/mod.rs b/crates/telefind-app/src/telegram/mod.rs index c4d48a2..b5aa855 100644 --- a/crates/telefind-app/src/telegram/mod.rs +++ b/crates/telefind-app/src/telegram/mod.rs @@ -1,4 +1,5 @@ mod client; +pub mod queue; mod update; use self::{ client::Failure, @@ -42,10 +43,17 @@ pub fn run(client: &Client, index: &mut S) -> Result<(), Box) -> Result<(), Box>, +) -> Result<(), Box> { 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,23 +66,47 @@ fn poll( where S::Error: Error + 'static, { + receive(client, offset, |update| { + process(client, index, bot, &update) + }) +} + +fn process( + client: &Client, + index: &mut S, + bot: &str, + update: &Update, +) -> Result<(), Box> +where + S::Error: Error + 'static, +{ + if let Some(payload) = dispatch(index, bot, update)? { + match client.call::("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()), + } + } + Ok(()) +} + +fn receive( + client: &Client, + offset: &mut Option, + mut accept: impl FnMut(Update) -> Result<(), Box>, +) -> Result<(), Box> { 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 = client.call("getUpdates", &request)?; for update in batch { - if let Some(payload) = dispatch(index, bot, &update)? { - match client.call::("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); + let next = update.update_id + 1; + accept(update)?; + *offset = Some(next); } Ok(()) } diff --git a/crates/telefind-app/src/telegram/queue.rs b/crates/telefind-app/src/telegram/queue.rs new file mode 100644 index 0000000..8686107 --- /dev/null +++ b/crates/telefind-app/src/telegram/queue.rs @@ -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 serde::{Deserialize, Serialize}; +use std::{error::Error, time::Duration}; +use telefind_core::SearchIndex; + +#[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 = Result>; + +/// 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>; + 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, + 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( + client: &Client, + index: &mut S, + consumer: &mut impl Consumer, +) -> QueueResult +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::().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) +} diff --git a/crates/telefind-app/src/telegram/tests.rs b/crates/telefind-app/src/telegram/tests.rs index 739ddaa..7940562 100644 --- a/crates/telefind-app/src/telegram/tests.rs +++ b/crates/telefind-app/src/telegram/tests.rs @@ -156,3 +156,5 @@ fn flood_wait_keeps_failed_update_pending_and_preserves_prior_progress() { .contains("401")); peer.join().unwrap(); } + +mod queued; diff --git a/crates/telefind-app/src/telegram/tests/queued.rs b/crates/telefind-app/src/telegram/tests/queued.rs new file mode 100644 index 0000000..13c2530 --- /dev/null +++ b/crates/telefind-app/src/telegram/tests/queued.rs @@ -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, +} +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> { + 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(&telefind_core::Query::new("tutorial")) + .unwrap() + .total, + 0 + ); + peer.join().unwrap(); +} diff --git a/crates/telefind-app/src/telegram/update.rs b/crates/telefind-app/src/telegram/update.rs index 8510046..fc1c6b2 100644 --- a/crates/telefind-app/src/telegram/update.rs +++ b/crates/telefind-app/src/telegram/update.rs @@ -1,9 +1,9 @@ -use serde::Deserialize; +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, @@ -11,7 +11,7 @@ pub struct Update { edited_channel_post: Option, } -#[derive(Deserialize)] +#[derive(Deserialize, Serialize)] struct Chat { id: i64, #[serde(rename = "type")] @@ -19,11 +19,11 @@ struct Chat { username: Option, title: Option, } -#[derive(Deserialize)] +#[derive(Deserialize, Serialize)] struct File { file_name: Option, } -#[derive(Deserialize)] +#[derive(Deserialize, Serialize)] struct Message { chat: Chat, message_id: u32, @@ -38,6 +38,63 @@ struct Message { message_thread_id: Option, } +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, String) { for (media, file) in [ diff --git a/docs/capacity.md b/docs/capacity.md new file mode 100644 index 0000000..b9ec4b0 --- /dev/null +++ b/docs/capacity.md @@ -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)