Skip to content

Commit 7de918d

Browse files
DanielleMaywoodaslilac
authored andcommitted
chore: test metricscache on postgres (#16711)
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 9823d30 commit 7de918d

File tree

6 files changed

+126
-96
lines changed

6 files changed

+126
-96
lines changed

coderd/coderd.go

+1
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

+22-14
Original file line numberDiff line numberDiff line change
@@ -271,7 +271,7 @@ type data struct {
271271
presetParameters []database.TemplateVersionPresetParameter
272272
}
273273

274-
func tryPercentile(fs []float64, p float64) float64 {
274+
func tryPercentileCont(fs []float64, p float64) float64 {
275275
if len(fs) == 0 {
276276
return -1
277277
}
@@ -284,6 +284,14 @@ func tryPercentile(fs []float64, p float64) float64 {
284284
return fs[lower] + (fs[upper]-fs[lower])*(pos-float64(lower))
285285
}
286286

287+
func tryPercentileDisc(fs []float64, p float64) float64 {
288+
if len(fs) == 0 {
289+
return -1
290+
}
291+
sort.Float64s(fs)
292+
return fs[max(int(math.Ceil(float64(len(fs))*p/100-1)), 0)]
293+
}
294+
287295
func validateDatabaseTypeWithValid(v reflect.Value) (handled bool, err error) {
288296
if v.Kind() == reflect.Struct {
289297
return false, nil
@@ -2791,8 +2799,8 @@ func (q *FakeQuerier) GetDeploymentWorkspaceAgentStats(_ context.Context, create
27912799
latencies = append(latencies, agentStat.ConnectionMedianLatencyMS)
27922800
}
27932801

2794-
stat.WorkspaceConnectionLatency50 = tryPercentile(latencies, 50)
2795-
stat.WorkspaceConnectionLatency95 = tryPercentile(latencies, 95)
2802+
stat.WorkspaceConnectionLatency50 = tryPercentileCont(latencies, 50)
2803+
stat.WorkspaceConnectionLatency95 = tryPercentileCont(latencies, 95)
27962804

27972805
return stat, nil
27982806
}
@@ -2840,8 +2848,8 @@ func (q *FakeQuerier) GetDeploymentWorkspaceAgentUsageStats(_ context.Context, c
28402848
stat.WorkspaceTxBytes += agentStat.TxBytes
28412849
latencies = append(latencies, agentStat.ConnectionMedianLatencyMS)
28422850
}
2843-
stat.WorkspaceConnectionLatency50 = tryPercentile(latencies, 50)
2844-
stat.WorkspaceConnectionLatency95 = tryPercentile(latencies, 95)
2851+
stat.WorkspaceConnectionLatency50 = tryPercentileCont(latencies, 50)
2852+
stat.WorkspaceConnectionLatency95 = tryPercentileCont(latencies, 95)
28452853

28462854
for _, agentStat := range sessions {
28472855
stat.SessionCountVSCode += agentStat.SessionCountVSCode
@@ -4988,9 +4996,9 @@ func (q *FakeQuerier) GetTemplateAverageBuildTime(ctx context.Context, arg datab
49884996
}
49894997

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

@@ -6039,8 +6047,8 @@ func (q *FakeQuerier) GetUserLatencyInsights(_ context.Context, arg database.Get
60396047
Username: user.Username,
60406048
AvatarURL: user.AvatarURL,
60416049
TemplateIDs: seenTemplatesByUserID[userID],
6042-
WorkspaceConnectionLatency50: tryPercentile(latencies, 50),
6043-
WorkspaceConnectionLatency95: tryPercentile(latencies, 95),
6050+
WorkspaceConnectionLatency50: tryPercentileCont(latencies, 50),
6051+
WorkspaceConnectionLatency95: tryPercentileCont(latencies, 95),
60446052
}
60456053
rows = append(rows, row)
60466054
}
@@ -6684,8 +6692,8 @@ func (q *FakeQuerier) GetWorkspaceAgentStats(_ context.Context, createdAfter tim
66846692
if !ok {
66856693
continue
66866694
}
6687-
stat.WorkspaceConnectionLatency50 = tryPercentile(latencies, 50)
6688-
stat.WorkspaceConnectionLatency95 = tryPercentile(latencies, 95)
6695+
stat.WorkspaceConnectionLatency50 = tryPercentileCont(latencies, 50)
6696+
stat.WorkspaceConnectionLatency95 = tryPercentileCont(latencies, 95)
66896697
statByAgent[stat.AgentID] = stat
66906698
}
66916699

@@ -6822,8 +6830,8 @@ func (q *FakeQuerier) GetWorkspaceAgentUsageStats(_ context.Context, createdAt t
68226830
for key, latencies := range latestAgentLatencies {
68236831
val, ok := latestAgentStats[key]
68246832
if ok {
6825-
val.WorkspaceConnectionLatency50 = tryPercentile(latencies, 50)
6826-
val.WorkspaceConnectionLatency95 = tryPercentile(latencies, 95)
6833+
val.WorkspaceConnectionLatency50 = tryPercentileCont(latencies, 50)
6834+
val.WorkspaceConnectionLatency95 = tryPercentileCont(latencies, 95)
68276835
}
68286836
latestAgentStats[key] = val
68296837
}

coderd/database/queries.sql.go

+5-7
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

coderd/database/queries/workspaces.sql

+5-7
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

+8-5
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,
@@ -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: dbtime.Time(c.clock.Now()),
162+
NextUpdateAt: dbtime.Time(c.clock.Now().Add(c.intervals.DeploymentStats)),
160163
Workspaces: codersdk.WorkspaceDeploymentStats{
161164
Pending: workspaceStats.PendingWorkspaces,
162165
Building: workspaceStats.BuildingWorkspaces,

0 commit comments

Comments
 (0)