Serge Bazanski | 6f59951 | 2023-04-26 19:08:19 +0200 | [diff] [blame^] | 1 | package model |
| 2 | |
| 3 | import "context" |
| 4 | |
| 5 | // MetricValue is a prometheus-style labeled numerical metric value. In other |
| 6 | // words, it's a number accompanied by string key/value pairs. |
| 7 | type MetricValue struct { |
| 8 | Count int64 |
| 9 | Labels map[string]string |
| 10 | } |
| 11 | |
| 12 | // WrapSimpleMetric turns a SQL model function which returns a single number into |
| 13 | // a function which returns one-length MetricValue list with no labels. |
| 14 | func WrapSimpleMetric(fn func(*Queries, context.Context) (int64, error)) func(*Queries, context.Context) ([]MetricValue, error) { |
| 15 | return func(q *Queries, ctx context.Context) ([]MetricValue, error) { |
| 16 | v, err := fn(q, ctx) |
| 17 | if err != nil { |
| 18 | return nil, err |
| 19 | } |
| 20 | return []MetricValue{ |
| 21 | { |
| 22 | Count: v, |
| 23 | Labels: nil, |
| 24 | }, |
| 25 | }, nil |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | // A SQLMetricRow is a row that is the result of some kind of SQL 'metric query'. |
| 30 | // For each such query we define in our *.sql files, a corresponding |
| 31 | // implementation exists here. |
| 32 | type SQLMetricRow interface { |
| 33 | Value() MetricValue |
| 34 | } |
| 35 | |
| 36 | // Value implements SQLMetricRow for a row of the result of the |
| 37 | // CountActiveBackoffs SQL metric query. |
| 38 | func (c CountActiveBackoffsRow) Value() MetricValue { |
| 39 | return MetricValue{ |
| 40 | Count: c.Count, |
| 41 | Labels: map[string]string{ |
| 42 | "process": string(c.Process), |
| 43 | }, |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | // Value implements SQLMetricRow for a row of the result of the |
| 48 | // CountActiveWork SQL metric query. |
| 49 | func (c CountActiveWorkRow) Value() MetricValue { |
| 50 | return MetricValue{ |
| 51 | Count: c.Count, |
| 52 | Labels: map[string]string{ |
| 53 | "process": string(c.Process), |
| 54 | }, |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | // WrapLabeledMetric turns a SQL model function which returns a list of rows |
| 59 | // implementing SQLMetricRow into a function which returns a list of MetricValues |
| 60 | // with labels corresponding to the data returned in the rows. |
| 61 | func WrapLabeledMetric[M SQLMetricRow](fn func(*Queries, context.Context) ([]M, error)) func(*Queries, context.Context) ([]MetricValue, error) { |
| 62 | return func(q *Queries, ctx context.Context) ([]MetricValue, error) { |
| 63 | v, err := fn(q, ctx) |
| 64 | if err != nil { |
| 65 | return nil, err |
| 66 | } |
| 67 | res := make([]MetricValue, len(v)) |
| 68 | for i, vv := range v { |
| 69 | res[i] = vv.Value() |
| 70 | } |
| 71 | return res, nil |
| 72 | } |
| 73 | } |