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 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use std::fmt::Debug;
use std::fmt::Formatter;
use std::sync::Arc;
use std::time::Duration;
use backon::BlockingRetryable;
use backon::ExponentialBuilder;
use backon::Retryable;
use futures::FutureExt;
use log::warn;
use crate::raw::oio::ListOperation;
use crate::raw::oio::ReadOperation;
use crate::raw::oio::WriteOperation;
use crate::raw::*;
use crate::*;
/// Add retry for temporary failed operations.
///
/// # Notes
///
/// This layer will retry failed operations when [`Error::is_temporary`]
/// returns true. If operation still failed, this layer will set error to
/// `Persistent` which means error has been retried.
///
/// `write` and `blocking_write` don't support retry so far, visit [this issue](https://github.com/apache/opendal/issues/1223) for more details.
///
/// # Examples
///
/// ```no_run
/// use anyhow::Result;
/// use opendal::layers::RetryLayer;
/// use opendal::services;
/// use opendal::Operator;
/// use opendal::Scheme;
///
/// let _ = Operator::new(services::Memory::default())
/// .expect("must init")
/// .layer(RetryLayer::new())
/// .finish();
/// ```
///
/// ## Customize retry interceptor
///
/// RetryLayer accepts [`RetryInterceptor`] to allow users to customize
/// their own retry interceptor logic.
///
/// ```no_run
/// use std::time::Duration;
///
/// use anyhow::Result;
/// use opendal::layers::RetryInterceptor;
/// use opendal::layers::RetryLayer;
/// use opendal::services;
/// use opendal::Error;
/// use opendal::Operator;
/// use opendal::Scheme;
///
/// struct MyRetryInterceptor;
///
/// impl RetryInterceptor for MyRetryInterceptor {
/// fn intercept(&self, err: &Error, dur: Duration, ctx: &[(&str, &str)]) {
/// // do something
/// }
/// }
///
/// let _ = Operator::new(services::Memory::default())
/// .expect("must init")
/// .layer(RetryLayer::new().with_notify(MyRetryInterceptor))
/// .finish();
/// ```
pub struct RetryLayer<I = DefaultRetryInterceptor> {
builder: ExponentialBuilder,
notify: Arc<I>,
}
impl<I> Clone for RetryLayer<I> {
fn clone(&self) -> Self {
Self {
builder: self.builder.clone(),
notify: self.notify.clone(),
}
}
}
impl Default for RetryLayer {
fn default() -> Self {
Self {
builder: ExponentialBuilder::default(),
notify: Arc::new(DefaultRetryInterceptor),
}
}
}
impl RetryLayer {
/// Create a new retry layer.
/// # Examples
///
/// ```no_run
/// use anyhow::Result;
/// use opendal::layers::RetryLayer;
/// use opendal::services;
/// use opendal::Operator;
/// use opendal::Scheme;
///
/// let _ = Operator::new(services::Memory::default())
/// .expect("must init")
/// .layer(RetryLayer::new());
/// ```
pub fn new() -> Self {
Self::default()
}
/// Set the retry interceptor as new notify.
///
/// ```no_run
/// use std::time::Duration;
///
/// use anyhow::Result;
/// use opendal::layers::RetryInterceptor;
/// use opendal::layers::RetryLayer;
/// use opendal::services;
/// use opendal::Error;
/// use opendal::Operator;
/// use opendal::Scheme;
///
/// struct MyRetryInterceptor;
///
/// impl RetryInterceptor for MyRetryInterceptor {
/// fn intercept(&self, err: &Error, dur: Duration, ctx: &[(&str, &str)]) {
/// // do something
/// }
/// }
///
/// let _ = Operator::new(services::Memory::default())
/// .expect("must init")
/// .layer(RetryLayer::new().with_notify(MyRetryInterceptor))
/// .finish();
/// ```
pub fn with_notify<I: RetryInterceptor>(self, notify: I) -> RetryLayer<I> {
RetryLayer {
builder: self.builder,
notify: Arc::new(notify),
}
}
/// Set jitter of current backoff.
///
/// If jitter is enabled, ExponentialBackoff will add a random jitter in `[0, min_delay)
/// to current delay.
pub fn with_jitter(mut self) -> Self {
self.builder = self.builder.with_jitter();
self
}
/// Set factor of current backoff.
///
/// # Panics
///
/// This function will panic if input factor smaller than `1.0`.
pub fn with_factor(mut self, factor: f32) -> Self {
self.builder = self.builder.with_factor(factor);
self
}
/// Set min_delay of current backoff.
pub fn with_min_delay(mut self, min_delay: Duration) -> Self {
self.builder = self.builder.with_min_delay(min_delay);
self
}
/// Set max_delay of current backoff.
///
/// Delay will not increasing if current delay is larger than max_delay.
pub fn with_max_delay(mut self, max_delay: Duration) -> Self {
self.builder = self.builder.with_max_delay(max_delay);
self
}
/// Set max_times of current backoff.
///
/// Backoff will return `None` if max times is reaching.
pub fn with_max_times(mut self, max_times: usize) -> Self {
self.builder = self.builder.with_max_times(max_times);
self
}
}
impl<A: Access, I: RetryInterceptor> Layer<A> for RetryLayer<I> {
type LayeredAccess = RetryAccessor<A, I>;
fn layer(&self, inner: A) -> Self::LayeredAccess {
RetryAccessor {
inner,
builder: self.builder.clone(),
notify: self.notify.clone(),
}
}
}
/// RetryInterceptor is used to intercept while retry happened.
pub trait RetryInterceptor: Send + Sync + 'static {
/// Everytime RetryLayer is retrying, this function will be called.
///
/// # Timing
///
/// just before the retry sleep.
///
/// # Inputs
///
/// - err: The error that caused the current retry.
/// - dur: The duration that will sleep before next retry.
/// - ctx: The context (`name`, `value`) of current operation, like `operation` and `path`.
///
/// # Notes
///
/// The intercept must be quick and non-blocking. No heavy IO is
/// allowed. Otherwise the retry will be blocked.
fn intercept(&self, err: &Error, dur: Duration, ctx: &[(&str, &str)]);
}
/// The DefaultRetryInterceptor will log the retry error in warning level.
pub struct DefaultRetryInterceptor;
impl RetryInterceptor for DefaultRetryInterceptor {
fn intercept(&self, err: &Error, dur: Duration, ctx: &[(&str, &str)]) {
let context = ctx
.iter()
.map(|(k, v)| format!("{}={}", k, v))
.collect::<Vec<_>>()
.join(" ");
warn!(
target: "opendal::service",
"{} -> retry after {}s: error={}",
context, dur.as_secs_f64(), err)
}
}
pub struct RetryAccessor<A: Access, I: RetryInterceptor> {
inner: A,
builder: ExponentialBuilder,
notify: Arc<I>,
}
impl<A: Access, I: RetryInterceptor> Debug for RetryAccessor<A, I> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RetryAccessor")
.field("inner", &self.inner)
.finish_non_exhaustive()
}
}
impl<A: Access, I: RetryInterceptor> LayeredAccess for RetryAccessor<A, I> {
type Inner = A;
type Reader = RetryWrapper<A::Reader, I>;
type BlockingReader = RetryWrapper<A::BlockingReader, I>;
type Writer = RetryWrapper<A::Writer, I>;
type BlockingWriter = RetryWrapper<A::BlockingWriter, I>;
type Lister = RetryWrapper<A::Lister, I>;
type BlockingLister = RetryWrapper<A::BlockingLister, I>;
fn inner(&self) -> &Self::Inner {
&self.inner
}
async fn create_dir(&self, path: &str, args: OpCreateDir) -> Result<RpCreateDir> {
{ || self.inner.create_dir(path, args.clone()) }
.retry(&self.builder)
.when(|e| e.is_temporary())
.notify(|err, dur: Duration| {
self.notify.intercept(
err,
dur,
&[
("operation", Operation::CreateDir.into_static()),
("path", path),
],
)
})
.map(|v| v.map_err(|e| e.set_persistent()))
.await
}
async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
{ || self.inner.read(path, args.clone()) }
.retry(&self.builder)
.when(|e| e.is_temporary())
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[("operation", Operation::Read.into_static()), ("path", path)],
)
})
.map(|v| {
v.map(|(rp, r)| {
(
rp,
RetryWrapper::new(r, self.notify.clone(), path, self.builder.clone()),
)
})
.map_err(|e| e.set_persistent())
})
.await
}
/// Return `Interrupted` Error even after retry.
///
/// Allowing users to retry the write request from upper logic.
async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
{ || self.inner.write(path, args.clone()) }
.retry(&self.builder)
.when(|e| e.is_temporary())
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[
("operation", Operation::Write.into_static()),
("path", path),
],
)
})
.map(|v| {
v.map(|(rp, r)| {
(
rp,
RetryWrapper::new(r, self.notify.clone(), path, self.builder.clone()),
)
})
.map_err(|e| e.set_persistent())
})
.await
}
async fn stat(&self, path: &str, args: OpStat) -> Result<RpStat> {
{ || self.inner.stat(path, args.clone()) }
.retry(&self.builder)
.when(|e| e.is_temporary())
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[("operation", Operation::Stat.into_static()), ("path", path)],
)
})
.map(|v| v.map_err(|e| e.set_persistent()))
.await
}
async fn delete(&self, path: &str, args: OpDelete) -> Result<RpDelete> {
{ || self.inner.delete(path, args.clone()) }
.retry(&self.builder)
.when(|e| e.is_temporary())
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[
("operation", Operation::Delete.into_static()),
("path", path),
],
)
})
.map(|v| v.map_err(|e| e.set_persistent()))
.await
}
async fn copy(&self, from: &str, to: &str, args: OpCopy) -> Result<RpCopy> {
{ || self.inner.copy(from, to, args.clone()) }
.retry(&self.builder)
.when(|e| e.is_temporary())
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[
("operation", Operation::Copy.into_static()),
("from", from),
("to", to),
],
)
})
.map(|v| v.map_err(|e| e.set_persistent()))
.await
}
async fn rename(&self, from: &str, to: &str, args: OpRename) -> Result<RpRename> {
{ || self.inner.rename(from, to, args.clone()) }
.retry(&self.builder)
.when(|e| e.is_temporary())
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[
("operation", Operation::Rename.into_static()),
("from", from),
("to", to),
],
)
})
.map(|v| v.map_err(|e| e.set_persistent()))
.await
}
async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
{ || self.inner.list(path, args.clone()) }
.retry(&self.builder)
.when(|e| e.is_temporary())
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[("operation", Operation::List.into_static()), ("path", path)],
)
})
.map(|v| {
v.map(|(l, p)| {
let lister =
RetryWrapper::new(p, self.notify.clone(), path, self.builder.clone());
(l, lister)
})
.map_err(|e| e.set_persistent())
})
.await
}
async fn batch(&self, args: OpBatch) -> Result<RpBatch> {
{
|| async {
let rp = self.inner.batch(args.clone()).await?;
let mut nrp = Vec::with_capacity(rp.results().len());
for (path, result) in rp.into_results() {
let result = result?;
nrp.push((path, Ok(result)))
}
Ok(RpBatch::new(nrp))
}
}
.retry(&self.builder)
.when(|e: &Error| e.is_temporary())
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[
("operation", Operation::Batch.into_static()),
("count", &args.operation().len().to_string()),
],
)
})
.await
.map_err(|e| e.set_persistent())
}
fn blocking_create_dir(&self, path: &str, args: OpCreateDir) -> Result<RpCreateDir> {
{ || self.inner.blocking_create_dir(path, args.clone()) }
.retry(&self.builder)
.when(|e| e.is_temporary())
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[
("operation", Operation::BlockingCreateDir.into_static()),
("path", path),
],
)
})
.call()
.map_err(|e| e.set_persistent())
}
fn blocking_read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::BlockingReader)> {
{ || self.inner.blocking_read(path, args.clone()) }
.retry(&self.builder)
.when(|e| e.is_temporary())
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[
("operation", Operation::BlockingRead.into_static()),
("path", path),
],
)
})
.call()
.map(|(rp, r)| {
(
rp,
RetryWrapper::new(r, self.notify.clone(), path, self.builder.clone()),
)
})
.map_err(|e| e.set_persistent())
}
fn blocking_write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::BlockingWriter)> {
{ || self.inner.blocking_write(path, args.clone()) }
.retry(&self.builder)
.when(|e| e.is_temporary())
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[
("operation", Operation::BlockingWrite.into_static()),
("path", path),
],
)
})
.call()
.map(|(rp, r)| {
(
rp,
RetryWrapper::new(r, self.notify.clone(), path, self.builder.clone()),
)
})
.map_err(|e| e.set_persistent())
}
fn blocking_stat(&self, path: &str, args: OpStat) -> Result<RpStat> {
{ || self.inner.blocking_stat(path, args.clone()) }
.retry(&self.builder)
.when(|e| e.is_temporary())
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[
("operation", Operation::BlockingStat.into_static()),
("path", path),
],
)
})
.call()
.map_err(|e| e.set_persistent())
}
fn blocking_delete(&self, path: &str, args: OpDelete) -> Result<RpDelete> {
{ || self.inner.blocking_delete(path, args.clone()) }
.retry(&self.builder)
.when(|e| e.is_temporary())
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[
("operation", Operation::BlockingDelete.into_static()),
("path", path),
],
)
})
.call()
.map_err(|e| e.set_persistent())
}
fn blocking_copy(&self, from: &str, to: &str, args: OpCopy) -> Result<RpCopy> {
{ || self.inner.blocking_copy(from, to, args.clone()) }
.retry(&self.builder)
.when(|e| e.is_temporary())
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[
("operation", Operation::BlockingCopy.into_static()),
("from", from),
("to", to),
],
)
})
.call()
.map_err(|e| e.set_persistent())
}
fn blocking_rename(&self, from: &str, to: &str, args: OpRename) -> Result<RpRename> {
{ || self.inner.blocking_rename(from, to, args.clone()) }
.retry(&self.builder)
.when(|e| e.is_temporary())
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[
("operation", Operation::BlockingRename.into_static()),
("from", from),
("to", to),
],
)
})
.call()
.map_err(|e| e.set_persistent())
}
fn blocking_list(&self, path: &str, args: OpList) -> Result<(RpList, Self::BlockingLister)> {
{ || self.inner.blocking_list(path, args.clone()) }
.retry(&self.builder)
.when(|e| e.is_temporary())
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[
("operation", Operation::BlockingList.into_static()),
("path", path),
],
)
})
.call()
.map(|(rp, p)| {
let p = RetryWrapper::new(p, self.notify.clone(), path, self.builder.clone());
(rp, p)
})
.map_err(|e| e.set_persistent())
}
}
pub struct RetryWrapper<R, I> {
inner: Option<R>,
notify: Arc<I>,
path: String,
builder: ExponentialBuilder,
}
impl<R, I> RetryWrapper<R, I> {
fn new(inner: R, notify: Arc<I>, path: &str, backoff: ExponentialBuilder) -> Self {
Self {
inner: Some(inner),
notify,
path: path.to_string(),
builder: backoff,
}
}
}
impl<R: oio::Read, I: RetryInterceptor> oio::Read for RetryWrapper<R, I> {
async fn read_at(&self, offset: u64, limit: usize) -> Result<Buffer> {
{
|| {
self.inner
.as_ref()
.expect("inner must be valid")
.read_at(offset, limit)
}
}
.retry(&self.builder)
.when(|e| e.is_temporary())
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[
("operation", ReadOperation::Read.into_static()),
("path", &self.path),
],
)
})
.await
.map_err(|e| e.set_persistent())
}
}
impl<R: oio::BlockingRead, I: RetryInterceptor> oio::BlockingRead for RetryWrapper<R, I> {
fn read_at(&self, offset: u64, limit: usize) -> Result<Buffer> {
{ || self.inner.as_ref().unwrap().read_at(offset, limit) }
.retry(&self.builder)
.when(|e| e.is_temporary())
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[
("operation", ReadOperation::BlockingRead.into_static()),
("path", &self.path),
],
);
})
.call()
.map_err(|e| e.set_persistent())
}
}
impl<R: oio::Write, I: RetryInterceptor> oio::Write for RetryWrapper<R, I> {
async fn write(&mut self, bs: Buffer) -> Result<usize> {
use backon::RetryableWithContext;
let inner = self.inner.take().expect("inner must be valid");
let ((inner, _), res) = {
|(mut r, bs): (R, Buffer)| async move {
let res = r.write(bs.clone()).await;
((r, bs), res)
}
}
.retry(&self.builder)
.when(|e| e.is_temporary())
.context((inner, bs))
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[
("operation", WriteOperation::Write.into_static()),
("path", &self.path),
],
)
})
.map(|(r, res)| (r, res.map_err(|err| err.set_persistent())))
.await;
self.inner = Some(inner);
res
}
async fn abort(&mut self) -> Result<()> {
use backon::RetryableWithContext;
let inner = self.inner.take().expect("inner must be valid");
let (inner, res) = {
|mut r: R| async move {
let res = r.abort().await;
(r, res)
}
}
.retry(&self.builder)
.when(|e| e.is_temporary())
.context(inner)
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[
("operation", WriteOperation::Abort.into_static()),
("path", &self.path),
],
)
})
.map(|(r, res)| (r, res.map_err(|err| err.set_persistent())))
.await;
self.inner = Some(inner);
res
}
async fn close(&mut self) -> Result<()> {
use backon::RetryableWithContext;
let inner = self.inner.take().expect("inner must be valid");
let (inner, res) = {
|mut r: R| async move {
let res = r.close().await;
(r, res)
}
}
.retry(&self.builder)
.when(|e| e.is_temporary())
.context(inner)
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[
("operation", WriteOperation::Close.into_static()),
("path", &self.path),
],
)
})
.map(|(r, res)| (r, res.map_err(|err| err.set_persistent())))
.await;
self.inner = Some(inner);
res
}
}
impl<R: oio::BlockingWrite, I: RetryInterceptor> oio::BlockingWrite for RetryWrapper<R, I> {
fn write(&mut self, bs: Buffer) -> Result<usize> {
{ || self.inner.as_mut().unwrap().write(bs.clone()) }
.retry(&self.builder)
.when(|e| e.is_temporary())
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[
("operation", WriteOperation::BlockingWrite.into_static()),
("path", &self.path),
],
);
})
.call()
.map_err(|e| e.set_persistent())
}
fn close(&mut self) -> Result<()> {
{ || self.inner.as_mut().unwrap().close() }
.retry(&self.builder)
.when(|e| e.is_temporary())
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[
("operation", WriteOperation::BlockingClose.into_static()),
("path", &self.path),
],
);
})
.call()
.map_err(|e| e.set_persistent())
}
}
impl<P: oio::List, I: RetryInterceptor> oio::List for RetryWrapper<P, I> {
async fn next(&mut self) -> Result<Option<oio::Entry>> {
use backon::RetryableWithContext;
let inner = self.inner.take().expect("inner must be valid");
let (inner, res) = {
|mut p: P| async move {
let res = p.next().await;
(p, res)
}
}
.retry(&self.builder)
.when(|e| e.is_temporary())
.context(inner)
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[
("operation", ListOperation::Next.into_static()),
("path", &self.path),
],
)
})
.map(|(r, res)| (r, res.map_err(|err| err.set_persistent())))
.await;
self.inner = Some(inner);
res
}
}
impl<P: oio::BlockingList, I: RetryInterceptor> oio::BlockingList for RetryWrapper<P, I> {
fn next(&mut self) -> Result<Option<oio::Entry>> {
{ || self.inner.as_mut().unwrap().next() }
.retry(&self.builder)
.when(|e| e.is_temporary())
.notify(|err, dur| {
self.notify.intercept(
err,
dur,
&[
("operation", ListOperation::BlockingNext.into_static()),
("path", &self.path),
],
);
})
.call()
.map_err(|e| e.set_persistent())
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Mutex;
use bytes::Bytes;
use futures::TryStreamExt;
use super::*;
#[derive(Default, Clone)]
struct MockBuilder {
attempt: Arc<Mutex<usize>>,
}
impl Builder for MockBuilder {
const SCHEME: Scheme = Scheme::Custom("mock");
type Accessor = MockService;
fn from_map(_: HashMap<String, String>) -> Self {
Self::default()
}
fn build(&mut self) -> Result<Self::Accessor> {
Ok(MockService {
attempt: self.attempt.clone(),
})
}
}
#[derive(Debug, Clone, Default)]
struct MockService {
attempt: Arc<Mutex<usize>>,
}
impl Access for MockService {
type Reader = MockReader;
type Writer = ();
type Lister = MockLister;
type BlockingReader = ();
type BlockingWriter = ();
type BlockingLister = ();
fn info(&self) -> AccessorInfo {
let mut am = AccessorInfo::default();
am.set_native_capability(Capability {
read: true,
list: true,
list_with_recursive: true,
batch: true,
..Default::default()
});
am
}
async fn read(&self, _: &str, _: OpRead) -> Result<(RpRead, Self::Reader)> {
Ok((
RpRead::new(),
MockReader {
attempt: self.attempt.clone(),
},
))
}
async fn list(&self, _: &str, _: OpList) -> Result<(RpList, Self::Lister)> {
let lister = MockLister::default();
Ok((RpList::default(), lister))
}
async fn batch(&self, op: OpBatch) -> Result<RpBatch> {
let mut attempt = self.attempt.lock().unwrap();
*attempt += 1;
match *attempt {
1 => Err(
Error::new(ErrorKind::Unexpected, "retryable_error from reader")
.set_temporary(),
),
2 => Ok(RpBatch::new(
op.into_operation()
.into_iter()
.map(|(s, _)| {
(
s,
Err(Error::new(
ErrorKind::Unexpected,
"retryable_error from reader",
)
.set_temporary()),
)
})
.collect(),
)),
3 => Ok(RpBatch::new(
op.into_operation()
.into_iter()
.enumerate()
.map(|(i, (s, _))| {
(
s,
match i {
0 => Err(Error::new(
ErrorKind::Unexpected,
"retryable_error from reader",
)
.set_temporary()),
_ => Ok(RpDelete {}.into()),
},
)
})
.collect(),
)),
4 => Err(
Error::new(ErrorKind::Unexpected, "retryable_error from reader")
.set_temporary(),
),
5 => Ok(RpBatch::new(
op.into_operation()
.into_iter()
.map(|(s, _)| (s, Ok(RpDelete {}.into())))
.collect(),
)),
_ => unreachable!(),
}
}
}
#[derive(Debug, Clone, Default)]
struct MockReader {
attempt: Arc<Mutex<usize>>,
}
impl oio::Read for MockReader {
async fn read_at(&self, _: u64, _: usize) -> Result<Buffer> {
let mut attempt = self.attempt.lock().unwrap();
*attempt += 1;
match *attempt {
1 => Err(
Error::new(ErrorKind::Unexpected, "retryable_error from reader")
.set_temporary(),
),
2 => Err(
Error::new(ErrorKind::Unexpected, "retryable_error from reader")
.set_temporary(),
),
3 => Ok(Bytes::copy_from_slice("Hello, World!".as_bytes()).into()),
_ => unreachable!(),
}
}
}
#[derive(Debug, Clone, Default)]
struct MockLister {
attempt: usize,
}
impl oio::List for MockLister {
async fn next(&mut self) -> Result<Option<oio::Entry>> {
self.attempt += 1;
match self.attempt {
1 => Err(Error::new(
ErrorKind::RateLimited,
"retryable rate limited error from lister",
)
.set_temporary()),
2 => Ok(Some(oio::Entry::new(
"hello",
Metadata::new(EntryMode::FILE),
))),
3 => Ok(Some(oio::Entry::new(
"world",
Metadata::new(EntryMode::FILE),
))),
4 => Err(
Error::new(ErrorKind::Unexpected, "retryable internal server error")
.set_temporary(),
),
5 => Ok(Some(oio::Entry::new(
"2023/",
Metadata::new(EntryMode::DIR),
))),
6 => Ok(Some(oio::Entry::new(
"0208/",
Metadata::new(EntryMode::DIR),
))),
7 => Ok(None),
_ => {
unreachable!()
}
}
}
}
#[tokio::test]
async fn test_retry_read() {
let _ = tracing_subscriber::fmt().with_test_writer().try_init();
let builder = MockBuilder::default();
let op = Operator::new(builder.clone())
.unwrap()
.layer(RetryLayer::new())
.finish();
let r = op.reader("retryable_error").await.unwrap();
let mut content = Vec::new();
let size = r
.read_into(&mut content, ..)
.await
.expect("read must succeed");
assert_eq!(size, 13);
assert_eq!(content, "Hello, World!".as_bytes());
// The error is retryable, we should request it 3 times.
assert_eq!(*builder.attempt.lock().unwrap(), 3);
}
#[tokio::test]
async fn test_retry_list() {
let _ = tracing_subscriber::fmt().with_test_writer().try_init();
let builder = MockBuilder::default();
let op = Operator::new(builder.clone())
.unwrap()
.layer(RetryLayer::new())
.finish();
let expected = vec!["hello", "world", "2023/", "0208/"];
let mut lister = op
.lister("retryable_error/")
.await
.expect("service must support list");
let mut actual = Vec::new();
while let Some(obj) = lister.try_next().await.expect("must success") {
actual.push(obj.name().to_owned());
}
assert_eq!(actual, expected);
}
#[tokio::test]
async fn test_retry_batch() {
let _ = tracing_subscriber::fmt().with_test_writer().try_init();
let builder = MockBuilder::default();
// set to a lower delay to make it run faster
let op = Operator::new(builder.clone())
.unwrap()
.layer(
RetryLayer::new()
.with_min_delay(Duration::from_secs_f32(0.1))
.with_max_times(5),
)
.finish();
let paths = vec![
"hello".into(),
"world".into(),
"test".into(),
"batch".into(),
];
op.remove(paths).await.expect("batch must succeed");
assert_eq!(*builder.attempt.lock().unwrap(), 5);
}
}