-
Notifications
You must be signed in to change notification settings - Fork 2
/
ElasticsearchReaderAPI.ts
697 lines (605 loc) · 24.3 KB
/
ElasticsearchReaderAPI.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
import { EventEmitter } from 'events';
import {
AnyObject,
DataEntity,
isObjectEntity,
getTypeOf,
Logger,
isSimpleObject,
isNumber,
isValidDate,
isFunction,
isString,
isWildCardString,
matchWildcard,
toIntegerOrThrow
} from '@terascope/utils';
import { DataFrame } from '@terascope/data-mate';
import { DataTypeConfig } from '@terascope/data-types';
import moment from 'moment';
import type { CountParams, SearchParams } from 'elasticsearch';
import { inspect } from 'util';
import {
dateSlicer,
idSlicer,
getKeyArray,
dateOptions,
processInterval,
dateFormat,
dateFormatSeconds,
parseDate,
delayedStreamSegment,
determineIDSlicerRanges,
determineDateSlicerRanges,
} from './algorithms';
import {
ESReaderOptions,
DateSegments,
InputDateSegments,
SlicerArgs,
IDType,
DateSlicerArgs,
IDSlicerArgs,
IDSlicerConfig,
DateSlicerResults,
ReaderClient,
SettingResults,
IDSlicerRanges,
DateSlicerRanges,
DateSlicerRange,
IDSlicerRange,
DateSlicerMetadata,
GetIntervalResult,
ReaderSlice,
IDSlicerResults,
FetchResponseType
} from './interfaces';
import { WindowState } from './WindowState';
import { buildQuery } from './utils';
type FetchDate = moment.Moment | null;
function isValidDataTypeConfig(record: unknown): record is DataTypeConfig {
if (!record || !isSimpleObject(record)) return false;
if (!record.version || !isNumber(record.version)) return false;
if (!record.fields || !isSimpleObject(record.fields)) return false;
return true;
}
export class ElasticsearchReaderAPI {
readonly config: ESReaderOptions;
logger: Logger;
protected readonly client: ReaderClient;
/**
* we should expose this because in some cases
* it might be an optimization to set this externally
*/
windowSize: number|undefined = undefined;
protected readonly dateFormat: string;
protected readonly emitter: EventEmitter;
constructor(
config: ESReaderOptions, client: ReaderClient, emitter: EventEmitter, logger: Logger
) {
const { time_resolution } = config;
if (config.response_type === FetchResponseType.data_frame) {
if (!isValidDataTypeConfig(config.type_config)) {
throw new Error('Parameter "type_config" must be set if DataFrames are being returned');
}
}
this.config = Object.freeze(config);
this.emitter = emitter;
this.logger = logger;
this.client = client;
const timeResolution = time_resolution ? dateOptions(time_resolution) : '';
this.dateFormat = timeResolution === 'ms' ? dateFormat : dateFormatSeconds;
this.count = this.count.bind(this);
}
makeWindowState(numOfSlicers: number): WindowState {
return new WindowState(numOfSlicers);
}
async count(queryParams: ReaderSlice = {}): Promise<number> {
const query = buildQuery(this.config, { ...queryParams, count: 0 });
return this.client.count(query as CountParams);
}
/**
* Fetch a given slice, the data will be returned in the format
* specified under `response_type` in the config
*/
async fetch(queryParams: ReaderSlice = {}): Promise<DataEntity[]|DataFrame|Buffer> {
// attempt to get window if not set
if (!this.windowSize) await this.setWindowSize();
// if we did go ahead and complete query
const query = buildQuery(this.config, {
...queryParams, count: this.windowSize
});
return this.client.search(
query,
this.config.response_type ?? FetchResponseType.data_entities,
this.config.type_config
);
}
_searchRequest(query: SearchParams, fullResponse?: false): Promise<DataEntity[]>;
_searchRequest(query: SearchParams, fullResponse: true): Promise<unknown>;
async _searchRequest(
query: SearchParams, fullResponse?: boolean
): Promise<DataEntity[]|unknown> {
return this.client._searchRequest(
query,
fullResponse
);
}
async determineSliceInterval(
interval: string, esDates?: InputDateSegments
): Promise<GetIntervalResult> {
if (this.config.interval !== 'auto') {
return {
interval: processInterval(interval, this.config.time_resolution, esDates),
count: null,
};
}
if (esDates == null) {
throw new Error('Missing required dates to create interval');
}
const count = await this.count({
start: moment(esDates.start).format(this.dateFormat),
end: moment(esDates.limit).format(this.dateFormat),
});
// we need to return early so the millisecondInterval doesn't
// end up being Infinity because 1/0 === Infinity
if (count === 0) {
return {
interval: null,
count
};
}
const numOfSlices = Math.ceil(count / this.config.size);
const timeRangeMilliseconds = moment(esDates.limit).diff(esDates.start);
const millisecondInterval = Math.floor(timeRangeMilliseconds / numOfSlices);
if (this.config.time_resolution === 's') {
let seconds = Math.floor(millisecondInterval / 1000);
if (seconds < 1) seconds = 1;
if (!Number.isSafeInteger(seconds)) {
throw new Error(`Invalid interval diff found "${inspect(seconds)}" ${inspect({
esDates,
numOfSlices,
count,
millisecondInterval,
seconds,
config: this.config
})}`);
}
return { interval: [seconds, 's'], count };
}
const millisecondIntervalResults = millisecondInterval < 1 ? 1 : millisecondInterval;
if (!Number.isSafeInteger(millisecondIntervalResults)) {
throw new Error(`Invalid interval diff found "${inspect(millisecondIntervalResults)}" ${inspect({
esDates,
millisecondInterval,
config: this.config
})}`);
}
return {
interval: [millisecondIntervalResults, 'ms'],
count
};
}
async setWindowSize(): Promise<void> {
const { size } = this.config;
const windowSize = await this.getWindowSize();
if (size > windowSize) {
throw new Error(`Invalid parameter size: ${size}, it cannot exceed the "index.max_result_window" index setting of ${windowSize} for index ${this.config.index}`);
}
this.windowSize = windowSize;
}
private validateIDSlicerConfig(config: IDSlicerConfig): void {
if (isObject(config)) {
if (!isNumber(config.slicerID)) {
throw new Error(`Parameter slicerID must be a number, got ${getTypeOf(config.slicerID)}`);
}
if (
!isString(this.config.id_field_name) || this.config.id_field_name.length === 0
) {
throw new Error(`Parameter idFieldName must be a string, got ${getTypeOf(this.config.id_field_name)}`);
}
if (config.recoveryData) {
if (Array.isArray(config.recoveryData)) {
const areAllObjects = config.recoveryData.every(isSimpleObject);
if (!areAllObjects) {
throw new Error('Input recoveryData must be an array of recovered slices, cannot have mixed values');
}
} else {
throw new Error(`Input recoveryData must be an array of recovered slices, got ${getTypeOf(config.recoveryData)}`);
}
}
} else {
throw new Error(`Input must be an object, received ${getTypeOf(config)}`);
}
}
/**
* This used to subdivide all the of the key ranges for each
* slicer instance, then each "range" should be passed into
* {@link ElasticsearchReaderAPI.makeIDSlicerFromRange}
*/
async makeIDSlicerRanges(
config: Pick<IDSlicerConfig, 'numOfSlicers'>
): Promise<IDSlicerRanges> {
const {
numOfSlicers,
} = config;
if (!this.config.key_type || !(this.config.key_type in IDType)) {
throw new Error(`Invalid parameter key_type, got ${this.config.key_type}`);
}
if (this.config.key_range) {
if (this.config.key_range.length === 0) {
throw new Error('Invalid key_range parameter, must be an array with length > 0');
}
if (!this.config.key_range.every(isString)) {
throw new Error('Invalid key_range parameter, must be an array of strings');
}
}
if (!isNumber(numOfSlicers)) {
throw new Error(`Parameter numOfSlicers must be a number, got ${getTypeOf(numOfSlicers)}`);
}
const baseKeyArray = getKeyArray(this.config.key_type);
// we slice as not to mutate for when this is called again
const keyArray: readonly string[] = this.config.key_range
? this.config.key_range.slice()
: baseKeyArray;
if (difference(keyArray, baseKeyArray).length > 0) {
throw new Error(`key_range specified for id_reader contains keys not found in: ${this.config.key_type}`);
}
return determineIDSlicerRanges(
keyArray, numOfSlicers, this.count
);
}
/**
* Returns an instance of the slicer using the id algorithm,
* this is a higher level API and is not recommended when using many
* slicers since making all of the slicer ranges at once is more efficient
*/
async makeIDSlicer(config: IDSlicerConfig): Promise<() => Promise<IDSlicerResults>> {
const ranges = await this.makeIDSlicerRanges(config);
return this.makeIDSlicerFromRange(config, ranges[config.slicerID]);
}
/**
* Returns an instance of the slicer using the id algorithm,
* from a given slicer range, this should be used in conjunction
* with {@link ElasticsearchReaderAPI.makeIDSlicerRanges}
*/
async makeIDSlicerFromRange(
config: IDSlicerConfig,
range: IDSlicerRange
): Promise<() => Promise<IDSlicerResults>> {
this.validateIDSlicerConfig(config);
const {
slicerID,
recoveryData,
} = config;
const { size } = this.config;
const baseKeyArray = getKeyArray(this.config.key_type);
// we slice as not to mutate for when this is called again
const keyArray: readonly string[] = this.config.key_range
? this.config.key_range.slice()
: baseKeyArray;
if (difference(keyArray, baseKeyArray).length > 0) {
throw new Error(`key_range specified for id_reader contains keys not found in: ${this.config.key_type}`);
}
if (!this.windowSize) await this.setWindowSize();
const slicerConfig: IDSlicerArgs = {
events: this.emitter,
logger: this.logger,
keySet: range.keys.slice(),
baseKeyArray,
startingKeyDepth: this.config.starting_key_depth,
countFn: this.count,
size
};
if (recoveryData && recoveryData.length > 0) {
// TODO: verify what retryData is
// real retry of executionContext here, need to reformat retry data
const parsedRetry: (string|undefined)[] = recoveryData.map((obj) => {
const slice = (obj.lastSlice as ReaderSlice|undefined);
// when we get here there should only be one key
if (slice?.keys?.length === 1) {
return slice.keys[0];
}
// some slicers might not have a previous slice, need to start from scratch
return undefined;
});
slicerConfig.retryData = parsedRetry[slicerID];
}
return idSlicer(slicerConfig);
}
private validateDateSlicerConfig(config: unknown): void {
if (isObject(config)) {
if (!(config.lifecycle === 'once' || config.lifecycle === 'persistent')) {
throw new Error('Parameter lifecycle must be set to "once" or "persistent"');
}
if (!isNumber(config.numOfSlicers)) {
throw new Error(`Parameter numOfSlicers must be a number, got ${getTypeOf(config.numOfSlicers)}`);
}
if (config.recoveryData) {
if (Array.isArray(config.recoveryData)) {
const areAllObjects = config.recoveryData.every(isSimpleObject);
if (!areAllObjects) {
throw new Error('Input recoveryData must be an array of recovered slices, cannot have mixed values');
}
} else {
throw new Error(`Input recoveryData must be an array of recovered slices, got ${getTypeOf(config.recoveryData)}`);
}
}
if (config.hook && !isFunction(config.hook)) {
throw new Error('Input hook must be a function if provided');
}
} else {
throw new Error(`Input must be an object, received ${getTypeOf(config)}`);
}
}
/**
* This used to subdivide all the of the date ranges for each
* slicer instance, then each "range" should be passed into
* {@link ElasticsearchReaderAPI.makeDateSlicerFromRange}
*/
async makeDateSlicerRanges(config: Omit<DateSlicerArgs, 'slicerID'|'windowState'>): Promise<DateSlicerRanges|undefined> {
this.validateDateSlicerConfig(config);
const {
lifecycle,
numOfSlicers,
} = config;
const isPersistent = lifecycle === 'persistent';
await this.verifyIndex();
const recoveryData = config.recoveryData?.map(
(slice) => slice.lastSlice
).filter(Boolean) as ReaderSlice[]|undefined || [];
if (isPersistent) {
// we need to interval to get starting dates
const [{ interval }, { interval: latencyInterval }] = await Promise.all([
this.determineSliceInterval(this.config.interval),
this.determineSliceInterval(this.config.delay)
]);
if (interval == null || latencyInterval == null) {
this.logger.warn(`No data was found in index: ${this.config.index} using query: ${this.config.query}`);
// slicer will run and complete when a null is returned
return;
}
const { start, limit } = delayedStreamSegment(
config.startTime,
interval,
latencyInterval
);
return determineDateSlicerRanges({
dates: { start, limit },
numOfSlicers,
recoveryData,
getInterval: async (dates) => this.determineSliceInterval(
this.config.interval,
dates,
)
});
}
const _esDates = await this.determineDateRanges();
// query with no results
if (_esDates.start == null || _esDates.limit == null) {
this.logger.warn(`No data was found in index: ${this.config.index} using query: ${this.config.query}`);
// slicer will run and complete when a null is returned
return;
}
const allSlicerDates = _esDates as DateSegments;
const slicerMetadata: DateSlicerMetadata = {};
const slicerRanges = await determineDateSlicerRanges({
dates: allSlicerDates,
numOfSlicers,
recoveryData,
getInterval: async (dates, slicerId) => {
const result = await this.determineSliceInterval(
this.config.interval,
dates
);
slicerMetadata[slicerId] = {
...result,
start: moment(dates.start.format(this.dateFormat)).toISOString(),
end: moment(dates.limit.format(this.dateFormat)).toISOString(),
};
if (result.interval == null) {
this.logger.warn(dates, `No data was found in index: ${this.config.index} using query: ${this.config.query} for slicer range`);
return result;
}
return result;
}
});
// This was originally created to update the job configuration
// with the correct interval so it exposes the discovered intervals
// and date ranges for each slicer to the user
if (config.hook) {
await config.hook(slicerMetadata);
}
return slicerRanges;
}
/**
* Returns an instance of the slicer using the date algorithm,
* this is a higher level API and is not recommended when using many
* slicers since making all of the slicer ranges at once is more efficient
*/
async makeDateSlicer(config: DateSlicerArgs): Promise<() => Promise<DateSlicerResults>> {
const ranges = await this.makeDateSlicerRanges(config);
if (ranges == null || ranges[config.slicerID] == null) {
// if it gets here there is probably no data for the query
// the logging is done elsewhere
return async () => null;
}
return this.makeDateSlicerFromRange(config, ranges[config.slicerID]!);
}
/**
* Returns an instance of the slicer using the date algorithm,
* from a given slicer range, this should be used in conjunction
* with {@link ElasticsearchReaderAPI.makeDateSlicerRanges}
*/
async makeDateSlicerFromRange(
config: Omit<DateSlicerArgs, 'recoveryData'>, range: DateSlicerRange
): Promise<() => Promise<DateSlicerResults>> {
if (!isNumber(config.slicerID)) {
throw new Error(`Parameter slicerID must be a number, got ${getTypeOf(config.slicerID)}`);
}
this.validateDateSlicerConfig(config);
const {
slicerID,
lifecycle,
numOfSlicers,
} = config;
const isPersistent = lifecycle === 'persistent';
const {
time_resolution: timeResolution,
size,
subslice_by_key: subsliceByKey,
subslice_key_threshold: subsliceKeyThreshold,
key_type: keyType,
id_field_name: idFieldName,
starting_key_depth: startingKeyDepth
} = this.config;
if (!this.windowSize) await this.setWindowSize();
const slicerFnArgs: SlicerArgs = {
lifecycle,
numOfSlicers,
logger: this.logger,
id: slicerID,
events: this.emitter,
countFn: this.count,
timeResolution,
size,
subsliceByKey,
subsliceKeyThreshold,
keyType,
idFieldName,
startingKeyDepth
};
if (isPersistent) {
const windowState = config.windowState as WindowState|undefined;
if (!windowState || !windowState.checkin) {
throw new Error(`Invalid parameter windowState, must provide a valid windowState in "persistent" mode, got ${getTypeOf(windowState)}`);
}
if (!config.startTime || !isValidDate(config.startTime)) {
throw new Error(`Invalid parameter startTime, must provide a valid date in "persistent" mode, got ${getTypeOf(config.startTime)}`);
}
// we need to interval to get starting dates
const [{ interval }, { interval: latencyInterval }] = await Promise.all([
this.determineSliceInterval(this.config.interval),
this.determineSliceInterval(this.config.delay)
]);
if (interval == null || latencyInterval == null) {
this.logger.warn(`No data was found in index: ${this.config.index} using query: ${this.config.query}`);
// slicer will run and complete when a null is returned
return async () => null;
}
return dateSlicer({
...slicerFnArgs,
interval,
latencyInterval,
windowState,
dates: range.dates,
primaryRange: range.range,
});
}
// we do not care for range for once jobs
return dateSlicer({
...slicerFnArgs,
interval: range.interval,
dates: range.dates,
});
}
async determineDateRanges(): Promise<{ start: FetchDate; limit: FetchDate; }> {
const [start, limit] = await Promise.all([
this.getIndexDate(this.config.start, 'start'),
this.getIndexDate(this.config.end, 'end')
]);
return { start, limit };
}
private async getIndexDate(date: string|null|undefined, order: string): Promise<FetchDate> {
// we have a date, parse and return it
if (date) return parseDate(date);
// we are in auto, so we determine each part
const sortObj = {};
const sortOrder = order === 'start' ? 'asc' : 'desc';
sortObj[this.config.date_field_name] = { order: sortOrder };
const query: AnyObject = {
index: this.config.index,
size: 1,
body: {
sort: [
sortObj
]
}
};
if (this.config.query) {
query.q = this.config.query;
}
// using this query to catch potential errors even if a date is given already
const [data] = await this._searchRequest(query, false);
if (data == null) {
this.logger.warn(`No data was found using query ${JSON.stringify(query)} for index: ${this.config.index}`);
return null;
}
if (data[this.config.date_field_name] == null) {
throw new Error(`Invalid date_field_name: "${this.config.date_field_name}" for index: ${this.config.index}, field does not exist on record`);
}
if (order === 'start') {
return parseDate(data[this.config.date_field_name]);
}
// end date is non-inclusive, adding 1s so range will cover it
const newDate = data[this.config.date_field_name];
const time = moment(newDate).add(1, this.config.time_resolution);
return parseDate(time.format(this.dateFormat));
}
/**
* Get the index settings, used to determine the max_result_window size
*/
async getSettings(index: string): Promise<SettingResults> {
return this.client.getSettings(index);
}
/**
* This used verify the index.max_result_window size
* will be big enough to fix the within the requested
* slice size
*/
async getWindowSize(): Promise<number> {
const window = 'index.max_result_window';
const { index } = this.config;
const settings = await this.getSettings(index);
const matcher = indexMatcher(index);
for (const [key, configs] of Object.entries(settings)) {
if (matcher(key)) {
const defaultPath = configs.defaults[window];
const configPath = configs.settings[window];
// config goes first as it overrides an defaults
if (configPath) return toIntegerOrThrow(configPath);
if (defaultPath) return toIntegerOrThrow(defaultPath);
}
}
return this.config.size;
}
get version(): number {
return this.client.getESVersion();
}
async verifyIndex(): Promise<void> {
// this is method in api is badly named
return this.client.verify();
}
}
function isObject(val: unknown): val is AnyObject {
return isObjectEntity(val);
}
function difference(
srcArray: readonly string[] | null,
valArray: readonly string[]
): readonly string[] {
const results: string[] = [];
if (!srcArray) return results;
for (const val of srcArray) {
if (!valArray.includes(val)) {
results.push(val);
}
}
return results;
}
function indexMatcher(index: string): (input: string) => boolean {
if (isWildCardString(index)) {
return (indexVal) => matchWildcard(index, indexVal);
}
return (indexVal) => indexVal.includes(index);
}