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
#![allow(async_fn_in_trait)]
#![deny(missing_docs, missing_debug_implementations)]

//! An experimental service framework.
//!
//! The [`Service`] trait is the central abstraction. It is an
//! [asynchronous function](Service::call), accepting a request and returning a response, which
//! can only be executed _after_ a [permit](Service::Permit) is [acquired](Service::acquire).
//!
//! The root exports [`Service`] constructors, and an extension trait, [`ServiceExt`] containing
//! combinators to modify a [`Service`]. Both the combinators and constructors each have an
//! associated module containing related documentation, traits, and types.
//!
//! # Example
//!
//! ```rust
//! use burger::*;
//! # use tokio::time::sleep;
//! # use std::time::Duration;
//!
//! # #[tokio::main]
//! # async fn main() {
//! let svc = service_fn(|x| async move {
//!     sleep(Duration::from_secs(1)).await;
//!     2 * x
//! })
//! .map(|x| x + 3)
//! .concurrency_limit(1)
//! .buffer(3)
//! .load_shed();
//! let response = svc.oneshot(30).await;
//! assert_eq!(Ok(63), response);
//! # }
//! ```
//!
//! # Usage
//!
//! A typical [`Service`] will consist of distinct layers, each providing specific dynamics. The
//! following flowchart attempts to categorize the exports of this crate:
//!
//! <pre class="mermaid" style="text-align:center">
#![doc = include_str!("flowchart.mmd")]
//! </pre>
//! <script type="module">
//! import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs';
//! let config = { theme: "dark", startOnLoad: true, flowchart: { useMaxWidth: true, htmlLabels: true } };
//! mermaid.initialize(config);
//! </script>

pub mod balance;
pub mod buffer;
#[cfg(feature = "compat")]
pub mod compat;
pub mod concurrency_limit;
pub mod depressurize;
pub mod either;
pub mod leak;
pub mod load;
pub mod load_shed;
pub mod map;
pub mod rate_limit;
pub mod retry;
pub mod select;
pub mod service_fn;
pub mod steer;
pub mod then;

use std::{convert::Infallible, sync::Arc, time::Duration};

use buffer::Buffer;
use concurrency_limit::ConcurrencyLimit;
use depressurize::Depressurize;
use either::Either;
use leak::Leak;
use load::{Load, PendingRequests};
use load_shed::LoadShed;
use map::Map;
use rate_limit::RateLimit;
use retry::Retry;
use then::Then;
use tokio::sync::{Mutex, RwLock};

#[cfg(feature = "compat")]
#[doc(inline)]
pub use compat::compat;
#[doc(inline)]
pub use select::select;
#[doc(inline)]
pub use service_fn::service_fn;
#[doc(inline)]
pub use steer::steer;

/// An asynchronous function call, which can only be executed _after_ obtaining a permit.
///
/// # Example
///
/// ```rust
/// use burger::{service_fn::ServiceFn, *};
///
/// # #[tokio::main]
/// # async fn main() {
/// let svc = service_fn(|x: usize| async move { x.to_string() });
/// let permit = svc.acquire().await;
/// let response = ServiceFn::call(permit, 32).await;
/// # }
/// ```
pub trait Service<Request> {
    /// The type produced by the service call.
    type Response;
    /// The type of the permit required to call the service.
    type Permit<'a>
    where
        Self: 'a;

    /// Obtains a permit.
    async fn acquire(&self) -> Self::Permit<'_>;

    /// Consumes a permit to call the service.
    async fn call<'a>(permit: Self::Permit<'a>, request: Request) -> Self::Response
    where
        Self: 'a;
}

