mirror of
https://github.com/lensapp/lens.git
synced 2025-05-20 05:10:56 +00:00
Release/v5.3.1 (#4465)
Co-authored-by: Roman <ixrock@gmail.com> Co-authored-by: Alex Andreev <alex.andreev.email@gmail.com> Co-authored-by: Juho Heikka <juho.heikka@gmail.com> Co-authored-by: Jan Jansen <farodin91@users.noreply.github.com>
This commit is contained in:
44 files changed
+635
-461
No files matched your search
@@ -23,7 +23,7 @@ import path from "path";
|
||||
import Config from "conf";
|
||||
import type { Options as ConfOptions } from "conf/dist/source/types";
|
||||
import { ipcMain, ipcRenderer } from "electron";
|
||||
import { IReactionOptions, makeObservable, reaction, runInAction } from "mobx";
|
||||
import { IEqualsComparer, makeObservable, reaction, runInAction } from "mobx";
|
||||
import { getAppVersion, Singleton, toJS, Disposer } from "./utils";
|
||||
import logger from "../main/logger";
|
||||
import { broadcastMessage, ipcMainOn, ipcRendererOn } from "./ipc";
|
||||
@@ -33,7 +33,10 @@ import { kebabCase } from "lodash";
|
||||
import { AppPaths } from "./app-paths";
|
||||
|
||||
export interface BaseStoreParams<T> extends ConfOptions<T> {
|
||||
syncOptions?: IReactionOptions;
|
||||
syncOptions?: {
|
||||
fireImmediately?: boolean;
|
||||
equals?: IEqualsComparer<T>;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -29,7 +29,6 @@ export default function configurePackages() {
|
||||
// Docs: https://mobx.js.org/configuration.html
|
||||
Mobx.configure({
|
||||
enforceActions: "never",
|
||||
isolateGlobalState: true,
|
||||
|
||||
// TODO: enable later (read more: https://mobx.js.org/migrating-from-4-or-5.html)
|
||||
// computedRequiresReaction: true,
|
||||
|
||||
@@ -230,6 +230,7 @@ export class HotbarStore extends BaseStore<HotbarStoreModel> {
|
||||
return index;
|
||||
}
|
||||
|
||||
@action
|
||||
restackItems(from: number, to: number): void {
|
||||
const { items } = this.getActive();
|
||||
const source = items[from];
|
||||
|
||||
@@ -25,6 +25,7 @@ import { KubeJsonApi } from "../kube-json-api";
|
||||
import { KubeObject } from "../kube-object";
|
||||
import AbortController from "abort-controller";
|
||||
import { delay } from "../../utils/delay";
|
||||
import { PassThrough } from "stream";
|
||||
|
||||
class TestKubeObject extends KubeObject {
|
||||
static kind = "Pod";
|
||||
@@ -133,7 +134,10 @@ describe("KubeApi", () => {
|
||||
checkPreferredVersion: true,
|
||||
});
|
||||
|
||||
await kubeApi.get();
|
||||
await kubeApi.get({
|
||||
name: "foo",
|
||||
namespace: "default",
|
||||
});
|
||||
expect(kubeApi.apiPrefix).toEqual("/apis");
|
||||
expect(kubeApi.apiGroup).toEqual("networking.k8s.io");
|
||||
});
|
||||
@@ -167,13 +171,15 @@ describe("KubeApi", () => {
|
||||
const fallbackApiBase = "/apis/extensions/v1beta1/ingresses";
|
||||
const kubeApi = new KubeApi({
|
||||
request,
|
||||
objectConstructor: KubeObject,
|
||||
apiBase,
|
||||
objectConstructor: Object.assign(KubeObject, { apiBase }),
|
||||
fallbackApiBases: [fallbackApiBase],
|
||||
checkPreferredVersion: true,
|
||||
});
|
||||
|
||||
await kubeApi.get();
|
||||
await kubeApi.get({
|
||||
name: "foo",
|
||||
namespace: "default",
|
||||
});
|
||||
expect(kubeApi.apiPrefix).toEqual("/apis");
|
||||
expect(kubeApi.apiGroup).toEqual("extensions");
|
||||
});
|
||||
@@ -298,21 +304,30 @@ describe("KubeApi", () => {
|
||||
|
||||
describe("watch", () => {
|
||||
let api: TestKubeApi;
|
||||
let stream: PassThrough;
|
||||
|
||||
beforeEach(() => {
|
||||
api = new TestKubeApi({
|
||||
request,
|
||||
objectConstructor: TestKubeObject,
|
||||
});
|
||||
stream = new PassThrough();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
stream.end();
|
||||
stream.destroy();
|
||||
});
|
||||
|
||||
it("sends a valid watch request", () => {
|
||||
const spy = jest.spyOn(request, "getResponse");
|
||||
|
||||
(fetch as any).mockResponse(async () => {
|
||||
return {};
|
||||
return {
|
||||
body: stream,
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
api.watch({ namespace: "kube-system" });
|
||||
expect(spy).toHaveBeenCalledWith("/api/v1/namespaces/kube-system/pods?watch=1&resourceVersion=", expect.anything(), expect.anything());
|
||||
});
|
||||
@@ -321,9 +336,11 @@ describe("KubeApi", () => {
|
||||
const spy = jest.spyOn(request, "getResponse");
|
||||
|
||||
(fetch as any).mockResponse(async () => {
|
||||
return {};
|
||||
return {
|
||||
body: stream,
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
api.watch({ namespace: "kube-system", timeout: 60 });
|
||||
expect(spy).toHaveBeenCalledWith("/api/v1/namespaces/kube-system/pods?watch=1&resourceVersion=", { query: { timeoutSeconds: 60 }}, expect.anything());
|
||||
});
|
||||
@@ -336,11 +353,13 @@ describe("KubeApi", () => {
|
||||
done();
|
||||
});
|
||||
|
||||
return {};
|
||||
return {
|
||||
body: stream,
|
||||
};
|
||||
});
|
||||
|
||||
const abortController = new AbortController();
|
||||
|
||||
|
||||
api.watch({
|
||||
namespace: "kube-system",
|
||||
timeout: 60,
|
||||
@@ -358,30 +377,32 @@ describe("KubeApi", () => {
|
||||
it("if request ended", (done) => {
|
||||
const spy = jest.spyOn(request, "getResponse");
|
||||
|
||||
jest.spyOn(stream, "on").mockImplementation((eventName: string, callback: Function) => {
|
||||
// End the request in 100ms.
|
||||
if (eventName === "end") {
|
||||
setTimeout(() => {
|
||||
callback();
|
||||
}, 100);
|
||||
}
|
||||
|
||||
return stream;
|
||||
});
|
||||
|
||||
// we need to mock using jest as jest-fetch-mock doesn't support mocking the body completely
|
||||
jest.spyOn(global, "fetch").mockImplementation(async () => {
|
||||
return {
|
||||
ok: true,
|
||||
body: {
|
||||
on: (eventName: string, callback: Function) => {
|
||||
// End the request in 100ms.
|
||||
if (eventName === "end") {
|
||||
setTimeout(() => {
|
||||
callback();
|
||||
}, 100);
|
||||
}
|
||||
},
|
||||
},
|
||||
body: stream,
|
||||
} as any;
|
||||
});
|
||||
|
||||
|
||||
api.watch({
|
||||
namespace: "kube-system",
|
||||
});
|
||||
|
||||
expect(spy).toHaveBeenCalledTimes(1);
|
||||
|
||||
setTimeout(() => {
|
||||
setTimeout(() => {
|
||||
expect(spy).toHaveBeenCalledTimes(2);
|
||||
done();
|
||||
}, 2000);
|
||||
@@ -391,11 +412,13 @@ describe("KubeApi", () => {
|
||||
const spy = jest.spyOn(request, "getResponse");
|
||||
|
||||
(fetch as any).mockResponse(async () => {
|
||||
return {};
|
||||
return {
|
||||
body: stream,
|
||||
};
|
||||
});
|
||||
|
||||
const timeoutSeconds = 1;
|
||||
|
||||
|
||||
api.watch({
|
||||
namespace: "kube-system",
|
||||
timeout: timeoutSeconds,
|
||||
@@ -403,7 +426,7 @@ describe("KubeApi", () => {
|
||||
|
||||
expect(spy).toHaveBeenCalledTimes(1);
|
||||
|
||||
setTimeout(() => {
|
||||
setTimeout(() => {
|
||||
expect(spy).toHaveBeenCalledTimes(2);
|
||||
done();
|
||||
}, timeoutSeconds * 1000 * 1.2);
|
||||
@@ -412,25 +435,27 @@ describe("KubeApi", () => {
|
||||
it("retries only once if request ends and timeout is set", (done) => {
|
||||
const spy = jest.spyOn(request, "getResponse");
|
||||
|
||||
jest.spyOn(stream, "on").mockImplementation((eventName: string, callback: Function) => {
|
||||
// End the request in 100ms.
|
||||
if (eventName === "end") {
|
||||
setTimeout(() => {
|
||||
callback();
|
||||
}, 100);
|
||||
}
|
||||
|
||||
return stream;
|
||||
});
|
||||
|
||||
// we need to mock using jest as jest-fetch-mock doesn't support mocking the body completely
|
||||
jest.spyOn(global, "fetch").mockImplementation(async () => {
|
||||
return {
|
||||
ok: true,
|
||||
body: {
|
||||
on: (eventName: string, callback: Function) => {
|
||||
// End the request in 100ms
|
||||
if (eventName === "end") {
|
||||
setTimeout(() => {
|
||||
callback();
|
||||
}, 100);
|
||||
}
|
||||
},
|
||||
},
|
||||
body: stream,
|
||||
} as any;
|
||||
});
|
||||
|
||||
|
||||
const timeoutSeconds = 0.5;
|
||||
|
||||
|
||||
api.watch({
|
||||
namespace: "kube-system",
|
||||
timeout: timeoutSeconds,
|
||||
@@ -438,7 +463,7 @@ describe("KubeApi", () => {
|
||||
|
||||
expect(spy).toHaveBeenCalledTimes(1);
|
||||
|
||||
setTimeout(() => {
|
||||
setTimeout(() => {
|
||||
expect(spy).toHaveBeenCalledTimes(2);
|
||||
done();
|
||||
}, 2000);
|
||||
|
||||
@@ -25,4 +25,5 @@ export interface ClusterContext {
|
||||
cluster?: Cluster;
|
||||
allNamespaces: string[]; // available / allowed namespaces from cluster.ts
|
||||
contextNamespaces: string[]; // selected by user (see: namespace-select.tsx)
|
||||
hasSelectedAll: boolean;
|
||||
}
|
||||
@@ -21,7 +21,6 @@
|
||||
|
||||
// Base class for building all kubernetes apis
|
||||
|
||||
import merge from "lodash/merge";
|
||||
import { isFunction } from "lodash";
|
||||
import { stringify } from "querystring";
|
||||
import { apiKubePrefix, isDevelopment } from "../../common/vars";
|
||||
@@ -221,6 +220,29 @@ const patchTypeHeaders: Record<KubeApiPatchType, string> = {
|
||||
"strategic": "application/strategic-merge-patch+json",
|
||||
};
|
||||
|
||||
export interface ResourceDescriptor {
|
||||
/**
|
||||
* The name of the kubernetes resource
|
||||
*/
|
||||
name: string;
|
||||
|
||||
/**
|
||||
* The namespace that the resource lives in (if the resource is namespaced)
|
||||
*
|
||||
* Note: if not provided and the resource kind is namespaced, then this defaults to `"default"`
|
||||
*/
|
||||
namespace?: string;
|
||||
}
|
||||
|
||||
export interface DeleteResourceDescriptor extends ResourceDescriptor {
|
||||
/**
|
||||
* This determinines how child resources should be handled by kubernetes
|
||||
*
|
||||
* @default "Background"
|
||||
*/
|
||||
propagationPolicy?: PropagationPolicy;
|
||||
}
|
||||
|
||||
export class KubeApi<T extends KubeObject> {
|
||||
readonly kind: string;
|
||||
readonly apiBase: string;
|
||||
@@ -273,14 +295,18 @@ export class KubeApi<T extends KubeObject> {
|
||||
*/
|
||||
private async getLatestApiPrefixGroup() {
|
||||
// Note that this.options.apiBase is the "full" url, whereas this.apiBase is parsed
|
||||
const apiBases = [this.options.apiBase, ...this.options.fallbackApiBases];
|
||||
const apiBases = [this.options.apiBase, this.objectConstructor.apiBase, ...this.options.fallbackApiBases];
|
||||
|
||||
for (const apiUrl of apiBases) {
|
||||
// Split e.g. "/apis/extensions/v1beta1/ingresses" to parts
|
||||
const { apiPrefix, apiGroup, apiVersionWithGroup, resource } = parseKubeApi(apiUrl);
|
||||
if (!apiUrl) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Request available resources
|
||||
try {
|
||||
// Split e.g. "/apis/extensions/v1beta1/ingresses" to parts
|
||||
const { apiPrefix, apiGroup, apiVersionWithGroup, resource } = parseKubeApi(apiUrl);
|
||||
|
||||
// Request available resources
|
||||
const response = await this.request.get<IKubeResourceList>(`${apiPrefix}/${apiVersionWithGroup}`);
|
||||
|
||||
// If the resource is found in the group, use this apiUrl
|
||||
@@ -304,7 +330,7 @@ export class KubeApi<T extends KubeObject> {
|
||||
return await this.getLatestApiPrefixGroup();
|
||||
} catch (error) {
|
||||
// If valid API wasn't found, log the error and return defaults below
|
||||
logger.error(error);
|
||||
logger.error(`[KUBE-API]: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -355,12 +381,12 @@ export class KubeApi<T extends KubeObject> {
|
||||
return this.list(params, { limit: 1 });
|
||||
}
|
||||
|
||||
getUrl({ name = "", namespace = "" } = {}, query?: Partial<IKubeApiQueryParams>) {
|
||||
getUrl({ name, namespace = "default" }: Partial<ResourceDescriptor> = {}, query?: Partial<IKubeApiQueryParams>) {
|
||||
const resourcePath = createKubeApiURL({
|
||||
apiPrefix: this.apiPrefix,
|
||||
apiVersion: this.apiVersionWithGroup,
|
||||
resource: this.apiResource,
|
||||
namespace: this.isNamespaced ? namespace : undefined,
|
||||
namespace: this.isNamespaced ? namespace ?? "default" : undefined,
|
||||
name,
|
||||
});
|
||||
|
||||
@@ -438,10 +464,10 @@ export class KubeApi<T extends KubeObject> {
|
||||
throw new Error(`GET multiple request to ${url} returned not an array: ${JSON.stringify(parsed)}`);
|
||||
}
|
||||
|
||||
async get({ name = "", namespace = "default" } = {}, query?: IKubeApiQueryParams): Promise<T | null> {
|
||||
async get(desc: ResourceDescriptor, query?: IKubeApiQueryParams): Promise<T | null> {
|
||||
await this.checkPreferredVersion();
|
||||
|
||||
const url = this.getUrl({ namespace, name });
|
||||
const url = this.getUrl(desc);
|
||||
const res = await this.request.get(url, { query });
|
||||
const parsed = this.parseResponse(res);
|
||||
|
||||
@@ -452,19 +478,18 @@ export class KubeApi<T extends KubeObject> {
|
||||
return parsed;
|
||||
}
|
||||
|
||||
async create({ name = "", namespace = "default" } = {}, data?: Partial<T>): Promise<T | null> {
|
||||
async create({ name, namespace }: Partial<ResourceDescriptor>, data?: Partial<T>): Promise<T | null> {
|
||||
await this.checkPreferredVersion();
|
||||
|
||||
const apiUrl = this.getUrl({ namespace });
|
||||
const res = await this.request.post(apiUrl, {
|
||||
data: merge({
|
||||
kind: this.kind,
|
||||
apiVersion: this.apiVersionWithGroup,
|
||||
data: {
|
||||
...data,
|
||||
metadata: {
|
||||
name,
|
||||
namespace,
|
||||
},
|
||||
}, data),
|
||||
},
|
||||
});
|
||||
const parsed = this.parseResponse(res);
|
||||
|
||||
@@ -475,11 +500,19 @@ export class KubeApi<T extends KubeObject> {
|
||||
return parsed;
|
||||
}
|
||||
|
||||
async update({ name = "", namespace = "default" } = {}, data?: Partial<T>): Promise<T | null> {
|
||||
async update({ name, namespace }: ResourceDescriptor, data: Partial<T>): Promise<T | null> {
|
||||
await this.checkPreferredVersion();
|
||||
const apiUrl = this.getUrl({ namespace, name });
|
||||
|
||||
const res = await this.request.put(apiUrl, { data });
|
||||
const res = await this.request.put(apiUrl, {
|
||||
data: {
|
||||
...data,
|
||||
metadata: {
|
||||
name,
|
||||
namespace,
|
||||
},
|
||||
},
|
||||
});
|
||||
const parsed = this.parseResponse(res);
|
||||
|
||||
if (Array.isArray(parsed)) {
|
||||
@@ -489,9 +522,9 @@ export class KubeApi<T extends KubeObject> {
|
||||
return parsed;
|
||||
}
|
||||
|
||||
async patch({ name = "", namespace = "default" } = {}, data?: Partial<T> | Patch, strategy: KubeApiPatchType = "strategic"): Promise<T | null> {
|
||||
async patch(desc: ResourceDescriptor, data?: Partial<T> | Patch, strategy: KubeApiPatchType = "strategic"): Promise<T | null> {
|
||||
await this.checkPreferredVersion();
|
||||
const apiUrl = this.getUrl({ namespace, name });
|
||||
const apiUrl = this.getUrl(desc);
|
||||
|
||||
const res = await this.request.patch(apiUrl, { data }, {
|
||||
headers: {
|
||||
@@ -507,16 +540,15 @@ export class KubeApi<T extends KubeObject> {
|
||||
return parsed;
|
||||
}
|
||||
|
||||
async delete({ name = "", namespace = "default", propagationPolicy = "Background" }: { name: string, namespace?: string, propagationPolicy?: PropagationPolicy }) {
|
||||
async delete({ propagationPolicy = "Background", ...desc }: DeleteResourceDescriptor) {
|
||||
await this.checkPreferredVersion();
|
||||
const apiUrl = this.getUrl({ namespace, name });
|
||||
const reqInit = {
|
||||
const apiUrl = this.getUrl(desc);
|
||||
|
||||
return this.request.del(apiUrl, {
|
||||
query: {
|
||||
propagationPolicy,
|
||||
},
|
||||
};
|
||||
|
||||
return this.request.del(apiUrl, reqInit);
|
||||
});
|
||||
}
|
||||
|
||||
getWatchUrl(namespace = "", query: IKubeApiQueryParams = {}) {
|
||||
|
||||
@@ -33,9 +33,8 @@ import type { RequestInit } from "node-fetch";
|
||||
import AbortController from "abort-controller";
|
||||
import type { Patch } from "rfc6902";
|
||||
|
||||
export interface KubeObjectStoreLoadingParams<K extends KubeObject> {
|
||||
export interface KubeObjectStoreLoadingParams {
|
||||
namespaces: string[];
|
||||
api?: KubeApi<K>;
|
||||
reqInit?: RequestInit;
|
||||
|
||||
/**
|
||||
@@ -63,6 +62,11 @@ export interface KubeObjectStoreSubscribeParams {
|
||||
* being rejected with
|
||||
*/
|
||||
onLoadFailure?: (err: any) => void;
|
||||
|
||||
/**
|
||||
* An optional parent abort controller
|
||||
*/
|
||||
abortController?: AbortController;
|
||||
}
|
||||
|
||||
export abstract class KubeObjectStore<T extends KubeObject> extends ItemStore<T> {
|
||||
@@ -167,8 +171,8 @@ export abstract class KubeObjectStore<T extends KubeObject> extends ItemStore<T>
|
||||
}
|
||||
}
|
||||
|
||||
protected async loadItems({ namespaces, api, reqInit, onLoadFailure }: KubeObjectStoreLoadingParams<T>): Promise<T[]> {
|
||||
if (!this.context?.cluster.isAllowedResource(api.kind)) {
|
||||
protected async loadItems({ namespaces, reqInit, onLoadFailure }: KubeObjectStoreLoadingParams): Promise<T[]> {
|
||||
if (!this.context?.cluster.isAllowedResource(this.api.kind)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -176,12 +180,12 @@ export abstract class KubeObjectStore<T extends KubeObject> extends ItemStore<T>
|
||||
&& this.context.cluster.accessibleNamespaces.length === 0
|
||||
&& this.context.allNamespaces.every(ns => namespaces.includes(ns));
|
||||
|
||||
if (!api.isNamespaced || isLoadingAll) {
|
||||
if (api.isNamespaced) {
|
||||
if (!this.api.isNamespaced || isLoadingAll) {
|
||||
if (this.api.isNamespaced) {
|
||||
this.loadedNamespaces = [];
|
||||
}
|
||||
|
||||
const res = api.list({ reqInit }, this.query);
|
||||
const res = this.api.list({ reqInit }, this.query);
|
||||
|
||||
if (onLoadFailure) {
|
||||
try {
|
||||
@@ -203,7 +207,7 @@ export abstract class KubeObjectStore<T extends KubeObject> extends ItemStore<T>
|
||||
this.loadedNamespaces = namespaces;
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
namespaces.map(namespace => api.list({ namespace, reqInit }, this.query)),
|
||||
namespaces.map(namespace => this.api.list({ namespace, reqInit }, this.query)),
|
||||
);
|
||||
const res: T[] = [];
|
||||
|
||||
@@ -215,7 +219,7 @@ export abstract class KubeObjectStore<T extends KubeObject> extends ItemStore<T>
|
||||
|
||||
case "rejected":
|
||||
if (onLoadFailure) {
|
||||
onLoadFailure(result.reason.message);
|
||||
onLoadFailure(result.reason.message || result.reason);
|
||||
} else {
|
||||
// if onLoadFailure is not provided then preserve old behaviour
|
||||
throw result.reason;
|
||||
@@ -231,24 +235,14 @@ export abstract class KubeObjectStore<T extends KubeObject> extends ItemStore<T>
|
||||
}
|
||||
|
||||
@action
|
||||
async loadAll(options: KubeObjectStoreLoadAllParams = {}): Promise<void | T[]> {
|
||||
async loadAll({ namespaces = this.context.contextNamespaces, merge = true, reqInit, onLoadFailure }: KubeObjectStoreLoadAllParams = {}): Promise<void | T[]> {
|
||||
await this.contextReady;
|
||||
this.isLoading = true;
|
||||
const {
|
||||
namespaces = this.context.allNamespaces, // load all namespaces by default
|
||||
merge = true, // merge loaded items or return as result
|
||||
reqInit,
|
||||
onLoadFailure,
|
||||
} = options;
|
||||
|
||||
try {
|
||||
const items = await this.loadItems({ namespaces, api: this.api, reqInit, onLoadFailure });
|
||||
const items = await this.loadItems({ namespaces, reqInit, onLoadFailure });
|
||||
|
||||
if (merge) {
|
||||
this.mergeItems(items, { replace: false });
|
||||
} else {
|
||||
this.mergeItems(items, { replace: true });
|
||||
}
|
||||
this.mergeItems(items, { merge });
|
||||
|
||||
this.isLoaded = true;
|
||||
this.failedLoading = false;
|
||||
@@ -275,11 +269,11 @@ export abstract class KubeObjectStore<T extends KubeObject> extends ItemStore<T>
|
||||
}
|
||||
|
||||
@action
|
||||
protected mergeItems(partialItems: T[], { replace = false, updateStore = true, sort = true, filter = true } = {}): T[] {
|
||||
protected mergeItems(partialItems: T[], { merge = true, updateStore = true, sort = true, filter = true } = {}): T[] {
|
||||
let items = partialItems;
|
||||
|
||||
// update existing items
|
||||
if (!replace) {
|
||||
if (merge) {
|
||||
const namespaces = partialItems.map(item => item.getNs());
|
||||
|
||||
items = [
|
||||
@@ -369,7 +363,8 @@ export abstract class KubeObjectStore<T extends KubeObject> extends ItemStore<T>
|
||||
return this.postUpdate(
|
||||
await this.api.update(
|
||||
{
|
||||
name: item.getName(), namespace: item.getNs(),
|
||||
name: item.getName(),
|
||||
namespace: item.getNs(),
|
||||
},
|
||||
data,
|
||||
),
|
||||
@@ -394,23 +389,21 @@ export abstract class KubeObjectStore<T extends KubeObject> extends ItemStore<T>
|
||||
});
|
||||
}
|
||||
|
||||
subscribe(opts: KubeObjectStoreSubscribeParams = {}) {
|
||||
const abortController = new AbortController();
|
||||
|
||||
subscribe({ onLoadFailure, abortController = new AbortController() }: KubeObjectStoreSubscribeParams = {}) {
|
||||
if (this.api.isNamespaced) {
|
||||
Promise.race([rejectPromiseBy(abortController.signal), Promise.all([this.contextReady, this.namespacesReady])])
|
||||
.then(() => {
|
||||
if (this.context.cluster.isGlobalWatchEnabled && this.loadedNamespaces.length === 0) {
|
||||
return this.watchNamespace("", abortController, opts);
|
||||
return this.watchNamespace("", abortController, { onLoadFailure });
|
||||
}
|
||||
|
||||
for (const namespace of this.loadedNamespaces) {
|
||||
this.watchNamespace(namespace, abortController, opts);
|
||||
this.watchNamespace(namespace, abortController, { onLoadFailure });
|
||||
}
|
||||
})
|
||||
.catch(noop); // ignore DOMExceptions
|
||||
} else {
|
||||
this.watchNamespace("", abortController, opts);
|
||||
this.watchNamespace("", abortController, { onLoadFailure });
|
||||
}
|
||||
|
||||
return () => abortController.abort();
|
||||
|
||||
@@ -105,8 +105,9 @@ export class KubeCreationError extends Error {
|
||||
}
|
||||
|
||||
export class KubeObject<Metadata extends KubeObjectMetadata = KubeObjectMetadata, Status = any, Spec = any> implements ItemObject {
|
||||
static readonly kind: string;
|
||||
static readonly namespaced: boolean;
|
||||
static readonly kind?: string;
|
||||
static readonly namespaced?: boolean;
|
||||
static readonly apiBase?: string;
|
||||
|
||||
apiVersion: string;
|
||||
kind: string;
|
||||
@@ -215,7 +216,7 @@ export class KubeObject<Metadata extends KubeObjectMetadata = KubeObjectMetadata
|
||||
]);
|
||||
|
||||
constructor(data: KubeJsonApiData) {
|
||||
if (typeof data !== "object") {
|
||||
if (typeof data !== "object") {
|
||||
throw new TypeError(`Cannot create a KubeObject from ${typeof data}`);
|
||||
}
|
||||
|
||||
@@ -329,9 +330,9 @@ export class KubeObject<Metadata extends KubeObjectMetadata = KubeObjectMetadata
|
||||
* Perform a full update (or more specifically a replace)
|
||||
*
|
||||
* Note: this is brittle if `data` is not actually partial (but instead whole).
|
||||
* As fields such as `resourceVersion` will probably out of date. This is a
|
||||
* As fields such as `resourceVersion` will probably out of date. This is a
|
||||
* common race condition.
|
||||
*
|
||||
*
|
||||
* @deprecated use KubeApi.update instead
|
||||
*/
|
||||
async update(data: Partial<this>): Promise<KubeJsonApiData | null> {
|
||||
|
||||
@@ -25,32 +25,36 @@
|
||||
import type { KubeObjectStore } from "./kube-object.store";
|
||||
import type { ClusterContext } from "./cluster-context";
|
||||
|
||||
import plimit from "p-limit";
|
||||
import { comparer, observable, reaction, makeObservable } from "mobx";
|
||||
import { autoBind, disposer, Disposer, noop } from "../utils";
|
||||
import type { KubeApi } from "./kube-api";
|
||||
import { comparer, reaction } from "mobx";
|
||||
import { disposer, Disposer, noop } from "../utils";
|
||||
import type { KubeJsonApiData } from "./kube-json-api";
|
||||
import { isDebugging, isProduction } from "../vars";
|
||||
import type { KubeObject } from "./kube-object";
|
||||
import AbortController from "abort-controller";
|
||||
import { once } from "lodash";
|
||||
import logger from "../logger";
|
||||
|
||||
class WrappedAbortController extends AbortController {
|
||||
constructor(protected parent: AbortController) {
|
||||
super();
|
||||
|
||||
parent.signal.addEventListener("abort", () => {
|
||||
this.abort();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export interface IKubeWatchEvent<T extends KubeJsonApiData> {
|
||||
type: "ADDED" | "MODIFIED" | "DELETED" | "ERROR";
|
||||
object?: T;
|
||||
}
|
||||
|
||||
interface KubeWatchPreloadOptions {
|
||||
export interface KubeWatchSubscribeStoreOptions {
|
||||
/**
|
||||
* The namespaces to watch
|
||||
* @default all-accessible
|
||||
* @default all selected namespaces
|
||||
*/
|
||||
namespaces?: string[];
|
||||
|
||||
/**
|
||||
* Whether to skip loading if the store is already loaded
|
||||
* @default false
|
||||
*/
|
||||
loadOnce?: boolean;
|
||||
|
||||
/**
|
||||
* A function that is called when listing fails. If set then blocks errors
|
||||
* being rejected with
|
||||
@@ -58,123 +62,148 @@ interface KubeWatchPreloadOptions {
|
||||
onLoadFailure?: (err: any) => void;
|
||||
}
|
||||
|
||||
export interface KubeWatchSubscribeStoreOptions extends KubeWatchPreloadOptions {
|
||||
/**
|
||||
* Whether to subscribe only after loading all stores
|
||||
* @default true
|
||||
*/
|
||||
waitUntilLoaded?: boolean;
|
||||
|
||||
/**
|
||||
* Whether to preload the stores before watching
|
||||
* @default true
|
||||
*/
|
||||
preload?: boolean;
|
||||
}
|
||||
|
||||
export interface IKubeWatchLog {
|
||||
message: string | string[] | Error;
|
||||
meta?: object;
|
||||
cssStyle?: string;
|
||||
}
|
||||
|
||||
interface SubscribeStoreParams {
|
||||
store: KubeObjectStore<KubeObject>;
|
||||
parent: AbortController;
|
||||
watchChanges: boolean;
|
||||
namespaces: string[];
|
||||
onLoadFailure?: (err: any) => void;
|
||||
}
|
||||
|
||||
class WatchCount {
|
||||
#data = new Map<KubeObjectStore<KubeObject>, number>();
|
||||
|
||||
public inc(store: KubeObjectStore<KubeObject>): number {
|
||||
if (!this.#data.has(store)) {
|
||||
this.#data.set(store, 0);
|
||||
}
|
||||
|
||||
const newCount = this.#data.get(store) + 1;
|
||||
|
||||
logger.info(`[KUBE-WATCH-API]: inc() count for ${store.api.objectConstructor.apiBase} is now ${newCount}`);
|
||||
this.#data.set(store, newCount);
|
||||
|
||||
return newCount;
|
||||
}
|
||||
|
||||
public dec(store: KubeObjectStore<KubeObject>): number {
|
||||
if (!this.#data.has(store)) {
|
||||
throw new Error(`Cannot dec count for store that has never been inc: ${store.api.objectConstructor.kind}`);
|
||||
}
|
||||
|
||||
const newCount = this.#data.get(store) - 1;
|
||||
|
||||
if (newCount < 0) {
|
||||
throw new Error(`Cannot dec count more times than it has been inc: ${store.api.objectConstructor.kind}`);
|
||||
}
|
||||
|
||||
logger.debug(`[KUBE-WATCH-API]: dec() count for ${store.api.objectConstructor.apiBase} is now ${newCount}`);
|
||||
this.#data.set(store, newCount);
|
||||
|
||||
return newCount;
|
||||
}
|
||||
}
|
||||
|
||||
export class KubeWatchApi {
|
||||
@observable context: ClusterContext = null;
|
||||
static context: ClusterContext = null;
|
||||
|
||||
constructor() {
|
||||
makeObservable(this);
|
||||
autoBind(this);
|
||||
}
|
||||
#watch = new WatchCount();
|
||||
|
||||
isAllowedApi(api: KubeApi<KubeObject>): boolean {
|
||||
return Boolean(this.context?.cluster.isAllowedResource(api.kind));
|
||||
}
|
||||
|
||||
preloadStores(stores: KubeObjectStore<KubeObject>[], { loadOnce, namespaces, onLoadFailure }: KubeWatchPreloadOptions = {}) {
|
||||
const limitRequests = plimit(1); // load stores one by one to allow quick skipping when fast clicking btw pages
|
||||
const preloading: Promise<any>[] = [];
|
||||
|
||||
for (const store of stores) {
|
||||
preloading.push(limitRequests(async () => {
|
||||
if (store.isLoaded && loadOnce) return; // skip
|
||||
|
||||
return store.loadAll({ namespaces, onLoadFailure });
|
||||
}));
|
||||
private subscribeStore({ store, parent, watchChanges, namespaces, onLoadFailure }: SubscribeStoreParams): Disposer {
|
||||
if (this.#watch.inc(store) > 1) {
|
||||
// don't load or subscribe to a store more than once
|
||||
return () => this.#watch.dec(store);
|
||||
}
|
||||
|
||||
return {
|
||||
loading: Promise.allSettled(preloading),
|
||||
cancelLoading: () => limitRequests.clearQueue(),
|
||||
};
|
||||
}
|
||||
let childController = new WrappedAbortController(parent);
|
||||
const unsubscribe = disposer();
|
||||
|
||||
subscribeStores(stores: KubeObjectStore<KubeObject>[], opts: KubeWatchSubscribeStoreOptions = {}): Disposer {
|
||||
const { preload = true, waitUntilLoaded = true, loadOnce = false, onLoadFailure } = opts;
|
||||
const subscribingNamespaces = opts.namespaces ?? this.context?.allNamespaces ?? [];
|
||||
const unsubscribeStores = disposer();
|
||||
let isUnsubscribed = false;
|
||||
|
||||
const load = (namespaces = subscribingNamespaces) => this.preloadStores(stores, { namespaces, loadOnce, onLoadFailure });
|
||||
let preloading = preload && load();
|
||||
let cancelReloading: Disposer = noop;
|
||||
|
||||
const subscribe = () => {
|
||||
if (isUnsubscribed) {
|
||||
return;
|
||||
}
|
||||
|
||||
unsubscribeStores.push(...stores.map(store => store.subscribe({ onLoadFailure })));
|
||||
};
|
||||
|
||||
if (preloading) {
|
||||
if (waitUntilLoaded) {
|
||||
preloading.loading.then(subscribe, error => {
|
||||
this.log({
|
||||
message: new Error("Loading stores has failed"),
|
||||
meta: { stores, error, options: opts },
|
||||
const loadThenSubscribe = async (namespaces: string[]) => {
|
||||
try {
|
||||
await store.loadAll({ namespaces, reqInit: { signal: childController.signal }, onLoadFailure });
|
||||
unsubscribe.push(store.subscribe({ onLoadFailure, abortController: childController }));
|
||||
} catch (error) {
|
||||
if (!(error instanceof DOMException)) {
|
||||
this.log(Object.assign(new Error("Loading stores has failed"), { cause: error }), {
|
||||
meta: { store, namespaces },
|
||||
});
|
||||
});
|
||||
} else {
|
||||
subscribe();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// reload stores only for context namespaces change
|
||||
cancelReloading = reaction(() => this.context?.contextNamespaces, namespaces => {
|
||||
preloading?.cancelLoading();
|
||||
unsubscribeStores();
|
||||
preloading = load(namespaces);
|
||||
preloading.loading.then(subscribe);
|
||||
}, {
|
||||
equals: comparer.shallow,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* We don't want to wait because we want to start reacting to namespace
|
||||
* selection changes ASAP
|
||||
*/
|
||||
loadThenSubscribe(namespaces).catch(noop);
|
||||
|
||||
const cancelReloading = watchChanges
|
||||
? reaction(
|
||||
// Note: must slice because reaction won't fire if it isn't there
|
||||
() => [KubeWatchApi.context.contextNamespaces.slice(), KubeWatchApi.context.hasSelectedAll] as const,
|
||||
([namespaces, curSelectedAll], [prevNamespaces, prevSelectedAll]) => {
|
||||
if (curSelectedAll && prevSelectedAll) {
|
||||
const action = namespaces.length > prevNamespaces.length ? "created" : "deleted";
|
||||
|
||||
return console.debug(`[KUBE-WATCH-API]: Not changing watch for ${store.api.apiBase} because a new namespace was ${action} but all namespaces are selected`);
|
||||
}
|
||||
|
||||
console.log(`[KUBE-WATCH-API]: changing watch ${store.api.apiBase}`, namespaces);
|
||||
childController.abort();
|
||||
unsubscribe();
|
||||
childController = new WrappedAbortController(parent);
|
||||
loadThenSubscribe(namespaces).catch(noop);
|
||||
},
|
||||
{
|
||||
equals: comparer.shallow,
|
||||
},
|
||||
)
|
||||
: noop; // don't watch namespaces if namespaces were provided
|
||||
|
||||
return () => {
|
||||
if (this.#watch.dec(store) === 0) {
|
||||
// only stop the subcribe if this is the last one
|
||||
cancelReloading();
|
||||
childController.abort();
|
||||
unsubscribe();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
subscribeStores(stores: KubeObjectStore<KubeObject>[], { namespaces, onLoadFailure }: KubeWatchSubscribeStoreOptions = {}): Disposer {
|
||||
const parent = new AbortController();
|
||||
const unsubscribe = disposer(
|
||||
...stores.map(store => this.subscribeStore({
|
||||
store,
|
||||
parent,
|
||||
watchChanges: !namespaces && store.api.isNamespaced,
|
||||
namespaces: namespaces ?? KubeWatchApi.context?.contextNamespaces ?? [],
|
||||
onLoadFailure,
|
||||
})),
|
||||
);
|
||||
|
||||
// unsubscribe
|
||||
return () => {
|
||||
if (isUnsubscribed) return;
|
||||
isUnsubscribed = true;
|
||||
cancelReloading();
|
||||
preloading?.cancelLoading();
|
||||
unsubscribeStores();
|
||||
};
|
||||
return once(() => {
|
||||
parent.abort();
|
||||
unsubscribe();
|
||||
});
|
||||
}
|
||||
|
||||
protected log({ message, cssStyle = "", meta = {}}: IKubeWatchLog) {
|
||||
if (isProduction && !isDebugging) {
|
||||
return;
|
||||
}
|
||||
protected log(message: any, meta: any) {
|
||||
const log = message instanceof Error
|
||||
? console.error
|
||||
: console.debug;
|
||||
|
||||
const logInfo = [`%c[KUBE-WATCH-API]:`, `font-weight: bold; ${cssStyle}`, message].flat().map(String);
|
||||
const logMeta = {
|
||||
log("[KUBE-WATCH-API]:", message, {
|
||||
time: new Date().toLocaleString(),
|
||||
...meta,
|
||||
};
|
||||
|
||||
if (message instanceof Error) {
|
||||
console.error(...logInfo, logMeta);
|
||||
} else {
|
||||
console.info(...logInfo, logMeta);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user