wechat-mp-sdk 0.3.0

WeChat Mini Program SDK for Rust
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
//! Retry middleware for automatic retry on failures.
//!
//! This middleware automatically retries failed requests that are likely to succeed
//! on a subsequent attempt (e.g., server errors, rate limiting, or temporary failures).
//!
//! # Retry Conditions
//!
//! - HTTP 5xx responses
//! - Network errors (reqwest::Error)
//! - WeChat API error codes: -1 (system busy), 45009 (rate limit)
//!
//! # Non-Idempotent Requests
//!
//! By default, POST requests are NOT retried as they may cause duplicate operations.
//! Use `with_retry_post(true)` to enable retrying POST requests.

use std::future::Future;
use std::pin::Pin;
use std::task::Context;
use std::task::Poll;

use tokio::time::sleep;
use tower::{Layer, Service};

use crate::error::WechatError;
use crate::utils::jittered_delay;

/// Middleware that retries requests on 5xx and retryable errors.
#[derive(Clone)]
pub struct RetryMiddleware {
    max_retries: usize,
    delay_ms: u64,
    retry_post: bool,
}

impl RetryMiddleware {
    /// Create a new RetryMiddleware with default settings.
    ///
    /// Default: max_retries = 3, delay_ms = 100ms, retry_post = false
    pub fn new() -> Self {
        Self {
            max_retries: 3,
            delay_ms: 100,
            retry_post: false,
        }
    }

    /// Set maximum number of retry attempts.
    ///
    /// `max = 0` means "disable retries" (one attempt is still executed).
    pub fn with_max_retries(mut self, max: usize) -> Self {
        self.max_retries = max;
        self
    }

    /// Set delay between retries in milliseconds.
    pub fn with_delay_ms(mut self, delay: u64) -> Self {
        self.delay_ms = delay;
        self
    }

    /// Enable retrying POST requests (disabled by default).
    pub fn with_retry_post(mut self, retry: bool) -> Self {
        self.retry_post = retry;
        self
    }

    /// Check if an error is retryable.
    ///
    /// Delegates to [`WechatError::is_transient()`] to ensure a single
    /// canonical retry-classification policy across the crate.
    pub fn is_retryable_error(error: &WechatError) -> bool {
        error.is_transient()
    }
}

impl Default for RetryMiddleware {
    fn default() -> Self {
        Self::new()
    }
}

impl<S> Layer<S> for RetryMiddleware {
    type Service = RetryMiddlewareService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        RetryMiddlewareService {
            inner,
            max_retries: self.max_retries,
            delay_ms: self.delay_ms,
            retry_post: self.retry_post,
        }
    }
}

#[derive(Clone)]
pub struct RetryMiddlewareService<S> {
    inner: S,
    pub(crate) max_retries: usize,
    pub(crate) delay_ms: u64,
    pub(crate) retry_post: bool,
}

/// A wrapper to identify if a request is idempotent (safe to retry).
/// This trait allows the retry middleware to work with different request types.
pub trait RetryableRequest {
    /// Returns true if the request is idempotent (GET, DELETE, etc.)
    /// POST and PUT are not idempotent by default.
    fn is_idempotent(&self) -> bool;
}

impl RetryableRequest for reqwest::Request {
    fn is_idempotent(&self) -> bool {
        !matches!(
            self.method(),
            &reqwest::Method::POST | &reqwest::Method::PUT | &reqwest::Method::PATCH
        )
    }
}

