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
// Copyright 2022 Datafuse Labs
//
// Licensed 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::io;
use std::task::Context;
use std::task::Poll;

use async_trait::async_trait;
use bytes::Bytes;
use futures::FutureExt;
use rand::prelude::*;
use rand::rngs::StdRng;

use crate::ops::*;
use crate::raw::*;
use crate::*;

/// Inject chaos into underlying services for robustness test.
///
/// # Chaos
///
/// Chaos tests is a part of stress test. By generating errors at specified
/// error ratio, we can reproduce underlying services error more reliable.
///
/// Running tests under ChaosLayer will make your application more robust.
///
/// For example: If we specify an error rate of 0.5, there is a 50% chance
/// of an EOF error for every read operation.
///
/// # Note
///
/// For now, ChaosLayer only injects read operations. More operations may
/// be added in the future.
///
/// # Examples
///
/// ```
/// use anyhow::Result;
/// use opendal::layers::ChaosLayer;
/// use opendal::services;
/// use opendal::Operator;
/// use opendal::Scheme;
///
/// let _ = Operator::new(services::Memory::default())
///     .expect("must init")
///     .layer(ChaosLayer::new(0.1))
///     .finish();
/// ```
#[derive(Debug, Clone)]
pub struct ChaosLayer {
    error_ratio: f64,
}

impl ChaosLayer {
    /// Create a new chaos layer with specified error ratio.
    ///
    /// # Panics
    ///
    /// Input error_ratio must in [0.0..=1.0]
    pub fn new(error_ratio: f64) -> Self {
        assert!(
            (0.0..=1.0).contains(&error_ratio),
            "error_ratio must between 0.0 and 1.0"
        );
        Self { error_ratio }
    }
}

impl<A: Accessor> Layer<A> for ChaosLayer {
    type LayeredAccessor = ChaosAccessor<A>;

    fn layer(&self, inner: A) -> Self::LayeredAccessor {
        ChaosAccessor {
            inner,
            rng: StdRng::from_entropy(),
            error_ratio: self.error_ratio,
        }
    }
}

#[derive(Debug)]
pub struct ChaosAccessor<A> {
    inner: A,
    rng: StdRng,

    error_ratio: f64,
}

#[async_trait]
impl<A: Accessor> LayeredAccessor for ChaosAccessor<A> {
    type Inner = A;
    type Reader = ChaosReader<A::Reader>;
    type BlockingReader = ChaosReader<A::BlockingReader>;
    type Writer = A::Writer;
    type BlockingWriter = A::BlockingWriter;
    type Pager = A::Pager;
    type BlockingPager = A::BlockingPager;

    fn inner(&self) -> &Self::Inner {
        &self.inner
    }

    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
        self.inner
            .read(path, args)
            .map(|v| v.map(|(rp, r)| (rp, ChaosReader::new(r, self.rng.clone(), self.error_ratio))))
            .await
    }

    fn blocking_read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::BlockingReader)> {
        self.inner
            .blocking_read(path, args)
            .map(|(rp, r)| (rp, ChaosReader::new(r, self.rng.clone(), self.error_ratio)))
    }

    async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
        self.inner.write(path, args).await
    }

    fn blocking_write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::BlockingWriter)> {
        self.inner.blocking_write(path, args)
    }

    async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Pager)> {
        self.inner.list(path, args).await
    }

    async fn scan(&self, path: &str, args: OpScan) -> Result<(RpScan, Self::Pager)> {
        self.inner.scan(path, args).await
    }

    fn blocking_list(&self, path: &str, args: OpList) -> Result<(RpList, Self::BlockingPager)> {
        self.inner.blocking_list(path, args)
    }

    fn blocking_scan(&self, path: &str, args: OpScan) -> Result<(RpScan, Self::BlockingPager)> {
        self.inner.blocking_scan(path, args)
    }
}

/// ChaosReader will inject error into read operations.
pub struct ChaosReader<R> {
    inner: R,
    rng: StdRng,

    error_ratio: f64,
}

impl<R> ChaosReader<R> {
    fn new(inner: R, rng: StdRng, error_ratio: f64) -> Self {
        Self {
            inner,
            rng,
            error_ratio,
        }
    }

    /// If I feel lucky, we can return the correct response. Otherwise,
    /// we need to generate an error.
    fn i_feel_lucky(&mut self) -> bool {
        let point = self.rng.gen_range(0..=100);
        point >= (self.error_ratio * 100.0) as i32
    }

    fn unexpected_eof() -> Error {
        Error::new(ErrorKind::Unexpected, "I am your chaos!")
            .with_operation("chaos")
            .set_temporary()
    }
}

impl<R: oio::Read> oio::Read for ChaosReader<R> {
    fn poll_read(&mut self, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<Result<usize>> {
        if self.i_feel_lucky() {
            self.inner.poll_read(cx, buf)
        } else {
            Poll::Ready(Err(Self::unexpected_eof()))
        }
    }

    fn poll_seek(&mut self, cx: &mut Context<'_>, pos: io::SeekFrom) -> Poll<Result<u64>> {
        if self.i_feel_lucky() {
            self.inner.poll_seek(cx, pos)
        } else {
            Poll::Ready(Err(Self::unexpected_eof()))
        }
    }

    fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<Bytes>>> {
        if self.i_feel_lucky() {
            self.inner.poll_next(cx)
        } else {
            Poll::Ready(Some(Err(Self::unexpected_eof())))
        }
    }
}

impl<R: oio::BlockingRead> oio::BlockingRead for ChaosReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        if self.i_feel_lucky() {
            self.inner.read(buf)
        } else {
            Err(Self::unexpected_eof())
        }
    }

    fn seek(&mut self, pos: io::SeekFrom) -> Result<u64> {
        if self.i_feel_lucky() {
            self.inner.seek(pos)
        } else {
            Err(Self::unexpected_eof())
        }
    }

    fn next(&mut self) -> Option<Result<Bytes>> {
        if self.i_feel_lucky() {
            self.inner.next()
        } else {
            Some(Err(Self::unexpected_eof()))
        }
    }
}