/// An extension trait for [`Service`].
pub trait ServiceExt<Request>: Service<Request> {
    /// Acquires the [`Service::Permit`] and then immediately uses it to [call](Service::call) the
    /// [`Service`].
    ///
    /// # Example
    ///
    /// ```rust
    /// use burger::*;
    ///
    /// # #[tokio::main]
    /// # async fn main() {
    /// let svc = service_fn(|x: usize| async move { x.to_string() });
    /// let response = svc.oneshot(32).await;
    /// # }
    /// ```
    async fn oneshot(&self, request: Request) -> Self::Response
    where
        Self: Sized,
    {
        let permit = self.acquire().await;
        Self::call(permit, request).await
    }

    /// Extends the service using a closure accepting [`Self::Response`](Service::Response) and
    /// returning a [`Future`](std::future::Future).
    ///
    /// See the [module](then) for more information.
    fn then<F>(self, closure: F) -> Then<Self, F>
    where
        Self: Sized,
    {
        Then::new(self, closure)
    }

    /// Extends the service using a closure accepting [Self::Response](Service::Response) and returning a
    /// [`Future`](std::future::Future).
    ///
    /// See the [module](map) for more information.
    fn map<F>(self, closure: F) -> Map<Self, F>
    where
        Self: Sized,
    {
        Map::new(self, closure)
    }

    /// Applies a concurrency limit to the service with a specified number of permits.
    ///
    /// See [concurrency limit](concurrency_limit) module for more information.
    fn concurrency_limit(self, n_permits: usize) -> ConcurrencyLimit<Self>
    where
        Self: Sized,
    {
        ConcurrencyLimit::new(self, n_permits)
    }

    /// Applies load shedding to the service.
    ///
    /// See [module](load_shed) for more information.
    fn load_shed(self) -> LoadShed<Self>
    where
        Self: Sized,
    {
        LoadShed::new(self)
    }

    /// Applies buffering to the service with a specified capacity.
    ///
    /// See the [module](buffer) for more information.
    fn buffer(self, capacity: usize) -> Buffer<Self>
    where
        Self: Sized,
    {
        Buffer::new(self, capacity)
    }

    /// Applies rate limiting to the service with a specified interval and number of permits.
    ///
    /// See the [module](rate_limit) for more information.
    fn rate_limit(self, interval: Duration, permits: usize) -> RateLimit<Self>
    where
        Self: Sized,
    {
        RateLimit::new(self, interval, permits)
    }

    /// Applies retries to tbe service with a specified [Policy](crate::retry::Policy).
    ///
    /// See the [module](retry) for more information.
    fn retry<P>(self, policy: P) -> Retry<Self, P>
    where
        Self: Sized,
    {
        Retry::new(self, policy)
    }

    /// Depressurizes the service.
    ///
    /// See the [module](depressurize) for more information,
    fn depressurize(self) -> Depressurize<Self>
    where
        Self: Sized,
    {
        Depressurize::new(self)
    }

    /// Records [`Load`] on the service, measured by number of pending requests.
    ///
    /// See the [load] module for more information.
    fn pending_requests(self) -> PendingRequests<Self>
    where
        Self: Sized,
    {
        PendingRequests::new(self)
    }

    /// Extends the lifetime of the permit.
    ///
    /// See the [module](leak) for more information.
    fn leak<'t>(self: Arc<Self>) -> Leak<'t, Self>
    where
        Self: Sized,
    {
        Leak::new(self)
    }

    /// Wraps as [Either::Left]. For the other variant see [ServiceExt::right].
    ///
    /// See the [module](either) for more information.
    fn left<T>(self) -> Either<Self, T>
    where
        Self: Sized,
    {
        Either::Left(self)
    }

    /// Wraps as [Either::Right]. For the other variant see [ServiceExt::right].
    ///
    /// See the [module](either) for more information.
    fn right<T>(self) -> Either<T, Self>
    where
        Self: Sized,
    {
        Either::Right(self)
    }
}

impl<Request, S> ServiceExt<Request> for S where S: Service<Request> {}

/// A fallible [`Service`].
pub trait TryService<Request>: Service<Request, Response = Result<Self::Ok, Self::Error>> {
    /// The [`Result::Ok`] variant of the [`Service::Response`].
    type Ok;
    /// The [`Result::Err`] variant of the [`Service::Response`].
    type Error;
}

