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
// 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::sync::Arc;
use std::sync::Mutex;

use futures::FutureExt;
use rand::prelude::*;
use rand::rngs::StdRng;

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
///
/// ```no_run
/// 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: Access> Layer<A> for ChaosLayer {
    type LayeredAccess = ChaosAccessor<A>;

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

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

    error_ratio: f64,
}

impl<A: Access> LayeredAccess 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 Lister = A::Lister;
    type BlockingLister = A::BlockingLister;

    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::Lister)> {
        self.inner.list(path, args).await
    }

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

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

    error_ratio: f64,
}

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

    /// If I feel lucky, we can return the correct response. Otherwise,
    /// we need to generate an error.
    fn i_feel_lucky(&self) -> bool {
        let point = self.rng.lock().unwrap().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> {
    async fn read_at(&self, offset: u64, limit: usize) -> Result<Buffer> {
        if self.i_feel_lucky() {
            self.inner.read_at(offset, limit).await
        } else {
            Err(Self::unexpected_eof())
        }
    }
}

impl<R: oio::BlockingRead> oio::BlockingRead for ChaosReader<R> {
    fn read_at(&self, offset: u64, limit: usize) -> Result<Buffer> {
        if self.i_feel_lucky() {
            self.inner.read_at(offset, limit)
        } else {
            Err(Self::unexpected_eof())
        }
    }
}