Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feat: add template delete notification#14250

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
BrunoQuaresma merged 13 commits intomainfrombq/notify-template-delete
Aug 14, 2024
Merged
Show file tree
Hide file tree
Changes from3 commits
Commits
Show all changes
13 commits
Select commitHold shift + click to select a range
5915daa
feat: add template delete notification
BrunoQuaresmaAug 12, 2024
76ee1f6
Merge branch 'main' of https://github.com/coder/coder into bq/notify-…
BrunoQuaresmaAug 13, 2024
1f7046c
Notify all template admins
BrunoQuaresmaAug 13, 2024
30faf4f
Apply Dannys suggestions
BrunoQuaresmaAug 13, 2024
1e11cb7
Fix lint
BrunoQuaresmaAug 13, 2024
99c1950
Merge branch 'main' of https://github.com/coder/coder into bq/notify-…
BrunoQuaresmaAug 13, 2024
be31ed8
Fix migration
BrunoQuaresmaAug 13, 2024
9e6462d
Merge branch 'main' of https://github.com/coder/coder into bq/notify-…
BrunoQuaresmaAug 14, 2024
7fb0fa2
Improve tests
BrunoQuaresmaAug 14, 2024
92c11de
Filter delete notifications
BrunoQuaresmaAug 14, 2024
450235e
Improve test
BrunoQuaresmaAug 14, 2024
eaf87c5
Fix test
BrunoQuaresmaAug 14, 2024
4688765
Add missing can render test
BrunoQuaresmaAug 14, 2024
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
Empty file.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
INSERT INTO
notification_templates (
id,
name,
title_template,
body_template,
"group",
actions
)
VALUES (
'29a09665-2a4c-403f-9648-54301670e7be',
'Template Deleted',
E'Template "{{.Labels.name}}" deleted',
E'Hi {{.UserName}}\n\nThe template **{{.Labels.name}}** was deleted by **{{ .Labels.initiator }}**.',
'Template Events',
'[
{
"label": "View templates",
"url": "{{ base_url }}/templates"
}
]'::jsonb
);
5 changes: 5 additions & 0 deletionscoderd/notifications/events.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,3 +19,8 @@ var (
TemplateUserAccountCreated = uuid.MustParse("4e19c0ac-94e1-4532-9515-d1801aa283b2")
TemplateUserAccountDeleted = uuid.MustParse("f44d9314-ad03-4bc8-95d0-5cad491da6b6")
)

// Template-related events.
var (
TemplateTemplateDeleted = uuid.MustParse("29a09665-2a4c-403f-9648-54301670e7be")
)
63 changes: 63 additions & 0 deletionscoderd/templates.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
package coderd

import (
"context"
"database/sql"
"errors"
"fmt"
Expand All@@ -12,12 +13,15 @@ import (
"github.com/google/uuid"
"golang.org/x/xerrors"

"cdr.dev/slog"

"github.com/coder/coder/v2/coderd/audit"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
"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/notifications"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/coderd/rbac/policy"
"github.com/coder/coder/v2/coderd/schedule"
Expand DownExpand Up@@ -56,6 +60,7 @@ func (api *API) template(rw http.ResponseWriter, r *http.Request) {
// @Router /templates/{template} [delete]
func (api *API) deleteTemplate(rw http.ResponseWriter, r *http.Request) {
var (
apiKey = httpmw.APIKey(r)
ctx = r.Context()
template = httpmw.TemplateParam(r)
auditor = *api.Auditor.Load()
Expand DownExpand Up@@ -101,11 +106,50 @@ func (api *API) deleteTemplate(rw http.ResponseWriter, r *http.Request) {
})
return
}

admins, err := findTemplateAdmins(ctx, api.Database)
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Internal error fetching template admins.",
Detail: err.Error(),
})
return
}
for _, admin := range admins {
if admin.ID == apiKey.UserID {
continue
}
api.notifyTemplateDeleted(ctx, template, apiKey.UserID, admin.ID)
}

httpapi.Write(ctx, rw, http.StatusOK, codersdk.Response{
Message: "Template has been deleted!",
})
}

func (api *API) notifyTemplateDeleted(ctx context.Context, template database.Template, initiatorID uuid.UUID, receiverID uuid.UUID) {
if initiatorID == receiverID {
return
}

initiator, err := api.Database.GetUserByID(ctx, initiatorID)
if err != nil {
api.Logger.Warn(ctx, "failed to fetch initiator for template deletion notification", slog.F("initiator_id", initiatorID), slog.Error(err))
return
}

if _, err := api.NotificationsEnqueuer.Enqueue(ctx, receiverID, notifications.TemplateTemplateDeleted,
map[string]string{
"name": template.Name,
"initiator": initiator.Username,
}, "api-templates-delete",
// Associate this notification with all the related entities.
template.ID, template.OrganizationID,
); err != nil {
api.Logger.Warn(ctx, "failed to notify of template deletion", slog.F("deleted_template", template.ID), slog.Error(err))
}
}