impl<Request, Ok, Error, S> TryService<Request> for S
where
    S: Service<Request, Response = Result<Ok, Error>>,
{
    type Ok = Ok;
    type Error = Error;
}

impl<Request, S> Service<Request> for Arc<S>
where
    S: Service<Request>,
{
    type Response = S::Response;
    type Permit<'a> = S::Permit<'a>
    where
        S: 'a;

    async fn acquire(&self) -> Self::Permit<'_> {
        S::acquire(self).await
    }

    async fn call(permit: Self::Permit<'_>, request: Request) -> Self::Response {
        S::call(permit, request).await
    }
}

impl<S> Load for Arc<S>
where
    S: Load,
{
    type Metric = S::Metric;

    fn load(&self) -> Self::Metric {
        S::load(self)
    }
}

impl<'t, Request, S> Service<Request> for &'t S
where
    S: Service<Request>,
{
    type Response = S::Response;
    type Permit<'a> = S::Permit<'a>
    where
        S:'a, 't: 'a;

    async fn acquire(&self) -> Self::Permit<'_> {
        S::acquire(self).await
    }

    async fn call<'a>(permit: Self::Permit<'a>, request: Request) -> Self::Response
    where
        Self: 'a,
    {
        S::call(permit, request).await
    }
}

impl<'t, S> Load for &'t S
where
    S: Load,
{
    type Metric = S::Metric;

    fn load(&self) -> Self::Metric {
        S::load(self)
    }
}

impl<Request, Permit, S> Service<Request> for Mutex<S>
where
    // NOTE: These bounds seem too tight
    for<'a> S: Service<Request, Permit<'a> = Permit>,
    S: 'static,
{
    type Response = S::Response;
    type Permit<'a> = Permit
    where
        S: 'a;

    async fn acquire(&self) -> Self::Permit<'_> {
        let guard = self.lock().await;
        guard.acquire().await
    }

    async fn call(permit: Self::Permit<'_>, request: Request) -> Self::Response {
        S::call(permit, request).await
    }
}

impl<Request, S, Permit> Service<Request> for RwLock<S>
where
    // NOTE: These bounds seem too tight
    for<'a> S: Service<Request, Permit<'a> = Permit>,
    S: 'static,
{
    type Response = S::Response;
    type Permit<'a> = S::Permit<'a>
    where
        Self: 'a;

    async fn acquire(&self) -> Self::Permit<'_> {
        self.read().await.acquire().await
    }

    async fn call(permit: Self::Permit<'_>, request: Request) -> Self::Response {
        S::call(permit, request).await
    }
}

/// A middleware, used to incrementally add behaviour to a [`Service`].
pub trait Middleware<S> {
    /// The resultant service.
    type Service;

    /// Applies this middleware to an existing service.
    fn apply(self, svc: S) -> Self::Service;
}

/// The root of a chain of [`Middleware`]s.
///
/// The [`ServiceExt`] combinators can be used to extend with additional middleware.
///
/// # Example
///
/// ```
/// use burger::*;
///
/// let middleware = MiddlewareBuilder.concurrency_limit(3).buffer(2).load_shed();
/// let svc = service_fn(|x: u32| async move { x.to_string() });
/// let svc = middleware.apply(svc);
/// ```
#[derive(Debug, Clone)]
pub struct MiddlewareBuilder;

impl Service<Infallible> for MiddlewareBuilder {
    type Permit<'a> = ();
    type Response = Infallible;

    async fn acquire(&self) -> Self::Permit<'_> {}

    async fn call<'a>(_permit: Self::Permit<'a>, request: Infallible) -> Self::Response
    where
        Self: 'a,
    {
        request
    }
}

impl<S> Middleware<S> for MiddlewareBuilder {
    type Service = S;

    fn apply(self, svc: S) -> Self::Service {
        svc
    }
}