fix(coderd): use insights for DAUs, simplify metricscache (#12775)

Fixes #12134
Fixes https://github.com/coder/customers/issues/384
Refs #12122
This commit is contained in:
Mathias Fredriksson
2024-03-27 18:10:14 +02:00
committed by GitHub
parent 5d82a78d4c
commit 421bf7e785
7 changed files with 90 additions and 657 deletions

View File

@ -32,14 +32,19 @@ const insightsTimeLayout = time.RFC3339
// @Success 200 {object} codersdk.DAUsResponse
// @Router /insights/daus [get]
func (api *API) deploymentDAUs(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if !api.Authorize(r, rbac.ActionRead, rbac.ResourceDeploymentValues) {
httpapi.Forbidden(rw)
return
}
vals := r.URL.Query()
api.returnDAUsInternal(rw, r, nil)
}
func (api *API) returnDAUsInternal(rw http.ResponseWriter, r *http.Request, templateIDs []uuid.UUID) {
ctx := r.Context()
p := httpapi.NewQueryParamParser()
vals := r.URL.Query()
tzOffset := p.Int(vals, 0, "tz_offset")
p.ErrorExcessParams(vals)
if len(p.Errors) > 0 {
@ -50,12 +55,41 @@ func (api *API) deploymentDAUs(rw http.ResponseWriter, r *http.Request) {
return
}
_, resp, _ := api.metricsCache.DeploymentDAUs(tzOffset)
if resp == nil || resp.Entries == nil {
httpapi.Write(ctx, rw, http.StatusOK, &codersdk.DAUsResponse{
Entries: []codersdk.DAUEntry{},
loc := time.FixedZone("", tzOffset*3600)
// If the time is 14:01 or 14:31, we still want to include all the
// data between 14:00 and 15:00. Our rollups buckets are 30 minutes
// so this works nicely. It works just as well for 23:59 as well.
nextHourInLoc := time.Now().In(loc).Truncate(time.Hour).Add(time.Hour)
// Always return 60 days of data (2 months).
sixtyDaysAgo := nextHourInLoc.In(loc).Truncate(24*time.Hour).AddDate(0, 0, -60)
rows, err := api.Database.GetTemplateInsightsByInterval(ctx, database.GetTemplateInsightsByIntervalParams{
StartTime: sixtyDaysAgo,
EndTime: nextHourInLoc,
IntervalDays: 1,
TemplateIDs: templateIDs,
})
if err != nil {
if httpapi.Is404Error(err) {
httpapi.ResourceNotFound(rw)
return
}
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Internal error fetching DAUs.",
Detail: err.Error(),
})
}
resp := codersdk.DAUsResponse{
TZHourOffset: tzOffset,
Entries: make([]codersdk.DAUEntry, 0, len(rows)),
}
for _, row := range rows {
resp.Entries = append(resp.Entries, codersdk.DAUEntry{
Date: row.StartTime.Format(time.DateOnly),
Amount: int(row.ActiveUsers),
})
return
}
httpapi.Write(ctx, rw, http.StatusOK, resp)
}