Skip to content

feat: use active users instead of total users in Template views #3900

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 6 commits into from
Sep 9, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ site/out/
.terraform/

.vscode/*.log
.vscode/launch.json
**/*.swp
.coderv2/*
**/__debug_bin
14 changes: 4 additions & 10 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -161,16 +161,10 @@
// To reduce redundancy in tests, it's covered by other packages.
// Since package coverage pairing can't be defined, all packages cover
// all other packages.
"go.testFlags": ["-short", "-coverpkg=./..."],
"go.coverageDecorator": {
"type": "gutter",
"coveredHighlightColor": "rgba(64,128,128,0.5)",
"uncoveredHighlightColor": "rgba(128,64,64,0.25)",
"coveredBorderColor": "rgba(64,128,128,0.5)",
"uncoveredBorderColor": "rgba(128,64,64,0.25)",
"coveredGutterStyle": "blockgreen",
"uncoveredGutterStyle": "blockred"
},
"go.testFlags": [
"-short",
"-coverpkg=./..."
],
// We often use a version of TypeScript that's ahead of the version shipped
// with VS Code.
"typescript.tsdk": "./site/node_modules/typescript/lib"
Expand Down
8 changes: 4 additions & 4 deletions cli/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func create() *cobra.Command {
}

slices.SortFunc(templates, func(a, b codersdk.Template) bool {
return a.WorkspaceOwnerCount > b.WorkspaceOwnerCount
return a.ActiveUserCount > b.ActiveUserCount
})

