Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove request and request-promise-native in favour of got #3974

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
36 changes: 17 additions & 19 deletions build/download_kubectl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,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 @@ -28,14 +27,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 @@ -71,11 +70,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
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@
"got": "^11.8.3",
"grapheme-splitter": "^1.0.4",
"handlebars": "^4.7.7",
"hpagent": "^0.1.2",
"http-proxy": "^1.18.1",
"immer": "^9.0.6",
"joi": "^17.5.0",
Expand Down Expand Up @@ -246,8 +247,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",
"shell-env": "^3.0.1",
Expand Down
34 changes: 0 additions & 34 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 @@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/

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

export function getAppVersion(): string {
Expand All @@ -14,13 +14,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;
}
10 changes: 7 additions & 3 deletions src/common/utils/downloadFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/

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

export interface DownloadFileOptions {
url: string;
Expand All @@ -19,7 +19,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 @@ -36,7 +40,7 @@ export function downloadFile({ url, timeout, gzip = true }: DownloadFileOptions)
url,
promise,
cancel() {
req.abort();
req.destroy();
},
};
}
Expand Down
1 change: 0 additions & 1 deletion src/main/__test__/cluster.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ jest.mock("winston", () => ({

jest.mock("../../common/ipc");
jest.mock("request");
jest.mock("request-promise-native");

import { Console } from "console";
import mockFs from "mock-fs";
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 @@ -3,26 +3,23 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/

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

export type ClusterDetectionResult = {
value: string | number | boolean
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);
}
}
50 changes: 29 additions & 21 deletions src/main/cluster-detectors/detector-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,43 +5,51 @@

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 "../../common/cluster/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;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What means as const and why do we need it here?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions

It is the way to say that you want a tuple of distinct types instead of an array of the union of all possible types.

});

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 [key, data] = await detection;

if (
data && (
!results.has(key)
|| results.get(key).accuracy <= data.accuracy
)
) {
results.set(key, data);
}
} catch {
// ignore errors
}
}
const metadata: ClusterMetadata = {};

for (const [key, result] of Object.entries(results)) {
metadata[key] = result.value;
}

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