Shorten workspace directory names to app, bot and core
This commit is contained in:
@@ -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 = "../core" }
|
||||
telefind-bot = { path = "../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,115 @@
|
||||
mod client;
|
||||
pub mod queue;
|
||||
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,
|
||||
{
|
||||
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(|| cycle(&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,
|
||||
{
|
||||
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 {
|
||||
let next = update.update_id + 1;
|
||||
accept(update)?;
|
||||
*offset = Some(next);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
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();
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use telefind_bot::{handle, Reply};
|
||||
use telefind_core::{Document, DocumentId, Media, PublicName, SearchIndex};
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct Update {
|
||||
pub update_id: i64,
|
||||
message: Option<Message>,
|
||||
channel_post: Option<Message>,
|
||||
edited_channel_post: Option<Message>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct Chat {
|
||||
id: i64,
|
||||
#[serde(rename = "type")]
|
||||
kind: String,
|
||||
username: Option<String>,
|
||||
title: Option<String>,
|
||||
}
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct File {
|
||||
file_name: Option<String>,
|
||||
}
|
||||
#[derive(Deserialize, Serialize)]
|
||||
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 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 [
|
||||
(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 筛选;可在关键词前加 from:@频道名 限定来源,或 exclude:广告 排除含该文字的结果。用 /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"));
|
||||
}
|
||||
Reference in New Issue
Block a user