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

feat(global store): implement golbal store destory #24

Merged
merged 1 commit into from
Oct 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
},
"scripts": {
"start": "tsup --watch",
"prepublish": "tsup",
"build": "tsup",
"lint": "eslint src --ext .ts --quiet",
"typings": "tsc",
Expand Down
52 changes: 38 additions & 14 deletions src/data-provider/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
CreateResponse,
MetaQuery,
UpdateResponse,
DeleteOneResponse
DeleteOneResponse,
} from '@refinedev/core';
import { KubeSdk, Unstructured } from '../kube-api';
import { filterData } from '../utils/filter-data';
Expand Down Expand Up @@ -46,8 +46,8 @@ export const dataProvider = (
item.metadata.name === name && item.metadata.namespace === namespace
);
if (!data) {
console.error(`resource: ${resource} not include id: ${id}`)
return { data: null as unknown as TData }
console.error(`resource: ${resource} not include id: ${id}`);
return { data: null as unknown as TData };
}
return {
data: {
Expand Down Expand Up @@ -87,27 +87,35 @@ export const dataProvider = (
};
},

getMany: async<TData extends BaseRecord = BaseRecord, TVariables = unknown> (params: {
getMany: async <
TData extends BaseRecord = BaseRecord,
TVariables = unknown
>(params: {
resource: string;
ids: BaseKey[];
variables?: TVariables | undefined;
meta?: MetaQuery | undefined;
metaData?: MetaQuery | undefined;
}): Promise<GetManyResponse<TData>> => {
const { ids, ...rest } = params
const { ids, ...rest } = params;
const data = await Promise.all(
ids.map(id => getOne({ id, ...rest }).then(v => v.data))
);

return {
data: data as unknown as TData[],
data: data as unknown as TData[],
};
},

create: async<TData extends BaseRecord = BaseRecord> ({ variables, meta }:Parameters<DataProvider['create']>['0']): Promise<CreateResponse<TData>> => {
create: async <TData extends BaseRecord = BaseRecord>({
variables,
meta,
}: Parameters<DataProvider['create']>['0']): Promise<
CreateResponse<TData>
> => {
const sdk = new KubeSdk({
basePath: globalStore.apiUrl,
fieldManager: globalStore.fieldManager
fieldManager: globalStore.fieldManager,
});

const data = await sdk.applyYaml([
Expand All @@ -123,19 +131,28 @@ export const dataProvider = (
};
},

update: async<TData extends BaseRecord = BaseRecord> ({ variables, meta }:Parameters<DataProvider['update']>['0']): Promise<UpdateResponse<TData>> => {
update: async <TData extends BaseRecord = BaseRecord>({
variables,
meta,
}: Parameters<DataProvider['update']>['0']): Promise<
UpdateResponse<TData>
> => {
const sdk = new KubeSdk({
basePath: globalStore.apiUrl,
fieldManager: globalStore.fieldManager
fieldManager: globalStore.fieldManager,
});
const params = [
{
...(variables as unknown as Unstructured),
apiVersion: getApiVersion(meta?.resourceBasePath),
kind: meta?.kind,
},
]
const data = await sdk.applyYaml(params, meta?.strategy, meta?.replacePaths);
];
const data = await sdk.applyYaml(
params,
meta?.strategy,
meta?.replacePaths
);

return {
data: data[0] as unknown as TData,
Expand All @@ -144,10 +161,17 @@ export const dataProvider = (

getOne,

deleteOne: async<TData extends BaseRecord = BaseRecord> ({ resource, id, meta, ...rest }:Parameters<DataProvider['deleteOne']>['0']): Promise<DeleteOneResponse<TData>> => {
deleteOne: async <TData extends BaseRecord = BaseRecord>({
resource,
id,
meta,
...rest
}: Parameters<DataProvider['deleteOne']>['0']): Promise<
DeleteOneResponse<TData>
> => {
const sdk = new KubeSdk({
basePath: globalStore.apiUrl,
fieldManager: globalStore.fieldManager
fieldManager: globalStore.fieldManager,
});

const { data: current } = await getOne({ id, resource, meta, ...rest });
Expand Down
22 changes: 19 additions & 3 deletions src/global-store.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { MetaQuery } from '@refinedev/core';
import { KubeApi, UnstructuredList, WatchEvent } from './kube-api';
import {
KubeApi,
UnstructuredList,
WatchEvent,
StopWatchHandler,
} from './kube-api';
import { relationPlugin } from './plugins/relation';

export function getObjectConstructor(resource: string, meta?: MetaQuery) {
Expand Down Expand Up @@ -30,6 +35,8 @@ export class GlobalStore {

private store = new Map<string, UnstructuredList>();
private subscribers = new Map<string, ((data: WatchEvent) => void)[]>();
private kubeApi?: KubeApi<UnstructuredList>;
private stopWatch?: StopWatchHandler;

constructor(params: GlobalStoreInitParams) {
this.init(params);
Expand All @@ -40,15 +47,15 @@ export class GlobalStore {
get<T = UnstructuredList>(resource: string, meta?: MetaQuery): Promise<T> {
return new Promise((resolve, reject) => {
if (!this.store.has(resource)) {
const api = new KubeApi({
this.kubeApi = new KubeApi({
basePath: this._apiUrl,
watchWsBasePath: this.watchWsApiUrl,
objectConstructor: getObjectConstructor(resource, meta),
});

let resolved = false;

api
this.kubeApi
.listWatch({
onResponse: res => {
relationPlugin.processData(res);
Expand All @@ -63,6 +70,9 @@ export class GlobalStore {
this.notify(resource, event);
},
})
.then(stop => {
this.stopWatch = stop;
})
.catch(e => reject(e));
} else {
resolve(this.store.get(resource)! as unknown as T);
Expand Down Expand Up @@ -98,6 +108,7 @@ export class GlobalStore {
this.notify(resource, data);
}
init(params: GlobalStoreInitParams) {
this.destroy();
const { apiUrl, watchWsApiUrl, prefix, fieldManager } = params;
this.store = new Map();
this.subscribers = new Map();
Expand All @@ -106,4 +117,9 @@ export class GlobalStore {
this.prefix = prefix;
this.fieldManager = fieldManager;
}
destroy() {
this.store.clear();
this.subscribers.clear();
this.stopWatch?.();
}
}
13 changes: 4 additions & 9 deletions src/kube-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,6 @@ export class KubeApi<T extends UnstructuredList> {
stops.push(this.watchByHttp(url, response, handleEvent, retry));
}
}

return () => {
stops.forEach(stop => stop());
};
Expand Down Expand Up @@ -433,7 +432,7 @@ export class KubeApi<T extends UnstructuredList> {
let shouldCloseAfterConnected = false;
let stopWatch: () => void = () => {
if (socket.readyState === socket.OPEN) {
socket.close(3001, 'DOVETAIL_MANUAL_CLOSE');
socket.close(3001, 'KUBEAPI_MANUAL_CLOSE');
} else {
shouldCloseAfterConnected = true;
}
Expand All @@ -445,7 +444,7 @@ export class KubeApi<T extends UnstructuredList> {

socket.addEventListener('open', () => {
if (shouldCloseAfterConnected) {
socket.close(3001, 'DOVETAIL_MANUAL_CLOSE');
socket.close(3001, 'KUBEAPI_MANUAL_CLOSE');
return;
}
heartbeat(socket);
Expand All @@ -459,7 +458,7 @@ export class KubeApi<T extends UnstructuredList> {
socket.addEventListener('close', evt => {
clearTimeout((socket as ExtendedWebsocketClient).pingTimeout);

if (evt.reason === 'DOVETAIL_MANUAL_CLOSE') {
if (evt.reason === 'KUBEAPI_MANUAL_CLOSE') {
return;
}

Expand Down Expand Up @@ -661,11 +660,7 @@ export class KubeSdk {
}

const response = exist
? await this.patch(
spec,
strategy,
replacePaths?.[index]
)
? await this.patch(spec, strategy, replacePaths?.[index])
: await this.create(spec);

if (exist) {
Expand Down
4 changes: 2 additions & 2 deletions src/utils/filter-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ function deepFilter(item: Unstructured, filter: CrudFilter): boolean {

export const filterData = (
filters: CrudFilters,
data: Unstructured[],
data: Unstructured[]
): Unstructured[] => {
if (!filters || filters.length === 0) {
return data;
Expand All @@ -35,7 +35,7 @@ export function evaluateFilter(
field: string,
operator: Exclude<CrudOperators, 'or' | 'and'>,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
value: any,
value: any
): boolean {
if (!_.has(item, field)) {
return false;
Expand Down
6 changes: 2 additions & 4 deletions src/utils/paginate-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,8 @@ export const paginateData = (
): Unstructured[] => {
const { current = 1, pageSize = 20, mode } = pagination ?? {};
if (mode !== 'client') {
console.warn(
'k8s no support server paginateData'
);
return data
console.warn('k8s no support server paginateData');
return data;
}
let start = 0;
let end = data.length;
Expand Down