impl<S, R> Service<R> for RetryMiddlewareService<S>
where
    S: Service<R> + Send + Clone + 'static,
    S::Future: Send,
    S::Error: std::fmt::Debug + Send + 'static,
    S::Response: Send,
    R: Send + Clone + RetryableRequest + 'static,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, req: R) -> Self::Future {
        let mut inner = self.inner.clone();
        let max_retries = self.max_retries;
        let delay_ms = self.delay_ms;
        let retry_post = self.retry_post;

        Box::pin(async move {
            // max_retries=0 means "no retry", but still perform one attempt.
            let attempts = max_retries.max(1);
            let mut last_error: Option<S::Error> = None;

            // Check if request is retryable
            if !req.is_idempotent() && !retry_post {
                // Non-idempotent request and retry not enabled, try once
                return inner.call(req).await;
            }

            for attempt in 0..attempts {
                // Clone the request for each attempt
                let req_clone = req.clone();

                match inner.call(req_clone).await {
                    Ok(response) => return Ok(response),
                    Err(e) => {
                        // Check if error is retryable
                        // We need to downcast the error to check if it's a WechatError
                        let is_retryable = check_error_retryable(&e);

                        if is_retryable {
                            last_error = Some(e);
                            if attempt < attempts - 1 {
                                sleep(jittered_delay(
                                    delay_ms,
                                    u32::try_from(attempt).unwrap_or(u32::MAX),
                                ))
                                .await;
                            }
                        } else {
                            // Non-retryable error, return immediately
                            return Err(e);
                        }
                    }
                }
            }

            // At least one attempt always runs. If we reached here all attempts failed.
            Err(last_error.expect("retry loop completed without capturing an error"))
        })
    }
}

/// Check if an error is retryable by attempting to downcast to WechatError.
fn check_error_retryable<E: std::fmt::Debug + 'static>(error: &E) -> bool {
    // Try to downcast to WechatError
    if let Some(wechat_err) = (error as &dyn std::any::Any).downcast_ref::<WechatError>() {
        return RetryMiddleware::is_retryable_error(wechat_err);
    }

    // Retry raw reqwest errors as well. This is required when middleware is
    // layered over reqwest-based services where error type is reqwest::Error.
    if let Some(reqwest_err) = (error as &dyn std::any::Any).downcast_ref::<reqwest::Error>() {
        return is_retryable_reqwest_error(reqwest_err);
    }

    // For unknown error types, don't retry by default
    false
}

