loveyu-kit 0.2.0

面向 Axum 项目的可组合 API 工具库
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
//! 企业微信消息推送 HTTP 客户端。

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;

/// 企业微信消息推送客户端配置。
///
/// Webhook Key 使用秘密容器保存,`Debug` 不会输出原值。
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 {
    /// 使用 Webhook Key 创建配置。
    ///
    /// # Errors
    ///
    /// Webhook Key 为空、包含空白或超过长度上限时返回配置错误。
    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,
        })
    }

    /// 直接从企业微信复制的完整 Webhook URL 创建配置。
    ///
    /// 完整 URL 只在构造期被解析,实例内会将 Key 和基础 URL 分开存储。
    ///
    /// # Errors
    ///
    /// URL 无效、非本机地址未使用 HTTPS、缺少 Key 或路径不是发送端点时返回配置错误。
    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
    }

    /// 设置单个客户端允许同时进行的最大 HTTP 请求数,默认 32。
    #[must_use]
    pub const fn with_max_in_flight_requests(mut self, max_requests: usize) -> Self {
        self.max_in_flight_requests = max_requests;
        self
    }

    /// 设置最大 JSON 请求体字节数,默认 3 MiB,可容纳协议允许的 2 MiB 原始图片编码结果。
    #[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
    }

    /// 替换 API 基础地址。
    ///
    /// 主要用于私有网关、代理或自动化测试;生产环境应优先使用默认 HTTPS 地址。
    ///
    /// # Errors
    ///
    /// 地址无法解析、包含凭据或查询参数,或非本机地址未使用 HTTPS 时返回配置错误。
    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)
    }

    /// 校验配置,不创建 HTTP 客户端或访问网络。
    ///
    /// # Errors
    ///
    /// 超时、并发数、请求体或响应体限制为零时返回配置错误。
    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()
    }
}

/// 企业微信消息推送客户端。
///
/// 该类型内部的 `reqwest::Client` 自带连接池,克隆只会克隆共享句柄,
/// 适合直接放入 Axum `AppState` 并在请求之间复用。
#[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 {
    /// 使用库内创建的 HTTP 客户端构造消息推送客户端。
    ///
    /// # Errors
    ///
    /// 配置无效或底层 HTTP 客户端无法创建时返回错误。
    pub fn new(config: WeComRobotConfig) -> Result<Self, MessagingError> {
        let http_client = Client::builder()
            // Webhook Key 位于查询参数中,禁止自动重定向和 Referer,避免凭据传播到其他主机。
            .redirect(reqwest::redirect::Policy::none())
            .referer(false)
            .build()
            .map_err(|source| request_error(source.without_url()))?;
        Self::with_http_client(config, http_client)
    }

    /// 注入应用共享的 HTTP 客户端。
    ///
    /// 这便于统一代理、DNS、TLS 与连接池配置,也便于测试。共享客户端应禁用自动重定向
    /// 和 Referer,因为企业微信 Webhook Key 位于请求 URL 的查询参数中。
    ///
    /// # Errors
    ///
    /// 企业微信配置未通过本地校验时返回配置错误。
    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,
        })
    }

    /// 发送强类型消息。
    ///
    /// # Errors
    ///
    /// 消息无效、请求或响应超限、网络请求失败或企业微信拒绝消息时返回错误。
    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),
        })
    }

    /// 发送简单文本消息。
    ///
    /// # Errors
    ///
    /// 内容无效或消息发送失败时返回错误。
    pub async fn send_text(
        &self,
        content: impl Into<String>,
    ) -> Result<WeComRobotReceipt, MessagingError> {
        self.send(&WeComRobotMessage::text(content)).await
    }

    /// 发送简单 Markdown 消息。
    ///
    /// # Errors
    ///
    /// 内容无效或消息发送失败时返回错误。
    pub async fn send_markdown(
        &self,
        content: impl Into<String>,
    ) -> Result<WeComRobotReceipt, MessagingError> {
        self.send(&WeComRobotMessage::markdown(content)).await
    }

    /// 发送 Markdown V2 消息。
    ///
    /// # Errors
    ///
    /// 内容无效或消息发送失败时返回错误。
    pub async fn send_markdown_v2(
        &self,
        content: impl Into<String>,
    ) -> Result<WeComRobotReceipt, MessagingError> {
        self.send(&WeComRobotMessage::markdown_v2(content)).await
    }

    /// 发送 JPG 或 PNG 图片,Base64 和 MD5 由客户端自动生成。
    ///
    /// # Errors
    ///
    /// 图片格式或大小无效,或消息发送失败时返回错误。
    pub async fn send_image_bytes(
        &self,
        bytes: &[u8],
    ) -> Result<WeComRobotReceipt, MessagingError> {
        self.send(&WeComRobotMessage::image_from_bytes(bytes)?)
            .await
    }

    /// 发送 1 至 8 条图文。
    ///
    /// # Errors
    ///
    /// 图文数量或字段无效,或消息发送失败时返回错误。
    pub async fn send_news(
        &self,
        articles: impl IntoIterator<Item = WeComNewsArticle>,
    ) -> Result<WeComRobotReceipt, MessagingError> {
        self.send(&WeComRobotMessage::news(articles)).await
    }

    /// 发送模板卡片。
    ///
    /// # Errors
    ///
    /// 卡片不符合协议约束或消息发送失败时返回错误。
    pub async fn send_template_card(
        &self,
        card: impl Into<WeComTemplateCard>,
    ) -> Result<WeComRobotReceipt, MessagingError> {
        self.send(&WeComRobotMessage::template_card(card)).await
    }

    /// 上传内存中的普通文件或 AMR 语音。
    ///
    /// # Errors
    ///
    /// 文件名、格式或大小无效,或媒体上传失败时返回错误。
    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
    }

    /// 以流式方式上传本地普通文件或 AMR 语音。
    ///
    /// 文件不会被整体读入内存,上传前会先校验文件类型与大小。
    ///
    /// # Errors
    ///
    /// 路径无法读取、文件类型或大小无效,或媒体上传失败时返回错误。
    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))?;
        }

        // 文件可能在读取元数据后继续增长;take 保证实际上传字节数不突破已校验长度。
        let multipart = build_media_body(
            media_type,
            &file_name,
            metadata.len(),
            file.take(metadata.len()),
        )?;
        self.upload_media_body(media_type, multipart).await
    }

    /// 上传并发送本地普通文件。
    ///
    /// # Errors
    ///
    /// 文件读取、上传或消息发送失败时返回错误。
    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
    }

    /// 上传并发送本地 AMR 语音。
    ///
    /// # Errors
    ///
    /// 语音读取、格式校验、上传或消息发送失败时返回错误。
    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 {
        // 反向代理或错误页可能回显完整请求 URL,进入错误链前再次移除 Key。
        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 {
    /// 企业微信业务码,成功时为 `0`。
    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 {
    /// 返回媒体 ID。该 ID 仅能由上传它的同一 Webhook 使用,且有效期为三天。
    #[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);
    // 企业微信协议要求 filelength 位于 Content-Disposition 参数中。
    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() {
        // Base64 最坏长度为 4 * ceil(n / 3),再为 JSON 字段保留少量协议开销。
        let encoded_image_bytes = (2 * 1024 * 1024_usize).div_ceil(3) * 4;
        assert!(DEFAULT_MAX_REQUEST_BODY_BYTES > encoded_image_bytes + 1024);
    }
}