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