Skip to content

fix: revert commit d37b131 (#11987) #12144

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion coderd/agentapi/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,6 @@ func New(opts Options) *API {
api.StatsAPI = &StatsAPI{
AgentFn: api.agent,
Database: opts.Database,
Pubsub: opts.Pubsub,
Log: opts.Log,
StatsBatcher: opts.StatsBatcher,
TemplateScheduleStore: opts.TemplateScheduleStore,
Expand Down
14 changes: 0 additions & 14 deletions coderd/agentapi/stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,8 @@ import (
"github.com/coder/coder/v2/coderd/autobuild"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/coderd/database/pubsub"
"github.com/coder/coder/v2/coderd/prometheusmetrics"
"github.com/coder/coder/v2/coderd/schedule"
"github.com/coder/coder/v2/codersdk"
)

type StatsBatcher interface {
Expand All @@ -29,7 +27,6 @@ type StatsBatcher interface {
type StatsAPI struct {
AgentFn func(context.Context) (database.WorkspaceAgent, error)
Database database.Store
Pubsub pubsub.Pubsub
Log slog.Logger
StatsBatcher StatsBatcher
TemplateScheduleStore *atomic.Pointer[schedule.TemplateScheduleStore]
Expand Down Expand Up @@ -133,16 +130,5 @@ func (a *StatsAPI) UpdateStats(ctx context.Context, req *agentproto.UpdateStatsR
return nil, xerrors.Errorf("update stats in database: %w", err)
}

// Tell the frontend about the new agent report, now that everything is updated
a.publishWorkspaceAgentStats(ctx, workspace.ID)

return res, nil
}

func (a *StatsAPI) publishWorkspaceAgentStats(ctx context.Context, workspaceID uuid.UUID) {
err := a.Pubsub.Publish(codersdk.WorkspaceNotifyChannel(workspaceID), codersdk.WorkspaceNotifyDescriptionAgentStatsOnly)
if err != nil {
a.Log.Warn(ctx, "failed to publish workspace agent stats",
slog.F("workspace_id", workspaceID), slog.Error(err))
}
}
51 changes: 11 additions & 40 deletions coderd/agentapi/stats_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package agentapi_test

import (
"bytes"
"context"
"database/sql"
"sync"
Expand All @@ -20,11 +19,8 @@ import (
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbmock"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/coderd/database/pubsub"
"github.com/coder/coder/v2/coderd/prometheusmetrics"
"github.com/coder/coder/v2/coderd/schedule"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/testutil"
)

type statsBatcher struct {
Expand Down Expand Up @@ -82,10 +78,8 @@ func TestUpdateStates(t *testing.T) {
t.Parallel()

var (
now = dbtime.Now()
dbM = dbmock.NewMockStore(gomock.NewController(t))
ps = pubsub.NewInMemory()

now = dbtime.Now()
dbM = dbmock.NewMockStore(gomock.NewController(t))
templateScheduleStore = schedule.MockTemplateScheduleStore{
GetFn: func(context.Context, database.Store, uuid.UUID) (schedule.TemplateScheduleOptions, error) {
panic("should not be called")
Expand Down Expand Up @@ -131,7 +125,6 @@ func TestUpdateStates(t *testing.T) {
return agent, nil
},
Database: dbM,
Pubsub: ps,
StatsBatcher: batcher,
TemplateScheduleStore: templateScheduleStorePtr(templateScheduleStore),
AgentStatsRefreshInterval: 10 * time.Second,
Expand Down Expand Up @@ -171,15 +164,6 @@ func TestUpdateStates(t *testing.T) {
// User gets fetched to hit the UpdateAgentMetricsFn.
dbM.EXPECT().GetUserByID(gomock.Any(), user.ID).Return(user, nil)

// Ensure that pubsub notifications are sent.
publishAgentStats := make(chan bool)
ps.Subscribe(codersdk.WorkspaceNotifyChannel(workspace.ID), func(_ context.Context, description []byte) {
go func() {
publishAgentStats <- bytes.Equal(description, codersdk.WorkspaceNotifyDescriptionAgentStatsOnly)
close(publishAgentStats)
}()
})

resp, err := api.UpdateStats(context.Background(), req)
require.NoError(t, err)
require.Equal(t, &agentproto.UpdateStatsResponse{
Expand All @@ -195,13 +179,7 @@ func TestUpdateStates(t *testing.T) {
require.Equal(t, user.ID, batcher.lastUserID)
require.Equal(t, workspace.ID, batcher.lastWorkspaceID)
require.Equal(t, req.Stats, batcher.lastStats)
ctx := testutil.Context(t, testutil.WaitShort)
select {
case <-ctx.Done():
t.Error("timed out while waiting for pubsub notification")
case wasAgentStatsOnly := <-publishAgentStats:
require.Equal(t, wasAgentStatsOnly, true)
}

require.True(t, updateAgentMetricsFnCalled)
})

Expand All @@ -211,7 +189,6 @@ func TestUpdateStates(t *testing.T) {
var (
now = dbtime.Now()
dbM = dbmock.NewMockStore(gomock.NewController(t))
ps = pubsub.NewInMemory()
templateScheduleStore = schedule.MockTemplateScheduleStore{
GetFn: func(context.Context, database.Store, uuid.UUID) (schedule.TemplateScheduleOptions, error) {
panic("should not be called")
Expand All @@ -237,7 +214,6 @@ func TestUpdateStates(t *testing.T) {
return agent, nil
},
Database: dbM,
Pubsub: ps,
StatsBatcher: batcher,
TemplateScheduleStore: templateScheduleStorePtr(templateScheduleStore),
AgentStatsRefreshInterval: 10 * time.Second,
Expand Down Expand Up @@ -268,8 +244,7 @@ func TestUpdateStates(t *testing.T) {
t.Parallel()

var (
db = dbmock.NewMockStore(gomock.NewController(t))
ps = pubsub.NewInMemory()
dbM = dbmock.NewMockStore(gomock.NewController(t))
req = &agentproto.UpdateStatsRequest{
Stats: &agentproto.Stats{
ConnectionsByProto: map[string]int64{}, // len() == 0
Expand All @@ -280,8 +255,7 @@ func TestUpdateStates(t *testing.T) {
AgentFn: func(context.Context) (database.WorkspaceAgent, error) {
return agent, nil
},
Database: db,
Pubsub: ps,
Database: dbM,
StatsBatcher: nil, // should not be called
TemplateScheduleStore: nil, // should not be called
AgentStatsRefreshInterval: 10 * time.Second,
Expand Down Expand Up @@ -316,9 +290,7 @@ func TestUpdateStates(t *testing.T) {
nextAutostart := now.Add(30 * time.Minute).UTC() // always sent to DB as UTC

var (
db = dbmock.NewMockStore(gomock.NewController(t))
ps = pubsub.NewInMemory()

dbM = dbmock.NewMockStore(gomock.NewController(t))
templateScheduleStore = schedule.MockTemplateScheduleStore{
GetFn: func(context.Context, database.Store, uuid.UUID) (schedule.TemplateScheduleOptions, error) {
return schedule.TemplateScheduleOptions{
Expand Down Expand Up @@ -349,8 +321,7 @@ func TestUpdateStates(t *testing.T) {
AgentFn: func(context.Context) (database.WorkspaceAgent, error) {
return agent, nil
},
Database: db,
Pubsub: ps,
Database: dbM,
StatsBatcher: batcher,
TemplateScheduleStore: templateScheduleStorePtr(templateScheduleStore),
AgentStatsRefreshInterval: 15 * time.Second,
Expand All @@ -370,26 +341,26 @@ func TestUpdateStates(t *testing.T) {
}

// Workspace gets fetched.
db.EXPECT().GetWorkspaceByAgentID(gomock.Any(), agent.ID).Return(database.GetWorkspaceByAgentIDRow{
dbM.EXPECT().GetWorkspaceByAgentID(gomock.Any(), agent.ID).Return(database.GetWorkspaceByAgentIDRow{
Workspace: workspace,
TemplateName: template.Name,
}, nil)

// We expect an activity bump because ConnectionCount > 0. However, the
// next autostart time will be set on the bump.
db.EXPECT().ActivityBumpWorkspace(gomock.Any(), database.ActivityBumpWorkspaceParams{
dbM.EXPECT().ActivityBumpWorkspace(gomock.Any(), database.ActivityBumpWorkspaceParams{
WorkspaceID: workspace.ID,
NextAutostart: nextAutostart,
}).Return(nil)

// Workspace last used at gets bumped.
db.EXPECT().UpdateWorkspaceLastUsedAt(gomock.Any(), database.UpdateWorkspaceLastUsedAtParams{
dbM.EXPECT().UpdateWorkspaceLastUsedAt(gomock.Any(), database.UpdateWorkspaceLastUsedAtParams{
ID: workspace.ID,
LastUsedAt: now,
}).Return(nil)

// User gets fetched to hit the UpdateAgentMetricsFn.
db.EXPECT().GetUserByID(gomock.Any(), user.ID).Return(user, nil)
dbM.EXPECT().GetUserByID(gomock.Any(), user.ID).Return(user, nil)

resp, err := api.UpdateStats(context.Background(), req)
require.NoError(t, err)
Expand Down
44 changes: 1 addition & 43 deletions coderd/workspaces.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package coderd

import (
"bytes"
"context"
"database/sql"
"encoding/json"
Expand Down Expand Up @@ -1344,48 +1343,7 @@ func (api *API) watchWorkspace(rw http.ResponseWriter, r *http.Request) {
<-senderClosed
}()

sendUpdate := func(_ context.Context, description []byte) {
// The agent stats get updated frequently, so we treat these as a special case and only
// send a partial update. We primarily care about updating the `last_used_at` and
// `latest_build.deadline` properties.
if bytes.Equal(description, codersdk.WorkspaceNotifyDescriptionAgentStatsOnly) {
workspace, err := api.Database.GetWorkspaceByID(ctx, workspace.ID)
if err != nil {
_ = sendEvent(ctx, codersdk.ServerSentEvent{
Type: codersdk.ServerSentEventTypeError,
Data: codersdk.Response{
Message: "Internal error fetching workspace.",
Detail: err.Error(),
},
})
return
}

workspaceBuild, err := api.Database.GetLatestWorkspaceBuildByWorkspaceID(ctx, workspace.ID)
if err != nil {
_ = sendEvent(ctx, codersdk.ServerSentEvent{
Type: codersdk.ServerSentEventTypeError,
Data: codersdk.Response{
Message: "Internal error fetching workspace build.",
Detail: err.Error(),
},
})
return
}

_ = sendEvent(ctx, codersdk.ServerSentEvent{
Type: codersdk.ServerSentEventTypePartial,
Data: struct {
database.Workspace
LatestBuild database.WorkspaceBuild `json:"latest_build"`
}{
Workspace: workspace,
LatestBuild: workspaceBuild,
},
})
return
}

sendUpdate := func(_ context.Context, _ []byte) {
workspace, err := api.Database.GetWorkspaceByID(ctx, workspace.ID)
if err != nil {
_ = sendEvent(ctx, codersdk.ServerSentEvent{
Expand Down
7 changes: 3 additions & 4 deletions codersdk/serversentevents.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,9 @@ type ServerSentEvent struct {
type ServerSentEventType string

const (
ServerSentEventTypePing ServerSentEventType = "ping"
ServerSentEventTypeData ServerSentEventType = "data"
ServerSentEventTypePartial ServerSentEventType = "partial"
ServerSentEventTypeError ServerSentEventType = "error"
ServerSentEventTypePing ServerSentEventType = "ping"
ServerSentEventTypeData ServerSentEventType = "data"
ServerSentEventTypeError ServerSentEventType = "error"
)

func ServerSentEventReader(ctx context.Context, rc io.ReadCloser) func() (*ServerSentEvent, error) {
Expand Down
2 changes: 0 additions & 2 deletions codersdk/workspaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -497,8 +497,6 @@ func (c *Client) UnfavoriteWorkspace(ctx context.Context, workspaceID uuid.UUID)
return nil
}

var WorkspaceNotifyDescriptionAgentStatsOnly = []byte("agentStatsOnly")

// WorkspaceNotifyChannel is the PostgreSQL NOTIFY
// channel to listen for updates on. The payload is empty,
// because the size of a workspace payload can be very large.
Expand Down
3 changes: 1 addition & 2 deletions site/src/api/typesGenerated.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

32 changes: 0 additions & 32 deletions site/src/hooks/useTime.ts

This file was deleted.

45 changes: 0 additions & 45 deletions site/src/modules/workspaces/activity.ts

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,12 @@ describe("AccountPage", () => {
Promise.resolve({
id: userId,
email: "user@coder.com",
created_at: new Date().toISOString(),
created_at: new Date().toString(),
status: "active",
organization_ids: ["123"],
roles: [],
avatar_url: "",
last_seen_at: new Date().toISOString(),
last_seen_at: new Date().toString(),
login_type: "password",
theme_preference: "",
...data,
Expand Down
Loading