Skip to content

Commit

Permalink
Remove request and request-promise-native in favour of got
Browse files Browse the repository at this point in the history
Signed-off-by: Sebastian Malton <sebastian@malton.name>
  • Loading branch information
Nokel81 committed Oct 7, 2021
1 parent e10c13c commit c65f874
Show file tree
Hide file tree
Showing 14 changed files with 224 additions and 244 deletions.
36 changes: 17 additions & 19 deletions build/download_kubectl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,18 @@
*/
import packageInfo from "../package.json";
import fs from "fs";
import request from "request";
import md5File from "md5-file";
import requestPromise from "request-promise-native";
import { ensureDir, pathExists } from "fs-extra";
import path from "path";
import { noop } from "lodash";
import { isLinux, isMac } from "../src/common/vars";
import got from "got";

class KubectlDownloader {
public kubectlVersion: string;
protected url: string;
protected path: string;
protected dirname: string;
public readonly kubectlVersion: string;
protected readonly url: string;
protected readonly path: string;
protected readonly dirname: string;

constructor(clusterVersion: string, platform: string, arch: string, target: string) {
this.kubectlVersion = clusterVersion;
Expand All @@ -44,14 +43,14 @@ class KubectlDownloader {
}

protected async urlEtag() {
const response = await requestPromise({
method: "HEAD",
uri: this.url,
resolveWithFullResponse: true
}).catch(console.error);

if (response.headers["etag"]) {
return response.headers["etag"].replace(/"/g, "");
try {
const response = await got.head(this.url);

if (response.headers["etag"]) {
return response.headers["etag"].replace(/"/g, "");
}
} catch (error) {
console.error(error);
}

return "";
Expand Down Expand Up @@ -87,11 +86,10 @@ class KubectlDownloader {
const file = fs.createWriteStream(this.path);

console.log(`Downloading kubectl ${this.kubectlVersion} from ${this.url} to ${this.path}`);
const requestOpts: request.UriOptions & request.CoreOptions = {
uri: this.url,
gzip: true
};
const stream = request(requestOpts);
const stream = got.stream({
url: this.url,
decompress: true,
});

stream.on("complete", () => {
console.log("kubectl binary download finished");
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -202,9 +202,11 @@
"filehound": "^1.17.4",
"fs-extra": "^9.0.1",
"glob-to-regexp": "^0.4.1",
"got": "^11.8.2",
"grapheme-splitter": "^1.0.4",
"handlebars": "^4.7.7",
"http-proxy": "^1.18.1",
"http-proxy-agent": "^5.0.0",
"immer": "^8.0.4",
"joi": "^17.4.2",
"js-yaml": "^3.14.0",
Expand Down Expand Up @@ -235,8 +237,6 @@
"react-router": "^5.2.0",
"react-virtualized-auto-sizer": "^1.0.6",
"readable-stream": "^3.6.0",
"request": "^2.88.2",
"request-promise-native": "^1.0.9",
"rfc6902": "^4.0.2",
"semver": "^7.3.2",
"serializr": "^2.0.5",
Expand Down
50 changes: 0 additions & 50 deletions src/common/request.ts

This file was deleted.

15 changes: 8 additions & 7 deletions src/common/utils/app-version.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import requestPromise from "request-promise-native";
import got from "got";
import packageInfo from "../../../package.json";

export function getAppVersion(): string {
Expand All @@ -30,13 +30,14 @@ export function getBundledKubectlVersion(): string {
return packageInfo.config.bundledKubectlVersion;
}

interface AppVersion {
version: string;
}

export async function getAppVersionFromProxyServer(proxyPort: number): Promise<string> {
const response = await requestPromise({
method: "GET",
uri: `http://127.0.0.1:${proxyPort}/version`,
resolveWithFullResponse: true,
proxy: undefined,
const { body } = await got<AppVersion>(`http://localhost:${proxyPort}/version`, {
responseType: "json",
});

return JSON.parse(response.body).version;
return body.version;
}
12 changes: 8 additions & 4 deletions src/common/utils/downloadFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import request from "request";
import got from "got";

export interface DownloadFileOptions {
url: string;
Expand All @@ -35,7 +35,11 @@ export interface DownloadFileTicket<T> {

export function downloadFile({ url, timeout, gzip = true }: DownloadFileOptions): DownloadFileTicket<Buffer> {
const fileChunks: Buffer[] = [];
const req = request(url, { gzip, timeout });
const req = got.stream({
url,
timeout,
decompress: gzip,
});
const promise: Promise<Buffer> = new Promise((resolve, reject) => {
req.on("data", (chunk: Buffer) => {
fileChunks.push(chunk);
Expand All @@ -52,8 +56,8 @@ export function downloadFile({ url, timeout, gzip = true }: DownloadFileOptions)
url,
promise,
cancel() {
req.abort();
}
req.destroy();
},
};
}

Expand Down
2 changes: 0 additions & 2 deletions src/main/__test__/cluster.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ jest.mock("winston", () => ({
jest.mock("../../common/ipc");
jest.mock("../context-handler");
jest.mock("request");
jest.mock("request-promise-native");

import { Console } from "console";
import mockFs from "mock-fs";
Expand Down Expand Up @@ -114,7 +113,6 @@ describe("create clusters", () => {
});

it("activating cluster should try to connect to cluster and do a refresh", async () => {

const c = new class extends Cluster {
// only way to mock protected methods, without these we leak promises
protected bindEvents() {
Expand Down
15 changes: 6 additions & 9 deletions src/main/cluster-detectors/base-cluster-detector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import type { RequestPromiseOptions } from "request-promise-native";
import type { OptionsOfJSONResponseBody } from "got";
import type { Cluster } from "../cluster";
import { k8sRequest } from "../k8s-request";

Expand All @@ -28,17 +28,14 @@ export type ClusterDetectionResult = {
accuracy: number
};

export class BaseClusterDetector {
key: string;
export abstract class BaseClusterDetector {
abstract key: string;

constructor(public cluster: Cluster) {
}
constructor(public cluster: Cluster) {}

detect(): Promise<ClusterDetectionResult> {
return null;
}
abstract detect(): Promise<ClusterDetectionResult>;

protected async k8sRequest<T = any>(path: string, options: RequestPromiseOptions = {}): Promise<T> {
protected async k8sRequest<T = any>(path: string, options: OptionsOfJSONResponseBody = {}): Promise<T> {
return k8sRequest(this.cluster, path, options);
}
}
48 changes: 27 additions & 21 deletions src/main/cluster-detectors/detector-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,43 +21,49 @@

import { observable } from "mobx";
import type { ClusterMetadata } from "../../common/cluster-types";
import { Singleton } from "../../common/utils";
import { iter, Singleton } from "../../common/utils";
import type { Cluster } from "../cluster";
import type { BaseClusterDetector, ClusterDetectionResult } from "./base-cluster-detector";

export type ClusterDetectionConstructor = new (cluster: Cluster) => BaseClusterDetector;

export class DetectorRegistry extends Singleton {
registry = observable.array<typeof BaseClusterDetector>([], { deep: false });
private registry = observable.array<ClusterDetectionConstructor>([], { deep: false });

add(detectorClass: typeof BaseClusterDetector): this {
add(detectorClass: ClusterDetectionConstructor): this {
this.registry.push(detectorClass);

return this;
}

async detectForCluster(cluster: Cluster): Promise<ClusterMetadata> {
const results: {[key: string]: ClusterDetectionResult } = {};
const results = new Map<string, ClusterDetectionResult>();
const detections = this.registry.map(async DetectorClass => {
const detector = new DetectorClass(cluster);

for (const detectorClass of this.registry) {
const detector = new detectorClass(cluster);
return [detector.key, await detector.detect()] as const;
});

for (const detection of detections) {
try {
const data = await detector.detect();

if (!data) continue;
const existingValue = results[detector.key];

if (existingValue && existingValue.accuracy > data.accuracy) continue; // previous value exists and is more accurate
results[detector.key] = data;
} catch (e) {
// detector raised error, do nothing
}
}
const metadata: ClusterMetadata = {};
const [key, data] = await detection;

for (const [key, result] of Object.entries(results)) {
metadata[key] = result.value;
if (
data && (
!results.has(key)
|| results.get(key).accuracy <= data.accuracy
)
) {
results.set(key, data);
}
} catch {} // ignore errors
}

return metadata;
return Object.fromEntries(
iter.map(
Object.entries(results),
([key, { value }]) => [key, value]
)
);
}
}

0 comments on commit c65f874

Please sign in to comment.