-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathQueryCache.ts
More file actions
1092 lines (1005 loc) · 33.4 KB
/
QueryCache.ts
File metadata and controls
1092 lines (1005 loc) · 33.4 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
import crypto from 'crypto';
import csvWriter from 'csv-write-stream';
import { LRUCache } from 'lru-cache';
import { pipeline } from 'stream';
import {
AsyncDebounce,
getEnv,
MaybeCancelablePromise,
streamToArray,
CacheMode,
LoggerFn,
} from '@cubejs-backend/shared';
import { CubeStoreCacheDriver, CubeStoreDriver } from '@cubejs-backend/cubestore-driver';
import {
BaseDriver,
InlineTables,
CacheDriverInterface,
TableStructure,
DriverInterface, QueryKey,
} from '@cubejs-backend/base-driver';
import { QueryQueue, QueryQueueOptions } from './QueryQueue';
import { ContinueWaitError } from './ContinueWaitError';
import { LocalCacheDriver } from './LocalCacheDriver';
import { DriverFactory, DriverFactoryByDataSource } from './DriverFactory';
import { LoadPreAggregationResult, PreAggregationDescription } from './PreAggregations';
import { getCacheHash } from './utils';
import { CacheAndQueryDriverType, MetadataOperationType } from './QueryOrchestrator';
export type CacheQueryResultOptions = {
renewalThreshold?: number,
renewalKey?: any,
priority?: number,
external?: boolean,
requestId?: string,
dataSource: string,
waitForRenew?: boolean,
forceNoCache?: boolean,
useInMemory?: boolean,
useCsvQuery?: boolean,
lambdaTypes?: TableStructure,
persistent?: boolean,
primaryQuery?: boolean,
renewCycle?: boolean,
};
type QueryOptions = {
external?: boolean;
renewalThreshold?: number;
updateWindowSeconds?: number;
renewalThresholdOutsideUpdateWindow?: number;
incremental?: boolean;
};
export type QueryWithParams = [
sql: string,
params: string[],
options?: QueryOptions
];
export type LoadRefreshKeyOptions = {
requestId?: string;
skipRefreshKeyWaitForRenew?: boolean;
dataSource: string
};
export type Query = {
requestId?: string;
dataSource: string;
preAggregations?: PreAggregationDescription[];
groupedPartitionPreAggregations?: PreAggregationDescription[][];
preAggregationsLoadCacheByDataSource?: any;
// @deprecated
renewQuery?: boolean;
cacheMode?: CacheMode;
compilerCacheFn?: <T>(subKey: string[], cacheFn: () => T) => T;
};
export type QueryBody = {
dataSource?: string;
persistent?: boolean;
query?: string;
values?: string[];
loadRefreshKeysOnly?: boolean;
scheduledRefresh?: boolean;
// @deprecated
renewQuery?: boolean;
cacheMode?: CacheMode;
requestId?: string;
external?: boolean;
isJob?: boolean;
forceNoCache?: boolean;
preAggregations?: PreAggregationDescription[];
groupedPartitionPreAggregations?: PreAggregationDescription[][];
aliasNameToMember?: {
[alias: string]: string;
};
preAggregationsLoadCacheByDataSource?: {
[key: string]: any;
};
[key: string]: any;
};
/**
* Temp (partition/lambda) table definition.
*/
export type TempTable = LoadPreAggregationResult;
/**
* Pre-aggregation table (stored in the first element) to temp table
* definition (stored in the second element) link.
*/
export type PreAggTableToTempTable = [
string, // common table name (without suffix)
TempTable,
];
export type PreAggTableToTempTableNames = [string, { targetTableName: string; usageTargetTableNames?: Record<string, string>; }];
export type CacheKeyItem = string | string[] | QueryWithParams | QueryWithParams[] | undefined;
export type CacheKey =
[CacheKeyItem, CacheKeyItem] |
[CacheKeyItem, CacheKeyItem, CacheKeyItem] |
[CacheKeyItem, CacheKeyItem, CacheKeyItem, CacheKeyItem];
type CacheEntry = {
time: number;
result: any;
renewalKey: string;
requestId?: string;
};
export interface QueryCacheOptions {
refreshKeyRenewalThreshold?: number;
externalQueueOptions?: any;
externalDriverFactory?: DriverFactory;
backgroundRenew?: Boolean;
queueOptions?: (dataSource: string) => Promise<{
concurrency: number;
continueWaitTimeout?: number;
executionTimeout?: number;
orphanedTimeout?: number;
heartBeatInterval?: number;
}>;
cubeStoreDriverFactory?: () => Promise<CubeStoreDriver>,
continueWaitTimeout?: number;
cacheAndQueueDriver: CacheAndQueryDriverType;
maxInMemoryCacheEntries?: number;
skipExternalCacheAndQueue?: boolean;
}
export class QueryCache {
protected readonly cacheDriver: CacheDriverInterface;
protected queue: { [dataSource: string]: QueryQueue } = {};
protected externalQueue: QueryQueue | null = null;
protected memoryCache: LRUCache<string, CacheEntry>;
public constructor(
protected readonly cachePrefix: string,
protected readonly driverFactory: DriverFactoryByDataSource,
protected readonly logger: LoggerFn,
public readonly options: QueryCacheOptions
) {
switch (options.cacheAndQueueDriver || 'memory') {
case 'memory':
this.cacheDriver = new LocalCacheDriver();
break;
case 'cubestore':
if (!options.cubeStoreDriverFactory) {
throw new Error('cubeStoreDriverFactory is a required option for Cube Store cache driver');
}
this.cacheDriver = new CubeStoreCacheDriver(
options.cubeStoreDriverFactory
);
break;
default:
throw new Error(`Unknown cache driver: ${options.cacheAndQueueDriver}`);
}
this.memoryCache = new LRUCache<string, CacheEntry>({
max: options.maxInMemoryCacheEntries || 10000
});
}
/**
* Returns cache driver instance.
*/
public getCacheDriver(): CacheDriverInterface {
return this.cacheDriver;
}
public getKey(catalog: string, key: string): string {
return `${this.cachePrefix}#${catalog}:${key}`;
}
/**
* Generates from the `queryBody` the final `sql` query and push it to
* the queue. Returns promise which will be resolved by the different
* objects, depend on the original `queryBody` object. For the
* persistent queries returns the `stream.Writable` instance.
*
* @throw Error
*/
public async cachedQueryResult(
queryBody: QueryBody,
preAggregationsTablesToTempTables: PreAggTableToTempTable[],
) {
const replacePreAggregationTableNames =
(queryAndParams: string | QueryWithParams) => (
QueryCache.replacePreAggregationTableNames(
queryAndParams,
preAggregationsTablesToTempTables,
)
);
const query = replacePreAggregationTableNames(queryBody.query);
const inlineTables = preAggregationsTablesToTempTables.flatMap(
([_, preAggregation]) => (
preAggregation.lambdaTable ? [preAggregation.lambdaTable] : []
)
);
let queuePriority = 10;
if (Number.isInteger(queryBody.queuePriority)) {
queuePriority = queryBody.queuePriority;
}
const forceNoCache = queryBody.forceNoCache || (queryBody.cacheMode === 'no-cache') || false;
const { values } = queryBody;
const cacheKeyQueries = this
.cacheKeyQueriesFrom(queryBody)
.map(replacePreAggregationTableNames);
const renewalThreshold = queryBody.cacheKeyQueries?.renewalThreshold;
const expireSecs = this.getExpireSecs(queryBody);
const cacheKey = QueryCache.queryCacheKey(queryBody);
if (
!cacheKeyQueries ||
queryBody.external && this.options.skipExternalCacheAndQueue ||
queryBody.persistent
) {
if (queryBody.persistent) {
// stream will be returned here
return this.queryWithRetryAndRelease(
query,
values,
{
cacheKey,
priority: queuePriority,
external: queryBody.external,
requestId: queryBody.requestId,
persistent: queryBody.persistent,
dataSource: queryBody.dataSource,
useCsvQuery: queryBody.useCsvQuery,
lambdaTypes: queryBody.lambdaTypes,
aliasNameToMember: queryBody.aliasNameToMember,
}
);
} else {
return {
data: await this.queryWithRetryAndRelease(
query,
values,
{
cacheKey: [query, values],
external: queryBody.external,
requestId: queryBody.requestId,
dataSource: queryBody.dataSource,
persistent: queryBody.persistent,
inlineTables,
}
),
};
}
}
// renewQuery has been deprecated, but keeping it for now
if (queryBody.cacheMode === 'must-revalidate' || queryBody.renewQuery) {
this.logger('Requested renew', { cacheKey, requestId: queryBody.requestId });
return this.renewQuery(
query,
values,
cacheKeyQueries,
expireSecs,
cacheKey,
renewalThreshold,
{
forceNoCache,
external: queryBody.external,
requestId: queryBody.requestId,
dataSource: queryBody.dataSource,
persistent: queryBody.persistent,
skipRefreshKeyWaitForRenew: true,
}
);
}
if (!this.options.backgroundRenew && queryBody.cacheMode !== 'stale-while-revalidate') {
const resultPromise = this.renewQuery(
query,
values,
cacheKeyQueries,
expireSecs,
cacheKey,
renewalThreshold,
{
forceNoCache,
external: queryBody.external,
requestId: queryBody.requestId,
dataSource: queryBody.dataSource,
persistent: queryBody.persistent,
skipRefreshKeyWaitForRenew: true,
}
);
this.startRenewCycle(
query,
values,
cacheKeyQueries,
expireSecs,
cacheKey,
renewalThreshold,
{
external: queryBody.external,
requestId: queryBody.requestId,
dataSource: queryBody.dataSource,
persistent: queryBody.persistent,
}
);
return resultPromise;
}
this.logger('Background fetch', { cacheKey, requestId: queryBody.requestId });
const mainPromise = this.cacheQueryResult(
query,
values,
cacheKey,
expireSecs,
{
priority: queuePriority,
forceNoCache,
external: queryBody.external,
requestId: queryBody.requestId,
dataSource: queryBody.dataSource,
persistent: queryBody.persistent,
}
);
if (!forceNoCache) {
this.startRenewCycle(
query,
values,
cacheKeyQueries,
expireSecs,
cacheKey,
renewalThreshold,
{
external: queryBody.external,
requestId: queryBody.requestId,
dataSource: queryBody.dataSource,
persistent: queryBody.persistent,
}
);
}
return {
data: await mainPromise,
lastRefreshTime: await this.lastRefreshTime(cacheKey)
};
}
private getExpireSecs(queryBody: QueryBody): number {
return queryBody.expireSecs || 24 * 3600;
}
private cacheKeyQueriesFrom(queryBody: QueryBody): QueryWithParams[] {
return queryBody.cacheKeyQueries?.queries ||
queryBody.cacheKeyQueries ||
[];
}
public static queryCacheKey(queryBody: QueryBody): CacheKey {
const key: CacheKey = [
queryBody.query,
queryBody.values,
(queryBody.preAggregations || []).map(p => p.loadSql)
];
if (queryBody.invalidate) {
key.push(queryBody.invalidate);
}
// @ts-ignore
key.persistent = queryBody.persistent;
return key;
}
public static extractRequestUUID(requestId: string): string {
const idx = requestId.lastIndexOf('-span-');
return idx !== -1 ? requestId.substring(0, idx) : requestId;
}
protected static replaceAll(replaceThis, withThis, inThis) {
withThis = withThis.replace(/\$/g, '$$$$');
return inThis.replace(
new RegExp(replaceThis.replace(/([/,!\\^${}[\]().*+?|<>\-&])/g, '\\$&'), 'g'),
withThis
);
}
public static replacePreAggregationTableNames(
queryAndParams: string | QueryWithParams,
preAggregationsTablesToTempTables: PreAggTableToTempTableNames[],
): string | QueryWithParams {
const [keyQuery, params, queryOptions] = Array.isArray(queryAndParams)
? queryAndParams
: [queryAndParams, []];
const replacedKeyQuery: string = preAggregationsTablesToTempTables.reduce(
(query, [tableName, { targetTableName, usageTargetTableNames }]) => {
// First replace usage-specific placeholders (e.g. tableName__usage_0)
if (usageTargetTableNames) {
for (const [suffix, usageTargetName] of Object.entries(usageTargetTableNames)) {
query = QueryCache.replaceAll(`${tableName}${suffix}`, usageTargetName, query);
}
}
// Then replace base table name for any remaining references
return QueryCache.replaceAll(tableName, targetTableName, query);
},
keyQuery
);
return Array.isArray(queryAndParams)
? [replacedKeyQuery, params, queryOptions]
: replacedKeyQuery;
}
/**
* Determines queue type, resolves `QueryQueue` instance and runs the
* `executeInQueue` method passing incoming `query` into it. Resolves
* promise with the `executeInQueue` method result for the not persistent
* queries and with the `stream.Writable` instance for the persistent.
*/
public async queryWithRetryAndRelease(
query: string | QueryWithParams,
values: string[],
{
cacheKey,
dataSource,
external,
priority,
requestId,
spanId,
inlineTables,
useCsvQuery,
lambdaTypes,
persistent,
aliasNameToMember,
}: {
cacheKey: CacheKey,
dataSource: string,
external: boolean,
priority?: number,
requestId?: string,
spanId?: string,
inlineTables?: InlineTables,
useCsvQuery?: boolean,
lambdaTypes?: TableStructure,
persistent?: boolean,
aliasNameToMember?: { [alias: string]: string },
}
) {
const queue = external
? this.getExternalQueue()
: await this.getQueue(dataSource);
const _query = {
queryKey: cacheKey,
query,
values,
requestId,
inlineTables,
useCsvQuery,
lambdaTypes,
};
const opt = {
stageQueryKey: cacheKey,
requestId,
spanId,
};
if (!persistent) {
return queue.executeInQueue('query', cacheKey as QueryKey, _query, priority, opt);
} else {
return queue.executeInQueue('stream', cacheKey as QueryKey, {
..._query,
aliasNameToMember,
}, priority, opt);
}
}
public async getQueue(dataSource = 'default') {
if (!this.queue[dataSource]) {
const queueOptions = await this.options.queueOptions(dataSource);
if (!this.queue[dataSource]) {
this.queue[dataSource] = QueryCache.createQueue(
`SQL_QUERY_${this.cachePrefix}_${dataSource}`,
() => this.driverFactory(dataSource),
(client, req) => {
this.logger('Executing SQL', { ...req });
if (req.useCsvQuery) {
return this.csvQuery(client, req);
} else {
return client.query(req.query, req.values, req);
}
},
{
logger: this.logger,
cacheAndQueueDriver: this.options.cacheAndQueueDriver,
cubeStoreDriverFactory: this.options.cubeStoreDriverFactory,
// Centralized continueWaitTimeout that can be overridden in queueOptions
continueWaitTimeout: this.options.continueWaitTimeout,
...queueOptions,
}
);
}
}
return this.queue[dataSource];
}
protected async csvQuery(client, q) {
const headers = q.lambdaTypes.map(c => c.name);
const writer = csvWriter({
headers,
sendHeaders: false,
});
let tableData;
try {
if (client.stream) {
tableData = await client.stream(q.query, q.values, q);
const errors = [];
await pipeline(tableData.rowStream, writer, (err) => {
if (err) {
errors.push(err);
}
});
if (errors.length > 0) {
throw new Error(`Lambda query errors ${errors.join(', ')}`);
}
} else {
tableData = await client.downloadQueryResults(q.query, q.values, q);
tableData.rows.forEach(
row => writer.write(row)
);
writer.end();
}
} finally {
if (tableData?.release) {
await tableData.release();
}
}
const lines = await streamToArray(writer);
const rowCount = lines.length;
const csvRows = lines.join('');
return {
types: q.lambdaTypes,
csvRows,
rowCount,
};
}
public getExternalQueue() {
if (!this.externalQueue) {
this.externalQueue = QueryCache.createQueue(
`SQL_QUERY_EXT_${this.cachePrefix}`,
this.options.externalDriverFactory,
(client, q) => {
this.logger('Executing SQL', {
...q
});
return client.query(q.query, q.values, q);
},
{
logger: this.logger,
cacheAndQueueDriver: this.options.cacheAndQueueDriver,
cubeStoreDriverFactory: this.options.cubeStoreDriverFactory,
// Centralized continueWaitTimeout that can be overridden in queueOptions
continueWaitTimeout: this.options.continueWaitTimeout,
skipQueue: this.options.skipExternalCacheAndQueue,
...this.options.externalQueueOptions
}
);
}
return this.externalQueue;
}
public static createQueue(
redisPrefix: string,
clientFactory: DriverFactory,
executeFn: (client: BaseDriver, req: any) => any,
options: Omit<QueryQueueOptions, 'queryHandlers' | 'cancelHandlers'>
): QueryQueue {
const queue: any = new QueryQueue(redisPrefix, {
queryHandlers: {
metadata: async (req, _setCancelHandle) => {
const client = await clientFactory();
const { operation } = req;
const params = req.params || {};
switch (operation) {
case MetadataOperationType.GET_SCHEMAS:
queue.logger('Getting datasource schemas', { dataSource: req.dataSource, requestId: req.requestId });
return client.getSchemas();
case MetadataOperationType.GET_TABLES_FOR_SCHEMAS:
queue.logger('Getting tables for schemas', {
dataSource: req.dataSource,
schemaCount: params.schemas?.length || 0,
requestId: req.requestId
});
return client.getTablesForSpecificSchemas(params.schemas);
case MetadataOperationType.GET_COLUMNS_FOR_TABLES:
queue.logger('Getting columns for tables', {
dataSource: req.dataSource,
tableCount: params.tables?.length || 0,
requestId: req.requestId
});
return client.getColumnsForSpecificTables(params.tables);
default:
throw new Error(`Unknown metadata operation: ${operation}`);
}
},
query: async (req, setCancelHandle) => {
const client = await clientFactory();
const resultPromise = executeFn(client, req);
let handle;
if (resultPromise.cancel) {
queue.cancelHandlerCounter += 1;
handle = queue.cancelHandlerCounter;
queue.handles[handle] = resultPromise;
await setCancelHandle(handle);
}
const result = await resultPromise;
if (handle) {
delete queue.handles[handle];
}
return result;
},
},
streamHandler: async (req, target) => {
queue.logger('Streaming SQL', { ...req });
await (new Promise((resolve, reject) => {
let logged = false;
Promise
.all([clientFactory()])
.then(([client]) => (<DriverInterface>client).stream(req.query, req.values, { highWaterMark: getEnv('dbQueryStreamHighWaterMark') }))
.then((source) => {
const cleanup = async (error) => {
if (source.release) {
const toRelease = source.release;
delete source.release;
await toRelease();
}
if (error && !target.destroyed) {
target.destroy(error);
}
if (!logged && target.destroyed) {
logged = true;
if (error) {
queue.logger('Streaming done with error', {
query: req.query,
query_values: req.values,
error,
});
reject(error);
} else {
queue.logger('Streaming successfully completed', {
requestId: req.requestId,
});
resolve(req.requestId);
}
}
};
source.rowStream.once('end', () => cleanup(undefined));
source.rowStream.once('error', cleanup);
source.rowStream.once('close', () => cleanup(undefined));
target.once('end', () => cleanup(undefined));
target.once('error', cleanup);
target.once('close', () => cleanup(undefined));
source.rowStream.pipe(target);
})
.catch((reason) => {
target.emit('error', reason);
resolve(reason);
});
}));
},
cancelHandlers: {
metadata: async (req) => {
if (req.cancelHandler && queue.handles[req.cancelHandler]) {
await queue.handles[req.cancelHandler].cancel();
delete queue.handles[req.cancelHandler];
}
},
query: async (req) => {
if (req.cancelHandler && queue.handles[req.cancelHandler]) {
await queue.handles[req.cancelHandler].cancel();
delete queue.handles[req.cancelHandler];
}
},
stream: async (req) => {
req.queryKey.persistent = true;
const queryKeyHash = queue.redisHash(req.queryKey);
if (queue.streams.has(queryKeyHash)) {
queue.streams.get(queryKeyHash).destroy();
}
},
},
logger: (msg, params) => options.logger(msg, params),
...options
});
queue.cancelHandlerCounter = 0;
queue.handles = {};
return queue;
}
/**
* Returns registered queries queues hash table.
*/
public getQueues(): {[dataSource: string]: QueryQueue} {
return this.queue;
}
public startRenewCycle(
query: string | QueryWithParams,
values: string[],
cacheKeyQueries: (string | QueryWithParams)[],
expireSecs: number,
cacheKey: CacheKey,
renewalThreshold: any,
options: {
requestId?: string,
skipRefreshKeyWaitForRenew?: boolean,
external?: boolean,
dataSource: string,
persistent?: boolean,
}
) {
this.renewQuery(
query,
values,
cacheKeyQueries,
expireSecs,
cacheKey,
renewalThreshold,
{
...options,
renewCycle: true
},
).catch(e => {
if (!(e instanceof ContinueWaitError)) {
this.logger('Error while renew cycle', {
query, query_values: values, error: e.stack || e, requestId: options.requestId
});
}
});
}
public renewQuery(
query: string | QueryWithParams,
values: string[],
cacheKeyQueries: (string | QueryWithParams)[],
expireSecs: number,
cacheKey: CacheKey,
renewalThreshold: any,
options: {
requestId?: string,
skipRefreshKeyWaitForRenew?: boolean,
external?: boolean,
forceNoCache?: boolean,
dataSource: string,
useCsvQuery?: boolean,
lambdaTypes?: TableStructure,
persistent?: boolean,
renewCycle?: boolean,
}
) {
options = options || { dataSource: 'default' };
return Promise.all(
this.loadRefreshKeys(<QueryWithParams[]>cacheKeyQueries, expireSecs, options),
)
.catch(e => {
if (e instanceof ContinueWaitError) {
throw e;
}
this.logger('Error fetching cache key queries', { error: e.stack || e, requestId: options.requestId });
return [];
})
.then(async cacheKeyQueryResults => (
{
data: await this.cacheQueryResult(
query,
values,
cacheKey,
expireSecs,
{
renewalThreshold: renewalThreshold || 6 * 60 * 60,
renewalKey: cacheKeyQueryResults && [
cacheKeyQueries,
cacheKeyQueryResults,
this.queryRedisKey([query, values]),
],
waitForRenew: true,
forceNoCache: options.forceNoCache,
external: options.external,
requestId: options.requestId,
dataSource: options.dataSource,
useCsvQuery: options.useCsvQuery,
lambdaTypes: options.lambdaTypes,
persistent: options.persistent,
primaryQuery: true,
renewCycle: options.renewCycle,
}
),
refreshKeyValues: cacheKeyQueryResults,
lastRefreshTime: await this.lastRefreshTime(cacheKey)
}
));
}
public async loadRefreshKeysFromQuery(query: Query) {
return Promise.all(
this.loadRefreshKeys(
this.cacheKeyQueriesFrom(query),
this.getExpireSecs(query),
{
requestId: query.requestId,
dataSource: query.dataSource,
}
)
);
}
public loadRefreshKeys(
cacheKeyQueries: QueryWithParams[],
expireSecs: number,
options: LoadRefreshKeyOptions
) {
return cacheKeyQueries.map((q) => this.loadRefreshKey(q, expireSecs, options));
}
@AsyncDebounce()
public async loadRefreshKey(q: QueryWithParams, expireSecs: number, options: LoadRefreshKeyOptions) {
const [query, values, queryOptions]: QueryWithParams = Array.isArray(q) ? q : [q, [], {}];
return this.cacheQueryResult(
query,
values,
[query, values],
expireSecs,
{
renewalThreshold: this.options.refreshKeyRenewalThreshold || queryOptions?.renewalThreshold || 2 * 60,
renewalKey: q,
waitForRenew: !options.skipRefreshKeyWaitForRenew,
requestId: options.requestId,
dataSource: options.dataSource,
useInMemory: true,
external: queryOptions?.external,
},
);
}
public withLock = <T = any>(
key: string,
ttl: number,
callback: () => MaybeCancelablePromise<T>,
) => this.cacheDriver.withLock(`lock:${key}`, callback, ttl, true);
public async cacheQueryResult(
query: string | QueryWithParams,
values: string[],
cacheKey: CacheKey,
expiration: number,
options: CacheQueryResultOptions,
) {
const spanId = crypto.randomBytes(16).toString('hex');
options = options || { dataSource: 'default' };
const { renewalThreshold, primaryQuery, renewCycle } = options;
const renewalKey = options.renewalKey && this.queryRedisKey(options.renewalKey);
const redisKey = this.queryRedisKey(cacheKey);
const fetchNew = () => (
this.queryWithRetryAndRelease(query, values, {
cacheKey,
priority: options.priority,
external: options.external,
requestId: options.requestId,
spanId,
persistent: options.persistent,
dataSource: options.dataSource,
useCsvQuery: options.useCsvQuery,
lambdaTypes: options.lambdaTypes,
}).then(res => {
const result = {
time: (new Date()).getTime(),
result: res,
renewalKey,
requestId: options.requestId,
};
return this
.cacheDriver
.set(redisKey, result, expiration)
.then(({ bytes }) => {
this.logger('Renewed', { cacheKey, requestId: options.requestId, spanId, primaryQuery, renewCycle });
this.logger('Outgoing network usage', {
service: 'cache',
requestId: options.requestId,
spanId,
bytes,
cacheKey,
});
return res;
});
}).catch(e => {
if (!(e instanceof ContinueWaitError)) {
this.logger('Dropping Cache', {
cacheKey,
error: e.stack || e,
requestId: options.requestId,
spanId,
primaryQuery,
renewCycle
});
this.cacheDriver.remove(redisKey)
.catch(err => this.logger('Error removing key', {
cacheKey,
spanId,
error: err.stack || err,
requestId: options.requestId
}));
}
throw e;
})
);
if (options.forceNoCache) {
this.logger('Force no cache for', { cacheKey, requestId: options.requestId, spanId, primaryQuery, renewCycle });
return fetchNew();
}
let res;
const inMemoryCacheDisablePeriod = 5 * 60 * 1000;
if (options.useInMemory) {
const inMemoryValue = this.memoryCache.get(redisKey);
if (inMemoryValue) {
const renewedAgo = (new Date()).getTime() - inMemoryValue.time;
if (
renewalKey && (
!renewalThreshold ||
!inMemoryValue.time ||
// Do not cache in memory in last 5 minutes of expiry.
// Most likely it'll cause race condition of refreshing data with different refreshKey values.
renewedAgo + inMemoryCacheDisablePeriod > renewalThreshold * 1000 ||
inMemoryValue.renewalKey !== renewalKey
) || renewedAgo > expiration * 1000 || renewedAgo > inMemoryCacheDisablePeriod
) {
this.memoryCache.delete(redisKey);
} else {
this.logger('Found in memory cache entry', {
cacheKey,
time: inMemoryValue.time,
renewedAgo,
renewalKey: inMemoryValue.renewalKey,
newRenewalKey: renewalKey,
renewalThreshold,
requestId: options.requestId,
spanId,
primaryQuery,
renewCycle
});
res = inMemoryValue;
}
}