Route Telegram updates to independently consumable index and query queues

This commit is contained in:
2026-12-03 04:01:39 +08:00
parent 90d048fdef
commit a1683415c1
7 changed files with 349 additions and 17 deletions
+44 -12
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,23 +66,47 @@ fn poll<S: SearchIndex>(
where
S::Error: Error + 'static,
{
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.
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<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 {
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);
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 [