3 Commits

7 changed files with 349 additions and 17 deletions
+2
View File
@@ -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).
+41 -9
View File
@@ -1,4 +1,5 @@
mod client;
pub mod queue;
mod update;
use self::{
client::Failure,
@@ -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);
}
let batch: Vec<Update> = client.call("getUpdates", &request)?;
for update in batch {
if let Some(payload) = dispatch(index, bot, &update)? {
receive(client, offset, |update| {
process(client, 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(())
}
+107
View File
@@ -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<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)
}
@@ -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(&telefind_core::Query::new("tutorial"))
.unwrap()
.total,
0
);
peer.join().unwrap();
}
+62 -5
View File
@@ -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<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 [
+15
View File
@@ -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)