forked from plotly/dash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcallbacks.ts
More file actions
818 lines (743 loc) · 27.3 KB
/
callbacks.ts
File metadata and controls
818 lines (743 loc) · 27.3 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
import {
concat,
flatten,
intersection,
keys,
map,
mergeDeepRight,
path,
pick,
pluck,
values,
toPairs,
zip,
assocPath
} from 'ramda';
import {STATUS, JWT_EXPIRED_MESSAGE} from '../constants/constants';
import {MAX_AUTH_RETRIES} from './constants';
import {
CallbackActionType,
CallbackAggregateActionType
} from '../reducers/callbacks';
import {
CallbackResult,
ICallback,
IExecutedCallback,
IExecutingCallback,
ICallbackPayload,
IStoredCallback,
IBlockedCallback,
IPrioritizedCallback,
LongCallbackInfo,
CallbackResponse,
CallbackResponseData
} from '../types/callbacks';
import {isMultiValued, stringifyId, isMultiOutputProp} from './dependencies';
import {urlBase} from './utils';
import {getCSRFHeader} from '.';
import {createAction, Action} from 'redux-actions';
import {addHttpHeaders} from '../actions';
import {notifyObservers, updateProps} from './index';
import {CallbackJobPayload} from '../reducers/callbackJobs';
import {handlePatch, isPatch} from './patch';
import {getPath} from './paths';
import {requestDependencies} from './requestDependencies';
export const addBlockedCallbacks = createAction<IBlockedCallback[]>(
CallbackActionType.AddBlocked
);
export const addCompletedCallbacks = createAction<number>(
CallbackAggregateActionType.AddCompleted
);
export const addExecutedCallbacks = createAction<IExecutedCallback[]>(
CallbackActionType.AddExecuted
);
export const addExecutingCallbacks = createAction<IExecutingCallback[]>(
CallbackActionType.AddExecuting
);
export const addPrioritizedCallbacks = createAction<ICallback[]>(
CallbackActionType.AddPrioritized
);
export const addRequestedCallbacks = createAction<ICallback[]>(
CallbackActionType.AddRequested
);
export const addStoredCallbacks = createAction<IStoredCallback[]>(
CallbackActionType.AddStored
);
export const addWatchedCallbacks = createAction<IExecutingCallback[]>(
CallbackActionType.AddWatched
);
export const removeExecutedCallbacks = createAction(
CallbackActionType.RemoveExecuted
);
export const removeBlockedCallbacks = createAction<IBlockedCallback[]>(
CallbackActionType.RemoveBlocked
);
export const removeExecutingCallbacks = createAction<IExecutingCallback[]>(
CallbackActionType.RemoveExecuting
);
export const removePrioritizedCallbacks = createAction<ICallback[]>(
CallbackActionType.RemovePrioritized
);
export const removeRequestedCallbacks = createAction<ICallback[]>(
CallbackActionType.RemoveRequested
);
export const removeStoredCallbacks = createAction<IStoredCallback[]>(
CallbackActionType.RemoveStored
);
export const removeWatchedCallbacks = createAction<IExecutingCallback[]>(
CallbackActionType.RemoveWatched
);
export const aggregateCallbacks = createAction<
(Action<ICallback[]> | Action<number> | null)[]
>(CallbackAggregateActionType.Aggregate);
const updateResourceUsage = createAction('UPDATE_RESOURCE_USAGE');
const addCallbackJob = createAction('ADD_CALLBACK_JOB');
const removeCallbackJob = createAction('REMOVE_CALLBACK_JOB');
const setCallbackJobOutdated = createAction('CALLBACK_JOB_OUTDATED');
function unwrapIfNotMulti(
paths: any,
idProps: any,
spec: any,
anyVals: any,
depType: any
) {
let msg = '';
if (isMultiValued(spec)) {
return [idProps, msg];
}
if (idProps.length !== 1) {
if (!idProps.length) {
const isStr = typeof spec.id === 'string';
msg =
'A nonexistent object was used in an `' +
depType +
'` of a Dash callback. The id of this object is ' +
(isStr
? '`' + spec.id + '`'
: JSON.stringify(spec.id) +
(anyVals ? ' with MATCH values ' + anyVals : '')) +
' and the property is `' +
spec.property +
(isStr
? '`. The string ids in the current layout are: [' +
keys(paths.strs).join(', ') +
']'
: '`. The wildcard ids currently available are logged above.');
} else {
msg =
'Multiple objects were found for an `' +
depType +
'` of a callback that only takes one value. The id spec is ' +
JSON.stringify(spec.id) +
(anyVals ? ' with MATCH values ' + anyVals : '') +
' and the property is `' +
spec.property +
'`. The objects we found are: ' +
JSON.stringify(map(pick(['id', 'property']), idProps));
}
}
return [idProps[0], msg];
}
function fillVals(
paths: any,
layout: any,
cb: ICallback,
specs: any,
depType: any,
allowAllMissing = false
) {
const getter = depType === 'Input' ? cb.getInputs : cb.getState;
const errors: any[] = [];
let emptyMultiValues = 0;
const inputVals = getter(paths).map((inputList: any, i: number) => {
const [inputs, inputError] = unwrapIfNotMulti(
paths,
inputList.map(({id, property, path: path_}: any) => ({
id,
property,
value: path([...path_, 'props', property], layout) as any
})),
specs[i],
cb.anyVals,
depType
);
if (isMultiValued(specs[i]) && !inputs.length) {
emptyMultiValues++;
}
if (inputError) {
errors.push(inputError);
}
return inputs;
});
if (errors.length) {
if (
allowAllMissing &&
errors.length + emptyMultiValues === inputVals.length
) {
// We have at least one non-multivalued input, but all simple and
// multi-valued inputs are missing.
// (if all inputs are multivalued and all missing we still return
// them as normal, and fire the callback.)
return null;
}
// If we get here we have some missing and some present inputs.
// Or all missing in a context that doesn't allow this.
// That's a real problem, so throw the first message as an error.
refErr(errors, paths);
}
return inputVals;
}
function refErr(errors: any, paths: any) {
const err = errors[0];
if (err.indexOf('logged above') !== -1) {
// Wildcard reference errors mention a list of wildcard specs logged
// TODO: unwrapped list of wildcard ids?
// eslint-disable-next-line no-console
console.error(paths.objs);
}
throw new ReferenceError(err);
}
const getVals = (input: any) =>
Array.isArray(input) ? pluck('value', input) : input.value;
const zipIfArray = (a: any, b: any) =>
Array.isArray(a) ? zip(a, b) : [[a, b]];
function cleanOutputProp(property: string) {
return property.split('@')[0];
}
async function handleClientside(
dispatch: any,
clientside_function: any,
config: any,
payload: ICallbackPayload
) {
const dc = ((window as any).dash_clientside =
(window as any).dash_clientside || {});
if (!dc.no_update) {
Object.defineProperty(dc, 'no_update', {
value: {description: 'Return to prevent updating an Output.'},
writable: false
});
Object.defineProperty(dc, 'PreventUpdate', {
value: {description: 'Throw to prevent updating all Outputs.'},
writable: false
});
}
const {inputs, outputs, state} = payload;
const requestTime = Date.now();
const inputDict = inputsToDict(inputs);
const stateDict = inputsToDict(state);
const result: any = {};
let status: any = STATUS.OK;
try {
const {namespace, function_name} = clientside_function;
let args = inputs.map(getVals);
if (state) {
args = concat(args, state.map(getVals));
}
// setup callback context
dc.callback_context = {};
dc.callback_context.triggered = payload.changedPropIds.map(prop_id => ({
prop_id: prop_id,
value: inputDict[prop_id]
}));
dc.callback_context.triggered_id = getTriggeredId(
payload.changedPropIds
);
dc.callback_context.inputs_list = inputs;
dc.callback_context.inputs = inputDict;
dc.callback_context.states_list = state;
dc.callback_context.states = stateDict;
let returnValue = dc[namespace][function_name](...args);
delete dc.callback_context;
if (typeof returnValue?.then === 'function') {
returnValue = await returnValue;
}
zipIfArray(outputs, returnValue).forEach(([outi, reti]) => {
zipIfArray(outi, reti).forEach(([outij, retij]) => {
const {id, property} = outij;
const idStr = stringifyId(id);
const dataForId = (result[idStr] = result[idStr] || {});
if (retij !== dc.no_update) {
dataForId[cleanOutputProp(property)] = retij;
}
});
});
} catch (e) {
if (e === dc.PreventUpdate) {
status = STATUS.PREVENT_UPDATE;
} else {
status = STATUS.CLIENTSIDE_ERROR;
throw e;
}
} finally {
delete dc.callback_context;
// Setting server = client forces network = 0
const totalTime = Date.now() - requestTime;
const resources = {
__dash_server: totalTime,
__dash_client: totalTime,
__dash_upload: 0,
__dash_download: 0
};
if (config.ui) {
dispatch(
updateResourceUsage({
id: payload.output,
usage: resources,
status,
result,
inputs,
state
})
);
}
}
return result;
}
function sideUpdate(outputs: any, dispatch: any, paths: any) {
toPairs(outputs).forEach(([id, value]) => {
const [componentId, propName] = id.split('.');
const componentPath = paths.strs[componentId];
dispatch(
updateProps({
props: {[propName]: value},
itempath: componentPath
})
);
dispatch(
notifyObservers({id: componentId, props: {[propName]: value}})
);
});
}
function handleServerside(
dispatch: any,
hooks: any,
config: any,
payload: any,
paths: any,
long: LongCallbackInfo | undefined,
additionalArgs: [string, string, boolean?][] | undefined,
getState: any,
output: string
): Promise<CallbackResponse> {
if (hooks.request_pre) {
hooks.request_pre(payload);
}
const requestTime = Date.now();
const body = JSON.stringify(payload);
let cacheKey: string;
let job: string;
let runningOff: any;
let progressDefault: any;
let moreArgs = additionalArgs;
const fetchCallback = () => {
const headers = getCSRFHeader() as any;
let url = `${urlBase(config)}_dash-update-component`;
const addArg = (name: string, value: string) => {
let delim = '?';
if (url.includes('?')) {
delim = '&';
}
url = `${url}${delim}${name}=${value}`;
};
if (cacheKey) {
addArg('cacheKey', cacheKey);
}
if (job) {
addArg('job', job);
}
if (moreArgs) {
moreArgs.forEach(([key, value]) => addArg(key, value));
moreArgs = moreArgs.filter(([_, __, single]) => !single);
}
return fetch(
url,
mergeDeepRight(config.fetch, {
method: 'POST',
headers,
body
})
);
};
return new Promise((resolve, reject) => {
const handleOutput = (res: any) => {
const {status} = res;
if (job) {
const callbackJob = getState().callbackJobs[job];
if (callbackJob?.outdated) {
dispatch(removeCallbackJob({jobId: job}));
return resolve({});
}
}
function recordProfile(result: any) {
if (config.ui) {
// Callback profiling - only relevant if we're showing the debug ui
const resources = {
__dash_server: 0,
__dash_client: Date.now() - requestTime,
__dash_upload: body.length,
__dash_download: Number(
res.headers.get('Content-Length')
)
} as any;
const timingHeaders =
res.headers.get('Server-Timing') || '';
timingHeaders.split(',').forEach((header: any) => {
const name = header.split(';')[0];
const dur = header.match(/;dur=[0-9.]+/);
if (dur) {
resources[name] = Number(dur[0].slice(5));
}
});
dispatch(
updateResourceUsage({
id: payload.output,
usage: resources,
status,
result,
inputs: payload.inputs,
state: payload.state
})
);
}
}
const finishLine = (data: CallbackResponseData) => {
const {multi, response} = data;
if (hooks.request_post) {
hooks.request_post(payload, response);
}
let result;
if (multi) {
result = response as CallbackResponse;
} else {
const {output} = payload;
const id = output.substr(0, output.lastIndexOf('.'));
result = {[id]: (response as CallbackResponse).props};
}
recordProfile(result);
resolve(result);
};
const completeJob = () => {
if (job) {
dispatch(removeCallbackJob({jobId: job}));
}
if (runningOff) {
sideUpdate(runningOff, dispatch, paths);
}
if (progressDefault) {
sideUpdate(progressDefault, dispatch, paths);
}
};
if (status === STATUS.OK) {
res.json().then((data: CallbackResponseData) => {
if (!cacheKey && data.cacheKey) {
cacheKey = data.cacheKey;
}
if (!job && data.job) {
const jobInfo: CallbackJobPayload = {
jobId: data.job,
cacheKey: data.cacheKey as string,
cancelInputs: data.cancel,
progressDefault: data.progressDefault,
output
};
dispatch(addCallbackJob(jobInfo));
job = data.job;
}
if (data.progress) {
sideUpdate(data.progress, dispatch, paths);
}
if (data.running) {
sideUpdate(data.running, dispatch, paths);
}
if (!runningOff && data.runningOff) {
runningOff = data.runningOff;
}
if (!progressDefault && data.progressDefault) {
progressDefault = data.progressDefault;
}
if (!long || data.response !== undefined) {
completeJob();
finishLine(data);
} else {
// Poll chain.
setTimeout(
handle,
long.interval !== undefined ? long.interval : 500
);
}
});
} else if (status === STATUS.PREVENT_UPDATE) {
completeJob();
recordProfile({});
resolve({});
} else {
completeJob();
reject(res);
}
};
const handleError = () => {
if (config.ui) {
dispatch(
updateResourceUsage({
id: payload.output,
status: STATUS.NO_RESPONSE,
result: {},
inputs: payload.inputs,
state: payload.state
})
);
}
reject(new Error('Callback failed: the server did not respond.'));
};
const handle = () => {
fetchCallback().then(handleOutput, handleError);
};
handle();
});
}
function inputsToDict(inputs_list: any) {
// Ported directly from _utils.py, inputs_to_dict
// takes an array of inputs (some inputs may be an array)
// returns an Object (map):
// keys of the form `id.property` or `{"id": 0}.property`
// values contain the property value
if (!inputs_list) {
return {};
}
const inputs: any = {};
for (let i = 0; i < inputs_list.length; i++) {
if (Array.isArray(inputs_list[i])) {
const inputsi = inputs_list[i];
for (let ii = 0; ii < inputsi.length; ii++) {
const id_str = `${stringifyId(inputsi[ii].id)}.${
inputsi[ii].property
}`;
inputs[id_str] = inputsi[ii].value ?? null;
}
} else {
const id_str = `${stringifyId(inputs_list[i].id)}.${
inputs_list[i].property
}`;
inputs[id_str] = inputs_list[i].value ?? null;
}
}
return inputs;
}
function getTriggeredId(triggered: string[]): string | object | undefined {
// for regular callbacks, takes the first triggered prop_id, e.g. "btn.n_clicks" and returns "btn"
// for pattern matching callback, e.g. '{"index":0, "type":"btn"}' and returns {index:0, type: "btn"}'
if (triggered && triggered.length) {
let componentId = triggered[0].split('.')[0];
if (componentId.startsWith('{')) {
componentId = JSON.parse(componentId);
}
return componentId;
}
}
export function executeCallback(
cb: IPrioritizedCallback,
config: any,
hooks: any,
paths: any,
layout: any,
{allOutputs}: any,
dispatch: any,
getState: any
): IExecutingCallback {
const {output, inputs, state, clientside_function, long, dynamic_creator} =
cb.callback;
try {
const inVals = fillVals(paths, layout, cb, inputs, 'Input', true);
/* Prevent callback if there's no inputs */
if (inVals === null) {
return {
...cb,
executionPromise: null
};
}
const outputs: any[] = [];
const outputErrors: any[] = [];
allOutputs.forEach((out: any, i: number) => {
const [outi, erri] = unwrapIfNotMulti(
paths,
map(pick(['id', 'property']), out),
cb.callback.outputs[i],
cb.anyVals,
'Output'
);
outputs.push(outi);
if (erri) {
outputErrors.push(erri);
}
});
if (outputErrors.length) {
if (flatten(inVals).length) {
refErr(outputErrors, paths);
}
// This case is all-empty multivalued wildcard inputs,
// which we would normally fire the callback for, except
// some outputs are missing. So instead we treat it like
// regular missing inputs and just silently prevent it.
return {
...cb,
executionPromise: null
};
}
const __execute = async (): Promise<CallbackResult> => {
try {
const payload: ICallbackPayload = {
output,
outputs: isMultiOutputProp(output) ? outputs : outputs[0],
inputs: inVals,
changedPropIds: keys(cb.changedPropIds),
state: cb.callback.state.length
? fillVals(paths, layout, cb, state, 'State')
: undefined
};
if (clientside_function) {
try {
const data = await handleClientside(
dispatch,
clientside_function,
config,
payload
);
return {data, payload};
} catch (error: any) {
return {error, payload};
}
}
let newConfig = config;
let newHeaders: Record<string, string> | null = null;
let lastError: any;
const additionalArgs: [string, string, boolean?][] = [];
values(getState().callbackJobs).forEach(
(job: CallbackJobPayload) => {
if (cb.callback.output === job.output) {
// Terminate the old jobs that are not completed
// set as outdated for the callback promise to
// resolve and remove after.
additionalArgs.push(['oldJob', job.jobId, true]);
dispatch(
setCallbackJobOutdated({jobId: job.jobId})
);
}
if (!job.cancelInputs) {
return;
}
const inter = intersection(
job.cancelInputs,
cb.callback.inputs
);
if (inter.length) {
additionalArgs.push(['cancelJob', job.jobId]);
if (job.progressDefault) {
sideUpdate(
job.progressDefault,
dispatch,
paths
);
}
}
}
);
for (let retry = 0; retry <= MAX_AUTH_RETRIES; retry++) {
try {
let data = await handleServerside(
dispatch,
hooks,
newConfig,
payload,
paths,
long,
additionalArgs.length ? additionalArgs : undefined,
getState,
cb.callback.output
);
if (newHeaders) {
dispatch(addHttpHeaders(newHeaders));
}
// Layout may have changed.
const currentLayout = getState().layout;
flatten(outputs).forEach((out: any) => {
const propName = cleanOutputProp(out.property);
const outputPath = getPath(paths, out.id);
const previousValue = path(
outputPath.concat(['props', propName]),
currentLayout
);
const dataPath = [stringifyId(out.id), propName];
const outputValue = path(dataPath, data);
if (isPatch(outputValue)) {
if (previousValue === undefined) {
throw new Error('Cannot patch undefined');
}
data = assocPath(
dataPath,
handlePatch(previousValue, outputValue),
data
);
}
});
if (dynamic_creator) {
setTimeout(
() => dispatch(requestDependencies()),
0
);
}
return {data, payload};
} catch (res: any) {
lastError = res;
if (
retry <= MAX_AUTH_RETRIES &&
(res.status === STATUS.UNAUTHORIZED ||
res.status === STATUS.BAD_REQUEST)
) {
const body = await res.text();
if (body.includes(JWT_EXPIRED_MESSAGE)) {
if (hooks.request_refresh_jwt !== null) {
let oldJwt = null;
if (config.fetch.headers.Authorization) {
oldJwt =
config.fetch.headers.Authorization.substr(
'Bearer '.length
);
}
const newJwt =
await hooks.request_refresh_jwt(oldJwt);
if (newJwt) {
newHeaders = {
Authorization: `Bearer ${newJwt}`
};
newConfig = mergeDeepRight(config, {
fetch: {
headers: newHeaders
}
});
continue;
}
}
}
}
break;
}
}
// we reach here when we run out of retries.
return {error: lastError, payload: null};
} catch (error: any) {
return {error, payload: null};
}
};
const newCb = {
...cb,
executionPromise: __execute()
};
return newCb;
} catch (error: any) {
return {
...cb,
executionPromise: {error, payload: null}
};
}
}