use std::{
fmt,
io::Cursor,
io::SeekFrom,
net::IpAddr,
path::{Path, PathBuf},
sync::Arc,
time::Duration,
};
use reqwest::{
Body, Client, Url,
header::{CONTENT_LENGTH, CONTENT_TYPE},
};
use secrecy::{ExposeSecret, SecretString};
use serde::Deserialize;
use tokio::{
fs::File,
io::{AsyncReadExt, AsyncSeekExt},
sync::{OwnedSemaphorePermit, Semaphore},
};
use tokio_util::io::ReaderStream;
use uuid::Uuid;
use crate::messaging::{MessagingError, wecom::message::PROVIDER};
use super::{
WeComMediaType, WeComNewsArticle, WeComRobotMessage, WeComTemplateCard,
message::{invalid_message, is_amr},
};
const DEFAULT_BASE_URL: &str = "https://qyapi.weixin.qq.com/cgi-bin/webhook/";
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
const DEFAULT_MAX_IN_FLIGHT_REQUESTS: usize = 32;
const DEFAULT_MAX_REQUEST_BODY_BYTES: usize = 3 * 1024 * 1024;
const DEFAULT_MAX_RESPONSE_BODY_BYTES: usize = 64 * 1024;
const RESPONSE_BODY_INITIAL_CAPACITY: usize = 8 * 1024;
const MAX_DIAGNOSTIC_CHARS: usize = 4 * 1024;
const MAX_WEBHOOK_KEY_BYTES: usize = 1024;
pub struct WeComRobotConfig {
webhook_key: SecretString,
base_url: Url,
timeout: Duration,
max_in_flight_requests: usize,
max_request_body_bytes: usize,
max_response_body_bytes: usize,
}
impl WeComRobotConfig {
pub fn new(webhook_key: impl Into<String>) -> Result<Self, MessagingError> {
let webhook_key = webhook_key.into();
let webhook_key = validate_webhook_key(&webhook_key)?;
let base_url = parse_base_url(DEFAULT_BASE_URL)?;
Ok(Self {
webhook_key: SecretString::from(webhook_key),
base_url,
timeout: DEFAULT_TIMEOUT,
max_in_flight_requests: DEFAULT_MAX_IN_FLIGHT_REQUESTS,
max_request_body_bytes: DEFAULT_MAX_REQUEST_BODY_BYTES,
max_response_body_bytes: DEFAULT_MAX_RESPONSE_BODY_BYTES,
})
}
pub fn from_webhook_url(webhook_url: impl AsRef<str>) -> Result<Self, MessagingError> {
let mut url =
Url::parse(webhook_url.as_ref()).map_err(|_| invalid_config("无法解析 Webhook URL"))?;
validate_http_url(&url, "Webhook URL")?;
let webhook_key = url
.query_pairs()
.find_map(|(name, value)| (name == "key").then(|| value.into_owned()))
.ok_or_else(|| invalid_config("Webhook URL 缺少 key 参数"))?;
let webhook_key = validate_webhook_key(&webhook_key)?;
if !url.path().trim_end_matches('/').ends_with("/send") {
return Err(invalid_config("Webhook URL 路径必须以 /send 结尾"));
}
url.set_query(None);
url.set_fragment(None);
{
let mut segments = url
.path_segments_mut()
.map_err(|()| invalid_config("Webhook URL 不支持作为基础地址"))?;
segments.pop_if_empty();
segments.pop();
segments.push("");
}
Ok(Self {
webhook_key: SecretString::from(webhook_key),
base_url: url,
timeout: DEFAULT_TIMEOUT,
max_in_flight_requests: DEFAULT_MAX_IN_FLIGHT_REQUESTS,
max_request_body_bytes: DEFAULT_MAX_REQUEST_BODY_BYTES,
max_response_body_bytes: DEFAULT_MAX_RESPONSE_BODY_BYTES,
})
}
#[must_use]
pub const fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
#[must_use]
pub const fn with_max_in_flight_requests(mut self, max_requests: usize) -> Self {
self.max_in_flight_requests = max_requests;
self
}
#[must_use]
pub const fn with_max_request_body_bytes(mut self, max_bytes: usize) -> Self {
self.max_request_body_bytes = max_bytes;
self
}
#[must_use]
pub const fn with_max_response_body_bytes(mut self, max_bytes: usize) -> Self {
self.max_response_body_bytes = max_bytes;
self
}
pub fn with_base_url(mut self, base_url: impl AsRef<str>) -> Result<Self, MessagingError> {
self.base_url = parse_base_url(base_url.as_ref())?;
Ok(self)
}
pub fn validate(&self) -> Result<(), MessagingError> {
if self.timeout.is_zero() {
return Err(invalid_config("请求超时必须大于 0"));
}
if self.max_response_body_bytes == 0 {
return Err(invalid_config("最大响应体字节数必须大于 0"));
}
if self.max_in_flight_requests == 0 {
return Err(invalid_config("最大并发请求数必须大于 0"));
}
if self.max_request_body_bytes == 0 {
return Err(invalid_config("最大请求体字节数必须大于 0"));
}
Ok(())
}
}
impl fmt::Debug for WeComRobotConfig {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("WeComRobotConfig")
.field("webhook_key", &"[已隐藏]")
.field("base_url", &safe_base_url(&self.base_url))
.field("timeout", &self.timeout)
.field("max_in_flight_requests", &self.max_in_flight_requests)
.field("max_request_body_bytes", &self.max_request_body_bytes)
.field("max_response_body_bytes", &self.max_response_body_bytes)
.finish()
}
}
#[derive(Clone)]
pub struct WeComRobotClient {
http_client: Client,
webhook_key: SecretString,
base_url: Url,
timeout: Duration,
max_in_flight_requests: usize,
in_flight_requests: Arc<Semaphore>,
max_request_body_bytes: usize,
max_response_body_bytes: usize,
}
impl WeComRobotClient {
pub fn new(config: WeComRobotConfig) -> Result<Self, MessagingError> {
let http_client = Client::builder()
.redirect(reqwest::redirect::Policy::none())
.referer(false)
.build()
.map_err(|source| request_error(source.without_url()))?;
Self::with_http_client(config, http_client)
}
pub fn with_http_client(
config: WeComRobotConfig,
http_client: Client,
) -> Result<Self, MessagingError> {
config.validate()?;
Ok(Self {
http_client,
webhook_key: config.webhook_key,
base_url: config.base_url,
timeout: config.timeout,
max_in_flight_requests: config.max_in_flight_requests,
in_flight_requests: Arc::new(Semaphore::new(config.max_in_flight_requests)),
max_request_body_bytes: config.max_request_body_bytes,
max_response_body_bytes: config.max_response_body_bytes,
})
}
pub async fn send(
&self,
message: &WeComRobotMessage,
) -> Result<WeComRobotReceipt, MessagingError> {
message.validate()?;
let body = serde_json::to_vec(message).map_err(|source| MessagingError::Serialize {
provider: PROVIDER,
source,
})?;
if body.len() > self.max_request_body_bytes {
return Err(MessagingError::RequestTooLarge {
provider: PROVIDER,
max_bytes: self.max_request_body_bytes,
});
}
let url = self.send_url()?;
let _permit = self.acquire_request_permit().await?;
let response = self
.http_client
.post(url)
.timeout(self.timeout)
.header(CONTENT_TYPE, "application/json")
.body(body)
.send()
.await
.map_err(|source| request_error(source.without_url()))?;
let (body, diagnostic) = self.read_success_response(response).await?;
let response: WeComApiResponse =
serde_json::from_slice(&body).map_err(|source| MessagingError::InvalidResponse {
provider: PROVIDER,
response: diagnostic,
source,
})?;
if response.errcode != 0 {
return Err(MessagingError::ProviderRejected {
provider: PROVIDER,
code: response.errcode,
message: self.sanitize_diagnostic(&response.errmsg),
});
}
Ok(WeComRobotReceipt {
code: response.errcode,
message: self.sanitize_diagnostic(&response.errmsg),
})
}
pub async fn send_text(
&self,
content: impl Into<String>,
) -> Result<WeComRobotReceipt, MessagingError> {
self.send(&WeComRobotMessage::text(content)).await
}
pub async fn send_markdown(
&self,
content: impl Into<String>,
) -> Result<WeComRobotReceipt, MessagingError> {
self.send(&WeComRobotMessage::markdown(content)).await
}
pub async fn send_markdown_v2(
&self,
content: impl Into<String>,
) -> Result<WeComRobotReceipt, MessagingError> {
self.send(&WeComRobotMessage::markdown_v2(content)).await
}
pub async fn send_image_bytes(
&self,
bytes: &[u8],
) -> Result<WeComRobotReceipt, MessagingError> {
self.send(&WeComRobotMessage::image_from_bytes(bytes)?)
.await
}
pub async fn send_news(
&self,
articles: impl IntoIterator<Item = WeComNewsArticle>,
) -> Result<WeComRobotReceipt, MessagingError> {
self.send(&WeComRobotMessage::news(articles)).await
}
pub async fn send_template_card(
&self,
card: impl Into<WeComTemplateCard>,
) -> Result<WeComRobotReceipt, MessagingError> {
self.send(&WeComRobotMessage::template_card(card)).await
}
pub async fn upload_media_bytes(
&self,
media_type: WeComMediaType,
file_name: impl Into<String>,
bytes: impl Into<Vec<u8>>,
) -> Result<WeComMediaUploadReceipt, MessagingError> {
let file_name = file_name.into();
let bytes = bytes.into();
media_type.validate_file_name(&file_name)?;
media_type.validate_bytes(&bytes)?;
let size = bytes.len() as u64;
let multipart = build_media_body(media_type, &file_name, size, Cursor::new(bytes))?;
self.upload_media_body(media_type, multipart).await
}
pub async fn upload_media_file(
&self,
media_type: WeComMediaType,
path: impl AsRef<Path>,
) -> Result<WeComMediaUploadReceipt, MessagingError> {
let path = PathBuf::from(path.as_ref());
let file_name = path
.file_name()
.map(|value| value.to_string_lossy().into_owned())
.ok_or_else(|| invalid_message("上传路径缺少文件名"))?;
media_type.validate_file_name(&file_name)?;
let mut file = File::open(&path)
.await
.map_err(|source| io_error("打开上传文件", source))?;
let metadata = file
.metadata()
.await
.map_err(|source| io_error("读取上传文件元数据", source))?;
if !metadata.is_file() {
return Err(invalid_message("上传路径必须指向普通文件"));
}
media_type.validate_size(metadata.len())?;
if media_type == WeComMediaType::Voice {
let mut header = [0_u8; 9];
let read = file
.read(&mut header)
.await
.map_err(|source| io_error("读取 AMR 文件头", source))?;
if !is_amr(&header[..read]) {
return Err(invalid_message("语音文件内容不是有效的 AMR 格式"));
}
file.seek(SeekFrom::Start(0))
.await
.map_err(|source| io_error("重置 AMR 文件读取位置", source))?;
}
let multipart = build_media_body(
media_type,
&file_name,
metadata.len(),
file.take(metadata.len()),
)?;
self.upload_media_body(media_type, multipart).await
}
pub async fn send_file_path(
&self,
path: impl AsRef<Path>,
) -> Result<WeComRobotReceipt, MessagingError> {
let upload = self.upload_media_file(WeComMediaType::File, path).await?;
self.send(&WeComRobotMessage::file(upload.media_id())).await
}
pub async fn send_voice_path(
&self,
path: impl AsRef<Path>,
) -> Result<WeComRobotReceipt, MessagingError> {
let upload = self.upload_media_file(WeComMediaType::Voice, path).await?;
self.send(&WeComRobotMessage::voice(upload.media_id()))
.await
}
async fn upload_media_body(
&self,
media_type: WeComMediaType,
multipart: WeComMultipartBody,
) -> Result<WeComMediaUploadReceipt, MessagingError> {
let _permit = self.acquire_request_permit().await?;
let response = self
.http_client
.post(self.upload_url(media_type)?)
.timeout(self.timeout)
.header(CONTENT_TYPE, multipart.content_type)
.header(CONTENT_LENGTH, multipart.content_length)
.body(multipart.body)
.send()
.await
.map_err(|source| request_error(source.without_url()))?;
let (body, diagnostic) = self.read_success_response(response).await?;
let common = parse_common_response(&body, &diagnostic)?;
if common.errcode != 0 {
return Err(MessagingError::ProviderRejected {
provider: PROVIDER,
code: common.errcode,
message: self.sanitize_diagnostic(&common.errmsg),
});
}
let upload: WeComUploadSuccess =
serde_json::from_slice(&body).map_err(|source| MessagingError::InvalidResponse {
provider: PROVIDER,
response: diagnostic.clone(),
source,
})?;
if upload.media_type != media_type.as_str() {
return Err(MessagingError::Protocol {
provider: PROVIDER,
message: format!("{} 上传响应中的媒体类型不一致", media_type.as_str()),
response: diagnostic,
});
}
if upload.media_id.trim().is_empty() {
return Err(MessagingError::Protocol {
provider: PROVIDER,
message: "上传成功响应缺少媒体 ID".to_owned(),
response: diagnostic,
});
}
Ok(WeComMediaUploadReceipt {
media_type,
media_id: upload.media_id,
created_at: upload.created_at,
})
}
async fn read_success_response(
&self,
response: reqwest::Response,
) -> Result<(Vec<u8>, String), MessagingError> {
let status = response.status().as_u16();
let body = read_limited_body(response, self.max_response_body_bytes).await?;
let diagnostic = self.sanitize_diagnostic(&String::from_utf8_lossy(&body));
if !(200..300).contains(&status) {
return Err(MessagingError::HttpStatus {
provider: PROVIDER,
status,
response: diagnostic,
});
}
Ok((body, diagnostic))
}
fn send_url(&self) -> Result<Url, MessagingError> {
let mut url = self
.base_url
.join("send")
.map_err(|_| invalid_config("无法生成企业微信发送地址"))?;
url.query_pairs_mut()
.append_pair("key", self.webhook_key.expose_secret());
Ok(url)
}
fn upload_url(&self, media_type: WeComMediaType) -> Result<Url, MessagingError> {
let mut url = self
.base_url
.join("upload_media")
.map_err(|_| invalid_config("无法生成企业微信媒体上传地址"))?;
url.query_pairs_mut()
.append_pair("key", self.webhook_key.expose_secret())
.append_pair("type", media_type.as_str());
Ok(url)
}
fn sanitize_diagnostic(&self, value: &str) -> String {
let redacted = value.replace(self.webhook_key.expose_secret(), "[已隐藏]");
truncate_chars(redacted.trim(), MAX_DIAGNOSTIC_CHARS)
}
async fn acquire_request_permit(&self) -> Result<OwnedSemaphorePermit, MessagingError> {
tokio::time::timeout(
self.timeout,
Arc::clone(&self.in_flight_requests).acquire_owned(),
)
.await
.map_err(|_| MessagingError::RequestQueueTimeout {
provider: PROVIDER,
timeout: self.timeout,
})?
.map_err(|_| invalid_config("HTTP 并发控制器已关闭"))
}
}
impl fmt::Debug for WeComRobotClient {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("WeComRobotClient")
.field("webhook_key", &"[已隐藏]")
.field("base_url", &safe_base_url(&self.base_url))
.field("timeout", &self.timeout)
.field("max_in_flight_requests", &self.max_in_flight_requests)
.field("max_request_body_bytes", &self.max_request_body_bytes)
.field("max_response_body_bytes", &self.max_response_body_bytes)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct WeComRobotReceipt {
pub code: i64,
pub message: String,
}
#[derive(Clone, Eq, PartialEq)]
#[non_exhaustive]
pub struct WeComMediaUploadReceipt {
pub media_type: WeComMediaType,
media_id: String,
pub created_at: String,
}
impl WeComMediaUploadReceipt {
#[must_use]
pub fn media_id(&self) -> &str {
&self.media_id
}
}
impl fmt::Debug for WeComMediaUploadReceipt {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("WeComMediaUploadReceipt")
.field("media_type", &self.media_type)
.field("media_id", &"[已隐藏]")
.field("created_at", &self.created_at)
.finish()
}
}
#[derive(Deserialize)]
struct WeComApiResponse {
errcode: i64,
#[serde(default)]
errmsg: String,
}
#[derive(Deserialize)]
struct WeComUploadSuccess {
#[serde(rename = "type")]
media_type: String,
media_id: String,
created_at: String,
}
fn parse_common_response(
body: &[u8],
diagnostic: &str,
) -> Result<WeComApiResponse, MessagingError> {
serde_json::from_slice(body).map_err(|source| MessagingError::InvalidResponse {
provider: PROVIDER,
response: diagnostic.to_owned(),
source,
})
}
struct WeComMultipartBody {
body: Body,
content_type: String,
content_length: u64,
}
fn build_media_body<R>(
media_type: WeComMediaType,
file_name: &str,
size: u64,
reader: R,
) -> Result<WeComMultipartBody, MessagingError>
where
R: tokio::io::AsyncRead + Send + Unpin + 'static,
{
let boundary = format!("loveyu-kit-{}", Uuid::now_v7().simple());
let file_name = escape_multipart_file_name(file_name);
let prefix = format!(
"--{boundary}\r\nContent-Disposition: form-data; name=\"media\"; filename=\"{file_name}\"; filelength={size}\r\nContent-Type: {}\r\n\r\n",
media_type.content_type()
)
.into_bytes();
let suffix = format!("\r\n--{boundary}--\r\n").into_bytes();
let framing_length = u64::try_from(prefix.len().saturating_add(suffix.len()))
.map_err(|_| invalid_message("无法计算媒体上传请求长度"))?;
let content_length = size
.checked_add(framing_length)
.ok_or_else(|| invalid_message("媒体上传请求长度溢出"))?;
let reader = Cursor::new(prefix).chain(reader).chain(Cursor::new(suffix));
Ok(WeComMultipartBody {
body: Body::wrap_stream(ReaderStream::new(reader)),
content_type: format!("multipart/form-data; boundary={boundary}"),
content_length,
})
}
fn escape_multipart_file_name(file_name: &str) -> String {
file_name.replace('"', "\\\"")
}
async fn read_limited_body(
mut response: reqwest::Response,
max_bytes: usize,
) -> Result<Vec<u8>, MessagingError> {
if response
.content_length()
.is_some_and(|length| length > max_bytes as u64)
{
return Err(MessagingError::ResponseTooLarge {
provider: PROVIDER,
max_bytes,
});
}
let initial_capacity = response
.content_length()
.and_then(|length| usize::try_from(length).ok())
.unwrap_or(0)
.min(max_bytes)
.min(RESPONSE_BODY_INITIAL_CAPACITY);
let mut body = Vec::with_capacity(initial_capacity);
while let Some(chunk) = response
.chunk()
.await
.map_err(|source| request_error(source.without_url()))?
{
if body.len().saturating_add(chunk.len()) > max_bytes {
return Err(MessagingError::ResponseTooLarge {
provider: PROVIDER,
max_bytes,
});
}
body.extend_from_slice(&chunk);
}
Ok(body)
}
fn parse_base_url(value: &str) -> Result<Url, MessagingError> {
let mut url = Url::parse(value.trim()).map_err(|_| invalid_config("无法解析 API 基础地址"))?;
validate_http_url(&url, "API 基础地址")?;
if url.query().is_some() || url.fragment().is_some() {
return Err(invalid_config("API 基础地址不能包含查询参数或片段"));
}
if !url.path().ends_with('/') {
let path = format!("{}/", url.path());
url.set_path(&path);
}
Ok(url)
}
fn validate_http_url(url: &Url, name: &str) -> Result<(), MessagingError> {
if !matches!(url.scheme(), "http" | "https") {
return Err(invalid_config(format!("{name}只支持 HTTP 或 HTTPS")));
}
if url.host_str().is_none() {
return Err(invalid_config(format!("{name}缺少主机名")));
}
if url.scheme() == "http" && !is_loopback_url(url) {
return Err(invalid_config(format!("{name}的非本机地址必须使用 HTTPS")));
}
if !url.username().is_empty() || url.password().is_some() {
return Err(invalid_config(format!("{name}不能包含用户名或密码")));
}
Ok(())
}
fn is_loopback_url(url: &Url) -> bool {
url.host_str().is_some_and(|host| {
host.eq_ignore_ascii_case("localhost")
|| host
.parse::<IpAddr>()
.is_ok_and(|address| address.is_loopback())
})
}
fn validate_webhook_key(webhook_key: &str) -> Result<String, MessagingError> {
let webhook_key = webhook_key.trim();
if webhook_key.is_empty() {
return Err(invalid_config("Webhook Key 不能为空"));
}
if webhook_key.chars().any(char::is_whitespace) {
return Err(invalid_config("Webhook Key 不能包含空白字符"));
}
if webhook_key.len() > MAX_WEBHOOK_KEY_BYTES {
return Err(invalid_config("Webhook Key 长度超过限制"));
}
Ok(webhook_key.to_owned())
}
fn safe_base_url(url: &Url) -> String {
let mut url = url.clone();
url.set_path("/");
url.set_query(None);
url.set_fragment(None);
url.to_string()
}
fn invalid_config(message: impl Into<String>) -> MessagingError {
MessagingError::InvalidConfig {
provider: PROVIDER,
message: message.into(),
}
}
const fn request_error(source: reqwest::Error) -> MessagingError {
MessagingError::Request {
provider: PROVIDER,
source,
}
}
const fn io_error(operation: &'static str, source: std::io::Error) -> MessagingError {
MessagingError::Io {
provider: PROVIDER,
operation,
source,
}
}
fn truncate_chars(value: &str, max_chars: usize) -> String {
if value.chars().count() <= max_chars {
return value.to_owned();
}
let mut truncated: String = value.chars().take(max_chars).collect();
truncated.push_str("…(已截断)");
truncated
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn full_webhook_url_is_split_without_exposing_key() {
let key = "secret-webhook-key";
let config = WeComRobotConfig::from_webhook_url(format!(
"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={key}"
))
.unwrap();
let debug = format!("{config:?}");
assert_eq!(
config.base_url.as_str(),
"https://qyapi.weixin.qq.com/cgi-bin/webhook/"
);
assert!(!debug.contains(key));
}
#[test]
fn remote_plain_http_webhook_is_rejected() {
let error = WeComRobotConfig::new("key")
.unwrap()
.with_base_url("http://example.com/cgi-bin/webhook/")
.unwrap_err();
assert!(error.to_string().contains("必须使用 HTTPS"));
}
#[test]
fn config_rejects_zero_limits() {
let error = WeComRobotClient::new(
WeComRobotConfig::new("key")
.unwrap()
.with_timeout(Duration::ZERO),
)
.unwrap_err();
assert!(error.to_string().contains("请求超时必须大于 0"));
let error = WeComRobotClient::new(
WeComRobotConfig::new("key")
.unwrap()
.with_max_response_body_bytes(0),
)
.unwrap_err();
assert!(error.to_string().contains("最大响应体字节数必须大于 0"));
let error = WeComRobotClient::new(
WeComRobotConfig::new("key")
.unwrap()
.with_max_in_flight_requests(0),
)
.unwrap_err();
assert!(error.to_string().contains("最大并发请求数必须大于 0"));
}
#[tokio::test]
async fn request_queue_wait_is_bounded_and_retryable() {
let client = WeComRobotClient::new(
WeComRobotConfig::new("key")
.unwrap()
.with_timeout(Duration::from_millis(1))
.with_max_in_flight_requests(1),
)
.unwrap();
let _permit = client.acquire_request_permit().await.unwrap();
let error = client.acquire_request_permit().await.unwrap_err();
assert!(matches!(error, MessagingError::RequestQueueTimeout { .. }));
assert!(error.is_retryable());
}
#[test]
fn default_json_limit_can_hold_the_largest_supported_image() {
let encoded_image_bytes = (2 * 1024 * 1024_usize).div_ceil(3) * 4;
assert!(DEFAULT_MAX_REQUEST_BODY_BYTES > encoded_image_bytes + 1024);
}
}