forked from apache/superset
/
chartAction.js
447 lines (404 loc) · 13.4 KB
/
chartAction.js
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
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/* eslint no-undef: 'error' */
/* eslint no-param-reassign: ["error", { "props": false }] */
import moment from 'moment';
import { t } from '@superset-ui/translation';
import {
getChartBuildQueryRegistry,
getChartMetadataRegistry,
} from '@superset-ui/chart';
import { SupersetClient } from '@superset-ui/connection';
import { isFeatureEnabled, FeatureFlag } from 'src/featureFlags';
import {
getExploreUrl,
getAnnotationJsonUrl,
postForm,
} from '../explore/exploreUtils';
import {
requiresQuery,
ANNOTATION_SOURCE_TYPES,
} from '../modules/AnnotationTypes';
import { addDangerToast } from '../messageToasts/actions';
import { logEvent } from '../logger/actions';
import { Logger, LOG_ACTIONS_LOAD_CHART } from '../logger/LogUtils';
import getClientErrorObject from '../utils/getClientErrorObject';
import { allowCrossDomain as allowDomainSharding } from '../utils/hostNamesConfig';
export const CHART_UPDATE_STARTED = 'CHART_UPDATE_STARTED';
export function chartUpdateStarted(queryController, latestQueryFormData, key) {
return {
type: CHART_UPDATE_STARTED,
queryController,
latestQueryFormData,
key,
};
}
export const CHART_UPDATE_SUCCEEDED = 'CHART_UPDATE_SUCCEEDED';
export function chartUpdateSucceeded(queryResponse, key) {
return { type: CHART_UPDATE_SUCCEEDED, queryResponse, key };
}
export const CHART_UPDATE_STOPPED = 'CHART_UPDATE_STOPPED';
export function chartUpdateStopped(key) {
return { type: CHART_UPDATE_STOPPED, key };
}
export const CHART_UPDATE_TIMEOUT = 'CHART_UPDATE_TIMEOUT';
export function chartUpdateTimeout(statusText, timeout, key) {
return { type: CHART_UPDATE_TIMEOUT, statusText, timeout, key };
}
export const CHART_UPDATE_FAILED = 'CHART_UPDATE_FAILED';
export function chartUpdateFailed(queryResponse, key) {
return { type: CHART_UPDATE_FAILED, queryResponse, key };
}
export const CHART_RENDERING_FAILED = 'CHART_RENDERING_FAILED';
export function chartRenderingFailed(error, key, stackTrace) {
return { type: CHART_RENDERING_FAILED, error, key, stackTrace };
}
export const CHART_RENDERING_SUCCEEDED = 'CHART_RENDERING_SUCCEEDED';
export function chartRenderingSucceeded(key) {
return { type: CHART_RENDERING_SUCCEEDED, key };
}
export const REMOVE_CHART = 'REMOVE_CHART';
export function removeChart(key) {
return { type: REMOVE_CHART, key };
}
export const ANNOTATION_QUERY_SUCCESS = 'ANNOTATION_QUERY_SUCCESS';
export function annotationQuerySuccess(annotation, queryResponse, key) {
return { type: ANNOTATION_QUERY_SUCCESS, annotation, queryResponse, key };
}
export const ANNOTATION_QUERY_STARTED = 'ANNOTATION_QUERY_STARTED';
export function annotationQueryStarted(annotation, queryController, key) {
return { type: ANNOTATION_QUERY_STARTED, annotation, queryController, key };
}
export const ANNOTATION_QUERY_FAILED = 'ANNOTATION_QUERY_FAILED';
export function annotationQueryFailed(annotation, queryResponse, key) {
return { type: ANNOTATION_QUERY_FAILED, annotation, queryResponse, key };
}
export function runAnnotationQuery(
annotation,
timeout = 60,
formData = null,
key,
) {
return function (dispatch, getState) {
const sliceKey = key || Object.keys(getState().charts)[0];
// make a copy of formData, not modifying original formData
const fd = {
...(formData || getState().charts[sliceKey].latestQueryFormData),
};
if (!requiresQuery(annotation.sourceType)) {
return Promise.resolve();
}
const granularity = fd.time_grain_sqla || fd.granularity;
fd.time_grain_sqla = granularity;
fd.granularity = granularity;
const overridesKeys = Object.keys(annotation.overrides);
if (overridesKeys.includes('since') || overridesKeys.includes('until')) {
annotation.overrides = {
...annotation.overrides,
time_range: null,
};
}
const sliceFormData = Object.keys(annotation.overrides).reduce(
(d, k) => ({
...d,
[k]: annotation.overrides[k] || fd[k],
}),
{},
);
if (fd !== null) {
const hasExtraFilters = fd.extra_filters && fd.extra_filters.length > 0;
sliceFormData.extra_filters = hasExtraFilters
? fd.extra_filters
: undefined;
}
const isNative = annotation.sourceType === ANNOTATION_SOURCE_TYPES.NATIVE;
const url = getAnnotationJsonUrl(annotation.value, sliceFormData, isNative);
const controller = new AbortController();
const { signal } = controller;
dispatch(annotationQueryStarted(annotation, controller, sliceKey));
return SupersetClient.get({
url,
signal,
timeout: timeout * 1000,
})
.then(({ json }) =>
dispatch(annotationQuerySuccess(annotation, json, sliceKey)),
)
.catch(response =>
getClientErrorObject(response).then(err => {
if (err.statusText === 'timeout') {
dispatch(
annotationQueryFailed(
annotation,
{ error: 'Query Timeout' },
sliceKey,
),
);
} else if ((err.error || '').toLowerCase().includes('no data')) {
dispatch(annotationQuerySuccess(annotation, err, sliceKey));
} else if (err.statusText !== 'abort') {
dispatch(annotationQueryFailed(annotation, err, sliceKey));
}
}),
);
};
}
export const TRIGGER_QUERY = 'TRIGGER_QUERY';
export function triggerQuery(value = true, key) {
return { type: TRIGGER_QUERY, value, key };
}
// this action is used for forced re-render without fetch data
export const RENDER_TRIGGERED = 'RENDER_TRIGGERED';
export function renderTriggered(value, key) {
return { type: RENDER_TRIGGERED, value, key };
}
export const UPDATE_QUERY_FORM_DATA = 'UPDATE_QUERY_FORM_DATA';
export function updateQueryFormData(value, key) {
return { type: UPDATE_QUERY_FORM_DATA, value, key };
}
// in the sql lab -> explore flow, user can inline edit chart title,
// then the chart will be assigned a new slice_id
export const UPDATE_CHART_ID = 'UPDATE_CHART_ID';
export function updateChartId(newId, key = 0) {
return { type: UPDATE_CHART_ID, newId, key };
}
export const ADD_CHART = 'ADD_CHART';
export function addChart(chart, key) {
return { type: ADD_CHART, chart, key };
}
function legacyChartDataRequest(
formData,
force,
method,
dashboardId,
requestParams,
) {
const url = getExploreUrl({
formData,
endpointType: 'json',
force,
allowDomainSharding,
method,
requestParams: dashboardId ? { dashboard_id: dashboardId } : {},
});
const querySettings = {
...requestParams,
url,
postPayload: { form_data: formData },
};
const clientMethod =
method === 'GET' && isFeatureEnabled(FeatureFlag.CLIENT_CACHE)
? SupersetClient.get
: SupersetClient.post;
return clientMethod(querySettings);
}
async function v1ChartDataRequest(formData, force, requestParams) {
const buildQuery = await getChartBuildQueryRegistry().get(formData.viz_type);
const payload = buildQuery({ ...formData, force });
const querySettings = {
...requestParams,
endpoint: '/api/v1/chart/data',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
};
return SupersetClient.post(querySettings);
}
export function exploreJSON(
formData,
force = false,
timeout = 60,
key,
method,
dashboardId,
) {
return async dispatch => {
const logStart = Logger.getTimestamp();
const controller = new AbortController();
const { useLegacyApi } = getChartMetadataRegistry().get(formData.viz_type);
let requestParams = {
signal: controller.signal,
timeout: timeout * 1000,
};
if (allowDomainSharding) {
requestParams = {
...requestParams,
mode: 'cors',
credentials: 'include',
};
}
const queryPromiseRaw = useLegacyApi
? legacyChartDataRequest(
formData,
force,
method,
dashboardId,
requestParams,
)
: v1ChartDataRequest(formData, force, requestParams);
dispatch(chartUpdateStarted(controller, formData, key));
const queryPromiseCaught = queryPromiseRaw
.then(({ json }) => {
// new API returns an object with an array of restults
// problem: json holds a list of results, when before we were just getting one result.
// `queryResponse` state is used all over the place.
// How to make the entire app compatible with multiple results?
// For now just use the first result.
const result = useLegacyApi ? json : json.result[0];
dispatch(
logEvent(LOG_ACTIONS_LOAD_CHART, {
slice_id: key,
is_cached: result.is_cached,
force_refresh: force,
row_count: result.rowcount,
datasource: formData.datasource,
start_offset: logStart,
ts: new Date().getTime(),
duration: Logger.getTimestamp() - logStart,
has_extra_filters:
formData.extra_filters && formData.extra_filters.length > 0,
viz_type: formData.viz_type,
data_age: result.is_cached
? moment(new Date()).diff(moment.utc(result.cached_dttm))
: null,
}),
);
return dispatch(chartUpdateSucceeded(result, key));
})
.catch(response => {
const appendErrorLog = (errorDetails, isCached) => {
dispatch(
logEvent(LOG_ACTIONS_LOAD_CHART, {
slice_id: key,
has_err: true,
is_cached: isCached,
error_details: errorDetails,
datasource: formData.datasource,
start_offset: logStart,
ts: new Date().getTime(),
duration: Logger.getTimestamp() - logStart,
}),
);
};
if (response.statusText === 'timeout') {
appendErrorLog('timeout');
return dispatch(
chartUpdateTimeout(response.statusText, timeout, key),
);
} else if (response.name === 'AbortError') {
appendErrorLog('abort');
return dispatch(chartUpdateStopped(key));
}
return getClientErrorObject(response).then(parsedResponse => {
// query is processed, but error out.
appendErrorLog(parsedResponse.error, parsedResponse.is_cached);
return dispatch(chartUpdateFailed(parsedResponse, key));
});
});
const annotationLayers = formData.annotation_layers || [];
return Promise.all([
queryPromiseCaught,
dispatch(triggerQuery(false, key)),
dispatch(updateQueryFormData(formData, key)),
...annotationLayers.map(x =>
dispatch(runAnnotationQuery(x, timeout, formData, key)),
),
]);
};
}
export const GET_SAVED_CHART = 'GET_SAVED_CHART';
export function getSavedChart(
formData,
force = false,
timeout = 60,
key,
dashboardId,
) {
/*
* Perform a GET request to `/explore_json`.
*
* This will return the payload of a saved chart, optionally filtered by
* ad-hoc or extra filters from dashboards. Eg:
*
* GET /explore_json?{"chart_id":1}
* GET /explore_json?{"chart_id":1,"extra_filters":"..."}
*
*/
return exploreJSON(formData, force, timeout, key, 'GET', dashboardId);
}
export const POST_CHART_FORM_DATA = 'POST_CHART_FORM_DATA';
export function postChartFormData(
formData,
force = false,
timeout = 60,
key,
dashboardId,
) {
/*
* Perform a POST request to `/explore_json`.
*
* This will post the form data to the endpoint, returning a new chart.
*
*/
return exploreJSON(formData, force, timeout, key, 'POST', dashboardId);
}
export function redirectSQLLab(formData) {
return dispatch => {
const url = getExploreUrl({
formData,
endpointType: 'query',
});
return SupersetClient.post({
url,
postPayload: { form_data: formData },
})
.then(({ json }) => {
const redirectUrl = '/superset/sqllab';
const payload = {
datasourceKey: formData.datasource,
sql: json.query,
};
postForm(redirectUrl, payload);
})
.catch(() =>
dispatch(addDangerToast(t('An error occurred while loading the SQL'))),
);
};
}
export function refreshChart(chartKey, force, dashboardId) {
return (dispatch, getState) => {
const chart = (getState().charts || {})[chartKey];
const timeout = getState().dashboardInfo.common.conf
.SUPERSET_WEBSERVER_TIMEOUT;
if (
!chart.latestQueryFormData ||
Object.keys(chart.latestQueryFormData).length === 0
) {
return;
}
dispatch(
postChartFormData(
chart.latestQueryFormData,
force,
timeout,
chart.id,
dashboardId,
),
);
};
}