-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Add date_diff pipeline function for date difference calculations #26143
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
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
b526a0b
Add date_diff pipeline function for date difference calculations
danotorrey a477cdb
Add PR number to changelog entry
danotorrey e82d992
Add direction and friendly keys to date_diff result map
danotorrey 3d27593
Address review nits on date_diff
danotorrey d2584ca
Round date_diff numeric units instead of truncating
danotorrey 75dcc09
Merge branch 'master' into issue-26142-date-diff
danotorrey 278612b
Merge branch 'master' into issue-26142-date-diff
danotorrey 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 hidden or 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,5 @@ | ||
| type = "a" | ||
| message = "Add `date_diff` pipeline function to compute the difference between two date objects." | ||
|
|
||
| issues = ["26142"] | ||
| pulls = ["26143"] |
This file contains hidden or 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
179 changes: 179 additions & 0 deletions
179
...-server/src/main/java/org/graylog/plugins/pipelineprocessor/functions/dates/DateDiff.java
This file contains hidden or 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,179 @@ | ||
| /* | ||
| * Copyright (C) 2020 Graylog, Inc. | ||
| * | ||
| * This program is free software: you can redistribute it and/or modify | ||
| * it under the terms of the Server Side Public License, version 1, | ||
| * as published by MongoDB, Inc. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
| * Server Side Public License for more details. | ||
| * | ||
| * You should have received a copy of the Server Side Public License | ||
| * along with this program. If not, see | ||
| * <http://www.mongodb.com/licensing/server-side-public-license>. | ||
| */ | ||
| package org.graylog.plugins.pipelineprocessor.functions.dates; | ||
|
|
||
| import com.google.common.collect.ImmutableList; | ||
| import com.google.common.collect.ImmutableMap; | ||
| import org.graylog.plugins.pipelineprocessor.EvaluationContext; | ||
| import org.graylog.plugins.pipelineprocessor.ast.functions.AbstractFunction; | ||
| import org.graylog.plugins.pipelineprocessor.ast.functions.FunctionArgs; | ||
| import org.graylog.plugins.pipelineprocessor.ast.functions.FunctionDescriptor; | ||
| import org.graylog.plugins.pipelineprocessor.ast.functions.ParameterDescriptor; | ||
| import org.graylog.plugins.pipelineprocessor.rulebuilder.RuleBuilderFunctionGroup; | ||
| import org.joda.time.DateTime; | ||
| import org.joda.time.Duration; | ||
|
|
||
| import java.util.Map; | ||
|
|
||
| public class DateDiff extends AbstractFunction<Map<String, Object>> { | ||
|
|
||
| public static final String NAME = "date_diff"; | ||
|
|
||
| private static final String LEFT = "left"; | ||
| private static final String RIGHT = "right"; | ||
| private static final String ABSOLUTE = "absolute"; | ||
|
|
||
| private static final long MS_PER_SECOND = 1000L; | ||
| private static final long MS_PER_MINUTE = 60L * MS_PER_SECOND; | ||
| private static final long MS_PER_HOUR = 60L * MS_PER_MINUTE; | ||
| private static final long MS_PER_DAY = 24L * MS_PER_HOUR; | ||
| private static final long MS_PER_WEEK = 7L * MS_PER_DAY; | ||
|
|
||
| private final ParameterDescriptor<DateTime, DateTime> left; | ||
| private final ParameterDescriptor<DateTime, DateTime> right; | ||
| private final ParameterDescriptor<Boolean, Boolean> absolute; | ||
|
|
||
| public DateDiff() { | ||
| left = ParameterDescriptor.type(LEFT, DateTime.class) | ||
| .description("Start of the interval. May be before or after the end; the result is signed by default (end - start).") | ||
| .ruleBuilderVariable() | ||
| .build(); | ||
| right = ParameterDescriptor.type(RIGHT, DateTime.class) | ||
| .description("End of the interval. May be before or after the start.") | ||
| .build(); | ||
| absolute = ParameterDescriptor.bool(ABSOLUTE) | ||
| .optional() | ||
| .description("If true, return absolute values; otherwise the result is signed (end - start). Defaults to false.") | ||
| .build(); | ||
| } | ||
|
|
||
| @Override | ||
| public Map<String, Object> evaluate(FunctionArgs args, EvaluationContext context) { | ||
| final DateTime leftValue = left.required(args, context); | ||
| final DateTime rightValue = right.required(args, context); | ||
| if (leftValue == null || rightValue == null) { | ||
| return null; | ||
| } | ||
| final boolean abs = absolute.optional(args, context).orElse(false); | ||
|
|
||
| final long signedMillis = new Duration(leftValue, rightValue).getMillis(); | ||
| final long value = (abs && signedMillis < 0) ? -signedMillis : signedMillis; | ||
|
|
||
| return ImmutableMap.<String, Object>builder() | ||
| .put("millis", value) | ||
| .put("seconds", roundDiv(value, MS_PER_SECOND)) | ||
| .put("minutes", roundDiv(value, MS_PER_MINUTE)) | ||
| .put("hours", roundDiv(value, MS_PER_HOUR)) | ||
| .put("days", roundDiv(value, MS_PER_DAY)) | ||
| .put("weeks", roundDiv(value, MS_PER_WEEK)) | ||
| .put("direction", direction(signedMillis)) | ||
| .put("friendly", friendly(value)) | ||
| .build(); | ||
| } | ||
|
|
||
| /** | ||
| * Divide {@code value} by {@code divisor} with half-away-from-zero rounding, symmetric | ||
| * across positive and negative values. e.g. 2350000ms ÷ 60000 = 39.17 → 39 minutes; | ||
| * 2370000ms ÷ 60000 = 39.5 → 40 minutes; -2370000ms → -40 minutes. | ||
| */ | ||
| private static long roundDiv(long value, long divisor) { | ||
| final long half = divisor / 2; | ||
| return value >= 0 ? (value + half) / divisor : (value - half) / divisor; | ||
| } | ||
|
|
||
| /** | ||
| * Describes {@code right} relative to {@code left}. Computed from the signed millis, | ||
| * so direction is preserved even when {@code absolute=true} strips the sign from the | ||
| * numeric components. | ||
| */ | ||
| private static String direction(long signedMillis) { | ||
| if (signedMillis > 0) { | ||
| return "ahead"; | ||
| } | ||
| if (signedMillis < 0) { | ||
| return "behind"; | ||
| } | ||
| return "equal"; | ||
| } | ||
|
|
||
| /** | ||
| * Human-readable rendering of the (possibly signed) interval. Zero-valued components are | ||
| * omitted. Sub-second remainder is included as a "ms" component only when the total | ||
| * interval is below one minute, so long intervals aren't cluttered with millisecond noise; | ||
| * the raw {@code millis} field always carries the exact value. | ||
| */ | ||
| private static String friendly(long signedMillis) { | ||
| if (signedMillis == 0) { | ||
| return "0 ms"; | ||
| } | ||
| final boolean neg = signedMillis < 0; | ||
| final long m = neg ? -signedMillis : signedMillis; | ||
| final StringBuilder sb = new StringBuilder(); | ||
| if (neg) { | ||
| sb.append('-'); | ||
| } | ||
| final long weeks = m / MS_PER_WEEK; | ||
| final long days = (m / MS_PER_DAY) % 7; | ||
| final long hours = (m / MS_PER_HOUR) % 24; | ||
| final long minutes = (m / MS_PER_MINUTE) % 60; | ||
| final long seconds = (m / MS_PER_SECOND) % 60; | ||
| final long millis = m % MS_PER_SECOND; | ||
| appendPart(sb, weeks, "week", "weeks"); | ||
| appendPart(sb, days, "day", "days"); | ||
| appendPart(sb, hours, "hour", "hours"); | ||
| appendPart(sb, minutes, "minute", "minutes"); | ||
| appendPart(sb, seconds, "second", "seconds"); | ||
| // Include sub-second remainder when the interval is below a minute, so callers see | ||
| // precision for short deltas without "2 weeks ... 47 ms" noise on long ones. | ||
| if (millis > 0 && m < MS_PER_MINUTE) { | ||
| appendPart(sb, millis, "ms", "ms"); | ||
| } | ||
| return sb.toString(); | ||
| } | ||
|
|
||
| private static void appendPart(StringBuilder sb, long value, String singular, String plural) { | ||
| if (value == 0) { | ||
| return; | ||
| } | ||
| if (sb.length() > 0 && sb.charAt(sb.length() - 1) != '-') { | ||
| sb.append(' '); | ||
| } | ||
| sb.append(value).append(' ').append(value == 1 ? singular : plural); | ||
| } | ||
|
|
||
| @Override | ||
| public FunctionDescriptor<Map<String, Object>> descriptor() { | ||
| @SuppressWarnings({"unchecked", "rawtypes"}) | ||
| final Class<? extends Map<String, Object>> returnType = (Class) Map.class; | ||
| return FunctionDescriptor.<Map<String, Object>>builder() | ||
| .name(NAME) | ||
| .returnType(returnType) | ||
| .params(ImmutableList.of(left, right, absolute)) | ||
| .description("Returns the difference between two dates as a map. The numeric units " + | ||
| "(millis, seconds, minutes, hours, days, weeks) are rounded to the nearest whole " + | ||
| "unit. The map also contains 'direction', which describes the end relative to the " + | ||
| "start as \"ahead\", \"behind\", or \"equal\", and 'friendly', a human-readable " + | ||
| "breakdown of the interval. Numeric values are signed by default (end - start). " + | ||
| "Pass absolute=true to return absolute values; direction is always derived from " + | ||
| "the signed result and is preserved.") | ||
| .ruleBuilderEnabled() | ||
| .ruleBuilderName("Date difference") | ||
| .ruleBuilderTitle("Difference between '${left}' and '${right}'") | ||
| .ruleBuilderFunctionGroup(RuleBuilderFunctionGroup.DATE) | ||
| .build(); | ||
| } | ||
| } | ||
This file contains hidden or 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
Oops, something went wrong.
Oops, something went wrong.
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.
Should we really do
half-away-from-zero rounding? Seems like if we want to keep whole numbers then truncation may be the better option. If you were to add adaysfield in your pipeline processing and then query fordays < 7you're really gettingdays < 6.5. @danotorrey