|
| 1 | +// Copyright Quesma, licensed under the Elastic License 2.0. |
| 2 | +// SPDX-License-Identifier: Elastic-2.0 |
| 3 | +package metrics_aggregations |
| 4 | + |
| 5 | +import ( |
| 6 | + "context" |
| 7 | + "fmt" |
| 8 | + "github.com/QuesmaOrg/quesma/platform/logger" |
| 9 | + "github.com/QuesmaOrg/quesma/platform/model" |
| 10 | + "github.com/QuesmaOrg/quesma/platform/util" |
| 11 | + "reflect" |
| 12 | + "strings" |
| 13 | + "time" |
| 14 | +) |
| 15 | + |
| 16 | +type ( |
| 17 | + Rate struct { |
| 18 | + ctx context.Context |
| 19 | + unit RateUnit |
| 20 | + multiplier float64 |
| 21 | + parentInterval time.Duration |
| 22 | + fieldPresent bool |
| 23 | + } |
| 24 | + RateUnit int |
| 25 | + RateMode string |
| 26 | +) |
| 27 | + |
| 28 | +const ( |
| 29 | + second RateUnit = iota |
| 30 | + minute |
| 31 | + hour |
| 32 | + day |
| 33 | + week |
| 34 | + month |
| 35 | + quarter |
| 36 | + year |
| 37 | +) |
| 38 | + |
| 39 | +const ( |
| 40 | + RateModeSum RateMode = "sum" |
| 41 | + RateModeValueCount RateMode = "value_count" |
| 42 | + RateModeInvalid RateMode = "invalid" |
| 43 | +) |
| 44 | + |
| 45 | +// NewRate creates a new Rate aggregation, during parsing. |
| 46 | +// 'multiplier' and 'parentIntervalInMs' are set later, during pancake transformation. |
| 47 | +func NewRate(ctx context.Context, unit string, fieldPresent bool) (*Rate, error) { |
| 48 | + rateUnit, err := newRateUnit(ctx, unit) |
| 49 | + rate := &Rate{ctx: ctx, unit: rateUnit, fieldPresent: fieldPresent} |
| 50 | + if err != nil { |
| 51 | + rate.unit = second |
| 52 | + } |
| 53 | + return rate, err |
| 54 | +} |
| 55 | + |
| 56 | +func (query *Rate) AggregationType() model.AggregationType { |
| 57 | + return model.MetricsAggregation |
| 58 | +} |
| 59 | + |
| 60 | +func (query *Rate) TranslateSqlResponseToJson(rows []model.QueryResultRow) model.JsonMap { |
| 61 | + // rows[0] is either: val (1 column) |
| 62 | + // or parent date_histogram's key, val (2 columns) |
| 63 | + if len(rows) != 1 || (len(rows[0].Cols) != 1 && len(rows[0].Cols) != 2) { |
| 64 | + logger.ErrorWithCtx(query.ctx).Msgf("unexpected number of rows or columns returned for %s: %+v.", query.String(), rows) |
| 65 | + return model.JsonMap{"value": nil} |
| 66 | + } |
| 67 | + |
| 68 | + parentVal, ok := util.ExtractNumeric64Maybe(rows[0].LastColValue()) |
| 69 | + if !ok { |
| 70 | + logger.WarnWithCtx(query.ctx).Msgf("cannot extract numeric value from %v, %T", rows[0].Cols[0], rows[0].Cols[0].Value) |
| 71 | + return model.JsonMap{"value": nil} |
| 72 | + } |
| 73 | + |
| 74 | + var ( |
| 75 | + fix = 1.0 // e.g. 90/88 if there are 88 days in 3 months, but our calculations are based on 90 days |
| 76 | + thirtyDays = 30 * util.Day() |
| 77 | + needToCountDaysNr = query.parentInterval.Milliseconds()%thirtyDays.Milliseconds() == 0 && |
| 78 | + (query.unit == second || query.unit == minute || query.unit == hour || query.unit == day || query.unit == week) |
| 79 | + weHaveParentDateHistogramKey = len(rows[0].Cols) == 2 |
| 80 | + ) |
| 81 | + |
| 82 | + if needToCountDaysNr && weHaveParentDateHistogramKey { |
| 83 | + // Calculating 'fix': |
| 84 | + // We need to count days of every month, as it can be 28, 29, 30 or 31... |
| 85 | + // So that our average is correct (in Elastic it always is) |
| 86 | + parentDateHistogramKey, ok := rows[0].Cols[0].Value.(int64) |
| 87 | + if !ok { |
| 88 | + logger.WarnWithCtx(query.ctx).Msgf("cannot extract parent date_histogram key from %v, %T", rows[0].Cols[0], rows[0].Cols[0].Value) |
| 89 | + return model.JsonMap{"value": nil} |
| 90 | + } |
| 91 | + |
| 92 | + someTime := time.UnixMilli(parentDateHistogramKey).Add(48 * time.Hour) |
| 93 | + // someTime.Day() is in [28, 31] U {1}. I want it to be >= 2, so I'm sure I'm in the right month for all timezones. |
| 94 | + for someTime.Day() == 1 || someTime.Day() > 25 { |
| 95 | + someTime = someTime.Add(24 * time.Hour) |
| 96 | + } |
| 97 | + |
| 98 | + actualDays := 0 |
| 99 | + currentDays := query.parentInterval.Milliseconds() / thirtyDays.Milliseconds() * 30 // e.g. 90 for 3 months date_histogram |
| 100 | + currentDaysConst := currentDays |
| 101 | + for currentDays > 0 { |
| 102 | + actualDays += util.DaysInMonth(someTime) |
| 103 | + currentDays -= 30 |
| 104 | + someTime = someTime.AddDate(0, -1, 0) |
| 105 | + } |
| 106 | + fix = float64(currentDaysConst) / float64(actualDays) |
| 107 | + } |
| 108 | + |
| 109 | + return model.JsonMap{"value": fix * parentVal * query.multiplier} |
| 110 | +} |
| 111 | + |
| 112 | +func (query *Rate) CalcAndSetMultiplier(parentInterval time.Duration) { |
| 113 | + query.parentInterval = parentInterval |
| 114 | + if parentInterval.Milliseconds() == 0 { |
| 115 | + logger.ErrorWithCtx(query.ctx).Msgf("parent interval is 0, cannot calculate rate multiplier") |
| 116 | + return |
| 117 | + } |
| 118 | + |
| 119 | + rate := query.unit.ToDuration(query.ctx) |
| 120 | + // unit month/quarter/year is special, only compatible with month/quarter/year calendar intervals |
| 121 | + if query.unit == month || query.unit == quarter || query.unit == year { |
| 122 | + oneMonth := 30 * util.Day() |
| 123 | + if parentInterval < oneMonth { |
| 124 | + logger.WarnWithCtx(query.ctx).Msgf("parent interval (%d ms) is not compatible with rate unit %s", parentInterval, query.unit.String(query.ctx)) |
| 125 | + return |
| 126 | + } |
| 127 | + if query.unit == year { |
| 128 | + rate = 360 * util.Day() // round to 360 days, so year/month = 12, year/quarter = 3, as should be |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + if rate.Milliseconds()%parentInterval.Milliseconds() == 0 { |
| 133 | + query.multiplier = float64(rate.Milliseconds() / parentInterval.Milliseconds()) |
| 134 | + } else { |
| 135 | + query.multiplier = float64(rate.Milliseconds()) / float64(parentInterval.Milliseconds()) |
| 136 | + } |
| 137 | +} |
| 138 | + |
| 139 | +func (query *Rate) String() string { |
| 140 | + return fmt.Sprintf("rate(unit: %s)", query.unit.String(query.ctx)) |
| 141 | +} |
| 142 | + |
| 143 | +func (query *Rate) FieldPresent() bool { |
| 144 | + return query.fieldPresent |
| 145 | +} |
| 146 | + |
| 147 | +func newRateUnit(ctx context.Context, unit string) (RateUnit, error) { |
| 148 | + switch strings.ToLower(unit) { |
| 149 | + case "second": |
| 150 | + return second, nil |
| 151 | + case "minute": |
| 152 | + return minute, nil |
| 153 | + case "hour": |
| 154 | + return hour, nil |
| 155 | + case "day": |
| 156 | + return day, nil |
| 157 | + case "week": |
| 158 | + return week, nil |
| 159 | + case "month": |
| 160 | + return month, nil |
| 161 | + case "quarter": |
| 162 | + return quarter, nil |
| 163 | + case "year": |
| 164 | + return year, nil |
| 165 | + default: |
| 166 | + logger.WarnWithCtxAndThrottling(ctx, "rate", "unit", "invalid rate unit: %s", unit) |
| 167 | + return second, fmt.Errorf("invalid rate unit: %s", unit) |
| 168 | + } |
| 169 | +} |
| 170 | + |
| 171 | +func (u RateUnit) String(ctx context.Context) string { |
| 172 | + switch u { |
| 173 | + case second: |
| 174 | + return "second" |
| 175 | + case minute: |
| 176 | + return "minute" |
| 177 | + case hour: |
| 178 | + return "hour" |
| 179 | + case day: |
| 180 | + return "day" |
| 181 | + case week: |
| 182 | + return "week" |
| 183 | + case month: |
| 184 | + return "month" |
| 185 | + case quarter: |
| 186 | + return "quarter" |
| 187 | + case year: |
| 188 | + return "year" |
| 189 | + default: |
| 190 | + // theoretically unreachable |
| 191 | + logger.WarnWithCtxAndThrottling(ctx, "rate", "unit", "invalid rate unit: %d", u) |
| 192 | + return "invalid" |
| 193 | + } |
| 194 | +} |
| 195 | + |
| 196 | +func (u RateUnit) ToDuration(ctx context.Context) time.Duration { |
| 197 | + switch u { |
| 198 | + case second: |
| 199 | + return time.Second |
| 200 | + case minute: |
| 201 | + return time.Minute |
| 202 | + case hour: |
| 203 | + return time.Hour |
| 204 | + case day: |
| 205 | + return util.Day() |
| 206 | + case week: |
| 207 | + return 7 * util.Day() |
| 208 | + case month: |
| 209 | + return 30 * util.Day() |
| 210 | + case quarter: |
| 211 | + return 90 * util.Day() |
| 212 | + case year: |
| 213 | + return 365 * util.Day() |
| 214 | + default: |
| 215 | + logger.ErrorWithCtx(ctx).Msgf("invalid rate unit: %s", u.String(ctx)) |
| 216 | + return 0 |
| 217 | + } |
| 218 | +} |
| 219 | + |
| 220 | +func NewRateMode(ctx context.Context, mode string) RateMode { |
| 221 | + switch mode { |
| 222 | + case "sum", "": |
| 223 | + return RateModeSum |
| 224 | + case "value_count": |
| 225 | + return RateModeValueCount |
| 226 | + default: |
| 227 | + logger.WarnWithCtxAndThrottling(ctx, "rate", "mode", "invalid rate mode: %s", mode) |
| 228 | + return RateModeInvalid |
| 229 | + } |
| 230 | +} |
| 231 | + |
| 232 | +func (m RateMode) String() string { |
| 233 | + switch m { |
| 234 | + case RateModeSum: |
| 235 | + return "sum" |
| 236 | + case RateModeValueCount: |
| 237 | + return "value_count" |
| 238 | + case RateModeInvalid: |
| 239 | + return "invalid" |
| 240 | + default: |
| 241 | + return "invalid, but not RateModeInvalid" |
| 242 | + } |
| 243 | +} |
| 244 | + |
| 245 | +// TODO make part of QueryType interface and implement for all aggregations |
| 246 | +// TODO add bad requests to tests |
| 247 | +// Doing so will ensure we see 100% of what we're interested in in our logs (now we see ~95%) |
| 248 | +func CheckParamsRate(ctx context.Context, paramsRaw any) error { |
| 249 | + requiredParams := map[string]string{ |
| 250 | + "unit": "string", |
| 251 | + } |
| 252 | + optionalParams := map[string]string{ |
| 253 | + "field": "string", |
| 254 | + "mode": "string", |
| 255 | + } |
| 256 | + |
| 257 | + params, ok := paramsRaw.(model.JsonMap) |
| 258 | + if !ok { |
| 259 | + return fmt.Errorf("params is not a map, but %+v", paramsRaw) |
| 260 | + } |
| 261 | + |
| 262 | + // check if required are present |
| 263 | + for paramName, paramType := range requiredParams { |
| 264 | + paramVal, exists := params[paramName] |
| 265 | + if !exists { |
| 266 | + return fmt.Errorf("required parameter %s not found in params", paramName) |
| 267 | + } |
| 268 | + if reflect.TypeOf(paramVal).Name() != paramType { // TODO I'll make a small rewrite to not use reflect here |
| 269 | + return fmt.Errorf("required parameter %s is not of type %s, but %T", paramName, paramType, paramVal) |
| 270 | + } |
| 271 | + } |
| 272 | + if _, err := newRateUnit(ctx, params["unit"].(string)); err != nil { |
| 273 | + return fmt.Errorf("invalid rate unit: %v", params["unit"]) |
| 274 | + } |
| 275 | + |
| 276 | + // check if only required/optional are present, and if present - that they have correct types |
| 277 | + for paramName := range params { |
| 278 | + if _, isRequired := requiredParams[paramName]; !isRequired { |
| 279 | + wantedType, isOptional := optionalParams[paramName] |
| 280 | + if !isOptional { |
| 281 | + return fmt.Errorf("unexpected parameter %s found in Rate params %v", paramName, params) |
| 282 | + } |
| 283 | + if reflect.TypeOf(params[paramName]).Name() != wantedType { // TODO I'll make a small rewrite to not use reflect here |
| 284 | + return fmt.Errorf("optional parameter %s is not of type %s, but %T", paramName, wantedType, params[paramName]) |
| 285 | + } |
| 286 | + } |
| 287 | + } |
| 288 | + if mode, exists := params["mode"]; exists && NewRateMode(ctx, mode.(string)) == RateModeInvalid { |
| 289 | + return fmt.Errorf("invalid rate mode: %v", params["mode"]) |
| 290 | + } |
| 291 | + |
| 292 | + return nil |
| 293 | +} |
0 commit comments