/
PreAggregations.ts
2245 lines (1999 loc) Β· 77.9 KB
/
PreAggregations.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
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
import crypto from 'crypto';
import R from 'ramda';
import {
addSecondsToLocalTimestamp,
extractDate,
FROM_PARTITION_RANGE,
getEnv,
inDbTimeZone,
timeSeries,
MAX_SOURCE_ROW_LIMIT,
TO_PARTITION_RANGE,
BUILD_RANGE_START_LOCAL,
BUILD_RANGE_END_LOCAL,
utcToLocalTimeZone,
} from '@cubejs-backend/shared';
import { cancelCombinator, SaveCancelFn, DriverInterface, BaseDriver,
DownloadTableData,
InlineTable,
StreamOptions,
UnloadOptions,
DriverCapabilities } from '@cubejs-backend/base-driver';
import { Query, QueryCache, QueryTuple, QueryWithParams } from './QueryCache';
import { ContinueWaitError } from './ContinueWaitError';
import { DriverFactory, DriverFactoryByDataSource } from './DriverFactory';
import { QueryQueue } from './QueryQueue';
import { LargeStreamWarning } from './StreamObjectsCounter';
/// Name of the inline table containing the lambda rows.
export const LAMBDA_TABLE_PREFIX = 'lambda';
function encodeTimeStamp(time) {
return Math.floor(time / 1000).toString(32);
}
function decodeTimeStamp(time) {
return parseInt(time, 32) * 1000;
}
function version(cacheKey) {
let result = '';
const hashCharset = 'abcdefghijklmnopqrstuvwxyz012345';
const digestBuffer = crypto.createHash('md5').update(JSON.stringify(cacheKey)).digest();
let residue = 0;
let shiftCounter = 0;
for (let i = 0; i < 5; i++) {
const byte = digestBuffer.readUInt8(i);
shiftCounter += 8;
// eslint-disable-next-line operator-assignment,no-bitwise
residue = (byte << (shiftCounter - 8)) | residue;
// eslint-disable-next-line no-bitwise
while (residue >> 5) {
result += hashCharset.charAt(residue % 32);
shiftCounter -= 5;
// eslint-disable-next-line operator-assignment,no-bitwise
residue = residue >> 5;
}
}
result += hashCharset.charAt(residue % 32);
return result;
}
// Thereβre community developed and custom drivers which not always up-to-date with latest BaseDriver.
// Extra defence for drivers that don't expose now() yet.
function nowTimestamp(client: DriverInterface) {
return client.nowTimestamp?.() ?? new Date().getTime();
}
// Returns the oldest timestamp, if any.
export function getLastUpdatedAtTimestamp(timestamps: (number | undefined)[]): number | undefined {
timestamps = timestamps.filter(t => t !== undefined);
if (timestamps.length === 0) {
return undefined;
} else {
return Math.min(...timestamps);
}
}
function getStructureVersion(preAggregation) {
const versionArray = [preAggregation.loadSql];
if (preAggregation.indexesSql && preAggregation.indexesSql.length) {
versionArray.push(preAggregation.indexesSql);
}
if (preAggregation.streamOffset) {
versionArray.push(preAggregation.streamOffset);
}
return version(versionArray.length === 1 ? versionArray[0] : versionArray);
}
type VersionEntry = {
// eslint-disable-next-line camelcase
table_name: string,
// eslint-disable-next-line camelcase
content_version: string,
// eslint-disable-next-line camelcase
structure_version: string,
// eslint-disable-next-line camelcase
last_updated_at: number,
// eslint-disable-next-line camelcase
build_range_end?: string,
// eslint-disable-next-line camelcase
naming_version?: number
};
type IndexesSql = { sql: [string, unknown[]], indexName: string }[];
type InvalidationKeys = unknown[];
type QueryKey = [QueryTuple, IndexesSql, InvalidationKeys] | [QueryTuple, InvalidationKeys];
type QueryOptions = {
queryKey: QueryKey;
newVersionEntry: VersionEntry;
query: string;
values: unknown[];
requestId: string;
buildRangeEnd?: string;
};
type TableCacheEntry = {
// eslint-disable-next-line camelcase
table_name?: string;
TABLE_NAME?: string;
// eslint-disable-next-line camelcase
build_range_end?: string;
};
type QueryDateRange = [string, string];
type PartitionRanges = {
buildRange: QueryDateRange,
partitionRanges: QueryDateRange[],
};
type IndexDescription = {
sql: QueryWithParams;
indexName: string;
};
type PreAggJob = {
request: string,
context: { securityContext: any },
preagg: string,
table: string,
target: string,
structure: string,
content: string,
updated: string,
key: any[],
status: string;
timezone: string,
dataSource: string,
};
export type LambdaOptions = {
maxSourceRows: number
};
export type LambdaQuery = {
sqlAndParams: QueryWithParams,
cacheKeyQueries: any[],
};
export type PreAggregationDescription = {
preAggregationsSchema: string;
type: 'rollup' | 'originalSql';
preAggregationId: string;
priority: number;
dataSource: string;
external: boolean;
previewSql: QueryWithParams;
timezone: string;
indexesSql: IndexDescription[];
invalidateKeyQueries: QueryWithParams[];
sql: QueryWithParams;
loadSql: QueryWithParams;
tableName: string;
matchedTimeDimensionDateRange: QueryDateRange;
granularity: string;
partitionGranularity: string;
preAggregationStartEndQueries: [QueryWithParams, QueryWithParams];
timestampFormat: string;
expandedPartition: boolean;
unionWithSourceData: LambdaOptions;
buildRangeEnd?: string;
updateWindowSeconds?: number;
sealAt?: string;
};
const tablesToVersionEntries = (schema, tables: TableCacheEntry[]): VersionEntry[] => R.sortBy(
table => -table.last_updated_at,
tables.map(table => {
const match = (table.table_name || table.TABLE_NAME).match(/(.+)_(.+)_(.+)_(.+)/);
if (!match) {
return null;
}
const entity: any = {
table_name: `${schema}.${match[1]}`,
content_version: match[2],
structure_version: match[3],
};
if (match[4].length < 13) {
entity.last_updated_at = decodeTimeStamp(match[4]);
entity.naming_version = 2;
} else {
entity.last_updated_at = parseInt(match[4], 10);
}
if (table.build_range_end) {
entity.build_range_end = table.build_range_end;
}
return entity;
}).filter(R.identity)
);
type PreAggregationLoadCacheOptions = {
requestId?: string,
dataSource: string,
tablePrefixes?: string[],
};
type VersionEntriesObj = {
versionEntries: VersionEntry[],
byStructure: { [key: string]: VersionEntry },
byContent: { [key: string]: VersionEntry },
byTableName: { [key: string]: VersionEntry },
};
class PreAggregationLoadCache {
private redisPrefix: string;
private driverFactory: DriverFactory;
private queryCache: QueryCache;
// eslint-disable-next-line no-use-before-define
private preAggregations: PreAggregations;
private queryResults: any;
private externalDriverFactory: any;
private requestId: any;
private versionEntries: { [redisKey: string]: Promise<VersionEntriesObj> };
private tables: { [redisKey: string]: TableCacheEntry[] };
// TODO this is in memory cache structure as well however it depends on
// data source only and load cache is per data source for now.
// Make it per data source key in case load cache scope is broaden.
private queryStageState: any;
private dataSource: string;
private tablePrefixes: string[] | null;
public constructor(
redisPrefix,
clientFactory: DriverFactory,
queryCache,
preAggregations,
options: PreAggregationLoadCacheOptions = { dataSource: 'default' }
) {
this.redisPrefix = `${redisPrefix}_${options.dataSource}`;
this.dataSource = options.dataSource;
this.driverFactory = clientFactory;
this.queryCache = queryCache;
this.preAggregations = preAggregations;
this.queryResults = {};
this.externalDriverFactory = preAggregations.externalDriverFactory;
this.requestId = options.requestId;
this.tablePrefixes = options.tablePrefixes;
this.versionEntries = {};
this.tables = {};
}
protected async tablesFromCache(preAggregation, forceRenew?) {
let tables = forceRenew ? null : await this.queryCache.getCacheDriver().get(this.tablesRedisKey(preAggregation));
if (!tables) {
tables = await this.preAggregations.getLoadCacheQueue(this.dataSource).executeInQueue(
'query',
`Fetch tables for ${preAggregation.preAggregationsSchema}`,
{
preAggregation, requestId: this.requestId
},
0,
{ requestId: this.requestId }
);
}
return tables;
}
public async fetchTables(preAggregation: PreAggregationDescription) {
if (preAggregation.external && !this.externalDriverFactory) {
throw new Error('externalDriverFactory is not provided. Please make sure @cubejs-backend/cubestore-driver is installed and use CUBEJS_DEV_MODE=true or provide Cube Store connection env variables for production usage.');
}
const newTables = await this.fetchTablesNoCache(preAggregation);
await this.queryCache.getCacheDriver().set(
this.tablesRedisKey(preAggregation),
newTables,
this.preAggregations.options.preAggregationsSchemaCacheExpire || 60 * 60
);
return newTables;
}
private async fetchTablesNoCache(preAggregation: PreAggregationDescription) {
const client = preAggregation.external ?
await this.externalDriverFactory() :
await this.driverFactory();
if (this.tablePrefixes && client.getPrefixTablesQuery && this.preAggregations.options.skipExternalCacheAndQueue) {
return client.getPrefixTablesQuery(preAggregation.preAggregationsSchema, this.tablePrefixes);
}
return client.getTablesQuery(preAggregation.preAggregationsSchema);
}
public tablesRedisKey(preAggregation: PreAggregationDescription) {
return `SQL_PRE_AGGREGATIONS_TABLES_${this.redisPrefix}_${preAggregation.dataSource}${preAggregation.preAggregationsSchema}${preAggregation.external ? '_EXT' : ''}`;
}
protected async getTablesQuery(preAggregation) {
const redisKey = this.tablesRedisKey(preAggregation);
if (!this.tables[redisKey]) {
const tables = this.preAggregations.options.skipExternalCacheAndQueue && preAggregation.external ?
await this.fetchTablesNoCache(preAggregation) :
await this.tablesFromCache(preAggregation);
if (tables === undefined) {
throw new Error('Pre-aggregation tables are undefined.');
}
this.tables[redisKey] = tables;
}
return this.tables[redisKey];
}
private async calculateVersionEntries(preAggregation): Promise<VersionEntriesObj> {
let versionEntries = tablesToVersionEntries(
preAggregation.preAggregationsSchema,
await this.getTablesQuery(preAggregation)
);
// It presumes strong consistency guarantees for external pre-aggregation tables ingestion
if (!preAggregation.external) {
// eslint-disable-next-line
const [active, toProcess, queries] = await this.fetchQueryStageState();
const targetTableNamesInQueue = (Object.keys(queries))
// eslint-disable-next-line no-use-before-define
.map(q => PreAggregations.targetTableName(queries[q].query.newVersionEntry));
versionEntries = versionEntries.filter(
// eslint-disable-next-line no-use-before-define
e => targetTableNamesInQueue.indexOf(PreAggregations.targetTableName(e)) === -1
);
}
const byContent: { [key: string]: VersionEntry } = {};
const byStructure: { [key: string]: VersionEntry } = {};
const byTableName: { [key: string]: VersionEntry } = {};
versionEntries.forEach(e => {
const contentKey = `${e.table_name}_${e.content_version}`;
if (!byContent[contentKey]) {
byContent[contentKey] = e;
}
const structureKey = `${e.table_name}_${e.structure_version}`;
if (!byStructure[structureKey]) {
byStructure[structureKey] = e;
}
if (!byTableName[e.table_name]) {
byTableName[e.table_name] = e;
}
});
return { versionEntries, byContent, byStructure, byTableName };
}
public async getVersionEntries(preAggregation): Promise<VersionEntriesObj> {
if (this.tablePrefixes && !this.tablePrefixes.find(p => preAggregation.tableName.split('.')[1].startsWith(p))) {
throw new Error(`Load cache tries to load table ${preAggregation.tableName} outside of tablePrefixes filter: ${this.tablePrefixes.join(', ')}`);
}
const redisKey = this.tablesRedisKey(preAggregation);
if (!this.versionEntries[redisKey]) {
this.versionEntries[redisKey] = this.calculateVersionEntries(preAggregation).catch(e => {
delete this.versionEntries[redisKey];
throw e;
});
}
return this.versionEntries[redisKey];
}
protected async keyQueryResult(sqlQuery: QueryWithParams, waitForRenew, priority) {
const [query, values, queryOptions]: QueryTuple = Array.isArray(sqlQuery) ? sqlQuery : [sqlQuery, [], {}];
if (!this.queryResults[this.queryCache.queryRedisKey([query, values])]) {
this.queryResults[this.queryCache.queryRedisKey([query, values])] = await this.queryCache.cacheQueryResult(
query,
values,
[query, values],
60 * 60,
{
renewalThreshold: this.queryCache.options.refreshKeyRenewalThreshold
|| queryOptions?.renewalThreshold || 2 * 60,
renewalKey: [query, values],
waitForRenew,
priority,
requestId: this.requestId,
dataSource: this.dataSource,
useInMemory: true,
external: queryOptions?.external
}
);
}
return this.queryResults[this.queryCache.queryRedisKey([query, values])];
}
protected hasKeyQueryResult(keyQuery) {
return !!this.queryResults[this.queryCache.queryRedisKey(keyQuery)];
}
protected async getQueryStage(stageQueryKey) {
const queue = await this.preAggregations.getQueue(this.dataSource);
await this.fetchQueryStageState(queue);
return queue.getQueryStage(stageQueryKey, undefined, this.queryStageState);
}
protected async fetchQueryStageState(queue?) {
queue = queue || await this.preAggregations.getQueue(this.dataSource);
if (!this.queryStageState) {
this.queryStageState = await queue.fetchQueryStageState();
}
return this.queryStageState;
}
protected async reset(preAggregation) {
await this.tablesFromCache(preAggregation, true);
this.tables = {};
this.queryStageState = undefined;
this.versionEntries = {};
}
}
type LoadPreAggregationResult = {
targetTableName: string;
refreshKeyValues: any[];
lastUpdatedAt: number;
buildRangeEnd?: string;
lambdaTable?: InlineTable;
queryKey?: any[];
};
export class PreAggregationLoader {
// eslint-disable-next-line no-use-before-define
private preAggregations: PreAggregations;
public preAggregation: any;
private preAggregationsTablesToTempTables: any;
private loadCache: any;
/**
* Determines whether current instance instantiated for a jobed build query
* (initialized by the /cubejs-system/v1/pre-aggregations/jobs endpoint) or
* not.
*/
private isJob: boolean;
private waitForRenew: boolean;
private forceBuild: boolean;
private orphanedTimeout: number;
private externalDriverFactory: DriverFactory;
private requestId: string;
private metadata: any;
private structureVersionPersistTime: any;
private externalRefresh: boolean;
public constructor(
private readonly redisPrefix: string,
private readonly driverFactory: DriverFactory,
private readonly logger: any,
private readonly queryCache: QueryCache,
// eslint-disable-next-line no-use-before-define
preAggregations: PreAggregations,
preAggregation,
preAggregationsTablesToTempTables,
loadCache,
options: any = {}
) {
this.preAggregations = preAggregations;
this.preAggregation = preAggregation;
this.preAggregationsTablesToTempTables = preAggregationsTablesToTempTables;
this.loadCache = loadCache;
this.isJob = !!options.isJob;
this.waitForRenew = options.waitForRenew;
this.forceBuild = options.forceBuild;
this.orphanedTimeout = options.orphanedTimeout;
this.externalDriverFactory = preAggregations.externalDriverFactory;
this.requestId = options.requestId;
this.metadata = options.metadata;
this.structureVersionPersistTime = preAggregations.structureVersionPersistTime;
this.externalRefresh = options.externalRefresh;
if (this.externalRefresh && this.waitForRenew) {
const message = 'Invalid configuration - when externalRefresh is true, it will not perform a renew, therefore you cannot wait for it using waitForRenew.';
if (['production', 'test'].includes(getEnv('nodeEnv'))) {
throw new Error(message);
} else {
this.logger('Invalid Configuration', {
requestId: this.requestId,
warning: message,
});
this.waitForRenew = false;
}
}
}
public async loadPreAggregation(
throwOnMissingPartition: boolean,
): Promise<null | LoadPreAggregationResult> {
const notLoadedKey = (this.preAggregation.invalidateKeyQueries || [])
.find(keyQuery => !this.loadCache.hasKeyQueryResult(keyQuery));
if (this.isJob || !(notLoadedKey && !this.waitForRenew)) {
// Case 1: pre-agg build job processing.
// Case 2: either we have no data cached for this rollup or waitForRenew
// is true, either way, synchronously renew what data is needed so that
// the most current data will be returned fo the current request.
const result = await this.loadPreAggregationWithKeys();
const refreshKeyValues = await this.getInvalidationKeyValues();
return {
...result,
refreshKeyValues,
queryKey: this.isJob
// We need to return a queryKey value for the jobed build query
// (initialized by the /cubejs-system/v1/pre-aggregations/jobs
// endpoint) as a part of the response to make it possible to get a
// query result from the cache by the other API call.
? this.preAggregationQueryKey(refreshKeyValues)
: undefined,
};
} else {
// Case 3: pre-agg is exists
const structureVersion = getStructureVersion(this.preAggregation);
const getVersionsStarted = new Date();
const { byStructure } = await this.loadCache.getVersionEntries(this.preAggregation);
this.logger('Load PreAggregations Tables', {
preAggregation: this.preAggregation,
requestId: this.requestId,
duration: (new Date().getTime() - getVersionsStarted.getTime())
});
const versionEntryByStructureVersion = byStructure[`${this.preAggregation.tableName}_${structureVersion}`];
if (this.externalRefresh) {
if (!versionEntryByStructureVersion && throwOnMissingPartition) {
// eslint-disable-next-line no-use-before-define
throw new Error(PreAggregations.noPreAggregationPartitionsBuiltMessage([this.preAggregation]));
}
if (!versionEntryByStructureVersion) {
return null;
} else {
// the rollups are being maintained independently of this instance of cube.js
// immediately return the latest rollup data that instance already has
return {
targetTableName: this.targetTableName(versionEntryByStructureVersion),
lastUpdatedAt: versionEntryByStructureVersion.last_updated_at,
refreshKeyValues: [],
};
}
}
if (versionEntryByStructureVersion) {
// this triggers an asyncronous/background load of the pre-aggregation but immediately
// returns the latest data it already has
this.loadPreAggregationWithKeys().catch(e => {
if (!(e instanceof ContinueWaitError)) {
this.logger('Error loading pre-aggregation', {
error: (e.stack || e),
preAggregation: this.preAggregation,
requestId: this.requestId
});
}
});
return {
targetTableName: this.targetTableName(versionEntryByStructureVersion),
refreshKeyValues: [],
lastUpdatedAt: versionEntryByStructureVersion.last_updated_at,
buildRangeEnd: versionEntryByStructureVersion.build_range_end,
};
} else {
// no rollup has been built yet - build it synchronously as part of responding to this request
return this.loadPreAggregationWithKeys();
}
}
}
protected async loadPreAggregationWithKeys(): Promise<LoadPreAggregationResult> {
const invalidationKeys = await this.getPartitionInvalidationKeyValues();
const contentVersion = this.contentVersion(invalidationKeys);
const structureVersion = getStructureVersion(this.preAggregation);
const versionEntries = await this.loadCache.getVersionEntries(this.preAggregation);
const getVersionEntryByContentVersion = ({ byContent }: VersionEntriesObj) => byContent[`${this.preAggregation.tableName}_${contentVersion}`];
const versionEntryByContentVersion = getVersionEntryByContentVersion(versionEntries);
if (versionEntryByContentVersion && !this.forceBuild) {
return {
targetTableName: this.targetTableName(versionEntryByContentVersion),
refreshKeyValues: [],
lastUpdatedAt: versionEntryByContentVersion.last_updated_at,
buildRangeEnd: versionEntryByContentVersion.build_range_end,
};
}
// TODO this check can be redundant due to structure version is already checked in loadPreAggregation()
if (
!this.waitForRenew &&
// eslint-disable-next-line no-use-before-define
await this.loadCache.getQueryStage(PreAggregations.preAggregationQueryCacheKey(this.preAggregation))
) {
const versionEntryByStructureVersion = versionEntries.byStructure[`${this.preAggregation.tableName}_${structureVersion}`];
if (versionEntryByStructureVersion) {
return {
targetTableName: this.targetTableName(versionEntryByStructureVersion),
refreshKeyValues: [],
lastUpdatedAt: versionEntryByStructureVersion.last_updated_at,
buildRangeEnd: versionEntryByStructureVersion.build_range_end,
};
}
}
const client = this.preAggregation.external ?
await this.externalDriverFactory() :
await this.driverFactory();
if (!versionEntries.versionEntries.length) {
await client.createSchemaIfNotExists(this.preAggregation.preAggregationsSchema);
}
// ensure we find appropriate structure version before invalidating anything
const versionEntry =
versionEntries.byStructure[`${this.preAggregation.tableName}_${structureVersion}`] ||
versionEntries.byTableName[this.preAggregation.tableName];
const newVersionEntry = {
table_name: this.preAggregation.tableName,
structure_version: structureVersion,
content_version: contentVersion,
last_updated_at: nowTimestamp(client),
naming_version: 2,
};
const mostRecentResult: () => Promise<LoadPreAggregationResult> = async () => {
await this.loadCache.reset(this.preAggregation);
const lastVersion = getVersionEntryByContentVersion(
await this.loadCache.getVersionEntries(this.preAggregation)
);
if (!lastVersion) {
throw new Error(`Pre-aggregation table is not found for ${this.preAggregation.tableName} after it was successfully created`);
}
return {
targetTableName: this.targetTableName(lastVersion),
refreshKeyValues: [],
lastUpdatedAt: lastVersion.last_updated_at,
buildRangeEnd: lastVersion.build_range_end,
};
};
if (this.forceBuild) {
this.logger('Force build pre-aggregation', {
preAggregation: this.preAggregation,
requestId: this.requestId,
metadata: this.metadata,
queryKey: this.preAggregationQueryKey(invalidationKeys),
newVersionEntry
});
if (this.isJob) {
// We don't want to wait for the jobed build query result. So we run the
// executeInQueue method and immediately return the LoadPreAggregationResult object.
this.executeInQueue(invalidationKeys, this.priority(10), newVersionEntry);
return {
targetTableName: this.targetTableName(newVersionEntry),
refreshKeyValues: [],
lastUpdatedAt: newVersionEntry.last_updated_at,
};
} else {
await this.executeInQueue(invalidationKeys, this.priority(10), newVersionEntry);
return mostRecentResult();
}
}
if (versionEntry) {
if (versionEntry.structure_version !== newVersionEntry.structure_version) {
this.logger('Invalidating pre-aggregation structure', {
preAggregation: this.preAggregation,
requestId: this.requestId,
queryKey: this.preAggregationQueryKey(invalidationKeys),
newVersionEntry
});
await this.executeInQueue(invalidationKeys, this.priority(10), newVersionEntry);
return mostRecentResult();
} else if (versionEntry.content_version !== newVersionEntry.content_version) {
if (this.waitForRenew) {
this.logger('Waiting for pre-aggregation renew', {
preAggregation: this.preAggregation,
requestId: this.requestId,
queryKey: this.preAggregationQueryKey(invalidationKeys),
newVersionEntry
});
await this.executeInQueue(invalidationKeys, this.priority(0), newVersionEntry);
return mostRecentResult();
} else {
this.scheduleRefresh(invalidationKeys, newVersionEntry);
}
}
} else {
this.logger('Creating pre-aggregation from scratch', {
preAggregation: this.preAggregation,
requestId: this.requestId,
queryKey: this.preAggregationQueryKey(invalidationKeys),
newVersionEntry
});
await this.executeInQueue(invalidationKeys, this.priority(10), newVersionEntry);
return mostRecentResult();
}
return {
targetTableName: this.targetTableName(versionEntry),
refreshKeyValues: [],
lastUpdatedAt: versionEntry.last_updated_at,
buildRangeEnd: versionEntry.build_range_end,
};
}
protected contentVersion(invalidationKeys) {
const versionArray = [this.preAggregation.loadSql];
if (this.preAggregation.indexesSql && this.preAggregation.indexesSql.length) {
versionArray.push(this.preAggregation.indexesSql);
}
if (this.preAggregation.streamOffset) {
versionArray.push(this.preAggregation.streamOffset);
}
versionArray.push(invalidationKeys);
return version(versionArray);
}
protected priority(defaultValue) {
return this.preAggregation.priority != null ? this.preAggregation.priority : defaultValue;
}
protected getInvalidationKeyValues() {
return Promise.all(
(this.preAggregation.invalidateKeyQueries || []).map(
(sqlQuery) => this.loadCache.keyQueryResult(sqlQuery, this.waitForRenew, this.priority(10))
)
);
}
protected getPartitionInvalidationKeyValues() {
if (this.preAggregation.partitionInvalidateKeyQueries) {
return Promise.all(
(this.preAggregation.partitionInvalidateKeyQueries || []).map(
(sqlQuery) => this.loadCache.keyQueryResult(sqlQuery, this.waitForRenew, this.priority(10))
)
);
} else {
return this.getInvalidationKeyValues();
}
}
protected scheduleRefresh(invalidationKeys, newVersionEntry) {
this.logger('Refreshing pre-aggregation content', {
preAggregation: this.preAggregation,
requestId: this.requestId,
queryKey: this.preAggregationQueryKey(invalidationKeys),
newVersionEntry
});
this.executeInQueue(invalidationKeys, this.priority(0), newVersionEntry)
.catch(e => {
if (!(e instanceof ContinueWaitError)) {
this.logger('Error refreshing pre-aggregation', {
error: (e.stack || e), preAggregation: this.preAggregation, requestId: this.requestId
});
}
});
}
protected async executeInQueue(invalidationKeys, priority, newVersionEntry) {
const queue = await this.preAggregations.getQueue(this.preAggregation.dataSource);
return queue.executeInQueue(
'query',
this.preAggregationQueryKey(invalidationKeys),
{
preAggregation: this.preAggregation,
preAggregationsTablesToTempTables: this.preAggregationsTablesToTempTables,
newVersionEntry,
requestId: this.requestId,
invalidationKeys,
forceBuild: this.forceBuild,
isJob: this.isJob,
metadata: this.metadata,
orphanedTimeout: this.orphanedTimeout,
},
priority,
// eslint-disable-next-line no-use-before-define
{ stageQueryKey: PreAggregations.preAggregationQueryCacheKey(this.preAggregation), requestId: this.requestId }
);
}
protected preAggregationQueryKey(invalidationKeys: InvalidationKeys): QueryKey {
return this.preAggregation.indexesSql && this.preAggregation.indexesSql.length ?
[this.preAggregation.loadSql, this.preAggregation.indexesSql, invalidationKeys] :
[this.preAggregation.loadSql, invalidationKeys];
}
protected targetTableName(versionEntry: VersionEntry): string {
// eslint-disable-next-line no-use-before-define
return PreAggregations.targetTableName(versionEntry);
}
public refresh(newVersionEntry: VersionEntry, invalidationKeys: InvalidationKeys, client) {
let refreshStrategy = this.refreshStoreInSourceStrategy;
if (this.preAggregation.external) {
const readOnly =
this.preAggregation.readOnly ||
client.config && client.config.readOnly ||
client.readOnly && (typeof client.readOnly === 'boolean' ? client.readOnly : client.readOnly());
if (readOnly) {
refreshStrategy = this.refreshReadOnlyExternalStrategy;
} else {
refreshStrategy = this.refreshWriteStrategy;
}
}
return cancelCombinator(
saveCancelFn => refreshStrategy.bind(this)(
client,
newVersionEntry,
saveCancelFn,
invalidationKeys
)
);
}
protected logExecutingSql(payload) {
this.logger(
'Executing Load Pre Aggregation SQL',
payload
);
}
protected queryOptions(invalidationKeys: InvalidationKeys, query: string, params: unknown[], targetTableName: string, newVersionEntry: VersionEntry) {
return {
queryKey: this.preAggregationQueryKey(invalidationKeys),
query,
values: params,
targetTableName,
requestId: this.requestId,
newVersionEntry,
buildRangeEnd: this.preAggregation.buildRangeEnd,
};
}
protected async refreshStoreInSourceStrategy(
client: DriverInterface,
newVersionEntry: VersionEntry,
saveCancelFn: SaveCancelFn,
invalidationKeys: InvalidationKeys
) {
const [loadSql, params] =
Array.isArray(this.preAggregation.loadSql) ? this.preAggregation.loadSql : [this.preAggregation.loadSql, []];
const targetTableName = this.targetTableName(newVersionEntry);
const query = QueryCache.replacePreAggregationTableNames(loadSql, this.preAggregationsTablesToTempTables)
.replace(
this.preAggregation.tableName,
targetTableName
);
const queryOptions = this.queryOptions(invalidationKeys, query, params, targetTableName, newVersionEntry);
this.logExecutingSql(queryOptions);
try {
// TODO move index creation to the driver
await saveCancelFn(client.loadPreAggregationIntoTable(
targetTableName,
query,
params,
{ streamOffset: this.preAggregation.streamOffset, ...queryOptions }
));
await this.createIndexes(client, newVersionEntry, saveCancelFn, queryOptions);
await this.loadCache.fetchTables(this.preAggregation);
} finally {
// We must clean orphaned in any cases: success or exception
await this.dropOrphanedTables(client, targetTableName, saveCancelFn, false, queryOptions);
await this.loadCache.fetchTables(this.preAggregation);
}
}
protected async refreshWriteStrategy(
client: DriverInterface,
newVersionEntry: VersionEntry,
saveCancelFn: SaveCancelFn,
invalidationKeys: InvalidationKeys,
) {
const capabilities = client?.capabilities();
const withTempTable = !(capabilities?.unloadWithoutTempTable);
const dropSourceTempTable = !capabilities?.streamingSource;
return this.runWriteStrategy(
client,
newVersionEntry,
saveCancelFn,
invalidationKeys,
withTempTable,
dropSourceTempTable
);
}
/**
* Runs export strategy with write access in data source
*/
protected async runWriteStrategy(
client: DriverInterface,
newVersionEntry: VersionEntry,
saveCancelFn: SaveCancelFn,
invalidationKeys: InvalidationKeys,
withTempTable: boolean,
dropSourceTempTable: boolean,
) {
if (withTempTable) {
await client.createSchemaIfNotExists(this.preAggregation.preAggregationsSchema);
}
const targetTableName = this.targetTableName(newVersionEntry);
const queryOptions = await this.prepareWriteStrategy(
client,
targetTableName,
newVersionEntry,
saveCancelFn,
invalidationKeys,
withTempTable,
);
try {
const tableData = await this.downloadExternalPreAggregation(
client,
newVersionEntry,
saveCancelFn,
queryOptions,
withTempTable,
);
try {
await this.uploadExternalPreAggregation(tableData, newVersionEntry, saveCancelFn, queryOptions);
} finally {
if (tableData && tableData.release) {
await tableData.release();
}
}
} finally {
await this.cleanupWriteStrategy(
client,
targetTableName,
queryOptions,
saveCancelFn,
withTempTable,
dropSourceTempTable,
);
}
}
/**
* Cleanup tables after write strategy
*/
protected async cleanupWriteStrategy(
client: DriverInterface,
targetTableName: string,
queryOptions: QueryOptions,
saveCancelFn: SaveCancelFn,
withTempTable: boolean,
dropSourceTempTable: boolean,
) {
if (withTempTable && dropSourceTempTable) {
const actualTables = await client.getTablesQuery(this.preAggregation.preAggregationsSchema);
const mappedActualTables = actualTables.map(t => `${this.preAggregation.preAggregationsSchema}.${t.table_name || t.TABLE_NAME}`);