Skip to content

Commit 991941e

Browse files
committed
Return latest non-null point in time series from QueryMetrics API
1 parent dfdef09 commit 991941e

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

main.go

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ func main() {
9696

9797
failures++
9898
} else {
99-
if value == nil || value.Get() == nil {
99+
if value == nil {
100100
slog.Warn("Query returned no data; the metric might not be real or there may not be any datapoints",
101101
slog.String("file", file),
102102
slog.String("query", query),
@@ -105,7 +105,7 @@ func main() {
105105
slog.Info("Query result",
106106
slog.String("file", file),
107107
slog.String("query", query),
108-
slog.Float64("value", *value.Get()),
108+
slog.Float64("value", *value),
109109
)
110110
}
111111
}
@@ -161,7 +161,7 @@ func extractQuery(filePath string) (string, error) {
161161
}
162162

163163
// Fetch the metric value for the specified query from the Datadog API, if possible.
164-
func fetchMetric(ctx context.Context, api *datadogV1.MetricsApi, query string) (*datadog.NullableFloat64, error) {
164+
func fetchMetric(ctx context.Context, api *datadogV1.MetricsApi, query string) (*float64, error) {
165165
fiveMinAgo := time.Now().Add(-1 * time.Minute).Unix()
166166
metricResp, httpResp, err := api.QueryMetrics(ctx, fiveMinAgo, time.Now().Unix(), query)
167167

@@ -188,15 +188,17 @@ func fetchMetric(ctx context.Context, api *datadogV1.MetricsApi, query string) (
188188
// The API call technically succeeded in that the query wasn't malformed.
189189
// Note that this doesn't mean the metric is necessarily a real metric, just that the query succeeded.
190190
if len(metricResp.Series) > 0 && metricResp.Series[0].End != nil {
191+
// Return the latest non-null value in the time series.
191192
series := metricResp.Series[0]
192-
if len(series.Pointlist) > 0 {
193-
// Return the value of the latest datapoint in the time series.
194-
lastestPoint := series.Pointlist[len(series.Pointlist)-1]
195-
return datadog.NewNullableFloat64(lastestPoint[1]), nil
193+
for i := len(series.Pointlist) - 1; i >= 0; i-- {
194+
point := series.Pointlist[i]
195+
if point[1] != nil {
196+
return point[1], nil
197+
}
196198
}
197199
}
198200

199-
// No time series was returned, so it's probably a metric without data or it doesn't exist.
201+
// No time series returned or all points were null. Probably a metric w/out data or it doesn't exist.
200202
//nolint:nilnil
201203
return nil, nil
202204
}

0 commit comments

Comments
 (0)