kibana/x-pack/packages/ml/response_stream/server/accept_compression.ts
Walter Rafelsberger 0ab24e566c
[ML] AIOps: Use Kibana's http service instead of fetch, fix throttling. (#162335)
- Originally Kibana's `http` service did not support receiving streams,
that's why we used plain `fetch` for this. This has been fixed in
#158678, so this PR updates the streaming helpers to use Kibana's `http`
service from now on.
- The PR also breaks out the response stream code into its own package
and restructures it to separate client and server side code. This brings
down the `aiops` bundle size by `~300KB`! 🥳
- The approach to client side throttling/buffering was also revamped:
There was an issue doing the throttling inside the generator function,
it always waited for the timeout. The buffering is now removed from
`fetchStream`, instead `useThrottle` from `react-use` is used on the
reduced `data` in `useFetchStream`. Loading log rate analysis results
got a lot snappier with this update!
2023-07-27 08:57:10 +02:00

44 lines
1.1 KiB
TypeScript

/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import type { Headers } from '@kbn/core-http-server';
function containsGzip(s: string) {
return s
.split(',')
.map((d) => d.trim())
.includes('gzip');
}
/**
* Returns whether request headers accept a response using gzip compression.
*
* @param headers - Request headers.
* @returns boolean
*/
export function acceptCompression(headers: Headers) {
let compressed = false;
Object.keys(headers).forEach((key) => {
if (key.toLocaleLowerCase() === 'accept-encoding') {
const acceptEncoding = headers[key];
if (typeof acceptEncoding === 'string') {
compressed = containsGzip(acceptEncoding);
} else if (Array.isArray(acceptEncoding)) {
for (const ae of acceptEncoding) {
if (containsGzip(ae)) {
compressed = true;
break;
}
}
}
}
});
return compressed;
}