-
Notifications
You must be signed in to change notification settings - Fork 8.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Data Plugin] Allow server-side date formatters to accept custom timezone #70668
Merged
tsullivan
merged 17 commits into
elastic:master
from
tsullivan:data/allow-custom-formatting
Jul 13, 2020
Merged
Changes from 3 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
6aacfbd
[Data Plugin] Allow server-side date formatters to accept custom time…
tsullivan 6428455
add more to tests - need help though
tsullivan 1789afc
simplify changes
tsullivan 76e2c30
Merge branch 'master' into data/allow-custom-formatting
tsullivan 5aa2d80
api doc changes
tsullivan 206aed6
Merge branch 'master' into data/allow-custom-formatting
tsullivan d42275c
Merge branch 'master' into data/allow-custom-formatting
tsullivan 231f793
fix src/plugins/data/public/field_formats/constants.ts
tsullivan 1e1d3c5
rerun api changes
tsullivan 1bebcc8
re-use public code in server, add test
tsullivan 736e9ee
fix path for tests
tsullivan fc9ff7b
Merge branch 'master' into data/allow-custom-formatting
tsullivan 1b6e9e8
weird api change needed but no real diff
tsullivan 54fa2fe
Merge branch 'master' into data/allow-custom-formatting
elasticmachine 34df331
Merge branch 'master' into data/allow-custom-formatting
tsullivan 4e5eebd
3td time api doc chagens
tsullivan ed749eb
move shared code to common
tsullivan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -180,10 +180,18 @@ export class FieldFormatsRegistry { | |
* @param {ES_FIELD_TYPES[]} esTypes | ||
* @return {FieldFormat} | ||
*/ | ||
getDefaultInstancePlain(fieldType: KBN_FIELD_TYPES, esTypes?: ES_FIELD_TYPES[]): FieldFormat { | ||
getDefaultInstancePlain( | ||
fieldType: KBN_FIELD_TYPES, | ||
esTypes?: ES_FIELD_TYPES[], | ||
params: Record<string, any> = {} | ||
): FieldFormat { | ||
const conf = this.getDefaultConfig(fieldType, esTypes); | ||
const instanceParams = { | ||
...conf.params, | ||
...params, | ||
}; | ||
|
||
return this.getInstance(conf.id, conf.params); | ||
return this.getInstance(conf.id, instanceParams); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This allows timezone to be passed from the browser and formatted correctly on the server |
||
} | ||
/** | ||
* Returns a cache key built by the given variables for caching in memoized | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -18,3 +18,4 @@ | |
*/ | ||
|
||
export { DateFormat } from './date'; | ||
export { DateNanosFormat } from './date_nanos'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
141 changes: 141 additions & 0 deletions
141
src/plugins/data/server/field_formats/converters/date_nanos_server.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,141 @@ | ||
/* | ||
* Licensed to Elasticsearch B.V. under one or more contributor | ||
* license agreements. See the NOTICE file distributed with | ||
* this work for additional information regarding copyright | ||
* ownership. Elasticsearch B.V. licenses this file to you under | ||
* the Apache License, Version 2.0 (the "License"); you may | ||
* not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, | ||
* software distributed under the License is distributed on an | ||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
* KIND, either express or implied. See the License for the | ||
* specific language governing permissions and limitations | ||
* under the License. | ||
*/ | ||
|
||
import { i18n } from '@kbn/i18n'; | ||
import { memoize, noop } from 'lodash'; | ||
import moment, { Moment } from 'moment-timezone'; | ||
import { | ||
FieldFormat, | ||
FIELD_FORMAT_IDS, | ||
KBN_FIELD_TYPES, | ||
TextContextTypeConvert, | ||
} from '../../../common'; | ||
|
||
/** | ||
* Analyse the given moment.js format pattern for the fractional sec part (S,SS,SSS...) | ||
* returning length, match, pattern and an escaped pattern, that excludes the fractional | ||
* part when formatting with moment.js -> e.g. [SSS] | ||
*/ | ||
export function analysePatternForFract(pattern: string) { | ||
const fracSecMatch = pattern.match('S+') as any; // extract fractional seconds sub-pattern | ||
const fracSecMatchStr = fracSecMatch ? fracSecMatch[0] : ''; | ||
|
||
return { | ||
length: fracSecMatchStr.length, | ||
patternNanos: fracSecMatchStr, | ||
pattern, | ||
patternEscaped: fracSecMatchStr ? pattern.replace(fracSecMatch, `[${fracSecMatch}]`) : '', | ||
}; | ||
} | ||
|
||
/** | ||
* Format a given moment.js date object | ||
* Since momentjs would loose the exact value for fractional seconds with a higher resolution than | ||
* milliseconds, the fractional pattern is replaced by the fractional value of the raw timestamp | ||
*/ | ||
export function formatWithNanos( | ||
dateMomentObj: Moment, | ||
valRaw: string, | ||
fracPatternObj: Record<string, any> | ||
) { | ||
if (fracPatternObj.length <= 3) { | ||
// S,SS,SSS is formatted correctly by moment.js | ||
return dateMomentObj.format(fracPatternObj.pattern); | ||
} else { | ||
// Beyond SSS the precise value of the raw datetime string is used | ||
const valFormatted = dateMomentObj.format(fracPatternObj.patternEscaped); | ||
// Extract fractional value of ES formatted timestamp, zero pad if necessary: | ||
// 2020-05-18T20:45:05.957Z -> 957000000 | ||
// 2020-05-18T20:45:05.957000123Z -> 957000123 | ||
// we do not need to take care of the year 10000 bug since max year of date_nanos is 2262 | ||
const valNanos = valRaw | ||
.substr(20, valRaw.length - 21) // remove timezone(Z) | ||
.padEnd(9, '0') // pad shorter fractionals | ||
.substr(0, fracPatternObj.patternNanos.length); | ||
return valFormatted.replace(fracPatternObj.patternNanos, valNanos); | ||
} | ||
} | ||
|
||
export class DateNanosFormat extends FieldFormat { | ||
static id = FIELD_FORMAT_IDS.DATE_NANOS; | ||
static title = i18n.translate('data.fieldFormats.date_nanos.title', { | ||
defaultMessage: 'Date nanos', | ||
}); | ||
static fieldType = KBN_FIELD_TYPES.DATE; | ||
|
||
private memoizedConverter: Function = noop; | ||
private memoizedPattern: string = ''; | ||
private timeZone: string = ''; | ||
|
||
getParamDefaults() { | ||
return { | ||
pattern: this.getConfig!('dateNanosFormat'), | ||
fallbackPattern: this.getConfig!('dateFormat'), | ||
timezone: this.getConfig!('dateFormat:tz'), | ||
}; | ||
} | ||
|
||
textConvert: TextContextTypeConvert = (val) => { | ||
// don't give away our ref to converter so | ||
// we can hot-swap when config changes | ||
const pattern = this.param('pattern'); | ||
const timezone = this.param('timezone'); | ||
const fractPattern = analysePatternForFract(pattern); | ||
const fallbackPattern = this.param('patternFallback'); | ||
|
||
const timezoneChanged = this.timeZone !== timezone; | ||
const datePatternChanged = this.memoizedPattern !== pattern; | ||
if (timezoneChanged || datePatternChanged) { | ||
this.timeZone = timezone; | ||
this.memoizedPattern = pattern; | ||
|
||
this.memoizedConverter = memoize((value: any) => { | ||
if (value === null || value === undefined) { | ||
return '-'; | ||
} | ||
|
||
/* On the server, importing moment returns a new instance. Unlike on | ||
* the client side, it doesn't have the dateFormat:tz configuration | ||
* baked in. | ||
* We need to set the timezone manually here. The date is taken in as | ||
* UTC and converted into the desired timezone. */ | ||
let date; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This section is copied from the |
||
if (this.timeZone === 'Browser') { | ||
// Assume a warning has been logged that this can be unpredictable. It | ||
// would be too verbose to log anything here. | ||
date = moment.utc(val); | ||
} else { | ||
date = moment.utc(val).tz(this.timeZone); | ||
} | ||
|
||
if (typeof value !== 'string' && date.isValid()) { | ||
// fallback for max/min aggregation, where unixtime in ms is returned as a number | ||
// aggregations in Elasticsearch generally just return ms | ||
return date.format(fallbackPattern); | ||
} else if (date.isValid()) { | ||
return formatWithNanos(date, value, fractPattern); | ||
} else { | ||
return value; | ||
} | ||
}); | ||
} | ||
|
||
return this.memoizedConverter(val); | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -18,3 +18,4 @@ | |
*/ | ||
|
||
export { DateFormat } from './date_server'; | ||
export { DateNanosFormat } from './date_nanos_server'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
DateNanosFormat
should not be a "common" formatter, since it requires different server-side behavior. It needs this because of the possibility thatdateFormat:tz
setting could beBrowser