// Create a new template in an organization.
// Returns a single template.
//
Expand DownExpand Up@@ -948,3 +992,22 @@ func (api *API) convertTemplate(
MaxPortShareLevel: maxPortShareLevel,
}
}

// findTemplateAdmins fetches all users with template admin permission including owners.
func findTemplateAdmins(ctx context.Context, store database.Store) ([]database.GetUsersRow, error) {
// Notice: we can't scrape the user information in parallel as pq
// fails with: unexpected describe rows response: 'D'
owners, err := store.GetUsers(ctx, database.GetUsersParams{
RbacRole: []string{codersdk.RoleOwner},
})
if err != nil {
return nil, xerrors.Errorf("get owners: %w", err)
}
templateAdmins, err := store.GetUsers(ctx, database.GetUsersParams{
RbacRole: []string{codersdk.RoleTemplateAdmin},
})
if err != nil {
return nil, xerrors.Errorf("get template admins: %w", err)
}
return append(owners, templateAdmins...), nil
}
55 changes: 55 additions & 0 deletionscoderd/templates_test.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@ import (
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/coderd/notifications"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/coderd/schedule"
"github.com/coder/coder/v2/coderd/util/ptr"
Expand DownExpand Up@@ -1326,3 +1327,57 @@ func TestTemplateMetrics(t *testing.T) {
dbtime.Now(), res.Workspaces[0].LastUsedAt, time.Minute,
)
}

func TestNotifyDeletedTemplate(t *testing.T) {
t.Parallel()

t.Run("OnlyNotifyOwnersAndTemplateAdmins", func(t *testing.T) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Please add a separate test to validate the functionality in isolation; you can then reduce some complexity in this test and keep it nicely scoped.

Copy link
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Not sure if I got it. What should I separate and what complexity does it solve?

t.Parallel()

var (
notifyEnq = &testutil.FakeNotificationsEnqueuer{}
client = coderdtest.New(t, &coderdtest.Options{
IncludeProvisionerDaemon: true,
NotificationsEnqueuer: notifyEnq,
})
firstUser = coderdtest.CreateFirstUser(t, client)
version = coderdtest.CreateTemplateVersion(t, client, firstUser.OrganizationID, nil)
_ = coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template = coderdtest.CreateTemplate(t, client, firstUser.OrganizationID, version.ID)
ctx = testutil.Context(t, testutil.WaitLong)
)

_, anotherOwner := coderdtest.CreateAnotherUser(t, client, firstUser.OrganizationID, rbac.RoleOwner())
_, tmplAdmin := coderdtest.CreateAnotherUser(t, client, firstUser.OrganizationID, rbac.RoleTemplateAdmin())
coderdtest.CreateAnotherUser(t, client, firstUser.OrganizationID, rbac.RoleMember())

// When: template is deleted
err := client.DeleteTemplate(ctx, template.ID)
require.NoError(t, err)

// Then: the template owners and template admins should receive the notification
shouldBeNotified := []uuid.UUID{anotherOwner.ID, tmplAdmin.ID}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

I think it'd be good to explicitly specify that the first user is not receiving the notification because they initiated it.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

I think it'd also be a good idea here to create another admin but with a different role likeuser admin, and validate that they don't receive the notification either.

BrunoQuaresma reacted with thumbs up emoji
var deleteTemplateNotifications []*testutil.Notification
for _, n := range notifyEnq.Sent {
if n.TemplateID == notifications.TemplateTemplateDeleted {
deleteTemplateNotifications = append(deleteTemplateNotifications, n)
}
}
require.Len(t, deleteTemplateNotifications, len(shouldBeNotified))

for _, userID := range shouldBeNotified {
var notification *testutil.Notification
for _, n := range deleteTemplateNotifications {
if n.UserID == userID {
notification = n
break
}
}
require.NotNil(t, notification)
require.Contains(t, notification.Targets, template.ID)
require.Contains(t, notification.Targets, template.OrganizationID)
require.Equal(t, notification.Labels["name"], template.Name)
require.Equal(t, notification.Labels["initiator"], coderdtest.FirstUserParams.Username)
}
})
}
2 changes: 1 addition & 1 deletioncoderd/workspaces_test.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -3441,7 +3441,7 @@ func TestWorkspaceUsageTracking(t *testing.T) {
})
}

funcTestNotifications(t *testing.T) {
funcTestWorkspaceNotifications(t *testing.T) {
t.Parallel()

t.Run("Dormant", func(t *testing.T) {
Expand Down

[8]ページ先頭

©2009-2025 Movatter.jp