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
#![deny(missing_docs)]
use super::p2c::Balance;
use crate::discover::Change;
use crate::load::Load;
use crate::make::MakeService;
use futures_core::{ready, Stream};
use pin_project_lite::pin_project;
use slab::Slab;
use std::{
fmt,
future::Future,
pin::Pin,
task::{Context, Poll},
};
use tower_service::Service;
#[cfg(test)]
mod test;
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
enum Level {
Low,
Normal,
High,
}
pin_project! {
pub struct PoolDiscoverer<MS, Target, Request>
where
MS: MakeService<Target, Request>,
{
maker: MS,
#[pin]
making: Option<MS::Future>,
target: Target,
load: Level,
services: Slab<()>,
died_tx: tokio::sync::mpsc::UnboundedSender<usize>,
#[pin]
died_rx: tokio::sync::mpsc::UnboundedReceiver<usize>,
limit: Option<usize>,
}
}
impl<MS, Target, Request> fmt::Debug for PoolDiscoverer<MS, Target, Request>
where
MS: MakeService<Target, Request> + fmt::Debug,
Target: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PoolDiscoverer")
.field("maker", &self.maker)
.field("making", &self.making.is_some())
.field("target", &self.target)
.field("load", &self.load)
.field("services", &self.services)
.field("limit", &self.limit)
.finish()
}
}
impl<MS, Target, Request> Stream for PoolDiscoverer<MS, Target, Request>
where
MS: MakeService<Target, Request>,
MS::MakeError: Into<crate::BoxError>,
MS::Error: Into<crate::BoxError>,
Target: Clone,
{
type Item = Result<Change<usize, DropNotifyService<MS::Service>>, MS::MakeError>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut this = self.project();
while let Poll::Ready(Some(sid)) = this.died_rx.as_mut().poll_recv(cx) {
this.services.remove(sid);
tracing::trace!(
pool.services = this.services.len(),
message = "removing dropped service"
);
}
if this.services.is_empty() && this.making.is_none() {
let _ = ready!(this.maker.poll_ready(cx))?;
tracing::trace!("construct initial pool connection");
this.making
.set(Some(this.maker.make_service(this.target.clone())));
}
if let Level::High = this.load {
if this.making.is_none() {
if this
.limit
.map(|limit| this.services.len() >= limit)
.unwrap_or(false)
{
return Poll::Pending;
}
tracing::trace!(
pool.services = this.services.len(),
message = "decided to add service to loaded pool"
);
ready!(this.maker.poll_ready(cx))?;
tracing::trace!("making new service");
this.making
.set(Some(this.maker.make_service(this.target.clone())));
}
}
if let Some(fut) = this.making.as_mut().as_pin_mut() {
let svc = ready!(fut.poll(cx))?;
this.making.set(None);
let id = this.services.insert(());
let svc = DropNotifyService {
svc,
id,
notify: this.died_tx.clone(),
};
tracing::trace!(
pool.services = this.services.len(),
message = "finished creating new service"
);
*this.load = Level::Normal;
return Poll::Ready(Some(Ok(Change::Insert(id, svc))));
}
match this.load {
Level::High => {
unreachable!("found high load but no Service being made");
}
Level::Normal => Poll::Pending,
Level::Low if this.services.len() == 1 => Poll::Pending,
Level::Low => {
*this.load = Level::Normal;
let rm = this.services.iter().next().unwrap().0;
tracing::trace!(
pool.services = this.services.len(),
message = "removing service for over-provisioned pool"
);
Poll::Ready(Some(Ok(Change::Remove(rm))))
}
}
}
}
#[derive(Copy, Clone, Debug)]
pub struct Builder {
low: f64,
high: f64,
init: f64,
alpha: f64,
limit: Option<usize>,
}
impl Default for Builder {
fn default() -> Self {
Builder {
init: 0.1,
low: 0.00001,
high: 0.2,
alpha: 0.03,
limit: None,
}
}
}
impl Builder {
pub fn new() -> Self {
Self::default()
}
pub fn underutilized_below(&mut self, low: f64) -> &mut Self {
self.low = low;
self
}
pub fn loaded_above(&mut self, high: f64) -> &mut Self {
self.high = high;
self
}
pub fn initial(&mut self, init: f64) -> &mut Self {
self.init = init;
self
}
pub fn urgency(&mut self, alpha: f64) -> &mut Self {
self.alpha = alpha.max(0.0).min(1.0);
self
}
pub fn max_services(&mut self, limit: Option<usize>) -> &mut Self {
self.limit = limit;
self
}
pub fn build<MS, Target, Request>(
&self,
make_service: MS,
target: Target,
) -> Pool<MS, Target, Request>
where
MS: MakeService<Target, Request>,
MS::Service: Load,
<MS::Service as Load>::Metric: std::fmt::Debug,
MS::MakeError: Into<crate::BoxError>,
MS::Error: Into<crate::BoxError>,
Target: Clone,
{
let (died_tx, died_rx) = tokio::sync::mpsc::unbounded_channel();
let d = PoolDiscoverer {
maker: make_service,
making: None,
target,
load: Level::Normal,
services: Slab::new(),
died_tx,
died_rx,
limit: self.limit,
};
Pool {
balance: Balance::new(Box::pin(d)),
options: *self,
ewma: self.init,
}
}
}
pub struct Pool<MS, Target, Request>
where
MS: MakeService<Target, Request>,
MS::MakeError: Into<crate::BoxError>,
MS::Error: Into<crate::BoxError>,
Target: Clone,
{
balance: Balance<Pin<Box<PoolDiscoverer<MS, Target, Request>>>, Request>,
options: Builder,
ewma: f64,
}
impl<MS, Target, Request> fmt::Debug for Pool<MS, Target, Request>
where
MS: MakeService<Target, Request> + fmt::Debug,
MS::MakeError: Into<crate::BoxError>,
MS::Error: Into<crate::BoxError>,
Target: Clone + fmt::Debug,
MS::Service: fmt::Debug,
Request: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Pool")
.field("balance", &self.balance)
.field("options", &self.options)
.field("ewma", &self.ewma)
.finish()
}
}
impl<MS, Target, Request> Pool<MS, Target, Request>
where
MS: MakeService<Target, Request>,
MS::Service: Load,
<MS::Service as Load>::Metric: std::fmt::Debug,
MS::MakeError: Into<crate::BoxError>,
MS::Error: Into<crate::BoxError>,
Target: Clone,
{
pub fn new(make_service: MS, target: Target) -> Self {
Builder::new().build(make_service, target)
}
}
type PinBalance<S, Request> = Balance<Pin<Box<S>>, Request>;
impl<MS, Target, Req> Service<Req> for Pool<MS, Target, Req>
where
MS: MakeService<Target, Req>,
MS::Service: Load,
<MS::Service as Load>::Metric: std::fmt::Debug,
MS::MakeError: Into<crate::BoxError>,
MS::Error: Into<crate::BoxError>,
Target: Clone,
{
type Response = <PinBalance<PoolDiscoverer<MS, Target, Req>, Req> as Service<Req>>::Response;
type Error = <PinBalance<PoolDiscoverer<MS, Target, Req>, Req> as Service<Req>>::Error;
type Future = <PinBalance<PoolDiscoverer<MS, Target, Req>, Req> as Service<Req>>::Future;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
if let Poll::Ready(()) = self.balance.poll_ready(cx)? {
self.ewma *= 1.0 - self.options.alpha;
let discover = self.balance.discover_mut().as_mut().project();
if self.ewma < self.options.low {
if *discover.load != Level::Low {
tracing::trace!({ ewma = %self.ewma }, "pool is over-provisioned");
}
*discover.load = Level::Low;
if discover.services.len() > 1 {
self.ewma = self.options.init;
}
} else {
if *discover.load != Level::Normal {
tracing::trace!({ ewma = %self.ewma }, "pool is appropriately provisioned");
}
*discover.load = Level::Normal;
}
return Poll::Ready(Ok(()));
}
let discover = self.balance.discover_mut().as_mut().project();
if discover.making.is_none() {
self.ewma = self.options.alpha + (1.0 - self.options.alpha) * self.ewma;
if self.ewma > self.options.high {
if *discover.load != Level::High {
tracing::trace!({ ewma = %self.ewma }, "pool is under-provisioned");
}
*discover.load = Level::High;
self.ewma = self.options.high;
return self.balance.poll_ready(cx);
} else {
*discover.load = Level::Normal;
}
}
Poll::Pending
}
fn call(&mut self, req: Req) -> Self::Future {
self.balance.call(req)
}
}
#[doc(hidden)]
#[derive(Debug)]
pub struct DropNotifyService<Svc> {
svc: Svc,
id: usize,
notify: tokio::sync::mpsc::UnboundedSender<usize>,
}
impl<Svc> Drop for DropNotifyService<Svc> {
fn drop(&mut self) {
let _ = self.notify.send(self.id).is_ok();
}
}
impl<Svc: Load> Load for DropNotifyService<Svc> {
type Metric = Svc::Metric;
fn load(&self) -> Self::Metric {
self.svc.load()
}
}
impl<Request, Svc: Service<Request>> Service<Request> for DropNotifyService<Svc> {
type Response = Svc::Response;
type Future = Svc::Future;
type Error = Svc::Error;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.svc.poll_ready(cx)
}
fn call(&mut self, req: Request) -> Self::Future {
self.svc.call(req)
}
}