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
// Copyright 2020 Tetrate
//
// 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.

//! `Envoy` `Stats API`.

use crate::host;

/// An interface of the `Envoy` `Stats API`.
///
/// # Examples
///
/// #### Basic usage of [`Stats`]:
///
/// ```
/// # use envoy_sdk as envoy;
/// # use envoy::host::Result;
/// # fn action() -> Result<()> {
/// use envoy::host::Stats;
///
/// let stats = Stats::default();
///
/// let requests_total = stats.counter("requests_total")?;
///
/// requests_total.inc();
/// # Ok(())
/// # }
/// ```
///
/// #### Injecting [`Stats`] into a HTTP Filter as a dependency:
///
/// ```
/// # use envoy_sdk as envoy;
/// use envoy::host::Stats;
///
/// struct MyHttpFilter<'a> {
///     stats: &'a dyn Stats,
/// }
///
/// impl<'a> MyHttpFilter<'a> {
///     /// Creates a new instance parameterized with a given [`Stats`] implementation.
///     pub fn new(stats: &'a dyn Stats) -> Self {
///         MyHttpFilter { stats }
///     }
///
///     /// Creates a new instance parameterized with the default [`Stats`] implementation.
///     pub fn default() -> Self {
///         Self::new(Stats::default())
///     }
/// }
/// ```
///
/// [`Stats`]: trait.Stats.html
pub trait Stats {
    /// Creates a [`Counter`] from the stat name.
    ///
    /// Tag extraction will be performed on the name.
    ///
    /// [`Counter`]: trait.Counter.html
    fn counter(&self, name: &str) -> host::Result<Box<dyn Counter>>;

    /// Creates a [`Gauge`] from the stat name.
    ///
    /// Tag extraction will be performed on the name.
    ///
    /// [`Gauge`]: trait.Gauge.html
    fn gauge(&self, name: &str) -> host::Result<Box<dyn Gauge>>;

    /// Creates a [`Histogram`] from the stat name.
    ///
    /// Tag extraction will be performed on the name.
    ///
    /// [`Histogram`]: trait.Histogram.html
    fn histogram(&self, name: &str) -> host::Result<Box<dyn Histogram>>;
}

/// An interface of the `Envoy` `Counter`.
///
/// A `Counter` can only be incremented.
///
/// # Examples
///
/// #### Basic usage of [`Counter`]:
///
/// ```
/// # use envoy_sdk as envoy;
/// # use envoy::host::Result;
/// # fn action() -> Result<()> {
/// use envoy::host::Stats;
///
/// let stats = Stats::default();
///
/// let requests_total = stats.counter("requests_total")?;
///
/// requests_total.inc()?;
/// # Ok(())
/// # }
/// ```
///
/// [`Counter`]: trait.Counter.html
pub trait Counter {
    /// Increments counter by `1`.
    fn inc(&self) -> host::Result<()> {
        self.add(1)
    }
    /// Increments counter by a given offset.
    fn add(&self, offset: u64) -> host::Result<()>;
    /// Returns current value of the counter.
    fn value(&self) -> host::Result<u64>;
}

/// An interface of the `Envoy` `Gauge`.
///
/// A `Gauge` can be both incremented and decremented.
///
/// # Examples
///
/// #### Basic usage of [`Gauge`]:
///
/// ```
/// # use envoy_sdk as envoy;
/// # use envoy::host::Result;
/// # fn action() -> Result<()> {
/// use envoy::host::Stats;
///
/// let stats = Stats::default();
///
/// let requests_active = stats.gauge("requests_active")?;
///
/// requests_active.inc()?;
///
/// # stringify! {
/// ... do some work ...
/// # };
///
/// requests_active.dec()?;
/// # Ok(())
/// # }
/// ```
///
/// [`Gauge`]: trait.Gauge.html
pub trait Gauge {
    /// Increments gauge by `1`.
    fn inc(&self) -> host::Result<()> {
        self.add(1)
    }
    /// Decrements gauge by `1`.
    fn dec(&self) -> host::Result<()> {
        self.sub(1)
    }
    /// Increments gauge by a given offset.
    fn add(&self, offset: u64) -> host::Result<()>;
    /// Decrements gauge by a given offset.
    fn sub(&self, offset: u64) -> host::Result<()>;
    /// Sets gauge to a given value.
    fn set(&self, value: u64) -> host::Result<()>;
    /// Returns current value of the gauge.
    fn value(&self) -> host::Result<u64>;
}

