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
//! # Request retry policy
//!
//! This module contains the [`RequestRetryConfiguration`] struct.
//! It is used to calculate delays between failed requests to the [`PubNub API`]
//! for next retry attempt.
//! It is intended to be used by the [`pubnub`] crate.
//!
//! [`PubNub API`]: https://www.pubnub.com/docs
//! [`pubnub`]: ../index.html
use crate::{core::PubNubError, lib::alloc::vec::Vec};
/// List of known endpoint groups (by context)
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Endpoint {
/// Unknown endpoint.
Unknown,
/// The endpoints to send messages.
MessageSend,
/// The endpoint for real-time update retrieval.
Subscribe,
/// The endpoint to access and manage `user_id` presence and fetch channel
/// presence information.
Presence,
/// The endpoint to access and manage files in channel-specific storage.
Files,
/// The endpoint to access and manage messages for a specific channel(s) in
/// the persistent storage.
MessageStorage,
/// The endpoint to access and manage channel groups.
ChannelGroups,
/// The endpoint to access and manage device registration for channel push
/// notifications.
DevicePushNotifications,
/// The endpoint to access and manage App Context objects.
AppContext,
/// The endpoint to access and manage reactions for a specific message.
MessageReactions,
}
/// Request retry policy.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RequestRetryConfiguration {
/// Requests shouldn't be tried again.
None,
/// Retry the request after the same amount of time.
Linear {
/// The delay between failed retry attempts in seconds.
delay: u64,
/// Number of times a request can be retried.
max_retry: u8,
/// Optional list of excluded endpoint groups.
///
/// Endpoint groups for which automatic retry shouldn't be used.
excluded_endpoints: Option<Vec<Endpoint>>,
},
/// Retry the request using exponential amount of time.
Exponential {
/// Minimum delay between failed retry attempts in seconds.
min_delay: u64,
/// Maximum delay between failed retry attempts in seconds.
max_delay: u64,
/// Number of times a request can be retried.
max_retry: u8,
/// Optional list of excluded endpoint groups.
///
/// Endpoint groups for which automatic retry shouldn't be used.
excluded_endpoints: Option<Vec<Endpoint>>,
},
}
impl RequestRetryConfiguration {
/// Creates a new instance of the `RequestRetryConfiguration` enum with a
/// default linear policy.
///
/// The `Linear` policy retries the operation with a fixed delay between
/// each retry. The default delay is 2 seconds and the default maximum
/// number of retries is 10.
///
/// # Example
///
/// ```
/// use pubnub::{Keyset, PubNubClientBuilder, RequestRetryConfiguration};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let retry_configuration = RequestRetryConfiguration::default_linear();
/// let client = PubNubClientBuilder::with_reqwest_transport()
/// .with_keyset(Keyset {
/// publish_key: Some("pub-c-abc123"),
/// subscribe_key: "sub-c-abc123",
/// secret_key: None,
/// })
/// .with_user_id("my-user-id")
/// .with_retry_configuration(retry_configuration)
/// .build()?;
/// # Ok(())
/// # }
/// ```
///
/// # Returns
///
/// A new instance of the `RetryPolicy` enum with the default linear policy.
pub fn default_linear() -> Self {
Self::Linear {
delay: 2,
max_retry: 10,
excluded_endpoints: None,
}
}
/// Creates a new instance of the `RequestRetryConfiguration` enum with a
/// default exponential backoff policy.
///
/// The `Exponential` backoff policy increases the delay between retries
/// exponentially. It starts with a minimum delay of 2 seconds and a
/// maximum delay of 150 seconds. It allows a maximum number of 6
/// retries.
///
/// # Example
///
/// ```
/// use pubnub::{Keyset, PubNubClientBuilder, RequestRetryConfiguration};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let retry_configuration = RequestRetryConfiguration::default_exponential();
/// let client = PubNubClientBuilder::with_reqwest_transport()
/// .with_keyset(Keyset {
/// publish_key: Some("pub-c-abc123"),
/// subscribe_key: "sub-c-abc123",
/// secret_key: None,
/// })
/// .with_user_id("my-user-id")
/// .with_retry_configuration(retry_configuration)
/// .build()?;
/// # Ok(())
/// # }
/// ```
pub fn default_exponential() -> Self {
Self::Exponential {
min_delay: 2,
max_delay: 150,
max_retry: 6,
excluded_endpoints: None,
}
}
/// Check whether next retry `attempt` is allowed.
///
/// # Arguments
///
/// * `path` - Optional path of the failed request.
/// * `attempt` - The attempt count of the request.
/// * `error` - An optional `PubNubError` representing the error response.
/// If `None`, the request cannot be retried.
///
/// # Returns
///
/// `true` if it is allowed to retry request one more time.
pub(crate) fn retriable<S>(
&self,
path: Option<S>,
attempt: &u8,
error: Option<&PubNubError>,
) -> bool
where
S: Into<String>,
{
if self.is_excluded_endpoint(path)
|| self.reached_max_retry(attempt)
|| matches!(self, RequestRetryConfiguration::None)
{
return false;
}
error
.and_then(|e| e.transport_response())
.map(|response| matches!(response.status, 429 | 500..=599))
.unwrap_or(false)
}
/// Calculate the delay before retrying a request.
///
/// If the request can be retried based on the given attempt count and
/// error, the delay is calculated based on the error response status code.
/// - If the status code is 429 (Too Many Requests), the delay is determined
/// by the `retry-after` header in the response, if present.
/// - If the status code is in the range 500-599 (Server Error), the delay
/// is calculated based on the configured retry strategy.
///
/// # Arguments
///
/// * `path` - Optional path of the failed request.
/// * `attempt` - The attempt count of the request.
/// * `error` - An optional `PubNubError` representing the error response.
/// If `None`, the request cannot be retried.
///
/// # Returns
///
/// An optional `u64` representing the delay in microseconds before retrying
/// the request. `None` if the request should not be retried.
pub(crate) fn retry_delay(
&self,
path: Option<String>,
attempt: &u8,
error: Option<&PubNubError>,
) -> Option<u64> {
if !self.retriable(path, attempt, error) {
return None;
}
error
.and_then(|err| err.transport_response())
.map(|response| match response.status {
// Respect service requested delay.
429 if response.headers.contains_key("retry-after") => {
(!matches!(self, Self::None))
.then(|| response.headers.get("retry-after"))
.flatten()
.and_then(|value| value.parse::<u64>().ok())
}
500..=599 => match self {
Self::None => None,
Self::Linear { delay, .. } => Some(*delay),
Self::Exponential {
min_delay,
max_delay,
..
} => Some((*min_delay * 2_u64.pow((*attempt - 1) as u32)).min(*max_delay)),
},
_ => None,
})
.map(Self::delay_in_microseconds)
.unwrap_or(None)
}
/// Check whether failed endpoint has been excluded or not.
///
/// # Arguments
///
/// * `path` - Optional path of the failed request.
///
/// # Returns
///
/// `true` in case if endpoint excluded from retry list or no path passed.
fn is_excluded_endpoint<S>(&self, path: Option<S>) -> bool
where
S: Into<String>,
{
let Some(path) = path.map(|p| Endpoint::from(p.into())) else {
return false;
};
let Some(excluded_endpoints) = (match self {
Self::Linear {
excluded_endpoints, ..
}
| Self::Exponential {
excluded_endpoints, ..
} => excluded_endpoints,
_ => &None,
}) else {
return false;
};
excluded_endpoints.contains(&path)
}
/// Check whether reached maximum retry count or not.
fn reached_max_retry(&self, attempt: &u8) -> bool {
match self {
Self::Linear { max_retry, .. } | Self::Exponential { max_retry, .. } => {
attempt.ge(max_retry)
}
_ => false,
}
}
/// Calculates the delay in microseconds given a delay in seconds.
///
/// # Arguments
///
/// * `delay_in_seconds` - The delay in seconds. If `None`, returns `None`.
///
/// # Returns
///
/// * `Some(delay_in_microseconds)` - The delay in microseconds.
/// * `None` - If `delay_in_seconds` is `None`.
fn delay_in_microseconds(delay_in_seconds: Option<u64>) -> Option<u64> {
let delay_in_seconds = delay_in_seconds?;
const MICROS_IN_SECOND: u64 = 1_000_000;
let delay = delay_in_seconds * MICROS_IN_SECOND;
let mut random_bytes = [0u8; 8];
if getrandom::fill(&mut random_bytes).is_err() {
return Some(delay);
}
Some(delay + u64::from_be_bytes(random_bytes) % MICROS_IN_SECOND)
}
}
impl Default for RequestRetryConfiguration {
fn default() -> Self {
Self::None
}
}
impl From<String> for Endpoint {
fn from(value: String) -> Self {
match value.as_str() {
path if path.starts_with("/v2/subscribe") => Endpoint::Subscribe,
path if path.starts_with("/publish/") || path.starts_with("/signal/") => {
Endpoint::MessageSend
}
path if path.starts_with("/v2/presence") => Endpoint::Presence,
path if path.starts_with("/v2/history/") || path.starts_with("/v3/history/") => {
Endpoint::MessageStorage
}
path if path.starts_with("/v1/message-actions/") => Endpoint::MessageReactions,
path if path.starts_with("/v1/channel-registration/") => Endpoint::ChannelGroups,
path if path.starts_with("/v2/objects/") => Endpoint::AppContext,
path if path.starts_with("/v1/push/") || path.starts_with("/v2/push/") => {
Endpoint::DevicePushNotifications
}
path if path.starts_with("/v1/files/") => Endpoint::Files,
_ => Endpoint::Unknown,
}
}
}
#[cfg(test)]
mod should {
use super::*;
use crate::{
core::TransportResponse,
lib::{alloc::boxed::Box, collections::HashMap},
};
fn client_error_response() -> TransportResponse {
TransportResponse {
status: 400,
..Default::default()
}
}
fn too_many_requests_error_response() -> TransportResponse {
TransportResponse {
status: 429,
headers: HashMap::from([(String::from("retry-after"), String::from("150"))]),
..Default::default()
}
}
fn server_error_response() -> TransportResponse {
TransportResponse {
status: 500,
..Default::default()
}
}
fn is_equal_with_accuracy(lhv: Option<u64>, rhv: Option<u64>) -> bool {
if lhv.is_none() && rhv.is_none() {
return true;
}
let Some(lhv) = lhv else { return false };
let Some(rhv) = rhv else { return false };
if !(rhv * 1_000_000..=rhv * 1_000_000 + 999_999).contains(&lhv) {
panic!(
"{lhv} is not within expected range {}..{}",
rhv * 1_000_000,
rhv * 1_000_000 + 999_999
)
}
true
}
#[test]
fn create_none_by_default() {
let policy: RequestRetryConfiguration = Default::default();
assert!(matches!(policy, RequestRetryConfiguration::None));
}
mod none_policy {
use super::*;
#[test]
fn return_none_delay_for_client_error_response() {
assert_eq!(
RequestRetryConfiguration::None.retry_delay(
None,
&1,
Some(&PubNubError::general_api_error(
"test",
None,
Some(Box::new(client_error_response()))
))
),
None
);
}
#[test]
fn return_none_delay_for_server_error_response() {
assert_eq!(
RequestRetryConfiguration::None.retry_delay(
None,
&1,
Some(&PubNubError::general_api_error(
"test",
None,
Some(Box::new(server_error_response()))
))
),
None
);
}
#[test]
fn return_none_delay_for_too_many_requests_error_response() {
assert_eq!(
RequestRetryConfiguration::None.retry_delay(
None,
&1,
Some(&PubNubError::general_api_error(
"test",
None,
Some(Box::new(too_many_requests_error_response()))
))
),
None
);
}
}
mod linear_policy {
use super::*;
#[test]
fn return_none_delay_for_client_error_response() {
let policy = RequestRetryConfiguration::Linear {
delay: 10,
max_retry: 5,
excluded_endpoints: None,
};
assert_eq!(
policy.retry_delay(
None,
&1,
Some(&PubNubError::general_api_error(
"test",
None,
Some(Box::new(client_error_response()))
))
),
None
);
}
#[test]
fn return_same_delay_for_server_error_response() {
let expected_delay: u64 = 10;
let policy = RequestRetryConfiguration::Linear {
delay: expected_delay,
max_retry: 5,
excluded_endpoints: None,
};
assert!(is_equal_with_accuracy(
policy.retry_delay(
None,
&1,
Some(&PubNubError::general_api_error(
"test",
None,
Some(Box::new(server_error_response()))
))
),
Some(expected_delay)
));
assert!(is_equal_with_accuracy(
policy.retry_delay(
None,
&2,
Some(&PubNubError::general_api_error(
"test",
None,
Some(Box::new(server_error_response()))
))
),
Some(expected_delay)
));
}
#[test]
fn return_none_delay_when_reach_max_retry_for_server_error_response() {
let expected_delay: u64 = 10;
let policy = RequestRetryConfiguration::Linear {
delay: expected_delay,
max_retry: 3,
excluded_endpoints: None,
};
assert!(is_equal_with_accuracy(
policy.retry_delay(
None,
&2,
Some(&PubNubError::general_api_error(
"test",
None,
Some(Box::new(server_error_response()))
))
),
Some(expected_delay)
));
assert_eq!(
policy.retry_delay(
None,
&4,
Some(&PubNubError::general_api_error(
"test",
None,
Some(Box::new(server_error_response()))
))
),
None
);
}
#[test]
fn return_service_delay_for_too_many_requests_error_response() {
let policy = RequestRetryConfiguration::Linear {
delay: 10,
max_retry: 3,
excluded_endpoints: None,
};
// 150 is from 'server_error_response' `Retry-After` header.
assert!(is_equal_with_accuracy(
policy.retry_delay(
None,
&2,
Some(&PubNubError::general_api_error(
"test",
None,
Some(Box::new(too_many_requests_error_response()))
))
),
Some(150)
));
}
}
mod exponential_policy {
use super::*;
#[test]
fn return_none_delay_for_client_error_response() {
let expected_delay = 8;
let policy = RequestRetryConfiguration::Exponential {
min_delay: expected_delay,
max_delay: 100,
max_retry: 2,
excluded_endpoints: None,
};
assert_eq!(
policy.retry_delay(
None,
&1,
Some(&PubNubError::general_api_error(
"test",
None,
Some(Box::new(client_error_response()))
))
),
None
);
}
#[test]
fn return_exponential_delay_for_server_error_response() {
let expected_delay = 8;
let policy = RequestRetryConfiguration::Exponential {
min_delay: expected_delay,
max_delay: 100,
max_retry: 3,
excluded_endpoints: None,
};
assert!(is_equal_with_accuracy(
policy.retry_delay(
None,
&1,
Some(&PubNubError::general_api_error(
"test",
None,
Some(Box::new(server_error_response()))
))
),
Some(expected_delay)
));
assert!(is_equal_with_accuracy(
policy.retry_delay(
None,
&2,
Some(&PubNubError::general_api_error(
"test",
None,
Some(Box::new(server_error_response()))
))
),
Some(expected_delay * 2_u64.pow(2 - 1))
));
}
#[test]
fn return_none_delay_when_reach_max_retry_for_server_error_response() {
let expected_delay = 8;
let policy = RequestRetryConfiguration::Exponential {
min_delay: expected_delay,
max_delay: 100,
max_retry: 3,
excluded_endpoints: None,
};
assert!(is_equal_with_accuracy(
policy.retry_delay(
None,
&2,
Some(&PubNubError::general_api_error(
"test",
None,
Some(Box::new(server_error_response()))
))
),
Some(expected_delay * 2_u64.pow(2 - 1))
));
assert_eq!(
policy.retry_delay(
None,
&4,
Some(&PubNubError::general_api_error(
"test",
None,
Some(Box::new(server_error_response()))
))
),
None
);
}
#[test]
fn return_max_delay_when_reach_max_value_for_server_error_response() {
let expected_delay = 8;
let max_delay = 50;
let policy = RequestRetryConfiguration::Exponential {
min_delay: expected_delay,
max_delay,
max_retry: 5,
excluded_endpoints: None,
};
assert!(is_equal_with_accuracy(
policy.retry_delay(
None,
&1,
Some(&PubNubError::general_api_error(
"test",
None,
Some(Box::new(server_error_response()))
))
),
Some(expected_delay)
));
assert!(is_equal_with_accuracy(
policy.retry_delay(
None,
&4,
Some(&PubNubError::general_api_error(
"test",
None,
Some(Box::new(server_error_response()))
))
),
Some(max_delay)
));
}
#[test]
fn return_service_delay_for_too_many_requests_error_response() {
let policy = RequestRetryConfiguration::Exponential {
min_delay: 10,
max_delay: 100,
max_retry: 3,
excluded_endpoints: None,
};
// 150 is from 'server_error_response' `Retry-After` header.
assert!(is_equal_with_accuracy(
policy.retry_delay(
None,
&2,
Some(&PubNubError::general_api_error(
"test",
None,
Some(Box::new(too_many_requests_error_response()))
))
),
Some(150)
));
}
}
}