Cascade different refactorings to eliminate global shared state from app paths

Co-authored-by: Mikko Aspiala <mikko.aspiala@gmail.com>

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>
This commit is contained in:
Janne SavolainenandMikko Aspiala committed 2022-01-05 13:26:49 +02:00
1 parent 908a40975e
commit 9d33fff906
336 files changed
+9105 -3307

No files matched your search

+1 -1
View File
@@ -19,7 +19,7 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import type { Cluster } from "../../main/cluster";
import type { Cluster } from "../cluster/cluster";
export interface ClusterContext {
cluster?: Cluster;
+1 -1
View File
@@ -23,7 +23,7 @@ import { JsonApi } from "./json-api";
import { KubeJsonApi } from "./kube-json-api";
import { apiKubePrefix, apiPrefix, isDebugging, isDevelopment } from "../../common/vars";
import { isClusterPageContext } from "../utils/cluster-id-url-parsing";
import { appEventBus } from "../event-bus";
import { appEventBus } from "../app-event-bus/event-bus";
let apiBase: JsonApi;
let apiKube: KubeJsonApi;
+1 -1
View File
@@ -30,7 +30,7 @@ import { apiBase, apiKube } from "./index";
import { createKubeApiURL, parseKubeApi } from "./kube-api-parse";
import { KubeObjectConstructor, KubeObject, KubeStatus } from "./kube-object";
import byline from "byline";
import type { IKubeWatchEvent } from "./kube-watch-api";
import type { IKubeWatchEvent } from "./kube-watch-event";
import { KubeJsonApi, KubeJsonApiData } from "./kube-json-api";
import { noop } from "../utils";
import type { RequestInit } from "node-fetch";
+3 -3
View File
@@ -24,7 +24,7 @@ import type { ClusterContext } from "./cluster-context";
import { action, computed, makeObservable, observable, reaction, when } from "mobx";
import { autoBind, noop, rejectPromiseBy } from "../utils";
import { KubeObject, KubeStatus } from "./kube-object";
import type { IKubeWatchEvent } from "./kube-watch-api";
import type { IKubeWatchEvent } from "./kube-watch-event";
import { ItemStore } from "../item.store";
import { ensureObjectSelfLink, IKubeApiQueryParams, KubeApi } from "./kube-api";
import { parseKubeApi } from "./kube-api-parse";
@@ -323,14 +323,14 @@ export abstract class KubeObjectStore<T extends KubeObject> extends ItemStore<T>
return this.api.create(params, data);
}
async create(params: { name: string; namespace?: string }, data?: Partial<T>): Promise<T> {
create = async (params: { name: string; namespace?: string }, data?: Partial<T>): Promise<T> => {
const newItem = await this.createItem(params, data);
const items = this.sortItems([...this.items, newItem]);
this.items.replace(items);
return newItem;
}
};
private postUpdate(rawItem: KubeJsonApiData): T {
const newItem = new this.api.objectConstructor(rawItem);
-210
View File
@@ -1,210 +0,0 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// Kubernetes watch-api client
// API: https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams
import type { KubeObjectStore } from "./kube-object.store";
import type { ClusterContext } from "./cluster-context";
import { comparer, reaction } from "mobx";
import { disposer, Disposer, noop } from "../utils";
import type { KubeJsonApiData } from "./kube-json-api";
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;
}
export interface KubeWatchSubscribeStoreOptions {
/**
* The namespaces to watch
* @default all selected namespaces
*/
namespaces?: string[];
/**
* A function that is called when listing fails. If set then blocks errors
* being rejected with
*/
onLoadFailure?: (err: any) => void;
}
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 {
static context: ClusterContext = null;
#watch = new WatchCount();
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);
}
let childController = new WrappedAbortController(parent);
const unsubscribe = disposer();
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 },
});
}
}
};
/**
* 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 once(() => {
parent.abort();
unsubscribe();
});
}
protected log(message: any, meta: any) {
const log = message instanceof Error
? console.error
: console.debug;
log("[KUBE-WATCH-API]:", message, {
time: new Date().toLocaleString(),
...meta,
});
}
}
export const kubeWatchApi = new KubeWatchApi();
+28
View File
@@ -0,0 +1,28 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import type { KubeJsonApiData } from "./kube-json-api";
export interface IKubeWatchEvent<T extends KubeJsonApiData> {
type: "ADDED" | "MODIFIED" | "DELETED" | "ERROR";
object?: T;
}