Skip to content

feat: store and display template owner #2228

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 7 commits into from
Jun 10, 2022
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
2 changes: 2 additions & 0 deletions coderd/audit/diff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ func TestDiff(t *testing.T) {
ActiveVersionID: uuid.UUID{3},
MaxTtl: int64(time.Hour),
MinAutostartInterval: int64(time.Minute),
CreatedBy: uuid.NullUUID{UUID: uuid.UUID{4}, Valid: true},
},
exp: audit.Map{
"id": uuid.UUID{1}.String(),
Expand All @@ -97,6 +98,7 @@ func TestDiff(t *testing.T) {
"active_version_id": uuid.UUID{3}.String(),
"max_ttl": int64(3600000000000),
"min_autostart_interval": int64(60000000000),
"created_by": uuid.UUID{4}.String(),
},
},
})
Expand Down
1 change: 1 addition & 0 deletions coderd/audit/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ var AuditableResources = auditMap(map[any]map[string]Action{
"description": ActionTrack,
"max_ttl": ActionTrack,
"min_autostart_interval": ActionTrack,
"created_by": ActionTrack,
},
&database.TemplateVersion{}: {
"id": ActionTrack,
Expand Down
1 change: 1 addition & 0 deletions coderd/database/databasefake/databasefake.go
Original file line number Diff line number Diff line change
Expand Up @@ -1316,6 +1316,7 @@ func (q *fakeQuerier) InsertTemplate(_ context.Context, arg database.InsertTempl
Description: arg.Description,
MaxTtl: arg.MaxTtl,
MinAutostartInterval: arg.MinAutostartInterval,
CreatedBy: arg.CreatedBy,
}
q.templates = append(q.templates, template)
return template, nil
Expand Down
6 changes: 5 additions & 1 deletion coderd/database/dump.sql

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

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ALTER TABLE ONLY templates DROP COLUMN IF EXISTS created_by;
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ALTER TABLE ONLY templates ADD COLUMN IF NOT EXISTS created_by uuid REFERENCES users (id) ON DELETE RESTRICT;
1 change: 1 addition & 0 deletions coderd/database/models.go

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

22 changes: 15 additions & 7 deletions coderd/database/queries.sql.go

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

5 changes: 3 additions & 2 deletions coderd/database/queries/templates.sql
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,11 @@ INSERT INTO
active_version_id,
description,
max_ttl,
min_autostart_interval
min_autostart_interval,
created_by
)
VALUES
($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING *;
($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING *;

-- name: UpdateTemplateActiveVersionByID :exec
UPDATE
Expand Down
83 changes: 74 additions & 9 deletions coderd/templates.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package coderd

import (
"context"
"database/sql"
"errors"
"fmt"
Expand Down Expand Up @@ -49,7 +50,16 @@ func (api *API) template(rw http.ResponseWriter, r *http.Request) {
count = uint32(workspaceCounts[0].Count)
}

httpapi.Write(rw, http.StatusOK, convertTemplate(template, count))
createdByNameMap, err := getCreatedByNamesByTemplateIDs(r.Context(), api.Database, []database.Template{template})
if err != nil {
httpapi.Write(rw, http.StatusInternalServerError, httpapi.Response{
Message: "Internal error fetching creator name.",
Detail: err.Error(),
})
return
}

httpapi.Write(rw, http.StatusOK, convertTemplate(template, count, createdByNameMap[template.ID.String()]))
}

func (api *API) deleteTemplate(rw http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -97,6 +107,7 @@ func (api *API) deleteTemplate(rw http.ResponseWriter, r *http.Request) {
func (api *API) postTemplateByOrganization(rw http.ResponseWriter, r *http.Request) {
var createTemplate codersdk.CreateTemplateRequest
organization := httpmw.OrganizationParam(r)
apiKey := httpmw.APIKey(r)
if !api.Authorize(rw, r, rbac.ActionCreate, rbac.ResourceTemplate.InOrg(organization.ID)) {
return
}
Expand Down Expand Up @@ -175,6 +186,10 @@ func (api *API) postTemplateByOrganization(rw http.ResponseWriter, r *http.Reque
Description: createTemplate.Description,
MaxTtl: int64(maxTTL),
MinAutostartInterval: int64(minAutostartInterval),
CreatedBy: uuid.NullUUID{
UUID: apiKey.UserID,
Valid: true,
},
})
if err != nil {
return xerrors.Errorf("insert template: %s", err)
Expand Down Expand Up @@ -208,7 +223,12 @@ func (api *API) postTemplateByOrganization(rw http.ResponseWriter, r *http.Reque
}
}

template = convertTemplate(dbTemplate, 0)
createdByNameMap, err := getCreatedByNamesByTemplateIDs(r.Context(), db, []database.Template{dbTemplate})
if err != nil {
return xerrors.Errorf("get creator name: %w", err)
}

template = convertTemplate(dbTemplate, 0, createdByNameMap[dbTemplate.ID.String()])
return nil
})
if err != nil {
Expand Down Expand Up @@ -258,7 +278,16 @@ func (api *API) templatesByOrganization(rw http.ResponseWriter, r *http.Request)
return
}

httpapi.Write(rw, http.StatusOK, convertTemplates(templates, workspaceCounts))
createdByNameMap, err := getCreatedByNamesByTemplateIDs(r.Context(), api.Database, templates)
if err != nil {
httpapi.Write(rw, http.StatusInternalServerError, httpapi.Response{
Message: "Internal error fetching creator names.",
Detail: err.Error(),
})
return
}

httpapi.Write(rw, http.StatusOK, convertTemplates(templates, workspaceCounts, createdByNameMap))
}

func (api *API) templateByOrganizationAndName(rw http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -304,7 +333,16 @@ func (api *API) templateByOrganizationAndName(rw http.ResponseWriter, r *http.Re
count = uint32(workspaceCounts[0].Count)
}

httpapi.Write(rw, http.StatusOK, convertTemplate(template, count))
createdByNameMap, err := getCreatedByNamesByTemplateIDs(r.Context(), api.Database, []database.Template{template})
if err != nil {
httpapi.Write(rw, http.StatusInternalServerError, httpapi.Response{
Message: "Internal error fetching creator name.",
Detail: err.Error(),
})
return
}

httpapi.Write(rw, http.StatusOK, convertTemplate(template, count, createdByNameMap[template.ID.String()]))
}

func (api *API) patchTemplateMeta(rw http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -400,29 +438,54 @@ func (api *API) patchTemplateMeta(rw http.ResponseWriter, r *http.Request) {
return
}

httpapi.Write(rw, http.StatusOK, convertTemplate(updated, count))
createdByNameMap, err := getCreatedByNamesByTemplateIDs(r.Context(), api.Database, []database.Template{updated})
if err != nil {
httpapi.Write(rw, http.StatusInternalServerError, httpapi.Response{
Message: "Internal error fetching creator name.",
Detail: err.Error(),
})
return
}

httpapi.Write(rw, http.StatusOK, convertTemplate(updated, count, createdByNameMap[updated.ID.String()]))
}

func getCreatedByNamesByTemplateIDs(ctx context.Context, db database.Store, templates []database.Template) (map[string]string, error) {
creators := make(map[string]string, len(templates))
for _, template := range templates {
if template.CreatedBy.Valid {
creator, err := db.GetUserByID(ctx, template.CreatedBy.UUID)
if err != nil {
return map[string]string{}, err
}
creators[template.ID.String()] = creator.Username
} else {
creators[template.ID.String()] = ""
}
}
return creators, nil
}

func convertTemplates(templates []database.Template, workspaceCounts []database.GetWorkspaceOwnerCountsByTemplateIDsRow) []codersdk.Template {
func convertTemplates(templates []database.Template, workspaceCounts []database.GetWorkspaceOwnerCountsByTemplateIDsRow, createdByNameMap map[string]string) []codersdk.Template {
apiTemplates := make([]codersdk.Template, 0, len(templates))
for _, template := range templates {
found := false
for _, workspaceCount := range workspaceCounts {
if workspaceCount.TemplateID.String() != template.ID.String() {
continue
}
apiTemplates = append(apiTemplates, convertTemplate(template, uint32(workspaceCount.Count)))
apiTemplates = append(apiTemplates, convertTemplate(template, uint32(workspaceCount.Count), createdByNameMap[template.ID.String()]))
found = true
break
}
if !found {
apiTemplates = append(apiTemplates, convertTemplate(template, uint32(0)))
apiTemplates = append(apiTemplates, convertTemplate(template, uint32(0), createdByNameMap[template.ID.String()]))
}
}
return apiTemplates
}

func convertTemplate(template database.Template, workspaceOwnerCount uint32) codersdk.Template {
func convertTemplate(template database.Template, workspaceOwnerCount uint32, createdByName string) codersdk.Template {
return codersdk.Template{
ID: template.ID,
CreatedAt: template.CreatedAt,
Expand All @@ -435,5 +498,7 @@ func convertTemplate(template database.Template, workspaceOwnerCount uint32) cod
Description: template.Description,
MaxTTLMillis: time.Duration(template.MaxTtl).Milliseconds(),
MinAutostartIntervalMillis: time.Duration(template.MinAutostartInterval).Milliseconds(),
CreatedByID: template.CreatedBy,
CreatedByName: createdByName,
}
}
2 changes: 2 additions & 0 deletions codersdk/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ type Template struct {
Description string `json:"description"`
MaxTTLMillis int64 `json:"max_ttl_ms"`
MinAutostartIntervalMillis int64 `json:"min_autostart_interval_ms"`
CreatedByID uuid.NullUUID `json:"created_by_id"`
CreatedByName string `json:"created_by_name"`
}

type UpdateActiveTemplateVersion struct {
Expand Down
8 changes: 5 additions & 3 deletions site/src/api/typesGenerated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,8 @@ export interface Template {
readonly description: string
readonly max_ttl_ms: number
readonly min_autostart_interval_ms: number
readonly created_by_id?: string
readonly created_by_name: string
}

// From codersdk/templateversions.go:14:6
Expand Down Expand Up @@ -276,12 +278,12 @@ export interface TemplateVersionParameter {
readonly default_source_value: boolean
}

// From codersdk/templates.go:98:6
// From codersdk/templates.go:100:6
export interface TemplateVersionsByTemplateRequest extends Pagination {
readonly template_id: string
}

// From codersdk/templates.go:30:6
// From codersdk/templates.go:32:6
export interface UpdateActiveTemplateVersion {
readonly id: string
}
Expand All @@ -291,7 +293,7 @@ export interface UpdateRoles {
readonly roles: string[]
}

// From codersdk/templates.go:34:6
// From codersdk/templates.go:36:6
export interface UpdateTemplateMeta {
readonly description?: string
readonly max_ttl_ms?: number
Expand Down
Loading