|
| 1 | +// Copyright Quesma, licensed under the Elastic License 2.0. |
| 2 | +// SPDX-License-Identifier: Elastic-2.0 |
| 3 | +package bucket_aggregations |
| 4 | + |
| 5 | +import ( |
| 6 | + "context" |
| 7 | + "fmt" |
| 8 | + "quesma/logger" |
| 9 | + "quesma/model" |
| 10 | + "reflect" |
| 11 | +) |
| 12 | + |
| 13 | +// BiggestIpv4 is "255.255.255.255 + 1", so to say. Used in Elastic, because it always uses exclusive upper bounds. |
| 14 | +// So instead of "<= 255.255.255.255", it uses "< ::1:0:0:0" |
| 15 | +const BiggestIpv4 = "::1:0:0:0" |
| 16 | + |
| 17 | +// Current limitation: we expect Clickhouse field to be IPv4 (and not IPv6) |
| 18 | + |
| 19 | +// Clickhouse table to test SQLs: |
| 20 | +// CREATE TABLE __quesma_table_name (clientip IPv4) ENGINE=Log |
| 21 | +// INSERT INTO __quesma_table_name VALUES ('0.0.0.0'), ('5.5.5.5'), ('90.180.90.180'), ('128.200.0.8'), ('192.168.1.67'), ('222.168.22.67') |
| 22 | + |
| 23 | +// TODO make part of QueryType interface and implement for all aggregations |
| 24 | +// TODO add bad requests to tests |
| 25 | +// Doing so will ensure we see 100% of what we're interested in in our logs (now we see ~95%) |
| 26 | +func CheckParamsIpRange(ctx context.Context, paramsRaw any) error { |
| 27 | + requiredParams := map[string]string{ |
| 28 | + "field": "string", |
| 29 | + "ranges": "map_todo_improve_this_check", // TODO should add same type check to this 'ranges' field, will be fixed |
| 30 | + } |
| 31 | + optionalParams := map[string]string{ |
| 32 | + "keyed": "bool", |
| 33 | + } |
| 34 | + |
| 35 | + params, ok := paramsRaw.(model.JsonMap) |
| 36 | + if !ok { |
| 37 | + return fmt.Errorf("params is not a map, but %+v", paramsRaw) |
| 38 | + } |
| 39 | + |
| 40 | + // check if required are present |
| 41 | + for paramName, paramType := range requiredParams { |
| 42 | + paramVal, exists := params[paramName] |
| 43 | + if !exists { |
| 44 | + return fmt.Errorf("required parameter %s not found in params", paramName) |
| 45 | + } |
| 46 | + if paramType == "map_todo_improve_this_check" { |
| 47 | + continue // uncontinue after TODO is fixed |
| 48 | + } |
| 49 | + if reflect.TypeOf(paramVal).Name() != paramType { // TODO I'll make a small rewrite to not use reflect here |
| 50 | + return fmt.Errorf("required parameter %s is not of type %s, but %T", paramName, paramType, paramVal) |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + // check if only required/optional are present |
| 55 | + for paramName := range params { |
| 56 | + if _, isRequired := requiredParams[paramName]; !isRequired { |
| 57 | + wantedType, isOptional := optionalParams[paramName] |
| 58 | + if !isOptional { |
| 59 | + return fmt.Errorf("unexpected parameter %s found in IP Range params %v", paramName, params) |
| 60 | + } |
| 61 | + if reflect.TypeOf(params[paramName]).Name() != wantedType { // TODO I'll make a small rewrite to not use reflect here |
| 62 | + return fmt.Errorf("optional parameter %s is not of type %s, but %T", paramName, wantedType, params[paramName]) |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + return nil |
| 68 | +} |
| 69 | + |
| 70 | +type ( |
| 71 | + IpRange struct { |
| 72 | + ctx context.Context |
| 73 | + field model.Expr |
| 74 | + intervals []IpInterval |
| 75 | + keyed bool |
| 76 | + } |
| 77 | + IpInterval struct { |
| 78 | + begin string |
| 79 | + end string |
| 80 | + key *string // when nil, key is not present |
| 81 | + } |
| 82 | +) |
| 83 | + |
| 84 | +func NewIpRange(ctx context.Context, intervals []IpInterval, field model.Expr, keyed bool) *IpRange { |
| 85 | + return &IpRange{ |
| 86 | + ctx: ctx, |
| 87 | + field: field, |
| 88 | + intervals: intervals, |
| 89 | + keyed: keyed, |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +func NewIpInterval(begin, end string, key *string) IpInterval { |
| 94 | + return IpInterval{begin: begin, end: end, key: key} |
| 95 | +} |
| 96 | + |
| 97 | +func (interval IpInterval) ToWhereClause(field model.Expr) model.Expr { |
| 98 | + isBegin := interval.begin != UnboundedInterval |
| 99 | + isEnd := interval.end != UnboundedInterval && interval.end != BiggestIpv4 |
| 100 | + |
| 101 | + begin := model.NewInfixExpr(field, ">=", model.NewLiteralSingleQuoted(interval.begin)) |
| 102 | + end := model.NewInfixExpr(field, "<", model.NewLiteralSingleQuoted(interval.end)) |
| 103 | + |
| 104 | + if isBegin && isEnd { |
| 105 | + return model.NewInfixExpr(begin, "AND", end) |
| 106 | + } else if isBegin { |
| 107 | + return begin |
| 108 | + } else if isEnd { |
| 109 | + return end |
| 110 | + } else { |
| 111 | + return model.TrueExpr |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +// String returns key part of the response, e.g. "1.0-2.0", or "*-6.55" |
| 116 | +func (interval IpInterval) String() string { |
| 117 | + if interval.key != nil { |
| 118 | + return *interval.key |
| 119 | + } |
| 120 | + return fmt.Sprintf("%s-%s", interval.begin, interval.end) |
| 121 | +} |
| 122 | + |
| 123 | +func (query *IpRange) AggregationType() model.AggregationType { |
| 124 | + return model.BucketAggregation |
| 125 | +} |
| 126 | + |
| 127 | +func (query *IpRange) TranslateSqlResponseToJson(rows []model.QueryResultRow) model.JsonMap { |
| 128 | + return nil |
| 129 | +} |
| 130 | + |
| 131 | +func (query *IpRange) String() string { |
| 132 | + return "ip_range" |
| 133 | +} |
| 134 | + |
| 135 | +func (query *IpRange) DoesNotHaveGroupBy() bool { |
| 136 | + return true |
| 137 | +} |
| 138 | + |
| 139 | +func (query *IpRange) CombinatorGroups() (result []CombinatorGroup) { |
| 140 | + for intervalIdx, interval := range query.intervals { |
| 141 | + prefix := fmt.Sprintf("range_%d__", intervalIdx) |
| 142 | + if len(query.intervals) == 1 { |
| 143 | + prefix = "" |
| 144 | + } |
| 145 | + result = append(result, CombinatorGroup{ |
| 146 | + idx: intervalIdx, |
| 147 | + Prefix: prefix, |
| 148 | + Key: interval.String(), |
| 149 | + WhereClause: interval.ToWhereClause(query.field), |
| 150 | + }) |
| 151 | + } |
| 152 | + return |
| 153 | +} |
| 154 | + |
| 155 | +// bad requests: both to/from and mask |
| 156 | + |
| 157 | +func (query *IpRange) CombinatorTranslateSqlResponseToJson(subGroup CombinatorGroup, rows []model.QueryResultRow) model.JsonMap { |
| 158 | + if len(rows) == 0 || len(rows[0].Cols) == 0 { |
| 159 | + logger.ErrorWithCtx(query.ctx).Msgf("need at least one row and column in ip_range aggregation response, rows: %d, cols: %d", len(rows), len(rows[0].Cols)) |
| 160 | + return model.JsonMap{} |
| 161 | + } |
| 162 | + count := rows[0].Cols[len(rows[0].Cols)-1].Value |
| 163 | + response := model.JsonMap{ |
| 164 | + "key": subGroup.Key, |
| 165 | + "doc_count": count, |
| 166 | + } |
| 167 | + |
| 168 | + interval := query.intervals[subGroup.idx] |
| 169 | + if interval.begin != UnboundedInterval { |
| 170 | + response["from"] = interval.begin |
| 171 | + } |
| 172 | + if interval.end != UnboundedInterval { |
| 173 | + response["to"] = interval.end |
| 174 | + } |
| 175 | + |
| 176 | + return response |
| 177 | +} |
| 178 | + |
| 179 | +func (query *IpRange) CombinatorSplit() []model.QueryType { |
| 180 | + result := make([]model.QueryType, 0, len(query.intervals)) |
| 181 | + for _, interval := range query.intervals { |
| 182 | + result = append(result, NewIpRange(query.ctx, []IpInterval{interval}, query.field, query.keyed)) |
| 183 | + } |
| 184 | + return result |
| 185 | +} |
0 commit comments