-
Notifications
You must be signed in to change notification settings - Fork 388
Expand file tree
/
Copy pathtimeQuery.ts
More file actions
539 lines (501 loc) · 16.5 KB
/
timeQuery.ts
File metadata and controls
539 lines (501 loc) · 16.5 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
import {
Dispatch,
SetStateAction,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { useRouter } from 'next/router';
import {
formatDuration,
intervalToDuration,
isValid,
startOfSecond,
sub,
subMilliseconds,
} from 'date-fns';
import { parseAsFloat, useQueryStates } from 'nuqs';
import {
NumberParam,
StringParam,
useQueryParam,
useQueryParams,
withDefault,
} from 'use-query-params';
import { formatDate } from '@hyperdx/common-utils/dist/core/utils';
import { DateRange } from '@hyperdx/common-utils/dist/types';
import { parseTimeRangeInput } from './components/TimePicker/utils';
import { useUserPreferences } from './useUserPreferences';
import { usePrevious } from './utils';
const LIVE_TAIL_TIME_QUERY = 'Live Tail';
const LIVE_TAIL_REFRESH_INTERVAL_MS = 1000;
const dateRangeToString = (range: [Date, Date], isUTC: boolean) => {
return `${formatDate(range[0], {
isUTC,
format: 'normal',
clock: '24h',
})} - ${formatDate(range[1], {
isUTC,
format: 'normal',
clock: '24h',
})}`;
};
function isInputTimeQueryLive(inputTimeQuery: string) {
return inputTimeQuery === '' || inputTimeQuery.includes(LIVE_TAIL_TIME_QUERY);
}
export function parseRelativeTimeQuery(interval: number) {
// eslint-disable-next-line no-restricted-syntax
const end = startOfSecond(new Date());
return [subMilliseconds(end, interval), end];
}
export function parseTimeQuery(
timeQuery: string,
isUTC: boolean,
): [Date | null, Date | null] {
return parseTimeRangeInput(timeQuery, isUTC);
}
function parseValidTimeRange(
timeQuery: string,
isUTC: boolean,
): [Date, Date] | undefined {
const [start, end] = parseTimeQuery(timeQuery, isUTC);
if (start != null && end != null) {
return [start, end];
}
return undefined;
}
export function useTimeQuery({
defaultValue = LIVE_TAIL_TIME_QUERY,
defaultTimeRange = [-1, -1],
isLiveEnabled = true,
}: {
defaultValue?: string;
defaultTimeRange?: [number, number];
isLiveEnabled?: boolean;
}) {
const router = useRouter();
// We need to return true in SSR to prevent mismatch issues
const isReady = typeof window === 'undefined' ? true : router.isReady;
const prevIsReady = usePrevious(isReady);
const {
userPreferences: { isUTC },
} = useUserPreferences();
const [displayedTimeInputValue, setDisplayedTimeInputValue] = useState<
undefined | string
>(undefined);
const [_timeRangeQuery, setTimeRangeQuery] = useQueryParams(
{
from: withDefault(NumberParam, undefined),
to: withDefault(NumberParam, undefined),
},
{
updateType: 'pushIn',
enableBatching: true,
},
);
const timeRangeQuery = useMemo(
() => ({
from: _timeRangeQuery.from ?? defaultTimeRange[0],
to: _timeRangeQuery.to ?? defaultTimeRange[1],
}),
[_timeRangeQuery, defaultTimeRange],
);
// Allow browser back/fwd button to modify the displayed time input value
const [inputTimeQuery, setInputTimeQuery] = useQueryParam(
'tq',
withDefault(StringParam, ''),
{
updateType: 'pushIn',
enableBatching: true,
},
);
const prevInputTimeQuery = usePrevious(inputTimeQuery);
useEffect(() => {
// Only trigger this once when the qparams have loaded
if (isReady && !prevIsReady) {
if (inputTimeQuery != '') {
setDisplayedTimeInputValue(inputTimeQuery);
} else if (_timeRangeQuery.from != null && _timeRangeQuery.to != null) {
// If we're missing the time range query, let's parse it from the input time query
const timeQueryDerivedInputValue = dateRangeToString(
[new Date(_timeRangeQuery.from), new Date(_timeRangeQuery.to)],
isUTC,
);
setDisplayedTimeInputValue(timeQueryDerivedInputValue);
setInputTimeQuery(timeQueryDerivedInputValue);
} else {
setDisplayedTimeInputValue(defaultValue);
}
}
}, [
_timeRangeQuery,
defaultValue,
inputTimeQuery,
isReady,
isUTC,
prevIsReady,
setInputTimeQuery,
setDisplayedTimeInputValue,
]);
const [liveTailTimeRange, setLiveTailTimeRange] = useState<
[Date, Date] | undefined
>(undefined);
// XXX: This hack is needed as setTimeRangeQuery doesn't update the query params immediately
// when switching from live -> not live
// this causes us to enter a temporary state where we're not live tailing,
// and liveTailTimeRange is undefined but the timeRangeQuery is [-1, -1]
// We still need to return the last live tail value or else we'll trigger
// unnecessary searches with the wrong time range
const [tempLiveTailTimeRange, setTempLiveTailTimeRange] = useState<
[Date, Date] | undefined
>(undefined);
const timeQueryDerivedInputValue =
isReady && timeRangeQuery.from != -1 && timeRangeQuery.to != -1
? dateRangeToString(
[new Date(timeRangeQuery.from), new Date(timeRangeQuery.to)],
isUTC,
)
: undefined;
const inputTimeQueryDerivedTimeQueryRef = useRef<[Date, Date] | undefined>(
undefined,
);
// When the inputTimeQuery changes, we should calculate the time range
// and set the timeRangeQuery if there is no existing time range query
// if we're not supposed to be in live tail
// Useful for relative time ranges where only tq is provided (ex. ?tq=Past+1d)
useEffect(() => {
if (
isReady &&
!isInputTimeQueryLive(inputTimeQuery) &&
prevInputTimeQuery != inputTimeQuery
) {
const timeRange = parseValidTimeRange(inputTimeQuery, isUTC);
inputTimeQueryDerivedTimeQueryRef.current = timeRange;
if (
timeRange != null &&
_timeRangeQuery.from == null &&
_timeRangeQuery.to == null
) {
setTimeRangeQuery({
from: timeRange[0].getTime(),
to: timeRange[1].getTime(),
});
}
}
}, [
isReady,
inputTimeQuery,
isUTC,
_timeRangeQuery,
setTimeRangeQuery,
prevInputTimeQuery,
]);
// Derive searchedTimeRange
const searchedTimeRange: [Date, Date] = useMemo(() => {
if (isReady && timeRangeQuery.from != -1 && timeRangeQuery.to != -1) {
// If we're ready and there's an existing time query, use that
return [new Date(timeRangeQuery.from), new Date(timeRangeQuery.to)];
} else if (
isReady &&
timeRangeQuery.from == -1 &&
timeRangeQuery.to == -1 &&
liveTailTimeRange != null
) {
// If we're ready, and there's no time query, but we have a live tail time range, use that
return liveTailTimeRange;
} else if (
isReady &&
timeRangeQuery.from == -1 &&
timeRangeQuery.to == -1 &&
liveTailTimeRange == null &&
tempLiveTailTimeRange != null
) {
// This is a transitive state where timeRangeQuery hasn't been set yet
// since setting qparams is async, but we've already unset liveTailTimeRange
// Transitioning from live -> not live
return tempLiveTailTimeRange;
} else if (
isReady &&
timeRangeQuery.from == -1 &&
timeRangeQuery.to == -1 &&
liveTailTimeRange == null &&
tempLiveTailTimeRange == null &&
!isInputTimeQueryLive(inputTimeQuery) &&
// eslint-disable-next-line react-hooks/refs
inputTimeQueryDerivedTimeQueryRef.current != null
) {
// Use the input time query, allows users to specify relative time ranges
// via url ex. /logs?tq=Last+30+minutes
// return inputTimeQueryDerivedTimeQuery as [Date, Date];
// eslint-disable-next-line react-hooks/refs
return inputTimeQueryDerivedTimeQueryRef.current;
} else if (
isReady &&
timeRangeQuery.from == -1 &&
timeRangeQuery.to == -1 &&
liveTailTimeRange == null &&
tempLiveTailTimeRange == null &&
isInputTimeQueryLive(inputTimeQuery)
) {
// If we haven't set a live tail time range yet, but we're ready and should be in live tail, let's just return one right now
// this is due to the first interval of live tail not kicking in until 2 seconds after our first render
// eslint-disable-next-line no-restricted-syntax
const end = startOfSecond(new Date());
const newLiveTailTimeRange: [Date, Date] = [
sub(end, { minutes: 15 }),
end,
];
return newLiveTailTimeRange;
} else {
// We're not ready yet, safe to return anything.
// Downstream querying components need to be disabled on isReady
// eslint-disable-next-line no-restricted-syntax
return [new Date(), new Date()];
}
}, [
isReady,
timeRangeQuery,
liveTailTimeRange,
tempLiveTailTimeRange,
inputTimeQuery,
]);
// ====================== LIVE MODE LOGIC ====================================
// We'll only enter live mode once we're ready and see the qparams are not set
// Live tail is defined by empty time range query, and inputTimeQuery either blank or containing 'Live Tail'
const isLive = useMemo(() => {
return (
isReady &&
isLiveEnabled &&
timeRangeQuery.from == -1 &&
timeRangeQuery.to == -1 &&
(inputTimeQuery == '' || inputTimeQuery.includes(LIVE_TAIL_TIME_QUERY))
);
}, [isReady, isLiveEnabled, timeRangeQuery, inputTimeQuery]);
const refreshLiveTailTimeRange = () => {
// eslint-disable-next-line no-restricted-syntax
const end = startOfSecond(new Date());
setLiveTailTimeRange([sub(end, { minutes: 15 }), end]);
};
useEffect(() => {
let interval: NodeJS.Timeout | undefined = undefined;
if (isLive) {
refreshLiveTailTimeRange();
interval = setInterval(
refreshLiveTailTimeRange,
LIVE_TAIL_REFRESH_INTERVAL_MS,
);
}
return () => {
if (interval != null) {
clearInterval(interval);
interval = undefined;
}
};
}, [isLive]);
const setIsLive = useCallback(
(newIsLive: boolean) => {
if (isLive === false && newIsLive) {
setTempLiveTailTimeRange(undefined);
setTimeRangeQuery({ from: undefined, to: undefined });
setDisplayedTimeInputValue(LIVE_TAIL_TIME_QUERY);
setInputTimeQuery(LIVE_TAIL_TIME_QUERY);
refreshLiveTailTimeRange();
} else if (isLive && newIsLive === false && liveTailTimeRange != null) {
const [start, end] = liveTailTimeRange;
setTempLiveTailTimeRange(liveTailTimeRange);
setTimeRangeQuery({ from: start.getTime(), to: end.getTime() });
setLiveTailTimeRange(undefined);
const dateRangeStr = dateRangeToString([start, end], isUTC);
setDisplayedTimeInputValue(dateRangeStr);
setInputTimeQuery(dateRangeStr);
}
},
[
isLive,
setTimeRangeQuery,
setDisplayedTimeInputValue,
liveTailTimeRange,
isUTC,
setInputTimeQuery,
],
);
// eslint-disable-next-line react-hooks/refs
return {
isReady, // Don't search until we know what we want to do
isLive,
displayedTimeInputValue:
displayedTimeInputValue ?? timeQueryDerivedInputValue ?? defaultValue,
setDisplayedTimeInputValue,
searchedTimeRange,
onSearch: useCallback(
(timeQuery: string) => {
const [start, end] = parseTimeQuery(timeQuery, isUTC);
// TODO: Add validation UI
if (start != null && end != null) {
setTimeRangeQuery({ from: start.getTime(), to: end.getTime() });
if (timeQuery.toLowerCase().indexOf('past') === -1) {
const dateRangeStr = dateRangeToString([start, end], isUTC);
setDisplayedTimeInputValue(dateRangeStr);
setInputTimeQuery(dateRangeStr);
} else {
setInputTimeQuery(timeQuery);
}
}
},
[isUTC, setTimeRangeQuery, setDisplayedTimeInputValue, setInputTimeQuery],
),
onTimeRangeSelect: useCallback(
(start: Date, end: Date) => {
setTimeRangeQuery({ from: start.getTime(), to: end.getTime() });
const dateRangeStr = dateRangeToString([start, end], isUTC);
setDisplayedTimeInputValue(dateRangeStr);
setInputTimeQuery(dateRangeStr);
},
[isUTC, setTimeRangeQuery, setDisplayedTimeInputValue, setInputTimeQuery],
),
setIsLive,
};
}
export type UseTimeQueryInputType = {
/**
* Optional initial value to be set as the `displayedTimeInputValue`.
* If no value is provided it will return a date string for the initial
* time range.
*/
initialDisplayValue?: string;
/** The initial time range to get values for */
initialTimeRange: [Date, Date];
showRelativeInterval?: boolean;
setDisplayedTimeInputValue?: (value: string) => void;
updateInput?: boolean;
};
export type UseTimeQueryReturnType = {
isReady: boolean;
displayedTimeInputValue: string;
setDisplayedTimeInputValue: Dispatch<SetStateAction<string>>;
searchedTimeRange: DateRange['dateRange'];
onSearch: (timeQuery: string) => void;
onTimeRangeSelect: (
start: Date,
end: Date,
displayedTimeInputValue?: string | null,
) => void;
from: number | null;
to: number | null;
};
const getRelativeInterval = (start: Date, end: Date): string | undefined => {
const duration = intervalToDuration({ start, end });
const durationStr = formatDuration(duration);
return `Past ${durationStr}`;
};
// This needs to be a stable reference to prevent rerenders
const timeRangeQueryStateMap = {
from: parseAsFloat,
to: parseAsFloat,
};
export function useNewTimeQuery({
initialDisplayValue,
initialTimeRange,
showRelativeInterval,
setDisplayedTimeInputValue,
updateInput,
}: UseTimeQueryInputType): UseTimeQueryReturnType {
const router = useRouter();
// We need to return true in SSR to prevent mismatch issues
const isReady = typeof window === 'undefined' ? true : router.isReady;
const {
userPreferences: { isUTC },
} = useUserPreferences();
const [
deprecatedDisplayedTimeInputValue,
deprecatedSetDisplayedTimeInputValue,
] = useState<string>(() => {
return initialDisplayValue ?? dateRangeToString(initialTimeRange, isUTC);
});
const _setDisplayedTimeInputValue =
setDisplayedTimeInputValue ?? deprecatedSetDisplayedTimeInputValue;
const [{ from, to }, setTimeRangeQuery] = useQueryStates(
timeRangeQueryStateMap,
{
history: 'push',
},
);
const [searchedTimeRange, setSearchedTimeRange] = useState<[Date, Date]>(
from != null && to != null
? [new Date(from), new Date(to)]
: initialTimeRange,
);
const onSearch = useCallback(
(timeQuery: string) => {
const [start, end] = parseTimeQuery(timeQuery, isUTC);
// TODO: Add validation UI
if (start != null && end != null) {
setTimeRangeQuery({ from: start.getTime(), to: end.getTime() });
}
},
[isUTC, setTimeRangeQuery],
);
useEffect(() => {
if (from != null && to != null && isReady) {
const start = new Date(from);
const end = new Date(to);
if (isValid(start) && isValid(end)) {
setSearchedTimeRange([start, end]);
const relativeInterval =
showRelativeInterval && getRelativeInterval(start, end);
const dateRangeStr =
relativeInterval || dateRangeToString([start, end], isUTC);
if (updateInput !== false) {
_setDisplayedTimeInputValue(dateRangeStr);
}
}
} else if (from == null && to == null && isReady) {
setSearchedTimeRange(initialTimeRange);
const dateRangeStr = dateRangeToString(initialTimeRange, isUTC);
if (updateInput !== false) {
if (!showRelativeInterval) {
_setDisplayedTimeInputValue(dateRangeStr);
} else {
_setDisplayedTimeInputValue(initialDisplayValue ?? dateRangeStr);
}
}
}
}, [
isReady,
isUTC,
from,
to,
initialDisplayValue,
initialTimeRange,
showRelativeInterval,
_setDisplayedTimeInputValue,
updateInput,
]);
return {
from,
to,
isReady,
displayedTimeInputValue: deprecatedDisplayedTimeInputValue,
setDisplayedTimeInputValue: () => {},
searchedTimeRange,
onSearch,
onTimeRangeSelect: useCallback(
(start: Date, end: Date, displayedTimeInputValue?: string | null) => {
setTimeRangeQuery({ from: start.getTime(), to: end.getTime() });
setSearchedTimeRange([start, end]);
const dateRangeStr = dateRangeToString([start, end], isUTC);
if (displayedTimeInputValue !== null) {
_setDisplayedTimeInputValue(displayedTimeInputValue ?? dateRangeStr);
}
},
[setTimeRangeQuery, isUTC, _setDisplayedTimeInputValue],
),
};
}
export function getLiveTailTimeRange(): [Date, Date] {
// eslint-disable-next-line no-restricted-syntax
const end = startOfSecond(new Date());
return [sub(end, { minutes: 15 }), end];
}