Skip to content

Commit fc2157d

Browse files
committed
remove all users, improve test comments
1 parent dafbba1 commit fc2157d

File tree

4 files changed

+36
-63
lines changed

4 files changed

+36
-63
lines changed

coderd/insights.go

Lines changed: 4 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -107,50 +107,21 @@ func (api *API) insightsUserLatency(rw http.ResponseWriter, r *http.Request) {
107107
return
108108
}
109109

110-
// Fetch all users so that we can still include users that have no
111-
// latency data.
112-
users, err := api.Database.GetUsers(ctx, database.GetUsersParams{})
113-
if err != nil {
114-
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
115-
Message: "Internal error fetching users.",
116-
Detail: err.Error(),
117-
})
118-
return
119-
}
120-
121110
templateIDSet := make(map[uuid.UUID]struct{})
122-
usersWithLatencyByID := make(map[uuid.UUID]codersdk.UserLatency)
111+
userLatencies := make([]codersdk.UserLatency, 0, len(rows))
123112
for _, row := range rows {
124113
for _, templateID := range row.TemplateIDs {
125114
templateIDSet[templateID] = struct{}{}
126115
}
127-
usersWithLatencyByID[row.UserID] = codersdk.UserLatency{
116+
userLatencies = append(userLatencies, codersdk.UserLatency{
128117
TemplateIDs: row.TemplateIDs,
129118
UserID: row.UserID,
130119
Username: row.Username,
131-
LatencyMS: &codersdk.ConnectionLatency{
120+
LatencyMS: codersdk.ConnectionLatency{
132121
P50: row.WorkspaceConnectionLatency50,
133122
P95: row.WorkspaceConnectionLatency95,
134123
},
135-
}
136-
}
137-
userLatencies := []codersdk.UserLatency{}
138-
for _, user := range users {
139-
userLatency, ok := usersWithLatencyByID[user.ID]
140-
if !ok {
141-
// We only include deleted/inactive users if they were
142-
// active as part of the requested timeframe.
143-
if user.Deleted || user.Status != database.UserStatusActive {
144-
continue
145-
}
146-
147-
userLatency = codersdk.UserLatency{
148-
TemplateIDs: []uuid.UUID{},
149-
UserID: user.ID,
150-
Username: user.Username,
151-
}
152-
}
153-
userLatencies = append(userLatencies, userLatency)
124+
})
154125
}
155126

156127
// TemplateIDs that contributed to the data.

coderd/insights_test.go

Lines changed: 27 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -112,8 +112,10 @@ func TestUserLatencyInsights(t *testing.T) {
112112
AgentStatsRefreshInterval: time.Millisecond * 100,
113113
})
114114

