-
Notifications
You must be signed in to change notification settings - Fork 509
/
cache.ts
251 lines (230 loc) · 8 KB
/
cache.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import { ADD, DELETE, ERROR, Informer, ListPromise, ObjectCallback, UPDATE } from './informer';
import { KubernetesObject } from './types';
import { RequestResult, Watch } from './watch';
export interface ObjectCache<T> {
get(name: string, namespace?: string): T | undefined;
list(namespace?: string): ReadonlyArray<T>;
}
export class ListWatch<T extends KubernetesObject> implements ObjectCache<T>, Informer<T> {
private objects: T[] = [];
private resourceVersion: string;
private readonly indexCache: { [key: string]: T[] } = {};
private readonly callbackCache: { [key: string]: Array<ObjectCallback<T>> } = {};
private request: RequestResult | undefined;
private stopped: boolean = false;
public constructor(
private readonly path: string,
private readonly watch: Watch,
private readonly listFn: ListPromise<T>,
autoStart: boolean = true,
) {
this.callbackCache[ADD] = [];
this.callbackCache[UPDATE] = [];
this.callbackCache[DELETE] = [];
this.callbackCache[ERROR] = [];
this.resourceVersion = '';
if (autoStart) {
this.doneHandler(null);
}
}
public async start(): Promise<void> {
this.stopped = false;
await this.doneHandler(null);
}
public async stop(): Promise<void> {
this.stopped = true;
this._stop();
}
public on(verb: string, cb: ObjectCallback<T>): void {
if (this.callbackCache[verb] === undefined) {
throw new Error(`Unknown verb: ${verb}`);
}
this.callbackCache[verb].push(cb);
}
public off(verb: string, cb: ObjectCallback<T>): void {
if (this.callbackCache[verb] === undefined) {
throw new Error(`Unknown verb: ${verb}`);
}
const indexToRemove: number = this.callbackCache[verb].findIndex(
(cachedCb: ObjectCallback<T>) => cachedCb === cb,
);
if (indexToRemove === -1) {
return;
}
this.callbackCache[verb].splice(indexToRemove, 1);
}
public get(name: string, namespace?: string): T | undefined {
return this.objects.find(
(obj: T): boolean => {
return obj.metadata!.name === name && (!namespace || obj.metadata!.namespace === namespace);
},
);
}
public list(namespace?: string | undefined): ReadonlyArray<T> {
if (!namespace) {
return this.objects;
}
return this.indexCache[namespace] as ReadonlyArray<T>;
}
public latestResourceVersion(): string {
return this.resourceVersion;
}
private _stop(): void {
if (this.request) {
this.request.abort();
this.request = undefined;
}
}
private async doneHandler(err: any): Promise<any> {
this._stop();
if (err) {
this.callbackCache[ERROR].forEach((elt: ObjectCallback<T>) => elt(err));
return;
}
if (this.stopped) {
// do not auto-restart
return;
}
// TODO: Don't always list here for efficiency
// try to restart the watch from resourceVersion, but detect 410 GONE and relist in that case.
// Or if resourceVersion is empty.
const promise = this.listFn();
const result = await promise;
const list = result.body;
this.objects = deleteItems(this.objects, list.items, this.callbackCache[DELETE].slice());
Object.keys(this.indexCache).forEach((key) => {
const updateObjects = deleteItems(this.indexCache[key], list.items);
if (updateObjects.length !== 0) {
this.indexCache[key] = updateObjects;
} else {
delete this.indexCache[key];
}
});
this.addOrUpdateItems(list.items);
this.request = await this.watch.watch(
this.path,
{ resourceVersion: list.metadata!.resourceVersion },
this.watchHandler.bind(this),
this.doneHandler.bind(this),
);
}
private addOrUpdateItems(items: T[]): void {
items.forEach((obj: T) => {
addOrUpdateObject(
this.objects,
obj,
this.callbackCache[ADD].slice(),
this.callbackCache[UPDATE].slice(),
);
if (obj.metadata!.namespace) {
this.indexObj(obj);
}
});
}
private indexObj(obj: T): void {
let namespaceList = this.indexCache[obj.metadata!.namespace!] as T[];
if (!namespaceList) {
namespaceList = [];
this.indexCache[obj.metadata!.namespace!] = namespaceList;
}
addOrUpdateObject(namespaceList, obj);
}
private watchHandler(phase: string, obj: T, watchObj?: any): void {
switch (phase) {
case 'ADDED':
case 'MODIFIED':
addOrUpdateObject(
this.objects,
obj,
this.callbackCache[ADD].slice(),
this.callbackCache[UPDATE].slice(),
);
if (obj.metadata!.namespace) {
this.indexObj(obj);
}
break;
case 'DELETED':
deleteObject(this.objects, obj, this.callbackCache[DELETE].slice());
if (obj.metadata!.namespace) {
const namespaceList = this.indexCache[obj.metadata!.namespace!] as T[];
if (namespaceList) {
deleteObject(namespaceList, obj);
}
}
break;
case 'BOOKMARK':
// nothing to do, here for documentation, mostly.
break;
}
if (watchObj && watchObj.metadata) {
this.resourceVersion = watchObj.metadata.resourceVersion;
}
}
}
// external for testing
export function deleteItems<T extends KubernetesObject>(
oldObjects: T[],
newObjects: T[],
deleteCallback?: Array<ObjectCallback<T>>,
): T[] {
return oldObjects.filter((obj: T) => {
if (findKubernetesObject(newObjects, obj) === -1) {
if (deleteCallback) {
deleteCallback.forEach((fn: ObjectCallback<T>) => fn(obj));
}
return false;
}
return true;
});
}
// Only public for testing.
export function addOrUpdateObject<T extends KubernetesObject>(
objects: T[],
obj: T,
addCallback?: Array<ObjectCallback<T>>,
updateCallback?: Array<ObjectCallback<T>>,
): void {
const ix = findKubernetesObject(objects, obj);
if (ix === -1) {
objects.push(obj);
if (addCallback) {
addCallback.forEach((elt: ObjectCallback<T>) => elt(obj));
}
} else {
if (!isSameVersion(objects[ix], obj)) {
objects[ix] = obj;
if (updateCallback) {
updateCallback.forEach((elt: ObjectCallback<T>) => elt(obj));
}
}
}
}
function isSameObject<T extends KubernetesObject>(o1: T, o2: T): boolean {
return o1.metadata!.name === o2.metadata!.name && o1.metadata!.namespace === o2.metadata!.namespace;
}
function isSameVersion<T extends KubernetesObject>(o1: T, o2: T): boolean {
return (
o1.metadata!.resourceVersion !== undefined &&
o1.metadata!.resourceVersion !== null &&
o1.metadata!.resourceVersion === o2.metadata!.resourceVersion
);
}
function findKubernetesObject<T extends KubernetesObject>(objects: T[], obj: T): number {
return objects.findIndex((elt: T) => {
return isSameObject(elt, obj);
});
}
// Public for testing.
export function deleteObject<T extends KubernetesObject>(
objects: T[],
obj: T,
deleteCallback?: Array<ObjectCallback<T>>,
): void {
const ix = findKubernetesObject(objects, obj);
if (ix !== -1) {
objects.splice(ix, 1);
if (deleteCallback) {
deleteCallback.forEach((elt: ObjectCallback<T>) => elt(obj));
}
}
}