feat: store and display template creator (#2228)

* design commit

* add owner_id to templates table

* add owner information in apis and ui

* update minWidth for statItem

* rename owner to created_by

* missing refactor to created_by

* handle errors in fetching created_by names
This commit is contained in:
Abhineet Jain
2022-06-10 15:24:21 -04:00
committed by GitHub
parent 46da59a6b5
commit 02d2aea7f2
17 changed files with 135 additions and 24 deletions

View File

@ -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(),
@ -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(),
},
},
})

View File

@ -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,

View File

@ -1341,6 +1341,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

View File

@ -248,7 +248,8 @@ CREATE TABLE templates (
active_version_id uuid NOT NULL,
description character varying(128) DEFAULT ''::character varying NOT NULL,
max_ttl bigint DEFAULT '604800000000000'::bigint NOT NULL,
min_autostart_interval bigint DEFAULT '3600000000000'::bigint NOT NULL
min_autostart_interval bigint DEFAULT '3600000000000'::bigint NOT NULL,
created_by uuid
);
CREATE TABLE users (
@ -476,6 +477,9 @@ ALTER TABLE ONLY template_versions
ALTER TABLE ONLY template_versions
ADD CONSTRAINT template_versions_template_id_fkey FOREIGN KEY (template_id) REFERENCES templates(id) ON DELETE CASCADE;
ALTER TABLE ONLY templates
ADD CONSTRAINT templates_created_by_fkey FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE RESTRICT;
ALTER TABLE ONLY templates
ADD CONSTRAINT templates_organization_id_fkey FOREIGN KEY (organization_id) REFERENCES organizations(id) ON DELETE CASCADE;

View File

@ -0,0 +1 @@
ALTER TABLE ONLY templates DROP COLUMN IF EXISTS created_by;

View File

@ -0,0 +1 @@
ALTER TABLE ONLY templates ADD COLUMN IF NOT EXISTS created_by uuid REFERENCES users (id) ON DELETE RESTRICT;

View File

@ -438,6 +438,7 @@ type Template struct {
Description string `db:"description" json:"description"`
MaxTtl int64 `db:"max_ttl" json:"max_ttl"`
MinAutostartInterval int64 `db:"min_autostart_interval" json:"min_autostart_interval"`
CreatedBy uuid.NullUUID `db:"created_by" json:"created_by"`
}
type TemplateVersion struct {

View File

@ -1603,7 +1603,7 @@ func (q *sqlQuerier) UpdateProvisionerJobWithCompleteByID(ctx context.Context, a
const getTemplateByID = `-- name: GetTemplateByID :one
SELECT
id, created_at, updated_at, organization_id, deleted, name, provisioner, active_version_id, description, max_ttl, min_autostart_interval
id, created_at, updated_at, organization_id, deleted, name, provisioner, active_version_id, description, max_ttl, min_autostart_interval, created_by
FROM
templates
WHERE
@ -1627,13 +1627,14 @@ func (q *sqlQuerier) GetTemplateByID(ctx context.Context, id uuid.UUID) (Templat
&i.Description,
&i.MaxTtl,
&i.MinAutostartInterval,
&i.CreatedBy,
)
return i, err
}
const getTemplateByOrganizationAndName = `-- name: GetTemplateByOrganizationAndName :one
SELECT
id, created_at, updated_at, organization_id, deleted, name, provisioner, active_version_id, description, max_ttl, min_autostart_interval
id, created_at, updated_at, organization_id, deleted, name, provisioner, active_version_id, description, max_ttl, min_autostart_interval, created_by
FROM
templates
WHERE
@ -1665,13 +1666,14 @@ func (q *sqlQuerier) GetTemplateByOrganizationAndName(ctx context.Context, arg G
&i.Description,
&i.MaxTtl,
&i.MinAutostartInterval,
&i.CreatedBy,
)
return i, err
}
const getTemplatesByIDs = `-- name: GetTemplatesByIDs :many
SELECT
id, created_at, updated_at, organization_id, deleted, name, provisioner, active_version_id, description, max_ttl, min_autostart_interval
id, created_at, updated_at, organization_id, deleted, name, provisioner, active_version_id, description, max_ttl, min_autostart_interval, created_by
FROM
templates
WHERE
@ -1699,6 +1701,7 @@ func (q *sqlQuerier) GetTemplatesByIDs(ctx context.Context, ids []uuid.UUID) ([]
&i.Description,
&i.MaxTtl,
&i.MinAutostartInterval,
&i.CreatedBy,
); err != nil {
return nil, err
}
@ -1715,7 +1718,7 @@ func (q *sqlQuerier) GetTemplatesByIDs(ctx context.Context, ids []uuid.UUID) ([]
const getTemplatesByOrganization = `-- name: GetTemplatesByOrganization :many
SELECT
id, created_at, updated_at, organization_id, deleted, name, provisioner, active_version_id, description, max_ttl, min_autostart_interval
id, created_at, updated_at, organization_id, deleted, name, provisioner, active_version_id, description, max_ttl, min_autostart_interval, created_by
FROM
templates
WHERE
@ -1749,6 +1752,7 @@ func (q *sqlQuerier) GetTemplatesByOrganization(ctx context.Context, arg GetTemp
&i.Description,
&i.MaxTtl,
&i.MinAutostartInterval,
&i.CreatedBy,
); err != nil {
return nil, err
}
@ -1775,10 +1779,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 id, created_at, updated_at, organization_id, deleted, name, provisioner, active_version_id, description, max_ttl, min_autostart_interval
($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING id, created_at, updated_at, organization_id, deleted, name, provisioner, active_version_id, description, max_ttl, min_autostart_interval, created_by
`
type InsertTemplateParams struct {
@ -1792,6 +1797,7 @@ type InsertTemplateParams struct {
Description string `db:"description" json:"description"`
MaxTtl int64 `db:"max_ttl" json:"max_ttl"`
MinAutostartInterval int64 `db:"min_autostart_interval" json:"min_autostart_interval"`
CreatedBy uuid.NullUUID `db:"created_by" json:"created_by"`
}
func (q *sqlQuerier) InsertTemplate(ctx context.Context, arg InsertTemplateParams) (Template, error) {
@ -1806,6 +1812,7 @@ func (q *sqlQuerier) InsertTemplate(ctx context.Context, arg InsertTemplateParam
arg.Description,
arg.MaxTtl,
arg.MinAutostartInterval,
arg.CreatedBy,
)
var i Template
err := row.Scan(
@ -1820,6 +1827,7 @@ func (q *sqlQuerier) InsertTemplate(ctx context.Context, arg InsertTemplateParam
&i.Description,
&i.MaxTtl,
&i.MinAutostartInterval,
&i.CreatedBy,
)
return i, err
}
@ -1873,7 +1881,7 @@ SET
WHERE
id = $1
RETURNING
id, created_at, updated_at, organization_id, deleted, name, provisioner, active_version_id, description, max_ttl, min_autostart_interval
id, created_at, updated_at, organization_id, deleted, name, provisioner, active_version_id, description, max_ttl, min_autostart_interval, created_by
`
type UpdateTemplateMetaByIDParams struct {

View File

@ -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

View File

@ -1,6 +1,7 @@
package coderd
import (
"context"
"database/sql"
"errors"
"fmt"
@ -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) {
@ -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
}
@ -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)
@ -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 {
@ -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) {
@ -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) {
@ -400,10 +438,35 @@ 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 convertTemplates(templates []database.Template, workspaceCounts []database.GetWorkspaceOwnerCountsByTemplateIDsRow) []codersdk.Template {
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, createdByNameMap map[string]string) []codersdk.Template {
apiTemplates := make([]codersdk.Template, 0, len(templates))
for _, template := range templates {
found := false
@ -411,18 +474,18 @@ func convertTemplates(templates []database.Template, workspaceCounts []database.
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,
@ -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,
}
}