115+
// Create two users, one that will appear in the report and another that
116+
// won't (due to not having/using a workspace).
115117
user := coderdtest.CreateFirstUser(t, client)
116-
_, user2 := coderdtest.CreateAnotherUser(t, client, user.OrganizationID)
118+
_, _ = coderdtest.CreateAnotherUser(t, client, user.OrganizationID)
117119
authToken := uuid.NewString()
118120
version := coderdtest.CreateTemplateVersion(t, client, user.OrganizationID, &echo.Responses{
119121
Parse: echo.ParseComplete,
@@ -127,6 +129,7 @@ func TestUserLatencyInsights(t *testing.T) {
127129
workspace := coderdtest.CreateWorkspace(t, client, user.OrganizationID, template.ID)
128130
coderdtest.AwaitWorkspaceBuildJob(t, client, workspace.LatestBuild.ID)
129131

132+
// Start an agent so that we can generate stats.
130133
agentClient := agentsdk.New(client.URL)
131134
agentClient.SetSessionToken(authToken)
132135
agentCloser := agent.New(agent.Options{
@@ -138,9 +141,15 @@ func TestUserLatencyInsights(t *testing.T) {
138141
}()
139142
resources := coderdtest.AwaitWorkspaceAgents(t, client, workspace.ID)
140143

144+
// Start must be at the beginning of the day, initialize it early in case
145+
// the day changes so that we get the relevant stats faster.
146+
y, m, d := time.Now().UTC().Date()
147+
today := time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
148+
141149
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
142150
defer cancel()
143151

152+
// Connect to the agent to generate usage/latency stats.
144153
conn, err := client.DialWorkspaceAgent(ctx, resources[0].Agents[0].ID, &codersdk.DialWorkspaceAgentOptions{
145154
Logger: logger.Named("client"),
146155
})
@@ -151,19 +160,6 @@ func TestUserLatencyInsights(t *testing.T) {
151160
require.NoError(t, err)
152161
defer sshConn.Close()
153162

154-
// Create users that will not appear in the report.
155-
_, user3 := coderdtest.CreateAnotherUser(t, client, user.OrganizationID)
156-
_, user4 := coderdtest.CreateAnotherUser(t, client, user.OrganizationID)
157-
_, err = client.UpdateUserStatus(ctx, user3.Username, codersdk.UserStatusSuspended)
158-
require.NoError(t, err)
159-
err = client.DeleteUser(ctx, user4.ID)
160-
require.NoError(t, err)
161-
162-
y, m, d := time.Now().Date()
163-
today := time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
164-
165-
_ = sshConn.Close()
166-
167163
var userLatencies codersdk.UserLatencyInsightsResponse
168164
require.Eventuallyf(t, func() bool {
169165
userLatencies, err = client.UserLatencyInsights(ctx, codersdk.UserLatencyInsightsRequest{
@@ -174,16 +170,16 @@ func TestUserLatencyInsights(t *testing.T) {
174170
if !assert.NoError(t, err) {
175171
return false
176172
}
177-
if userLatencies.Report.Users[0].UserID == user2.ID {
178-
userLatencies.Report.Users[0], userLatencies.Report.Users[1] = userLatencies.Report.Users[1], userLatencies.Report.Users[0]
179-
}
180-
return userLatencies.Report.Users[0].LatencyMS != nil
173+
return len(userLatencies.Report.Users) > 0 && userLatencies.Report.Users[0].LatencyMS.P50 > 0
181174
}, testutil.WaitShort, testutil.IntervalFast, "user latency is missing")
182175

183-
require.Len(t, userLatencies.Report.Users, 2, "want only 2 users")
176+
// We got our latency data, close the connection.
177+
_ = sshConn.Close()
178+
179+
require.Len(t, userLatencies.Report.Users, 1, "want only 1 user")
180+
require.Equal(t, userLatencies.Report.Users[0].UserID, user.UserID, "want user id to match")
184181
assert.Greater(t, userLatencies.Report.Users[0].LatencyMS.P50, float64(0), "want p50 to be greater than 0")
185182
assert.Greater(t, userLatencies.Report.Users[0].LatencyMS.P95, float64(0), "want p95 to be greater than 0")
186-
assert.Nil(t, userLatencies.Report.Users[1].LatencyMS, "want user 2 to have no latency")
187183
}
188184

189185
func TestUserLatencyInsights_BadRequest(t *testing.T) {
@@ -192,7 +188,7 @@ func TestUserLatencyInsights_BadRequest(t *testing.T) {
192188
client := coderdtest.New(t, &coderdtest.Options{})
193189
_ = coderdtest.CreateFirstUser(t, client)
194190

195-
y, m, d := time.Now().Date()
191+
y, m, d := time.Now().UTC().Date()
196192
today := time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
197193

198194
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
@@ -235,6 +231,7 @@ func TestTemplateInsights(t *testing.T) {
235231
workspace := coderdtest.CreateWorkspace(t, client, user.OrganizationID, template.ID)
236232
coderdtest.AwaitWorkspaceBuildJob(t, client, workspace.LatestBuild.ID)
237233

234+
// Start an agent so that we can generate stats.
238235
agentClient := agentsdk.New(client.URL)
239236
agentClient.SetSessionToken(authToken)
240237
agentCloser := agent.New(agent.Options{
@@ -246,12 +243,15 @@ func TestTemplateInsights(t *testing.T) {
246243
}()
247244
resources := coderdtest.AwaitWorkspaceAgents(t, client, workspace.ID)
248245

249-
y, m, d := time.Now().Date()
246+
// Start must be at the beginning of the day, initialize it early in case
247+
// the day changes so that we get the relevant stats faster.
248+
y, m, d := time.Now().UTC().Date()
250249
today := time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
251250

252251
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
253252
defer cancel()
254253

254+
// Connect to the agent to generate usage/latency stats.
255255
conn, err := client.DialWorkspaceAgent(ctx, resources[0].Agents[0].ID, &codersdk.DialWorkspaceAgentOptions{
256256
Logger: logger.Named("client"),
257257
})
@@ -262,18 +262,19 @@ func TestTemplateInsights(t *testing.T) {
262262
require.NoError(t, err)
263263
defer sshConn.Close()
264264

265+
// Start an SSH session to generate SSH usage stats.
265266
sess, err := sshConn.NewSession()
266267
require.NoError(t, err)
267268
defer sess.Close()
268269

269-
// Keep SSH session open for long enough to generate insights.
270270
r, w := io.Pipe()
271271
defer r.Close()
272272
defer w.Close()
273273
sess.Stdin = r
274274
err = sess.Start("cat")
275275
require.NoError(t, err)
276276

277+
// Start an rpty session to generate rpty usage stats.
277278
rpty, err := client.WorkspaceAgentReconnectingPTY(ctx, codersdk.WorkspaceAgentReconnectingPTYOpts{
278279
AgentID: resources[0].Agents[0].ID,
279280
Reconnect: uuid.New(),
@@ -289,7 +290,7 @@ func TestTemplateInsights(t *testing.T) {
289290
return func() bool {
290291
req = codersdk.TemplateInsightsRequest{
291292
StartTime: today,
292-
EndTime: time.Now().Truncate(time.Hour).Add(time.Hour),
293+
EndTime: time.Now().UTC().Truncate(time.Hour).Add(time.Hour),
293294
Interval: codersdk.InsightsReportIntervalDay,
294295
}
295296
resp, err = client.TemplateInsights(ctx, req)
@@ -308,6 +309,7 @@ func TestTemplateInsights(t *testing.T) {
308309
require.Eventually(t, waitForAppSeconds("reconnecting-pty"), testutil.WaitShort, testutil.IntervalFast, "reconnecting-pty seconds missing")
309310
require.Eventually(t, waitForAppSeconds("ssh"), testutil.WaitShort, testutil.IntervalFast, "ssh seconds missing")
310311

312+
// We got our data, close down sessions and connections.
311313
_ = rpty.Close()
312314
_ = sess.Close()
313315
_ = sshConn.Close()
@@ -335,7 +337,7 @@ func TestTemplateInsights_BadRequest(t *testing.T) {
335337
client := coderdtest.New(t, &coderdtest.Options{})
336338
_ = coderdtest.CreateFirstUser(t, client)
337339

338-
y, m, d := time.Now().Date()
340+
y, m, d := time.Now().UTC().Date()
339341
today := time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
340342

341343
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)

codersdk/insights.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,10 @@ type UserLatencyInsightsReport struct {
4141

4242
// UserLatency shows the connection latency for a user.
4343
type UserLatency struct {
44-
TemplateIDs []uuid.UUID `json:"template_ids" format:"uuid"`
45-
UserID uuid.UUID `json:"user_id" format:"uuid"`
46-
Username string `json:"username"`
47-
LatencyMS *ConnectionLatency `json:"latency_ms"`
44+
TemplateIDs []uuid.UUID `json:"template_ids" format:"uuid"`
45+
UserID uuid.UUID `json:"user_id" format:"uuid"`
46+
Username string `json:"username"`
47+
LatencyMS ConnectionLatency `json:"latency_ms"`
4848
}
4949

5050
// ConnectionLatency shows the latency for a connection.

site/src/api/typesGenerated.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1169,7 +1169,7 @@ export interface UserLatency {
11691169
readonly template_ids: string[]
11701170
readonly user_id: string
11711171
readonly username: string
1172-
readonly latency_ms?: ConnectionLatency
1172+
readonly latency_ms: ConnectionLatency
11731173
}
11741174

11751175
// From codersdk/insights.go

0 commit comments

Comments
 (0)