fn is_retryable_reqwest_error(error: &reqwest::Error) -> bool {
    match error.status() {
        Some(status) => status.is_server_error() || status.as_u16() == 429,
        None => true,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::WechatError;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[test]
    fn test_retry_middleware_exists() {
        let _ = RetryMiddleware::new();
    }

    #[test]
    fn test_is_retryable_error_exhaustive_variants() {
        use crate::error::HttpError;

        // Http(Reqwest) => retryable (transient transport failure)
        let reqwest_error = reqwest::Client::new().get("http://").build().unwrap_err();
        let reqwest_err = WechatError::Http(HttpError::Reqwest(std::sync::Arc::new(reqwest_error)));
        assert!(RetryMiddleware::is_retryable_error(&reqwest_err));

        // Http(Decode) => NOT retryable (response schema mismatch is not transient)
        let decode_err = WechatError::Http(HttpError::Decode("bad".into()));
        assert!(!RetryMiddleware::is_retryable_error(&decode_err));
        // Api with retryable code => retryable
        assert!(RetryMiddleware::is_retryable_error(&WechatError::Api {
            code: -1,
            message: "busy".into(),
        }));
        // Api with non-retryable code => not retryable
        assert!(!RetryMiddleware::is_retryable_error(&WechatError::Api {
            code: 40001,
            message: "invalid".into(),
        }));
        // All remaining variants => not retryable
        let non_retryable: Vec<WechatError> = vec![
            WechatError::Json(serde_json::from_str::<String>("bad").unwrap_err()),
            WechatError::Token("t".into()),
            WechatError::Config("c".into()),
            WechatError::Signature("s".into()),
            WechatError::Crypto("cr".into()),
            WechatError::InvalidAppId("a".into()),
            WechatError::InvalidOpenId("o".into()),
            WechatError::InvalidAccessToken("at".into()),
            WechatError::InvalidAppSecret("as".into()),
            WechatError::InvalidSessionKey("sk".into()),
            WechatError::InvalidUnionId("u".into()),
        ];
        for err in &non_retryable {
            assert!(
                !RetryMiddleware::is_retryable_error(err),
                "Expected non-retryable: {:?}",
                err,
            );
        }
    }

    #[test]
    fn test_retryable_error_codes() {
        let err = WechatError::Api {
            code: -1,
            message: "System busy".to_string(),
        };
        assert!(RetryMiddleware::is_retryable_error(&err));

        let err = WechatError::Api {
            code: 45009,
            message: "API limit".to_string(),
        };
        assert!(RetryMiddleware::is_retryable_error(&err));

        let err = WechatError::Api {
            code: 40001,
            message: "Invalid credential".to_string(),
        };
        assert!(!RetryMiddleware::is_retryable_error(&err));
    }

    #[test]
    fn test_decode_error_not_retryable() {
        use crate::error::HttpError;

        // Decode errors are NOT transient — a schema mismatch won't resolve on retry.
        let decode_err = WechatError::Http(HttpError::Decode("response decode error".to_string()));
        assert!(
            !RetryMiddleware::is_retryable_error(&decode_err),
            "Decode errors should not be retried",
        );
    }

    #[tokio::test]
    async fn test_check_error_retryable_for_reqwest_503_status_error() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/status-503"))
            .respond_with(ResponseTemplate::new(503))
            .mount(&mock_server)
            .await;

        let response = reqwest::Client::new()
            .get(format!("{}/status-503", mock_server.uri()))
            .send()
            .await
            .unwrap();
        let err = response.error_for_status().unwrap_err();

        assert!(
            check_error_retryable(&err),
            "503 status errors should be considered retryable",
        );
    }

    #[tokio::test]
    async fn test_check_error_retryable_for_reqwest_400_status_error() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/status-400"))
            .respond_with(ResponseTemplate::new(400))
            .mount(&mock_server)
            .await;

        let response = reqwest::Client::new()
            .get(format!("{}/status-400", mock_server.uri()))
            .send()
            .await
            .unwrap();
        let err = response.error_for_status().unwrap_err();

        assert!(
            !check_error_retryable(&err),
            "400 status errors should not be considered retryable",
        );
    }

    #[test]
    fn test_middleware_configuration() {
        let middleware = RetryMiddleware::new()
            .with_max_retries(5)
            .with_delay_ms(200)
            .with_retry_post(true);

        assert_eq!(middleware.max_retries, 5);
        assert_eq!(middleware.delay_ms, 200);
        assert!(middleware.retry_post);
    }

    // === Boundary Behavior Tests (TDD RED Phase) ===
    // These tests expose the last_error.unwrap() panic risk

    /// Mock request that is idempotent (safe to retry)
    #[derive(Clone)]
    struct MockIdempotentRequest;

    impl RetryableRequest for MockIdempotentRequest {
        fn is_idempotent(&self) -> bool {
            true
        }
    }

    /// Mock service that always returns a retryable error
    #[derive(Clone)]
    struct AlwaysRetryableErrorService;

    impl Service<MockIdempotentRequest> for AlwaysRetryableErrorService {
        type Response = String;
        type Error = WechatError;
        type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

        fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
            Poll::Ready(Ok(()))
        }

        fn call(&mut self, _req: MockIdempotentRequest) -> Self::Future {
            Box::pin(async {
                Err(WechatError::Api {
                    code: -1,
                    message: "system busy".to_string(),
                })
            })
        }
    }

    /// Mock service that always returns a NON-retryable error
    #[derive(Clone)]
    struct AlwaysNonRetryableErrorService;

    impl Service<MockIdempotentRequest> for AlwaysNonRetryableErrorService {
        type Response = String;
        type Error = WechatError;
        type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

        fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
            Poll::Ready(Ok(()))
        }

        fn call(&mut self, _req: MockIdempotentRequest) -> Self::Future {
            Box::pin(async {
                Err(WechatError::Api {
                    code: 40001,
                    message: "invalid credential".to_string(),
                })
            })
        }
    }

    /// Mock service that returns success
    #[derive(Clone)]
    struct SuccessService;

    impl Service<MockIdempotentRequest> for SuccessService {
        type Response = String;
        type Error = WechatError;
        type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

        fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
            Poll::Ready(Ok(()))
        }

        fn call(&mut self, _req: MockIdempotentRequest) -> Self::Future {
            Box::pin(async { Ok("success".to_string()) })
        }
    }

    /// Test: max_retries=0 should NOT panic and should still perform one attempt.
    #[tokio::test]
    async fn test_max_retries_zero_should_still_attempt_once() {
        let middleware = RetryMiddleware::new().with_max_retries(0);
        let mut service = middleware.layer(SuccessService);

        let result: Result<String, WechatError> = service.call(MockIdempotentRequest).await;

        assert!(result.is_ok(), "max_retries=0 should still execute once");
    }

    /// Test: non-retryable error should return immediately without retry
    #[tokio::test]
    async fn test_non_retryable_error_returns_immediately() {
        let middleware = RetryMiddleware::new().with_max_retries(3);
        let mut service = middleware.layer(AlwaysNonRetryableErrorService);

        let result: Result<String, WechatError> = service.call(MockIdempotentRequest).await;

        assert!(result.is_err());
        if let Err(WechatError::Api { code, .. }) = &result {
            assert_eq!(*code, 40001, "Should return the non-retryable error code");
        }
    }

    /// Test: retryable error with max_retries=1 should retry once then return error
    #[tokio::test]
    async fn test_retryable_error_with_max_retries_one() {
        let middleware = RetryMiddleware::new().with_max_retries(1).with_delay_ms(1);
        let mut service = middleware.layer(AlwaysRetryableErrorService);

        let result: Result<String, WechatError> = service.call(MockIdempotentRequest).await;

        assert!(result.is_err());
    }

    /// Test: terminal path - all retries exhausted should return last error
    #[tokio::test]
    async fn test_terminal_failure_all_retries_exhausted() {
        let middleware = RetryMiddleware::new().with_max_retries(2).with_delay_ms(1);
        let mut service = middleware.layer(AlwaysRetryableErrorService);

        let result: Result<String, WechatError> = service.call(MockIdempotentRequest).await;

        assert!(result.is_err());
        if let Err(e) = &result {
            assert!(matches!(e, WechatError::Api { code: -1, .. }));
        }
    }

    /// Test: success case - should return immediately without retry logic
    #[tokio::test]
    async fn test_success_case_no_retry() {
        let middleware = RetryMiddleware::new()
            .with_max_retries(3)
            .with_delay_ms(100);
        let mut service = middleware.layer(SuccessService);

        let result: Result<String, WechatError> = service.call(MockIdempotentRequest).await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "success");
    }

    /// Test: non-idempotent request with retry_post=false should try once only
    #[derive(Clone)]
    struct NonIdempotentRequest;

    impl RetryableRequest for NonIdempotentRequest {
        fn is_idempotent(&self) -> bool {
            false
        }
    }

    #[derive(Clone)]
    struct NonIdempotentErrorService;

    impl Service<NonIdempotentRequest> for NonIdempotentErrorService {
        type Response = String;
        type Error = WechatError;
        type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

        fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
            Poll::Ready(Ok(()))
        }

        fn call(&mut self, _req: NonIdempotentRequest) -> Self::Future {
            Box::pin(async {
                Err(WechatError::Api {
                    code: -1,
                    message: "system busy".to_string(),
                })
            })
        }
    }

    /// Test: POST request (non-idempotent) with retry_post=false should not retry
    #[tokio::test]
    async fn test_non_idempotent_no_retry() {
        let middleware = RetryMiddleware::new()
            .with_max_retries(3)
            .with_retry_post(false);
        let mut service = middleware.layer(NonIdempotentErrorService);

        let result: Result<String, WechatError> = service.call(NonIdempotentRequest).await;

        assert!(result.is_err());
    }

    /// Test: POST request (non-idempotent) with retry_post=true should retry
    #[tokio::test]
    async fn test_non_idempotent_with_retry_enabled() {
        let middleware = RetryMiddleware::new()
            .with_max_retries(2)
            .with_delay_ms(1)
            .with_retry_post(true);
        let mut service = middleware.layer(NonIdempotentErrorService);

        let result: Result<String, WechatError> = service.call(NonIdempotentRequest).await;

        assert!(result.is_err());
    }
}