Skip to content

Commit 0700680

Browse files
chore: test metricscache on postgres
metricscache_test has been running tests against dbmem only, instead of against postgres. Unfortunately the implementations of GetTemplateAverageBuildTime have diverged between dbmem and postgres. This change gets the tests working on Postgres and test for the behaviour postgres provides.
1 parent 4c438bd commit 0700680

File tree

6 files changed

+127
-97
lines changed

6 files changed

+127
-97
lines changed

coderd/coderd.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,7 @@ func New(options *Options) *API {
422422
metricsCache := metricscache.New(
423423
options.Database,
424424
options.Logger.Named("metrics_cache"),
425+
options.Clock,
425426
metricscache.Intervals{
426427
TemplateBuildTimes: options.MetricsCacheRefreshInterval,
427428
DeploymentStats: options.AgentStatsRefreshInterval,

coderd/database/dbmem/dbmem.go

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,7 @@ type data struct {
268268
presetParameters []database.TemplateVersionPresetParameter
269269
}
270270

271-
func tryPercentile(fs []float64, p float64) float64 {
271+
func tryPercentileCont(fs []float64, p float64) float64 {
272272
if len(fs) == 0 {
273273
return -1
274274
}
@@ -281,6 +281,14 @@ func tryPercentile(fs []float64, p float64) float64 {
281281
return fs[lower] + (fs[upper]-fs[lower])*(pos-float64(lower))
282282
}
283283

284+
func tryPercentileDisc(fs []float64, p float64) float64 {
285+
if len(fs) == 0 {
286+
return -1
287+
}
288+
sort.Float64s(fs)
289+
return fs[max(int(math.Ceil(float64(len(fs))*p/100-1)), 0)]
290+
}
291+
284292
func validateDatabaseTypeWithValid(v reflect.Value) (handled bool, err error) {
285293
if v.Kind() == reflect.Struct {
286294
return false, nil
@@ -2802,8 +2810,8 @@ func (q *FakeQuerier) GetDeploymentWorkspaceAgentStats(_ context.Context, create
28022810
latencies = append(latencies, agentStat.ConnectionMedianLatencyMS)
28032811
}
28042812

2805-
stat.WorkspaceConnectionLatency50 = tryPercentile(latencies, 50)
2806-
stat.WorkspaceConnectionLatency95 = tryPercentile(latencies, 95)
2813+
stat.WorkspaceConnectionLatency50 = tryPercentileCont(latencies, 50)
2814+
stat.WorkspaceConnectionLatency95 = tryPercentileCont(latencies, 95)
28072815

28082816
return stat, nil
28092817
}
@@ -2851,8 +2859,8 @@ func (q *FakeQuerier) GetDeploymentWorkspaceAgentUsageStats(_ context.Context, c
28512859
stat.WorkspaceTxBytes += agentStat.TxBytes
28522860
latencies = append(latencies, agentStat.ConnectionMedianLatencyMS)
28532861
}
2854-
stat.WorkspaceConnectionLatency50 = tryPercentile(latencies, 50)
2855-
stat.WorkspaceConnectionLatency95 = tryPercentile(latencies, 95)
2862+
stat.WorkspaceConnectionLatency50 = tryPercentileCont(latencies, 50)
2863+
stat.WorkspaceConnectionLatency95 = tryPercentileCont(latencies, 95)
28562864

28572865
for _, agentStat := range sessions {
28582866
stat.SessionCountVSCode += agentStat.SessionCountVSCode
@@ -4989,9 +4997,9 @@ func (q *FakeQuerier) GetTemplateAverageBuildTime(ctx context.Context, arg datab
49894997
}
49904998

49914999
var row database.GetTemplateAverageBuildTimeRow
4992-
row.Delete50, row.Delete95 = tryPercentile(deleteTimes, 50), tryPercentile(deleteTimes, 95)
4993-
row.Stop50, row.Stop95 = tryPercentile(stopTimes, 50), tryPercentile(stopTimes, 95)
4994-
row.Start50, row.Start95 = tryPercentile(startTimes, 50), tryPercentile(startTimes, 95)
5000+
row.Delete50, row.Delete95 = tryPercentileDisc(deleteTimes, 50), tryPercentileDisc(deleteTimes, 95)
5001+
row.Stop50, row.Stop95 = tryPercentileDisc(stopTimes, 50), tryPercentileDisc(stopTimes, 95)
5002+
row.Start50, row.Start95 = tryPercentileDisc(startTimes, 50), tryPercentileDisc(startTimes, 95)
49955003
return row, nil
49965004
}
49975005

@@ -6026,8 +6034,8 @@ func (q *FakeQuerier) GetUserLatencyInsights(_ context.Context, arg database.Get
60266034
Username: user.Username,
60276035
AvatarURL: user.AvatarURL,
60286036
TemplateIDs: seenTemplatesByUserID[userID],
6029-
WorkspaceConnectionLatency50: tryPercentile(latencies, 50),
6030-
WorkspaceConnectionLatency95: tryPercentile(latencies, 95),
6037+
WorkspaceConnectionLatency50: tryPercentileCont(latencies, 50),
6038+
WorkspaceConnectionLatency95: tryPercentileCont(latencies, 95),
60316039
}
60326040
rows = append(rows, row)
60336041
}
@@ -6671,8 +6679,8 @@ func (q *FakeQuerier) GetWorkspaceAgentStats(_ context.Context, createdAfter tim
66716679
if !ok {
66726680
continue
66736681
}
6674-
stat.WorkspaceConnectionLatency50 = tryPercentile(latencies, 50)
6675-
stat.WorkspaceConnectionLatency95 = tryPercentile(latencies, 95)
6682+
stat.WorkspaceConnectionLatency50 = tryPercentileCont(latencies, 50)
6683+
stat.WorkspaceConnectionLatency95 = tryPercentileCont(latencies, 95)
66766684
statByAgent[stat.AgentID] = stat
66776685
}
66786686

@@ -6809,8 +6817,8 @@ func (q *FakeQuerier) GetWorkspaceAgentUsageStats(_ context.Context, createdAt t
68096817
for key, latencies := range latestAgentLatencies {
68106818
val, ok := latestAgentStats[key]
68116819
if ok {
6812-
val.WorkspaceConnectionLatency50 = tryPercentile(latencies, 50)
6813-
val.WorkspaceConnectionLatency95 = tryPercentile(latencies, 95)
6820+
val.WorkspaceConnectionLatency50 = tryPercentileCont(latencies, 50)
6821+
val.WorkspaceConnectionLatency95 = tryPercentileCont(latencies, 95)
68146822
}
68156823
latestAgentStats[key] = val
68166824
}

coderd/database/queries.sql.go

Lines changed: 5 additions & 7 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

coderd/database/queries/workspaces.sql

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -415,13 +415,11 @@ WHERE
415415
ORDER BY created_at DESC;
416416

417417
-- name: GetWorkspaceUniqueOwnerCountByTemplateIDs :many
418-
SELECT
419-
template_id, COUNT(DISTINCT owner_id) AS unique_owners_sum
420-
FROM
421-
workspaces
422-
WHERE
423-
template_id = ANY(@template_ids :: uuid[]) AND deleted = false
424-
GROUP BY template_id;
418+
SELECT templates.id AS template_id, COUNT(DISTINCT workspaces.owner_id) AS unique_owners_sum
419+
FROM templates
420+
LEFT JOIN workspaces ON workspaces.template_id = templates.id AND workspaces.deleted = false
421+
WHERE templates.id = ANY(@template_ids :: uuid[])
422+
GROUP BY templates.id;
425423

426424
-- name: InsertWorkspace :one
427425
INSERT INTO

coderd/metricscache/metricscache.go

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import (
1515
"github.com/coder/coder/v2/coderd/database/dbauthz"
1616
"github.com/coder/coder/v2/coderd/database/dbtime"
1717
"github.com/coder/coder/v2/codersdk"
18+
"github.com/coder/quartz"
1819
"github.com/coder/retry"
1920
)
2021

@@ -26,6 +27,7 @@ import (
2627
type Cache struct {
2728
database database.Store
2829
log slog.Logger
30+
clock quartz.Clock
2931
intervals Intervals
3032

3133
templateWorkspaceOwners atomic.Pointer[map[uuid.UUID]int]
@@ -45,7 +47,7 @@ type Intervals struct {
4547
DeploymentStats time.Duration
4648
}
4749

48-
func New(db database.Store, log slog.Logger, intervals Intervals, usage bool) *Cache {
50+
func New(db database.Store, log slog.Logger, clock quartz.Clock, intervals Intervals, usage bool) *Cache {
4951
if intervals.TemplateBuildTimes <= 0 {
5052
intervals.TemplateBuildTimes = time.Hour
5153
}
@@ -55,6 +57,7 @@ func New(db database.Store, log slog.Logger, intervals Intervals, usage bool) *C
5557
ctx, cancel := context.WithCancel(context.Background())
5658

5759
c := &Cache{
60+
clock: clock,
5861
database: db,
5962
intervals: intervals,
6063
log: log,
@@ -84,7 +87,7 @@ func (c *Cache) refreshTemplateBuildTimes(ctx context.Context) error {
8487
//nolint:gocritic // This is a system service.
8588
ctx = dbauthz.AsSystemRestricted(ctx)
8689

87-
templates, err := c.database.GetTemplates(ctx)
90+
templates, err := c.database.GetTemplatesWithFilter(ctx, database.GetTemplatesWithFilterParams{})
8891
if err != nil {
8992
return err
9093
}
@@ -104,7 +107,7 @@ func (c *Cache) refreshTemplateBuildTimes(ctx context.Context) error {
104107
Valid: true,
105108
},
106109
StartTime: sql.NullTime{
107-
Time: dbtime.Time(time.Now().AddDate(0, 0, -30)),
110+
Time: dbtime.Time(c.clock.Now().AddDate(0, 0, -30)),
108111
Valid: true,
109112
},
110113
})
@@ -131,7 +134,7 @@ func (c *Cache) refreshTemplateBuildTimes(ctx context.Context) error {
131134

132135
func (c *Cache) refreshDeploymentStats(ctx context.Context) error {
133136
var (
134-
from = dbtime.Now().Add(-15 * time.Minute)
137+
from = c.clock.Now().Add(-15 * time.Minute)
135138
agentStats database.GetDeploymentWorkspaceAgentStatsRow
136139
err error
137140
)
@@ -155,8 +158,8 @@ func (c *Cache) refreshDeploymentStats(ctx context.Context) error {
155158
}
156159
c.deploymentStatsResponse.Store(&codersdk.DeploymentStats{
157160
AggregatedFrom: from,
158-
CollectedAt: dbtime.Now(),
159-
NextUpdateAt: dbtime.Now().Add(c.intervals.DeploymentStats),
161+
CollectedAt: c.clock.Now(),
162+
NextUpdateAt: c.clock.Now().Add(c.intervals.DeploymentStats),
160163
Workspaces: codersdk.WorkspaceDeploymentStats{
161164
Pending: workspaceStats.PendingWorkspaces,
162165
Building: workspaceStats.BuildingWorkspaces,

0 commit comments

Comments
 (0)