Skip to content

refactor(coderd/database): split Time and Now into dbtime package #9482

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 2 commits into from
Sep 1, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
refactor(coderd/database): split Time and Now into dbtime package
Ref: #9380
  • Loading branch information
mafredri committed Sep 1, 2023
commit dfce60add02090af1d8bc04324e261961482b250
4 changes: 2 additions & 2 deletions agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import (
"github.com/coder/coder/v2/agent/agentssh"
"github.com/coder/coder/v2/agent/reconnectingpty"
"github.com/coder/coder/v2/buildinfo"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/coderd/gitauth"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/agentsdk"
Expand Down Expand Up @@ -523,7 +523,7 @@ func (a *agent) reportLifecycleLoop(ctx context.Context) {
func (a *agent) setLifecycle(ctx context.Context, state codersdk.WorkspaceAgentLifecycle) {
report := agentsdk.PostLifecycleRequest{
State: state,
ChangedAt: database.Now(),
ChangedAt: dbtime.Now(),
}

a.lifecycleMu.Lock()
Expand Down
16 changes: 8 additions & 8 deletions cli/cliui/provisionerjob_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (

"github.com/coder/coder/v2/cli/clibase"
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/pty/ptytest"
)
Expand All @@ -29,13 +29,13 @@ func TestProvisionerJob(t *testing.T) {
<-test.Next
test.JobMutex.Lock()
test.Job.Status = codersdk.ProvisionerJobRunning
now := database.Now()
now := dbtime.Now()
test.Job.StartedAt = &now
test.JobMutex.Unlock()
<-test.Next
test.JobMutex.Lock()
test.Job.Status = codersdk.ProvisionerJobSucceeded
now = database.Now()
now = dbtime.Now()
test.Job.CompletedAt = &now
close(test.Logs)
test.JobMutex.Unlock()
Expand All @@ -56,17 +56,17 @@ func TestProvisionerJob(t *testing.T) {
<-test.Next
test.JobMutex.Lock()
test.Job.Status = codersdk.ProvisionerJobRunning
now := database.Now()
now := dbtime.Now()
test.Job.StartedAt = &now
test.Logs <- codersdk.ProvisionerJobLog{
CreatedAt: database.Now(),
CreatedAt: dbtime.Now(),
Stage: "Something",
}
test.JobMutex.Unlock()
<-test.Next
test.JobMutex.Lock()
test.Job.Status = codersdk.ProvisionerJobSucceeded
now = database.Now()
now = dbtime.Now()
test.Job.CompletedAt = &now
close(test.Logs)
test.JobMutex.Unlock()
Expand Down Expand Up @@ -99,7 +99,7 @@ func TestProvisionerJob(t *testing.T) {
<-test.Next
test.JobMutex.Lock()
test.Job.Status = codersdk.ProvisionerJobCanceled
now := database.Now()
now := dbtime.Now()
test.Job.CompletedAt = &now
close(test.Logs)
test.JobMutex.Unlock()
Expand All @@ -123,7 +123,7 @@ type provisionerJobTest struct {
func newProvisionerJob(t *testing.T) provisionerJobTest {
job := &codersdk.ProvisionerJob{
Status: codersdk.ProvisionerJobPending,
CreatedAt: database.Now(),
CreatedAt: dbtime.Now(),
}
jobLock := sync.Mutex{}
logs := make(chan codersdk.ProvisionerJobLog, 1)
Expand Down
9 changes: 4 additions & 5 deletions cli/cliui/resources.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ import (
"github.com/jedib0t/go-pretty/v6/table"
"golang.org/x/mod/semver"

"github.com/coder/coder/v2/coderd/database"

"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/codersdk"
)

Expand Down Expand Up @@ -122,15 +121,15 @@ func WorkspaceResources(writer io.Writer, resources []codersdk.WorkspaceResource
func renderAgentStatus(agent codersdk.WorkspaceAgent) string {
switch agent.Status {
case codersdk.WorkspaceAgentConnecting:
since := database.Now().Sub(agent.CreatedAt)
since := dbtime.Now().Sub(agent.CreatedAt)
return DefaultStyles.Warn.Render("⦾ connecting") + " " +
DefaultStyles.Placeholder.Render("["+strconv.Itoa(int(since.Seconds()))+"s]")
case codersdk.WorkspaceAgentDisconnected:
since := database.Now().Sub(*agent.DisconnectedAt)
since := dbtime.Now().Sub(*agent.DisconnectedAt)
return DefaultStyles.Error.Render("⦾ disconnected") + " " +
DefaultStyles.Placeholder.Render("["+strconv.Itoa(int(since.Seconds()))+"s]")
case codersdk.WorkspaceAgentTimeout:
since := database.Now().Sub(agent.CreatedAt)
since := dbtime.Now().Sub(agent.CreatedAt)
return fmt.Sprintf(
"%s %s",
DefaultStyles.Warn.Render("⦾ timeout"),
Expand Down
6 changes: 3 additions & 3 deletions cli/cliui/resources_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"github.com/stretchr/testify/assert"

"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/pty/ptytest"
)
Expand Down Expand Up @@ -44,7 +44,7 @@ func TestWorkspaceResources(t *testing.T) {
t.Run("MultipleStates", func(t *testing.T) {
t.Parallel()
ptty := ptytest.New(t)
disconnected := database.Now().Add(-4 * time.Second)
disconnected := dbtime.Now().Add(-4 * time.Second)
done := make(chan struct{})
go func() {
err := cliui.WorkspaceResources(ptty.Output(), []codersdk.WorkspaceResource{{
Expand All @@ -60,7 +60,7 @@ func TestWorkspaceResources(t *testing.T) {
Type: "google_compute_instance",
Name: "dev",
Agents: []codersdk.WorkspaceAgent{{
CreatedAt: database.Now().Add(-10 * time.Second),
CreatedAt: dbtime.Now().Add(-10 * time.Second),
Status: codersdk.WorkspaceAgentConnecting,
LifecycleState: codersdk.WorkspaceAgentLifecycleCreated,
Name: "dev",
Expand Down
13 changes: 7 additions & 6 deletions cli/server_createadminuser.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"github.com/coder/coder/v2/cli/clibase"
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/coderd/gitsshkey"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/rbac"
Expand Down Expand Up @@ -180,8 +181,8 @@ func (r *RootCmd) newCreateAdminUserCommand() *clibase.Cmd {
Email: newUserEmail,
Username: newUserUsername,
HashedPassword: []byte(hashedPassword),
CreatedAt: database.Now(),
UpdatedAt: database.Now(),
CreatedAt: dbtime.Now(),
UpdatedAt: dbtime.Now(),
RBACRoles: []string{rbac.RoleOwner()},
LoginType: database.LoginTypePassword,
})
Expand All @@ -196,8 +197,8 @@ func (r *RootCmd) newCreateAdminUserCommand() *clibase.Cmd {
}
_, err = tx.InsertGitSSHKey(ctx, database.InsertGitSSHKeyParams{
UserID: newUser.ID,
CreatedAt: database.Now(),
UpdatedAt: database.Now(),
CreatedAt: dbtime.Now(),
UpdatedAt: dbtime.Now(),
PrivateKey: privateKey,
PublicKey: publicKey,
})
Expand All @@ -210,8 +211,8 @@ func (r *RootCmd) newCreateAdminUserCommand() *clibase.Cmd {
_, err := tx.InsertOrganizationMember(ctx, database.InsertOrganizationMemberParams{
OrganizationID: org.ID,
UserID: newUser.ID,
CreatedAt: database.Now(),
UpdatedAt: database.Now(),
CreatedAt: dbtime.Now(),
UpdatedAt: dbtime.Now(),
Roles: []string{rbac.RoleOrgAdmin(org.ID)},
})
if err != nil {
Expand Down
9 changes: 5 additions & 4 deletions cli/server_createadminuser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (

"github.com/coder/coder/v2/cli/clitest"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/coderd/database/postgres"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/coderd/userpassword"
Expand Down Expand Up @@ -106,15 +107,15 @@ func TestServerCreateAdminUser(t *testing.T) {
_, err = db.InsertOrganization(ctx, database.InsertOrganizationParams{
ID: org1ID,
Name: org1Name,
CreatedAt: database.Now(),
UpdatedAt: database.Now(),
CreatedAt: dbtime.Now(),
UpdatedAt: dbtime.Now(),
})
require.NoError(t, err)
_, err = db.InsertOrganization(ctx, database.InsertOrganizationParams{
ID: org2ID,
Name: org2Name,
CreatedAt: database.Now(),
UpdatedAt: database.Now(),
CreatedAt: dbtime.Now(),
UpdatedAt: dbtime.Now(),
})
require.NoError(t, err)

Expand Down
16 changes: 8 additions & 8 deletions cmd/cliui/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (

"github.com/coder/coder/v2/cli/clibase"
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/codersdk"
)

Expand Down Expand Up @@ -82,21 +82,21 @@ func main() {
Handler: func(inv *clibase.Invocation) error {
job := codersdk.ProvisionerJob{
Status: codersdk.ProvisionerJobPending,
CreatedAt: database.Now(),
CreatedAt: dbtime.Now(),
}
go func() {
time.Sleep(time.Second)
if job.Status != codersdk.ProvisionerJobPending {
return
}
started := database.Now()
started := dbtime.Now()
job.StartedAt = &started
job.Status = codersdk.ProvisionerJobRunning
time.Sleep(3 * time.Second)
if job.Status != codersdk.ProvisionerJobRunning {
return
}
completed := database.Now()
completed := dbtime.Now()
job.CompletedAt = &completed
job.Status = codersdk.ProvisionerJobSucceeded
}()
Expand Down Expand Up @@ -154,7 +154,7 @@ func main() {
job.Status = codersdk.ProvisionerJobCanceling
time.Sleep(time.Second)
job.Status = codersdk.ProvisionerJobCanceled
completed := database.Now()
completed := dbtime.Now()
job.CompletedAt = &completed
return nil
},
Expand Down Expand Up @@ -236,7 +236,7 @@ func main() {
time.Sleep(144 * time.Millisecond)
}
agent.LifecycleState = codersdk.WorkspaceAgentLifecycleReady
readyAt := database.Now()
readyAt := dbtime.Now()
agent.ReadyAt = &readyAt
}()
} else {
Expand All @@ -258,7 +258,7 @@ func main() {
root.Children = append(root.Children, &clibase.Cmd{
Use: "resources",
Handler: func(inv *clibase.Invocation) error {
disconnected := database.Now().Add(-4 * time.Second)
disconnected := dbtime.Now().Add(-4 * time.Second)
return cliui.WorkspaceResources(inv.Stdout, []codersdk.WorkspaceResource{{
Transition: codersdk.WorkspaceTransitionStart,
Type: "google_compute_disk",
Expand All @@ -272,7 +272,7 @@ func main() {
Type: "google_compute_instance",
Name: "dev",
Agents: []codersdk.WorkspaceAgent{{
CreatedAt: database.Now().Add(-10 * time.Second),
CreatedAt: dbtime.Now().Add(-10 * time.Second),
Status: codersdk.WorkspaceAgentConnecting,
LifecycleState: codersdk.WorkspaceAgentLifecycleCreated,
Name: "dev",
Expand Down
5 changes: 3 additions & 2 deletions coderd/activitybump.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (

"cdr.dev/slog"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbtime"
)

// activityBumpWorkspace automatically bumps the workspace's auto-off timer
Expand Down Expand Up @@ -69,14 +70,14 @@ func activityBumpWorkspace(ctx context.Context, log slog.Logger, db database.Sto
return nil
}

newDeadline := database.Now().Add(bumpAmount)
newDeadline := dbtime.Now().Add(bumpAmount)
if !build.MaxDeadline.IsZero() && newDeadline.After(build.MaxDeadline) {
newDeadline = build.MaxDeadline
}

if err := s.UpdateWorkspaceBuildByID(ctx, database.UpdateWorkspaceBuildByIDParams{
ID: build.ID,
UpdatedAt: database.Now(),
UpdatedAt: dbtime.Now(),
ProvisionerState: build.ProvisionerState,
Deadline: newDeadline,
MaxDeadline: build.MaxDeadline,
Expand Down
9 changes: 5 additions & 4 deletions coderd/activitybump_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbtestutil"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/coderd/schedule"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/agentsdk"
Expand Down Expand Up @@ -77,10 +78,10 @@ func TestWorkspaceActivityBump(t *testing.T) {

err = db.UpdateWorkspaceBuildByID(ctx, database.UpdateWorkspaceBuildByIDParams{
ID: workspace.LatestBuild.ID,
UpdatedAt: database.Now(),
UpdatedAt: dbtime.Now(),
ProvisionerState: dbBuild.ProvisionerState,
Deadline: dbBuild.Deadline,
MaxDeadline: database.Now().Add(maxTTL),
MaxDeadline: dbtime.Now().Add(maxTTL),
})
require.NoError(t, err)
}
Expand Down Expand Up @@ -146,11 +147,11 @@ func TestWorkspaceActivityBump(t *testing.T) {

// If the workspace has a max deadline, the deadline must not exceed
// it.
if maxTTL != 0 && database.Now().Add(ttl).After(workspace.LatestBuild.MaxDeadline.Time) {
if maxTTL != 0 && dbtime.Now().Add(ttl).After(workspace.LatestBuild.MaxDeadline.Time) {
require.Equal(t, workspace.LatestBuild.Deadline.Time, workspace.LatestBuild.MaxDeadline.Time)
return
}
require.WithinDuration(t, database.Now().Add(ttl), workspace.LatestBuild.Deadline.Time, 3*time.Second)
require.WithinDuration(t, dbtime.Now().Add(ttl), workspace.LatestBuild.Deadline.Time, 3*time.Second)
}
}

Expand Down
5 changes: 3 additions & 2 deletions coderd/apikey.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"github.com/coder/coder/v2/coderd/apikey"
"github.com/coder/coder/v2/coderd/audit"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/httpmw"
"github.com/coder/coder/v2/coderd/rbac"
Expand Down Expand Up @@ -84,7 +85,7 @@ func (api *API) postToken(rw http.ResponseWriter, r *http.Request) {
UserID: user.ID,
LoginType: database.LoginTypeToken,
DeploymentValues: api.DeploymentValues,
ExpiresAt: database.Now().Add(lifeTime),
ExpiresAt: dbtime.Now().Add(lifeTime),
Scope: scope,
LifetimeSeconds: int64(lifeTime.Seconds()),
TokenName: tokenName,
Expand Down Expand Up @@ -132,7 +133,7 @@ func (api *API) postAPIKey(rw http.ResponseWriter, r *http.Request) {
RemoteAddr: r.RemoteAddr,
// All api generated keys will last 1 week. Browser login tokens have
// a shorter life.
ExpiresAt: database.Now().Add(lifeTime),
ExpiresAt: dbtime.Now().Add(lifeTime),
LifetimeSeconds: int64(lifeTime.Seconds()),
})
if err != nil {
Expand Down
9 changes: 5 additions & 4 deletions coderd/apikey/apikey.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"golang.org/x/xerrors"

"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/cryptorand"
)
Expand Down Expand Up @@ -43,9 +44,9 @@ func Generate(params CreateParams) (database.InsertAPIKeyParams, string, error)
// set.
if params.ExpiresAt.IsZero() {
if params.LifetimeSeconds != 0 {
params.ExpiresAt = database.Now().Add(time.Duration(params.LifetimeSeconds) * time.Second)
params.ExpiresAt = dbtime.Now().Add(time.Duration(params.LifetimeSeconds) * time.Second)
} else {
params.ExpiresAt = database.Now().Add(params.DeploymentValues.SessionDuration.Value())
params.ExpiresAt = dbtime.Now().Add(params.DeploymentValues.SessionDuration.Value())
params.LifetimeSeconds = int64(params.DeploymentValues.SessionDuration.Value().Seconds())
}
}
Expand Down Expand Up @@ -85,8 +86,8 @@ func Generate(params CreateParams) (database.InsertAPIKeyParams, string, error)
},
// Make sure in UTC time for common time zone
ExpiresAt: params.ExpiresAt.UTC(),
CreatedAt: database.Now(),
UpdatedAt: database.Now(),
CreatedAt: dbtime.Now(),
UpdatedAt: dbtime.Now(),
HashedSecret: hashed[:],
LoginType: params.LoginType,
Scope: scope,
Expand Down
Loading