forked from rancher/dashboard
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubscribe.js
More file actions
1693 lines (1395 loc) · 56 KB
/
subscribe.js
File metadata and controls
1693 lines (1395 loc) · 56 KB
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Handles subscriptions to websockets which receive updates to resources
*
* Covers three use cases
* 1) Handles subscription within this file
* 2) Handles `cluster` subscriptions for some basic types in a web worker (SETTING.UI_PERFORMANCE advancedWorker = false) (is this true??)
* 2) Handles `cluster` subscriptions and optimisations in an advanced worker (SETTING.UI_PERFORMANCE advancedWorker = true)
*
* Very roughly this does...
*
* 1. _Subscribes_ to a web socket (v1, v3, v1 cluster)
* 2. UI --> Rancher: Sends a _watch_ message for a specific resource type (which can have qualifying filters)
* 3. Rancher --> UI: Rancher can send a number of messages back
* - `resource.start` - watch has started
* - `resource.error` - watch has errored, usually a result of bad data in the resource.start message
* - `resource.change` - a resource has changed, this is it's new value
* - `resource.changes` - if in this mode, no resource.change events are sent, instead one debounced message is sent without any resource data
* - `resource.stop` - either we have requested the watch stops, or there has been a resource.error
* 4. UI --> Rancher: Sends an _unwatch_ request for a matching _watch_ request
*
* Below are some VERY brief steps for common flows. Some will link together
*
* # Successfully flow
* ## watch - standard mode
* 1. UI --> Rancher: _watch_ request
* 2. Rancher --> UI: `resource.start`. UI sets watch as started
* ...
* 3. Rancher --> UI: `resource.change` (contains data). UI caches data
*
* ## watch - new resource.changes mode
* 1. UI --> Rancher: _watch_ request
* 2. Rancher --> UI: `resource.start`. UI sets watch as started
* ...
* 3. Rancher --> UI: `resource.changes` (contains no data). UI makes a HTTP request to fetch data
*
* ## watch - unwatch
* 1. UI --> Rancher: _unwatch_ request
* 2. Rancher --> UI: `resource.stop`. UI sets watch as stopped
*
* ## watch - resource.stop received
* 1. Rancher --> UI: `resource.stop`. UI sets watch as stopped
* 2. UI --> Rancher: _watch_ request
*
* ## watch - socket disconnected
* 1. Socket closes|disconnects (not sure which)
* 2. UI: reopens socket
* 3. UI --> Rancher: _watch_ request (for every started watch)
*
* # Error Flow
* ## resource.error
* 1. UI --> Rancher: _watch_ request
* 2. Rancher --> UI: `resource.start`. UI sets watch as started
* 3. Rancher --> UI: `resource.error`. UI sets watch as errored.
* a) UI: in the event of 'too old' the UI will make a http request to fetch a new revision and re-watch with it. This process is delayed on each call
* 4. Rancher --> UI: `resource.stop`. UI sets watch as stop (note the resource.stop flow above is avoided given error state)
*
* # HA Support for Stale Replicates - https://github.com/rancher/dashboard/issues/14974
*
* ## Scenario 1 - handle case where watch request is handled by a stale replica
* 1. UI --> Rancher: _watch_ request (contains latest revision)
* 2. Rancher --> UI: `resource.error` (stale replica does not know new revision)
* 3. Rancher --> UI: `resource.stop` (stale replica cannot provide updates for unknown revision)
* 4. UI --> Rancher : UI makes a HTTP request to fetch data
* 5. Loop back to step 1 (if stale again, backoff retry)
*
* ## Scenario 2 - handle case where http request is handled by a stale replica (don't fetch stale data)
* 1. UI --> Rancher: _watch_ request
* 2. Rancher --> UI: `resource.start`. UI sets watch as started
* ...
* 3. Rancher --> UI: `resource.changes` (sent by good replica containing good revision)
* 4. UI --> Rancher : UI makes a HTTP request to fetch data. Stale Replica handles request, does not know revision, returns error
* 5. Loop back to step 4 (if errors with stale again, backoff retry)
*
* ## Scenario 3 - handle case where update request was sent by stale replica (don't overwrite good data with stale)
* 1. UI --> Rancher: _watch_ request
* 2. Rancher --> UI: `resource.start`. UI sets watch as started
* ...
* 3. Rancher --> UI: `resource.changes` (sent by stale replica containing stale revision)
* 4. UI compares stale revision with newer store revision
* 5. UI does not make new http request, which could be handled by stale replica --> overwrites newer local values
*
* Additionally
* - if we receive resource.stop, unless the watch is in error, we immediately send back a watch request to re-start the watch
* - if the web socket is disconnected (for steve based sockets it happens every 30 mins, or when there are permission changes)
* the ui will re-connect it and re-watch all previous watches using a best effort revision
*/
import { addObject, clear, removeObject } from '@shell/utils/array';
import { get, deepToRaw } from '@shell/utils/object';
import { SCHEMA, MANAGEMENT } from '@shell/config/types';
import { SETTING } from '@shell/config/settings';
import { CSRF } from '@shell/config/cookies';
import { getPerformanceSetting } from '@shell/utils/settings';
import Socket, {
EVENT_CONNECTED,
EVENT_DISCONNECTED,
EVENT_MESSAGE,
EVENT_CONNECT_ERROR,
EVENT_DISCONNECT_ERROR,
NO_WATCH,
NO_SCHEMA,
REVISION_TOO_OLD,
NO_PERMS
} from '@shell/utils/socket';
import { normalizeType } from '@shell/plugins/dashboard-store/normalize';
import day from 'dayjs';
import { DATE_FORMAT, TIME_FORMAT } from '@shell/store/prefs';
import { escapeHtml } from '@shell/utils/string';
import { keyForSubscribe } from '@shell/plugins/steve/resourceWatcher';
import { waitFor } from '@shell/utils/async';
import { WORKER_MODES } from './worker';
import acceptOrRejectSocketMessage from './accept-or-reject-socket-message';
import { BLANK_CLUSTER, STORE } from '@shell/store/store-types.js';
import { _MERGE } from '@shell/plugins/dashboard-store/actions';
import { STEVE_WATCH_EVENT_TYPES, STEVE_WATCH_MODE } from '@shell/types/store/subscribe.types';
import paginationUtils from '@shell/utils/pagination-utils';
import backOff from '@shell/utils/back-off';
import { SteveWatchEventListenerManager } from '@shell/plugins/subscribe-events';
import { SteveRevision } from '@shell/plugins/steve/revision';
import { STEVE_RESPONSE_CODE } from '@shell/types/rancher/steve.api';
// minimum length of time a disconnect notification is shown
const MINIMUM_TIME_NOTIFIED = 3000;
const workerQueues = {};
const supportedStores = [STORE.CLUSTER, STORE.RANCHER, STORE.MANAGEMENT];
const isWaitingForDestroy = (storeName, store) => {
return store.$workers[storeName]?.waitingForDestroy && store.$workers[storeName].waitingForDestroy();
};
const waitForSettingsSchema = (storeName, store) => {
return waitFor(
() => isWaitingForDestroy(storeName, store) || !!store.getters['management/byId'](SCHEMA, MANAGEMENT.SETTING),
'management settings schema to be available'
);
};
const waitForSettings = (storeName, store) => {
return waitFor(
() => isWaitingForDestroy(storeName, store) || !!store.getters['management/byId'](MANAGEMENT.SETTING, SETTING.UI_PERFORMANCE),
'UI performance settings to be available'
);
};
const isAdvancedWorker = (ctx) => {
const { rootGetters, getters } = ctx;
const storeName = getters.storeName;
const clusterId = rootGetters.clusterId;
if (!supportedStores.includes(storeName) || (clusterId === BLANK_CLUSTER && storeName === STORE.CLUSTER)) {
return false;
}
const perfSetting = getPerformanceSetting(rootGetters);
return perfSetting?.advancedWorker.enabled;
};
export async function createWorker(store, ctx) {
const { getters, dispatch } = ctx;
const storeName = getters.storeName;
store.$workers = store.$workers || {};
if (!supportedStores.includes(storeName)) {
return;
}
if (!store.$workers[storeName]) {
// we know we need a worker at this point but we don't know which one so we're creating a mock interface
// it will simply queue up any messages for the real worker to process when it loads up
store.$workers[storeName] = {
postMessage: (msg) => {
if (Object.keys(msg)?.[0] === 'destroyWorker') {
// The worker has been destroyed before it's been set up. Flag this so we stop waiting for mgmt settings and then can destroy worker.
// This can occur when the user is redirected to the log in page
// - workers created (but waiting)
// - logout is called
// - <store>/unsubscribe is dispatched
// - wait for worker object to be destroyed <-- requires initial wait to be unblocked
store.$workers[storeName].mode = WORKER_MODES.DESTROY_MOCK;
return;
}
if (workerQueues[storeName]) {
workerQueues[storeName].push(msg);
} else {
workerQueues[storeName] = [msg];
}
},
mode: WORKER_MODES.WAITING,
waitingForDestroy: () => {
return store.$workers[storeName]?.mode === WORKER_MODES.DESTROY_MOCK;
},
destroy: () => {
// Similar to workerActions.destroyWorker
delete store.$workers[storeName];
}
};
}
try {
await waitForSettingsSchema(storeName, store);
await waitForSettings(storeName, store);
} catch (e) {
// Clean up the mock worker and abort so callers are not permanently blocked.
if (store.$workers[storeName]?.destroy) {
store.$workers[storeName].destroy();
} else {
delete store.$workers[storeName];
}
return;
}
if (store.$workers[storeName].waitingForDestroy()) {
store.$workers[storeName].destroy();
return;
}
const advancedWorker = isAdvancedWorker(ctx);
const workerActions = {
load: (resource) => {
queueChange(ctx, resource, true, 'Change');
},
destroyWorker: () => {
if (store.$workers) {
store.$workers[storeName].terminate();
delete store.$workers[storeName];
}
},
batchChanges: (batch) => {
dispatch('batchChanges', acceptOrRejectSocketMessage.validateBatchChange(ctx, batch));
},
dispatch: (msg) => {
dispatch(`ws.${ msg.name }`, msg);
},
redispatch: (msg) => {
/**
* because we had to queue up some messages prior to loading the worker:
* the basic worker will need to redispatch some of the queued messages back to the UI thread
*/
Object.entries(msg).forEach(([action, params]) => {
dispatch(action, params);
});
},
[EVENT_CONNECT_ERROR]: (e) => {
dispatch('error', e );
},
[EVENT_DISCONNECT_ERROR]: (e) => {
dispatch('error', e );
},
};
if (!store.$workers[storeName] || store.$workers[storeName].mode === WORKER_MODES.WAITING) {
const workerMode = advancedWorker ? WORKER_MODES.ADVANCED : WORKER_MODES.BASIC;
const worker = store.steveCreateWorker(workerMode);
store.$workers[storeName] = worker;
worker.postMessage({ initWorker: { storeName } });
/**
* Covers message from Worker to UI thread
*/
store.$workers[storeName].onmessage = (e) => {
/* on the off chance there's more than key in the message, we handle them in the order that they "keys" method provides which is
// good enough for now considering that we never send more than one message action at a time right now */
const messageActions = Object.keys(e?.data);
messageActions.forEach((action) => {
workerActions[action](e?.data[action]);
});
};
}
while (workerQueues[storeName]?.length) {
const message = workerQueues[storeName].shift();
const safeMessage = deepToRaw(message);
store.$workers[storeName].postMessage(safeMessage);
}
}
export function equivalentWatch(a, b) {
const aResourceType = a.resourceType || a.type;
const bResourceType = b.resourceType || b.type;
if ( aResourceType !== bResourceType ) {
return false;
}
if (a.mode !== b.mode && (a.mode || b.mode)) {
return false;
}
if ( a.id !== b.id && (a.id || b.id) ) {
return false;
}
if ( a.namespace !== b.namespace && (a.namespace || b.namespace) ) {
return false;
}
if ( a.selector !== b.selector && (a.selector || b.selector) ) {
return false;
}
return true;
}
function queueChange({ getters, state, rootGetters }, { data, revision }, load, label) {
const type = getters.normalizeType(data.type);
const entry = getters.typeEntry(type);
if ( entry ) {
entry.revision = Math.max(entry.revision, parseInt(revision, 10));
} else {
return;
}
// console.log(`${ label } Event [${ state.config.namespace }]`, data.type, data.id); // eslint-disable-line no-console
if (!acceptOrRejectSocketMessage.validChange({ getters, rootGetters }, type, data)) {
return;
}
if ( load ) {
state.queue.push({
action: 'dispatch',
event: 'load',
body: data
});
} else {
const obj = getters.byId(data.type, data.id);
if ( obj ) {
state.queue.push({
action: 'commit',
event: 'remove',
body: obj
});
}
if ( type === SCHEMA ) {
// Clear the current records in the store when a type disappears
state.queue.push({
action: 'commit',
event: 'forgetType',
body: data.id
});
}
}
}
function growlsDisabled(rootGetters) {
return getPerformanceSetting(rootGetters)?.disableWebsocketNotification;
}
/**
* clear the provided error, but also ensure any backoff request associated with it is cleared as well
*/
const clearInError = ({ getters, commit }, error) => {
// for this watch ... get the specific prefix we care about ... reset back-offs related to it
backOff.resetPrefix(getters.backOffId(error.obj, ''));
// Clear out stale error state (next time around we can try again with a new revision that was just fetched)
commit('clearInError', error.obj);
};
/**
* Actions that cover all cases (see file description)
*/
const sharedActions = {
async subscribe(ctx, opt) {
const {
state, commit, dispatch, getters, rootGetters
} = ctx;
// ToDo: need to keep the worker up to date on CSRF cookie
if (rootGetters['isSingleProduct']?.disableSteveSockets) {
return;
}
let socket = state.socket;
commit('setWantSocket', true);
state.debugSocket && console.info(`Subscribe [${ getters.storeName }]`); // eslint-disable-line no-console
const url = `${ state.config.baseUrl }/subscribe`;
const maxTries = growlsDisabled(rootGetters) ? null : 3;
const metadata = get(opt, 'metadata');
if (isAdvancedWorker(ctx)) {
if (!this.$workers[getters.storeName]) {
await createWorker(this, ctx);
}
// createWorker cleans up and returns early when schema/settings are unavailable.
// Guard against calling postMessage on a non-existent worker.
if (!this.$workers[getters.storeName]) {
return;
}
const options = { parseJSON: false };
const csrf = rootGetters['cookies/get']({ key: CSRF, options });
// if the worker is in advanced mode then it'll contain it's own socket which it calls a 'watcher'
this.$workers[getters.storeName].postMessage({
createWatcher: {
metadata,
url: `${ state.config.baseUrl }/subscribe`,
csrf,
maxTries
}
});
} else if ( socket ) {
socket.setAutoReconnect(true);
socket.setUrl(url);
socket.connect(metadata);
} else {
socket = new Socket(`${ state.config.baseUrl }/subscribe`, true, null, null, maxTries);
commit('setSocket', socket);
socket.addEventListener(EVENT_CONNECTED, (e) => {
dispatch('opened', e);
});
socket.addEventListener(EVENT_DISCONNECTED, (e) => {
dispatch('closed', e);
});
socket.addEventListener(EVENT_CONNECT_ERROR, (e) => {
dispatch('error', e );
});
socket.addEventListener(EVENT_DISCONNECT_ERROR, (e) => {
dispatch('error', e );
});
socket.addEventListener(EVENT_MESSAGE, (e) => {
const event = e.detail;
if ( event.data) {
const msg = JSON.parse(event.data);
if (msg.name) {
dispatch(`ws.${ msg.name }`, msg);
}
}
});
socket.connect(metadata);
}
},
async unsubscribe({
commit, getters, state, dispatch
}) {
const socket = state.socket;
commit('setWantSocket', false);
const cleanupTasks = [];
const worker = (this.$workers || {})[getters.storeName];
if (worker) {
worker.postMessage({ destroyWorker: true }); // we're only passing the boolean here because the key needs to be something truthy to ensure it's passed on the object.
cleanupTasks.push(waitFor(() => !this.$workers[getters.storeName], 'Worker is destroyed', 3000000, 50));
}
if ( socket ) {
cleanupTasks.push(socket.disconnect());
}
await dispatch('resetWatchBackOff');
return Promise.all(cleanupTasks);
},
/**
* Create a trigger for a specific type of watch event
*
* For example if a watch on mgmt clusters exists and a page wants to know when any changes occur
* @param {} ctx
* @param {STEVE_WATCH_EVENT_PARAMS} event
*/
watchEvent(ctx, {
event = STEVE_WATCH_EVENT_TYPES.CHANGES,
id,
callback,
/**
* of type @STEVE_WATCH_PARAMS
*/
params
}) {
if (!ctx.getters.listenerManager.isSupportedEventType(event)) {
console.error(`Unknown event type "${ event }", only ${ Object.keys(ctx.getters.listenerManager.supportedEventTypes).join(',') } are supported`); // eslint-disable-line no-console
return;
}
ctx.getters.listenerManager.addEventListenerCallback({
callback,
args: {
event, params, id
}
});
const hasStandardWatch = ctx.getters.listenerManager.hasStandardWatch({ params });
if (!hasStandardWatch) {
// If there's nothing to piggy back on... start a watch to do so.
ctx.dispatch('watch', {
...params,
standardWatch: false // Ensure that we don't treat this as a standard watch
});
}
},
/**
* @param {} ctx
* @param {STEVE_UNWATCH_EVENT_PARAMS} event
*/
unwatchEvent(ctx, {
event = STEVE_WATCH_EVENT_TYPES.CHANGES,
id,
/**
* of type @STEVE_WATCH_PARAMS
*/
params
}) {
if (!ctx.getters.listenerManager.isSupportedEventType(event)) {
console.info(`Attempted to unwatch for an event "${ event }" but it had no watchers`); // eslint-disable-line no-console
return;
}
ctx.getters.listenerManager.removeEventListenerCallback({
event, params, id
});
// Unwatch the underlying standard watch
// Note - If we were piggybacking on a watch that previously existed we won't unwatch it
ctx.dispatch('unwatch', params);
},
/**
* @param {STEVE_WATCH_PARAMS} params
*/
watch({
state, dispatch, getters, rootGetters, commit
}, params) {
state.debugSocket && console.info(`Watch Request [${ getters.storeName }]`, JSON.stringify(params)); // eslint-disable-line no-console
let {
// eslint-disable-next-line prefer-const
type, selector, id, revision, namespace, stop, force, mode, standardWatch = true
} = params;
namespace = acceptOrRejectSocketMessage.subscribeNamespace(namespace);
type = getters.normalizeType(type);
if (rootGetters['type-map/isSpoofed'](type)) {
state.debugSocket && console.info('Will not Watch (type is spoofed)', JSON.stringify(params)); // eslint-disable-line no-console
return;
}
const schema = getters.schemaFor(type, false, false);
if (!!schema?.attributes?.verbs?.includes && !schema.attributes.verbs.includes('watch')) {
state.debugSocket && console.info('Will not Watch (type does not have watch verb)', JSON.stringify(params)); // eslint-disable-line no-console
return;
}
// If socket is in error don't try to watch.... unless we `force` it
const inError = getters.inError(params);
if ( !stop && !force && inError ) {
// REVISION_TOO_OLD is a temporary state and will be handled when `resyncWatch` completes
if (inError !== REVISION_TOO_OLD) {
console.error(`Aborting Watch Request [${ getters.storeName }]. Watcher in error (${ inError })`, JSON.stringify(params)); // eslint-disable-line no-console
}
return;
}
const messageMeta = {
type, id, selector, namespace, mode
};
if (!stop && getters.watchStarted(messageMeta)) {
// eslint-disable-next-line no-console
state.debugSocket && console.debug(`Already Watching [${ getters.storeName }]`, {
type, id, selector, namespace, mode
});
return;
}
// Watch errors mean we make a http request to get latest revision (which is still missing) and try to re-watch with it...
// etc
if (typeof revision === 'undefined') {
revision = getters.nextResourceVersion(type, id);
}
const msg = { resourceType: type };
if (mode) {
msg.mode = mode;
if (mode === STEVE_WATCH_MODE.RESOURCE_CHANGES) {
const debounceMs = paginationUtils.resourceChangesDebounceMs({ rootGetters });
if (debounceMs) {
msg.debounceMs = debounceMs;
}
// Anything in the queue will pollute the result set, so clear (and print to console so we know it's working)
commit('clearFromQueue', { type, log: true });
}
}
if ( revision ) {
msg.resourceVersion = `${ revision }`;
}
if ( namespace ) {
msg.namespace = namespace;
}
if ( stop ) {
msg.stop = true;
}
if ( id ) {
msg.id = id;
}
if ( selector ) {
msg.selector = selector;
}
const worker = this.$workers?.[getters.storeName] || {};
if (worker.mode === WORKER_MODES.ADVANCED || worker.mode === WORKER_MODES.WAITING) {
if ( force ) {
msg.force = true;
}
worker.postMessage({ watch: msg });
return;
}
if (!stop && standardWatch) {
// Track that this watch is just a normal one, not one kicked off by listeners
// This helps us keep the watch going (for listeners) instead of in unwatch just stopping it
getters.listenerManager.setStandardWatch({ standardWatch: true, args: { event: msg.mode, params: msg } });
}
return dispatch('send', msg);
},
/**
* @param {STEVE_WATCH_PARAMS} params
*/
unwatch(ctx, {
type, id, namespace, selector, all, mode
}) {
const { commit, getters, dispatch } = ctx;
if (getters['schemaFor'](type)) {
namespace = acceptOrRejectSocketMessage.subscribeNamespace(namespace);
const obj = {
type,
id,
namespace,
selector,
mode,
stop: true, // Stops the watch on a type
};
const unwatch = (obj) => {
// Has this normal watch got listeners? If so
const hasStandardWatch = ctx.getters.listenerManager.hasStandardWatch({ params: obj });
const watchHasListeners = ctx.getters.listenerManager.hasEventListeners({ params: obj });
if (hasStandardWatch) {
// If we have listeners for this watch... make sure it knows there's now no root standard watch
ctx.getters.listenerManager.setStandardWatch({ standardWatch: false, args: { params: obj } });
}
if (watchHasListeners) {
// Does this watch have listeners? if so we shouldn't stop it (they still need it)
return;
}
if (getters['watchStarted'](obj)) {
// Set that we don't want to watch this type
// Otherwise, the dispatch to unwatch below will just cause a re-watch when we
// detect the stop message from the backend over the web socket
commit('setWatchStopped', obj);
dispatch('watch', obj); // Ask the backend to stop watching the type
// Make sure anything in the pending queue for the type is removed, since we've now removed the type
commit('clearFromQueue', type);
}
};
const objKey = keyForSubscribe(obj);
const reset = [];
if (isAdvancedWorker(ctx)) {
dispatch('watch', obj); // Ask the backend to stop watching the type
} else if (all) {
reset.push(...getters['watchesOfType'](type));
} else if (getters['watchStarted'](obj)) {
reset.push(obj);
}
reset.forEach((obj) => {
unwatch(obj);
// Ensure anything pinging in the background is stopped
dispatch('resetWatchBackOff', {
type,
compareWatches: (entry) => objKey === keyForSubscribe(entry)
});
});
}
},
/**
* Ensure there's no back-off process waiting to run for
* - resource.changes fetchResources
* - resource.error resyncWatch
*/
resetWatchBackOff({ state, getters, commit }, {
type, compareWatches, resetInError = true, resetStarted = true
} = { resetInError: true, resetStarted: true }) {
// Step 1 - Reset back-offs related to watches that have STARTED
if (resetStarted && state.started?.length) {
let entries = state.started;
if (type || compareWatches) { // Filter out ones for types we're no interested in
entries = entries
.filter((obj) => compareWatches ? compareWatches(obj) : obj.type === type);
}
entries.forEach((obj) => backOff.resetPrefix(getters.backOffId(obj, '')));
}
// Step 2 - Reset back-offs related to watches that are in error (and may not be started)
if (resetInError && state.inError) {
// (it would be nicer if we could store backOff state in `state.started`,
// however resource.stop clears `started` and we need the settings to persist over start-->error-->stop-->start cycles
let entries = Object.values(state.inError || {});
if (type || compareWatches) { // Filter out ones for types we're no interested in
entries = entries
.filter((error) => compareWatches ? compareWatches(error.obj) : error.obj.type === type);
}
entries
.filter((error) => error.reason === REVISION_TOO_OLD) // Filter out ones for reasons we're not interested in
.forEach((error) => clearInError({ getters, commit }, error));
}
},
'ws.ping'({ getters, dispatch }, msg) {
if ( getters.storeName === 'management' ) {
const version = msg?.data?.version || null;
dispatch('updateServerVersion', version, { root: true });
console.info(`Ping [${ getters.storeName }] from ${ version || 'unknown version' }`); // eslint-disable-line no-console
}
},
};
/**
* Mutations that cover all cases (both subscriptions here and in advanced worker)
*/
const sharedMutations = {
debug(state, on, store) {
state.debugSocket = on !== false;
if (store && this.$workers[store]) {
this.$workers[store].postMessage({ toggleDebug: on !== false });
}
},
};
/**
* Actions that cover cases 1 & 2 (see file description)
*/
const defaultActions = {
async flush({
state, commit, dispatch, getters
}) {
const queue = state.queue;
let toLoad = [];
if ( !queue.length ) {
return;
}
const started = new Date().getTime();
state.queue = [];
state.debugSocket && console.debug(`Subscribe Flush [${ getters.storeName }]`, queue.length, 'items'); // eslint-disable-line no-console
for ( const { action, event, body } of queue ) {
if ( action === 'dispatch' && event === 'load' ) {
// Group loads into one loadMulti when possible
toLoad.push(body);
} else {
// When we hit a different kind of event, process all the previous loads, then the other event.
if ( toLoad.length ) {
await dispatch('loadMulti', toLoad);
toLoad = [];
}
if ( action === 'dispatch' ) {
await dispatch(event, body);
} else if ( action === 'commit' ) {
commit(event, body);
} else {
throw new Error('Invalid queued action');
}
}
}
// Process any remaining loads
if ( toLoad.length ) {
await dispatch('loadMulti', toLoad);
}
state.debugSocket && console.debug(`Subscribe Flush [${ getters.storeName }] finished`, (new Date().getTime()) - started, 'ms'); // eslint-disable-line no-console
},
rehydrateSubscribe({ state, dispatch }) {
if ( state.wantSocket && !state.socket ) {
dispatch('subscribe');
}
},
reconnectWatches({
state, getters, commit, dispatch
}) {
const promises = [];
for ( const entry of state.started.slice() ) {
console.info(`Reconnect [${ getters.storeName }]`, JSON.stringify(entry)); // eslint-disable-line no-console
if ( getters.schemaFor(entry.type) ) {
commit('setWatchStopped', entry);
// Delete the cached socket revision, forcing the watch to get latest revision from cached resources instead
delete entry.revision;
promises.push(dispatch('watch', entry));
}
}
return Promise.all(promises);
},
/**
* Socket has been closed, restart afresh (make http request, ensure we re-watch)
*/
async resyncWatch({ getters, dispatch }, params) {
console.info(`Resync [${ getters.storeName }]`, params); // eslint-disable-line no-console
const { backOffId, ...others } = params;
await dispatch('fetchResources', {
params: others,
backOffId,
opt: { force: true, forceWatch: true }
});
},
/**
* Helper function used by fetchResources
*
* Integrates the concept of 'back-off' to reduce spam, overwrite stale old requests, etc
*/
async fetchPageResources({ getters, dispatch }, {
opt, storePagination, params, backOffId
}) {
const { resourceType, namespace, revision } = params;
const type = resourceType || params.type;
const safeBackOffId = backOffId || getters.backOffId(params, `fetchPageResources`);
const activeRevisionSt = backOff.getBackOff(safeBackOffId)?.metadata?.revision;
const cachedRevisionSt = getters['typeEntry'](resourceType || type)?.revision;
const targetRevision = new SteveRevision(revision);
const activeRevision = new SteveRevision(activeRevisionSt);
const cachedRevision = new SteveRevision(cachedRevisionSt);
const currentRevision = new SteveRevision(activeRevisionSt || cachedRevisionSt);
// Three cases to support HA scenarios 2 + 3
// 1. current version is newer than target revision - abort/ignore (don't overwrite new with old)
// 2. current version is older than target revision - reset previous (drop older requests with older revision, use new revision)
// 3. current version is same as target revision - we're retrying
// There are two places we do this to cover the two cases we make http request following socket changes
// shell/utils/pagination-wrapper.ts - request
// shell/plugins/steve/subscribe.js - fetchPageResources
if (currentRevision.isNewerThan(targetRevision)) {
// Case 1 - abort/ignore (don't overwrite new with old)
// eslint-disable-next-line no-console
console.warn(`Ignoring subscribe request to update '${ type }' with revision '${ targetRevision.revision }' (active revision '${ currentRevision.revision } & cached revision '${ cachedRevision.revision }''). ` +
`This probably means the replica that provided the web socket message has not yet correctly synced it's cache with other fresher replicas.`);
return;
}
if (targetRevision.isNewerThan(activeRevision)) {
// Case 2 - reset previous (drop older requests with older revision, use new revision)
console.info(`Dropping previous subscribe request to update '${ type }' with revision '${ currentRevision.revision }' (new target revision '${ targetRevision.revision }'). `); // eslint-disable-line no-console
backOff.reset(safeBackOffId);
}
try {
// Keep making requests until we make one that succeeds, fails with unknown revision or we run out of retries
await backOff.recurse({
id: safeBackOffId,
metadata: { revision },
description: `Fetching resources for ${ type }. Triggered by web socket`,
canFn: () => {
if (!getters.canBackoff(this.$socket)) {
console.info(`Aborting subscribe request to update '${ type }' with revision '${ currentRevision.revision }' (socket closed). `); // eslint-disable-line no-console
return false;
}
if (!getters['watchStarted'](params)) {
// No watch has started... but are we in initial state where the watch failed due to a bad revision?
const inError = getters.inError(params);
if (inError !== REVISION_TOO_OLD) {
console.info(`Aborting subscribe request to update '${ type }' with revision '${ currentRevision.revision }' (resource not watched). `); // eslint-disable-line no-console
return false;
}
}
return true;
},
continueOnError: async(err) => {
// Have we made a request to a stale replica that does not know about the required revision? If so continue to try until we hit a ripe replica
return err?.status === 400 && err?.code === STEVE_RESPONSE_CODE.UNKNOWN_REVISION;
},
delayedFn: async() => {
return await dispatch('findPage', {
type,
opt: {
...opt,
namespaced: namespace,
revision,
// This brings in page, page size, filter, etc
...storePagination.request,
}
});
},
});
} catch (err) {
// Nothing depends on the error higher in the call stack, so prevent dev full screen errors by catching it
console.info(`Failed subscribe request to update '${ type }' with revision '${ currentRevision.revision }' (error). `, err); // eslint-disable-line no-console
}
},
async fetchResources({
state, getters, dispatch, commit
}, { opt, params, backOffId }) {
const {
resourceType, namespace, id, selector, mode, revision
} = params;
if (!resourceType) {
console.error(`A socket message has prompted a request to fetch a resource but no resource type was supplied`); // eslint-disable-line no-console
return;
}
if ( id ) {
// Fetch an individual resource
await dispatch('find', {