templateNames := make([]string, 0, len(templates))
Expand All @@ -81,13 +81,13 @@ func create() *cobra.Command {
for _, template := range templates {
templateName := template.Name

if template.WorkspaceOwnerCount > 0 {
if template.ActiveUserCount > 0 {
developerText := "developer"
if template.WorkspaceOwnerCount != 1 {
if template.ActiveUserCount != 1 {
developerText = "developers"
}

templateName += cliui.Styles.Placeholder.Render(fmt.Sprintf(" (used by %d %s)", template.WorkspaceOwnerCount, developerText))
templateName += cliui.Styles.Placeholder.Render(fmt.Sprintf(" (used by %d %s)", template.ActiveUserCount, developerText))
}

templateNames = append(templateNames, templateName)
Expand Down
3 changes: 2 additions & 1 deletion cli/portforward.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@ import (
"sync"
"syscall"

"cdr.dev/slog"
"github.com/pion/udp"
"github.com/spf13/cobra"
"golang.org/x/xerrors"

"cdr.dev/slog"

"github.com/coder/coder/agent"
"github.com/coder/coder/cli/cliui"
"github.com/coder/coder/codersdk"
Expand Down
4 changes: 2 additions & 2 deletions cli/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ func displayTemplates(filterColumns []string, templates ...codersdk.Template) (s
rows := make([]templateTableRow, len(templates))
for i, template := range templates {
suffix := ""
if template.WorkspaceOwnerCount != 1 {
if template.ActiveUserCount != 1 {
suffix = "s"
}

Expand All @@ -76,7 +76,7 @@ func displayTemplates(filterColumns []string, templates ...codersdk.Template) (s
OrganizationID: template.OrganizationID,
Provisioner: template.Provisioner,
ActiveVersionID: template.ActiveVersionID,
UsedBy: cliui.Styles.Fuchsia.Render(fmt.Sprintf("%d developer%s", template.WorkspaceOwnerCount, suffix)),
UsedBy: cliui.Styles.Fuchsia.Render(fmt.Sprintf("%d developer%s", template.ActiveUserCount, suffix)),
MaxTTL: (time.Duration(template.MaxTTLMillis) * time.Millisecond),
MinAutostartInterval: (time.Duration(template.MinAutostartIntervalMillis) * time.Millisecond),
}
Expand Down
25 changes: 14 additions & 11 deletions coderd/database/databasefake/databasefake.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,34 +163,37 @@ func (q *fakeQuerier) GetTemplateDAUs(_ context.Context, templateID uuid.UUID) (
q.mutex.Lock()
defer q.mutex.Unlock()

counts := make(map[time.Time]map[string]struct{})
seens := make(map[time.Time]map[uuid.UUID]struct{})

for _, as := range q.agentStats {
if as.TemplateID != templateID {
continue
}

date := as.CreatedAt.Truncate(time.Hour * 24)
dateEntry := counts[date]

dateEntry := seens[date]
if dateEntry == nil {
dateEntry = make(map[string]struct{})
dateEntry = make(map[uuid.UUID]struct{})
}
counts[date] = dateEntry

dateEntry[as.UserID.String()] = struct{}{}
dateEntry[as.UserID] = struct{}{}
seens[date] = dateEntry
}

countKeys := maps.Keys(counts)
countKeys := maps.Keys(seens)
sort.Slice(countKeys, func(i, j int) bool {
return countKeys[i].Before(countKeys[j])
})

var rs []database.GetTemplateDAUsRow
for _, key := range countKeys {
rs = append(rs, database.GetTemplateDAUsRow{
Date: key,
Amount: int64(len(counts[key])),
})
ids := seens[key]
for id := range ids {
rs = append(rs, database.GetTemplateDAUsRow{
Date: key,
UserID: id,
})
}
}

return rs, nil
Expand Down
8 changes: 4 additions & 4 deletions coderd/database/queries.sql.go

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

4 changes: 2 additions & 2 deletions coderd/database/queries/agentstats.sql
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ VALUES
-- name: GetTemplateDAUs :many
select
(created_at at TIME ZONE 'UTC')::date as date,
count(distinct(user_id)) as amount
user_id
from
agent_stats
where template_id = $1
group by
date
date, user_id
order by
date asc;

Expand Down
120 changes: 85 additions & 35 deletions coderd/metricscache/metricscache.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"sync/atomic"
"time"

"golang.org/x/exp/maps"
"golang.org/x/exp/slices"
"golang.org/x/xerrors"

"github.com/google/uuid"
Expand All @@ -24,9 +26,10 @@ type Cache struct {
database database.Store
log slog.Logger

templateDAUResponses atomic.Pointer[map[string]codersdk.TemplateDAUsResponse]
templateDAUResponses atomic.Pointer[map[uuid.UUID]codersdk.TemplateDAUsResponse]
templateUniqueUsers atomic.Pointer[map[uuid.UUID]int]

doneCh chan struct{}
done chan struct{}
cancel func()

interval time.Duration
Expand All @@ -41,42 +44,76 @@ func New(db database.Store, log slog.Logger, interval time.Duration) *Cache {
c := &Cache{
database: db,
log: log,
doneCh: make(chan struct{}),
done: make(chan struct{}),
cancel: cancel,
interval: interval,
}
go c.run(ctx)
return c
}

func fillEmptyDays(rows []database.GetTemplateDAUsRow) []database.GetTemplateDAUsRow {
var newRows []database.GetTemplateDAUsRow
func fillEmptyDays(sortedDates []time.Time) []time.Time {
var newDates []time.Time

for i, row := range rows {
for i, ti := range sortedDates {
if i == 0 {
newRows = append(newRows, row)
newDates = append(newDates, ti)
continue
}

last := rows[i-1]
last := sortedDates[i-1]

const day = time.Hour * 24
diff := row.Date.Sub(last.Date)
diff := ti.Sub(last)
for diff > day {
if diff <= day {
break
}
last.Date = last.Date.Add(day)
last.Amount = 0
newRows = append(newRows, last)
last = last.Add(day)
newDates = append(newDates, last)
diff -= day
}

newRows = append(newRows, row)
newDates = append(newDates, ti)
continue
}

return newRows
return newDates
}

func convertDAUResponse(rows []database.GetTemplateDAUsRow) codersdk.TemplateDAUsResponse {
respMap := make(map[time.Time][]uuid.UUID)
for _, row := range rows {
uuids := respMap[row.Date]
if uuids == nil {
uuids = make([]uuid.UUID, 0, 8)
}
uuids = append(uuids, row.UserID)
respMap[row.Date] = uuids
}

dates := maps.Keys(respMap)
slices.SortFunc(dates, func(a, b time.Time) bool {
return a.Before(b)
})

var resp codersdk.TemplateDAUsResponse
for _, date := range fillEmptyDays(dates) {
resp.Entries = append(resp.Entries, codersdk.DAUEntry{
Date: date,
Amount: len(respMap[date]),
})
}

return resp
}

func countUniqueUsers(rows []database.GetTemplateDAUsRow) int {
seen := make(map[uuid.UUID]struct{}, len(rows))
for _, row := range rows {
seen[row.UserID] = struct{}{}
}
return len(seen)
}

func (c *Cache) refresh(ctx context.Context) error {
Expand All @@ -90,30 +127,26 @@ func (c *Cache) refresh(ctx context.Context) error {
return err
}

templateDAUs := make(map[string]codersdk.TemplateDAUsResponse, len(templates))

var (
templateDAUs = make(map[uuid.UUID]codersdk.TemplateDAUsResponse, len(templates))
templateUniqueUsers = make(map[uuid.UUID]int)
)
for _, template := range templates {
daus, err := c.database.GetTemplateDAUs(ctx, template.ID)
rows, err := c.database.GetTemplateDAUs(ctx, template.ID)
if err != nil {
return err
}

var resp codersdk.TemplateDAUsResponse
for _, ent := range fillEmptyDays(daus) {
resp.Entries = append(resp.Entries, codersdk.DAUEntry{
Date: ent.Date,
Amount: int(ent.Amount),
})
}
templateDAUs[template.ID.String()] = resp
templateDAUs[template.ID] = convertDAUResponse(rows)
templateUniqueUsers[template.ID] = countUniqueUsers(rows)
}

c.templateDAUResponses.Store(&templateDAUs)
c.templateUniqueUsers.Store(&templateUniqueUsers)

return nil
}

func (c *Cache) run(ctx context.Context) {
defer close(c.doneCh)
defer close(c.done)

ticker := time.NewTicker(c.interval)
defer ticker.Stop()
Expand All @@ -140,7 +173,7 @@ func (c *Cache) run(ctx context.Context) {

select {
case <-ticker.C:
case <-c.doneCh:
case <-c.done:
return
case <-ctx.Done():
return
Expand All @@ -150,23 +183,40 @@ func (c *Cache) run(ctx context.Context) {

func (c *Cache) Close() error {
c.cancel()
<-c.doneCh
<-c.done
return nil
}

// TemplateDAUs returns an empty response if the template doesn't have users
// or is loading for the first time.
func (c *Cache) TemplateDAUs(id uuid.UUID) codersdk.TemplateDAUsResponse {
func (c *Cache) TemplateDAUs(id uuid.UUID) (*codersdk.TemplateDAUsResponse, bool) {
m := c.templateDAUResponses.Load()
if m == nil {
// Data loading.
return codersdk.TemplateDAUsResponse{}
return nil, false
}

resp, ok := (*m)[id.String()]
resp, ok := (*m)[id]
if !ok {
// Probably no data.
return codersdk.TemplateDAUsResponse{}
return nil, false
}
return resp
return &resp, true
}

// TemplateUniqueUsers returns the number of unique Template users
// from all Cache data.
func (c *Cache) TemplateUniqueUsers(id uuid.UUID) (int, bool) {
m := c.templateUniqueUsers.Load()
if m == nil {
// Data loading.
return -1, false
}

resp, ok := (*m)[id]
if !ok {
// Probably no data.
return -1, false
}
return resp, true
}
Loading