/// An interface of the `Envoy` `Histogram`.
///
/// A `Histogram` records values one at a time.
///
/// # Examples
///
/// #### Basic usage of [`Histogram`]:
///
/// ```
/// # use envoy_sdk as envoy;
/// # use envoy::host::Result;
/// # fn action() -> Result<()> {
/// use envoy::host::Stats;
///
/// let stats = Stats::default();
///
/// let response_times_millis = stats.histogram("response_times_millis")?;
///
/// response_times_millis.record(123)?;
/// # Ok(())
/// # }
/// ```
///
/// [`Histogram`]: trait.Histogram.html
pub trait Histogram {
    /// Records a given value.
    fn record(&self, value: u64) -> host::Result<()>;
}

impl dyn Stats {
    /// Returns the default implementation that interacts with `Envoy`
    /// through its [`ABI`].
    ///
    /// [`ABI`]: https://github.com/proxy-wasm/spec
    pub fn default() -> &'static dyn Stats {
        &impls::Host
    }
}

mod impls {
    use std::cmp;

    use super::Stats;
    use crate::abi::proxy_wasm::hostcalls;
    use crate::abi::proxy_wasm::types::{MetricHandle, MetricType};
    use crate::host;

    pub(super) struct Host;

    impl Stats for Host {
        fn counter(&self, name: &str) -> host::Result<Box<dyn super::Counter>> {
            hostcalls::define_metric(MetricType::Counter, name)
                .map(|handle| Box::new(Counter(handle)) as Box<dyn super::Counter>)
        }

        fn gauge(&self, name: &str) -> host::Result<Box<dyn super::Gauge>> {
            hostcalls::define_metric(MetricType::Gauge, name)
                .map(|handle| Box::new(Gauge(handle)) as Box<dyn super::Gauge>)
        }

        fn histogram(&self, name: &str) -> host::Result<Box<dyn super::Histogram>> {
            hostcalls::define_metric(MetricType::Histogram, name)
                .map(|handle| Box::new(Histogram(handle)) as Box<dyn super::Histogram>)
        }
    }

    struct Counter(MetricHandle);

    impl super::Counter for Counter {
        fn add(&self, offset: u64) -> host::Result<()> {
            let mut offset = offset;
            while 0 < offset {
                let delta = cmp::min(offset, std::i64::MAX as u64) as i64;
                if let Err(err) = hostcalls::increment_metric(self.0, delta) {
                    return Err(err);
                }
                offset -= delta as u64;
            }
            Ok(())
        }

        fn value(&self) -> host::Result<u64> {
            hostcalls::get_metric(self.0)
        }
    }

    struct Gauge(MetricHandle);

    impl super::Gauge for Gauge {
        fn add(&self, offset: u64) -> host::Result<()> {
            let mut offset = offset;
            while 0 < offset {
                let delta = cmp::min(offset, std::i64::MAX as u64) as i64;
                if let Err(err) = hostcalls::increment_metric(self.0, delta) {
                    return Err(err);
                }
                offset -= delta as u64;
            }
            Ok(())
        }

        fn sub(&self, offset: u64) -> host::Result<()> {
            let mut offset = offset;
            while 0 < offset {
                let delta = cmp::min(offset, std::i64::MAX as u64) as i64;
                if let Err(err) = hostcalls::increment_metric(self.0, -delta) {
                    return Err(err);
                }
                offset -= delta as u64;
            }
            Ok(())
        }

        fn set(&self, value: u64) -> host::Result<()> {
            hostcalls::record_metric(self.0, value)
        }

        fn value(&self) -> host::Result<u64> {
            hostcalls::get_metric(self.0)
        }
    }

    struct Histogram(MetricHandle);

    impl super::Histogram for Histogram {
        fn record(&self, value: u64) -> host::Result<()> {
            hostcalls::record_metric(self.0, value)
        }
    }
}