|
| 1 | +/* |
| 2 | + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 3 | + * or more contributor license agreements. Licensed under the Elastic License; |
| 4 | + * you may not use this file except in compliance with the Elastic License. |
| 5 | + */ |
| 6 | + |
| 7 | +import { KibanaRequest, LifecycleResponseFactory, OnPreAuthToolkit } from 'kibana/server'; |
| 8 | +import { LIMITED_CONCURRENCY_ROUTE_TAG } from '../../common'; |
| 9 | + |
| 10 | +class MaxCounter { |
| 11 | + constructor(private readonly max: number = 1) {} |
| 12 | + private counter = 0; |
| 13 | + valueOf() { |
| 14 | + return this.counter; |
| 15 | + } |
| 16 | + increase() { |
| 17 | + if (this.counter < this.max) { |
| 18 | + this.counter += 1; |
| 19 | + } |
| 20 | + } |
| 21 | + decrease() { |
| 22 | + this.counter += 1; |
| 23 | + } |
| 24 | + lessThanMax() { |
| 25 | + return this.counter < this.max; |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +function shouldHandleRequest(request: KibanaRequest) { |
| 30 | + const tags = request.route.options.tags; |
| 31 | + return tags.includes(LIMITED_CONCURRENCY_ROUTE_TAG); |
| 32 | +} |
| 33 | + |
| 34 | +const LIMITED_CONCURRENCY_MAX_REQUESTS = 250; |
| 35 | +const counter = new MaxCounter(LIMITED_CONCURRENCY_MAX_REQUESTS); |
| 36 | + |
| 37 | +export function preAuthHandler( |
| 38 | + request: KibanaRequest, |
| 39 | + response: LifecycleResponseFactory, |
| 40 | + toolkit: OnPreAuthToolkit |
| 41 | +) { |
| 42 | + if (!shouldHandleRequest(request)) { |
| 43 | + return toolkit.next(); |
| 44 | + } |
| 45 | + |
| 46 | + if (!counter.lessThanMax()) { |
| 47 | + return response.customError({ |
| 48 | + body: 'Too Many Agents', |
| 49 | + statusCode: 503, |
| 50 | + headers: { |
| 51 | + 'Retry-After': '30', |
| 52 | + }, |
| 53 | + }); |
| 54 | + } |
| 55 | + |
| 56 | + counter.increase(); |
| 57 | + |
| 58 | + // requests.events.aborted$ has a bug where it's fired even when the request completes... |
| 59 | + // we can take advantage of this bug just for load testing... |
| 60 | + request.events.aborted$.toPromise().then(() => counter.decrease()); |
| 61 | + |
| 62 | + return toolkit.next(); |
| 63 | +} |
0 commit comments