|
| 1 | +// Bounding the number of concurrent in-flight requests (← go-zero's `MaxConns` / |
| 2 | +// `handler.MaxConnsHandler`): a semaphore of `max` permits. Each admitted HTTP request holds a |
| 3 | +// permit for its whole duration and returns it when it finishes; a request that finds no permit |
| 4 | +// free is answered `503 Service Unavailable` without reaching the app. This caps the work in flight |
| 5 | +// so a burst of connections cannot exhaust the server, complementing the rate limiter (which bounds |
| 6 | +// the arrival rate) and the breaker (which sheds on downstream failure). |
| 7 | + |
| 8 | +///| |
| 9 | +/// A permit pool of `max` concurrent slots (← go-zero's `syncx.Limit`). |
| 10 | +pub struct MaxConns { |
| 11 | + max : Int |
| 12 | + mut in_flight : Int |
| 13 | +} |
| 14 | + |
| 15 | +///| |
| 16 | +/// A pool admitting at most `max` requests at once. |
| 17 | +pub fn MaxConns::new(max : Int) -> MaxConns { |
| 18 | + { max, in_flight: 0 } |
| 19 | +} |
| 20 | + |
| 21 | +///| |
| 22 | +/// Take a permit if one is free (`TryBorrow`), returning whether it was taken. |
| 23 | +pub fn MaxConns::try_acquire(self : MaxConns) -> Bool { |
| 24 | + if self.in_flight < self.max { |
| 25 | + self.in_flight = self.in_flight + 1 |
| 26 | + true |
| 27 | + } else { |
| 28 | + false |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +///| |
| 33 | +/// Return a permit taken by `try_acquire` (`Return`). |
| 34 | +pub fn MaxConns::release(self : MaxConns) -> Unit { |
| 35 | + if self.in_flight > 0 { |
| 36 | + self.in_flight = self.in_flight - 1 |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +///| |
| 41 | +/// The number of requests currently holding a permit. |
| 42 | +pub fn MaxConns::in_flight(self : MaxConns) -> Int { |
| 43 | + self.in_flight |
| 44 | +} |
| 45 | + |
| 46 | +///| |
| 47 | +/// Max-connections middleware (← go-zero's `MaxConns`): hold a permit for the wrapped app's |
| 48 | +/// duration, or answer `503 Service Unavailable` when every permit is taken. Non-HTTP scopes |
| 49 | +/// (lifespan, websocket) pass through untouched. |
| 50 | +pub fn max_conns(limit : MaxConns) -> Middleware { |
| 51 | + inner => { |
| 52 | + (scope, receive, send) => { |
| 53 | + match scope { |
| 54 | + Http(_) => |
| 55 | + if limit.try_acquire() { |
| 56 | + inner(scope, receive, send) |
| 57 | + limit.release() |
| 58 | + } else { |
| 59 | + for event in service_unavailable_events() { |
| 60 | + send(event) |
| 61 | + } |
| 62 | + } |
| 63 | + _ => inner(scope, receive, send) |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments