-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
RefreshScheduler.js
255 lines (238 loc) Β· 9.12 KB
/
RefreshScheduler.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
const uuid = require('uuid/v4');
const R = require('ramda');
class RefreshScheduler {
constructor(serverCore) {
this.serverCore = serverCore;
}
async refreshQueriesForPreAggregation(context, compilerApi, preAggregation, queryingOptions) {
const compilers = await compilerApi.getCompilers();
const query = compilerApi.createQueryByDataSource(compilers, queryingOptions);
if (preAggregation.preAggregation.partitionGranularity) {
const dataSource = query.cubeDataSource(preAggregation.cube);
const orchestratorApi = this.serverCore.getOrchestratorApi(context);
const [startDate, endDate] =
await Promise.all(
compilerApi.createQueryByDataSource(compilers, queryingOptions, dataSource)
.preAggregationStartEndQueries(preAggregation.cube, preAggregation.preAggregation)
.map(sql => orchestratorApi.executeQuery({
query: sql[0],
values: sql[1],
continueWait: true,
cacheKeyQueries: [],
dataSource
}))
);
const extractDate = ({ data }) => {
// TODO some backends return dates as objects here. Use ApiGateway data transformation ?
data = JSON.parse(JSON.stringify(data));
return data[0] && data[0][Object.keys(data[0])[0]];
};
const dateRange = [extractDate(startDate), extractDate(endDate)];
if (!dateRange[0] || !dateRange[1]) {
// Empty table. Nothing to refresh.
return [];
}
const baseQuery = {
...queryingOptions,
...preAggregation.references,
timeDimensions: [{
...preAggregation.references.timeDimensions[0],
dateRange
}]
};
const partitionQuery = compilerApi.createQueryByDataSource(compilers, baseQuery);
const { partitionDimension } = partitionQuery.preAggregations.partitionDimension(preAggregation);
return partitionDimension.timeSeries().map(range => ({
...baseQuery,
timeDimensions: [{
...preAggregation.references.timeDimensions[0],
dateRange: range
}]
}));
} else if (preAggregation.preAggregation.type === 'rollup') {
return [{ ...queryingOptions, ...preAggregation.references }];
} else if (preAggregation.preAggregation.type === 'originalSql') {
const cubeFromPath = query.cubeEvaluator.cubeFromPath(preAggregation.cube);
const measuresCount = Object.keys(cubeFromPath.measures || {}).length;
const dimensionsCount = Object.keys(cubeFromPath.dimensions || {}).length;
if (measuresCount === 0 && dimensionsCount === 0) {
throw new Error(
`Can't refresh pre-aggregation without measures and dimensions: ${preAggregation.preAggregationName}`
);
}
return [{
...queryingOptions,
...(
measuresCount &&
{ measures: [`${preAggregation.cube}.${Object.keys(cubeFromPath.measures)[0]}`] }
),
...(
dimensionsCount &&
{ dimensions: [`${preAggregation.cube}.${Object.keys(cubeFromPath.dimensions)[0]}`] }
)
}];
} else {
throw new Error(
`Scheduled refresh is unsupported for ${preAggregation.preAggregation.type} of ${preAggregation.preAggregationName}`
);
}
}
async runScheduledRefresh(context, queryingOptions) {
queryingOptions = { timezones: [queryingOptions.timezone || 'UTC'], ...queryingOptions };
const { throwErrors, ...restOptions } = queryingOptions;
context = { requestId: `scheduler-${context && context.requestId || uuid()}`, ...context };
this.serverCore.logger('Refresh Scheduler Run', {
authInfo: context.authInfo,
requestId: context.requestId
});
try {
const compilerApi = this.serverCore.getCompilerApi(context);
await Promise.all([
this.refreshCubesRefreshKey(context, compilerApi, restOptions),
this.refreshPreAggregations(context, compilerApi, restOptions)
]);
return {
finished: true
};
} catch (e) {
if (e.error !== 'Continue wait') {
this.serverCore.logger('Refresh Scheduler Error', {
error: e.error || e.stack || e.toString(),
authInfo: context.authInfo,
requestId: context.requestId
});
}
if (throwErrors) {
throw e;
}
}
return { finished: false };
}
async refreshCubesRefreshKey(context, compilerApi, queryingOptions) {
const compilers = await compilerApi.getCompilers();
const queryForEvaluation = compilerApi.createQueryByDataSource(compilers, {});
await Promise.all(queryForEvaluation.cubeEvaluator.cubeNames().map(async cube => {
const cubeFromPath = queryForEvaluation.cubeEvaluator.cubeFromPath(cube);
const measuresCount = Object.keys(cubeFromPath.measures || {}).length;
const dimensionsCount = Object.keys(cubeFromPath.dimensions || {}).length;
if (measuresCount === 0 && dimensionsCount === 0) {
return;
}
await Promise.all(queryingOptions.timezones.map(async timezone => {
const query = {
...queryingOptions,
...(
measuresCount &&
{ measures: [`${cube}.${Object.keys(cubeFromPath.measures)[0]}`] }
),
...(
dimensionsCount &&
{ dimensions: [`${cube}.${Object.keys(cubeFromPath.dimensions)[0]}`] }
),
timezone
};
const sqlQuery = await compilerApi.getSql(query);
const orchestratorApi = this.serverCore.getOrchestratorApi(context);
await orchestratorApi.executeQuery({
...sqlQuery,
preAggregations: [],
query: 'SELECT 1', // TODO get rid off it
continueWait: true,
renewQuery: true,
requestId: context.requestId
});
}));
}));
}
async roundRobinRefreshPreAggregationsQueryIterator(context, compilerApi, queryingOptions) {
const { timezones } = queryingOptions;
const scheduledPreAggregations = await compilerApi.scheduledPreAggregations();
let preAggregationCursor = null;
let timezoneCursor = 0;
let partitionCursor = 0;
const queriesCache = {};
const finishedPartitions = {};
scheduledPreAggregations.forEach((p, pi) => {
timezones.forEach((t, ti) => {
finishedPartitions[`${pi}_${ti}`] = false;
});
});
const queriesForPreAggregation = async (preAggregationIndex, timezone) => {
const key = `${preAggregationIndex}_${timezone}`;
if (!queriesCache[key]) {
const preAggregation = scheduledPreAggregations[preAggregationIndex];
queriesCache[key] = this.refreshQueriesForPreAggregation(
context, compilerApi, preAggregation, { ...queryingOptions, timezone }
);
}
return queriesCache[key];
};
const advance = async () => {
preAggregationCursor = preAggregationCursor != null ? preAggregationCursor + 1 : 0;
if (preAggregationCursor >= scheduledPreAggregations.length) {
preAggregationCursor = 0;
timezoneCursor += 1;
}
if (timezoneCursor >= timezones.length) {
timezoneCursor = 0;
partitionCursor += 1;
}
const queries = await queriesForPreAggregation(preAggregationCursor, timezones[timezoneCursor]);
if (partitionCursor < queries.length) {
const queryCursor = queries.length - 1 - partitionCursor;
const query = queries[queryCursor];
const sqlQuery = await compilerApi.getSql(query);
return {
...sqlQuery,
preAggregations: sqlQuery.preAggregations.map(
(p) => ({ ...p, priority: queryCursor - queries.length })
),
continueWait: true,
renewQuery: true,
requestId: context.requestId,
timezone: timezones[timezoneCursor]
};
} else {
finishedPartitions[`${preAggregationCursor}_${timezoneCursor}`] = true;
return null;
}
};
return {
next: async () => {
let next;
while (Object.keys(finishedPartitions).find(k => !finishedPartitions[k])) {
next = await advance();
if (next) {
return next;
}
}
return null;
}
};
}
async refreshPreAggregations(context, compilerApi, queryingOptions) {
let { concurrency, workerIndices } = queryingOptions;
concurrency = concurrency || 1;
workerIndices = workerIndices || R.range(0, concurrency);
return Promise.all(R.range(0, concurrency)
.filter(workerIndex => workerIndices.indexOf(workerIndex) !== -1)
.map(async workerIndex => {
const queryIterator = await this.roundRobinRefreshPreAggregationsQueryIterator(
context, compilerApi, queryingOptions
);
for (;;) {
for (let i = 0; i < concurrency; i++) {
const nextQuery = await queryIterator.next();
if (!nextQuery) {
return;
}
if (i === workerIndex) {
const orchestratorApi = this.serverCore.getOrchestratorApi(context);
await orchestratorApi.executeQuery(nextQuery);
}
}
}
}));
}
}
module.exports = RefreshScheduler;