Skip to content

feat(coderd): add mark-all-as-read endpoint for inbox notifications #16976

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 12 commits into from
Mar 20, 2025
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
19 changes: 19 additions & 0 deletions coderd/apidoc/docs.go

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

17 changes: 17 additions & 0 deletions coderd/apidoc/swagger.json

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

1 change: 1 addition & 0 deletions coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -1389,6 +1389,7 @@ func New(options *Options) *API {
r.Use(apiKeyMiddleware)
r.Route("/inbox", func(r chi.Router) {
r.Get("/", api.listInboxNotifications)
r.Put("/mark-all-as-read", api.markAllInboxNotificationsAsRead)
r.Get("/watch", api.watchInboxNotifications)
r.Put("/{id}/read-status", api.updateInboxNotificationReadStatus)
})
Expand Down
10 changes: 10 additions & 0 deletions coderd/database/dbauthz/dbauthz.go
Original file line number Diff line number Diff line change
Expand Up @@ -3554,6 +3554,16 @@ func (q *querier) ListWorkspaceAgentPortShares(ctx context.Context, workspaceID
return q.db.ListWorkspaceAgentPortShares(ctx, workspaceID)
}

func (q *querier) MarkAllInboxNotificationsAsRead(ctx context.Context, arg database.MarkAllInboxNotificationsAsReadParams) error {
resource := rbac.ResourceInboxNotification.WithOwner(arg.UserID.String())

if err := q.authorizeContext(ctx, policy.ActionUpdate, resource); err != nil {
return err
}

return q.db.MarkAllInboxNotificationsAsRead(ctx, arg)
}

func (q *querier) OIDCClaimFieldValues(ctx context.Context, args database.OIDCClaimFieldValuesParams) ([]string, error) {
resource := rbac.ResourceIdpsyncSettings
if args.OrganizationID != uuid.Nil {
Expand Down
9 changes: 9 additions & 0 deletions coderd/database/dbauthz/dbauthz_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4640,6 +4640,15 @@ func (s *MethodTestSuite) TestNotifications() {
ReadAt: sql.NullTime{Time: readAt, Valid: true},
}).Asserts(rbac.ResourceInboxNotification.WithID(notifID).WithOwner(u.ID.String()), policy.ActionUpdate)
}))

s.Run("MarkAllInboxNotificationsAsRead", s.Subtest(func(db database.Store, check *expects) {
u := dbgen.User(s.T(), db, database.User{})

check.Args(database.MarkAllInboxNotificationsAsReadParams{
UserID: u.ID,
ReadAt: sql.NullTime{Time: dbtestutil.NowInDefaultTimezone(), Valid: true},
}).Asserts(rbac.ResourceInboxNotification.WithOwner(u.ID.String()), policy.ActionUpdate)
}))
}

func (s *MethodTestSuite) TestOAuth2ProviderApps() {
Expand Down
15 changes: 15 additions & 0 deletions coderd/database/dbmem/dbmem.go
Original file line number Diff line number Diff line change
Expand Up @@ -9498,6 +9498,21 @@ func (q *FakeQuerier) ListWorkspaceAgentPortShares(_ context.Context, workspaceI
return shares, nil
}

func (q *FakeQuerier) MarkAllInboxNotificationsAsRead(_ context.Context, arg database.MarkAllInboxNotificationsAsReadParams) error {
err := validateDatabaseType(arg)
if err != nil {
return err
}

for idx, notif := range q.inboxNotifications {
if notif.UserID == arg.UserID && !notif.ReadAt.Valid {
q.inboxNotifications[idx].ReadAt = arg.ReadAt
}
}

return nil
}

// nolint:forcetypeassert
func (q *FakeQuerier) OIDCClaimFieldValues(_ context.Context, args database.OIDCClaimFieldValuesParams) ([]string, error) {
orgMembers := q.getOrganizationMemberNoLock(args.OrganizationID)
Expand Down
7 changes: 7 additions & 0 deletions coderd/database/dbmetrics/querymetrics.go

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

14 changes: 14 additions & 0 deletions coderd/database/dbmock/dbmock.go

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

1 change: 1 addition & 0 deletions coderd/database/querier.go

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

19 changes: 19 additions & 0 deletions coderd/database/queries.sql.go

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

8 changes: 8 additions & 0 deletions coderd/database/queries/notificationsinbox.sql
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,11 @@ SET
read_at = $1
WHERE
id = $2;

-- name: MarkAllInboxNotificationsAsRead :exec
UPDATE
inbox_notifications
SET
read_at = $1
WHERE
user_id = $2 and read_at IS NULL;
28 changes: 28 additions & 0 deletions coderd/inboxnotifications.go
Original file line number Diff line number Diff line change
Expand Up @@ -345,3 +345,31 @@ func (api *API) updateInboxNotificationReadStatus(rw http.ResponseWriter, r *htt
UnreadCount: int(unreadCount),
})
}

// markAllInboxNotificationsAsRead marks as read all unread notifications for authenticated user.
// @Summary Mark all unread notifications as read
// @ID mark-all-unread-notifications-as-read
// @Security CoderSessionToken
// @Tags Notifications
// @Success 204
// @Router /notifications/inbox/mark-all-as-read [put]
func (api *API) markAllInboxNotificationsAsRead(rw http.ResponseWriter, r *http.Request) {
var (
ctx = r.Context()
apikey = httpmw.APIKey(r)
)

err := api.Database.MarkAllInboxNotificationsAsRead(ctx, database.MarkAllInboxNotificationsAsReadParams{
UserID: apikey.UserID,
ReadAt: sql.NullTime{Time: dbtime.Now(), Valid: true},
})
if err != nil {
api.Logger.Error(ctx, "failed to mark all unread notifications as read", slog.Error(err))
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Failed to mark all unread notifications as read.",
})
return
}

rw.WriteHeader(http.StatusNoContent)
}
76 changes: 76 additions & 0 deletions coderd/inboxnotifications_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ func TestInboxNotification_Watch(t *testing.T) {
// I skip these tests specifically on windows as for now they are flaky - only on Windows.
// For now the idea is that the runner takes too long to insert the entries, could be worth
// investigating a manual Tx.
// see: https://github.com/coder/internal/issues/503
if runtime.GOOS == "windows" {
t.Skip("our runners are randomly taking too long to insert entries")
}
Expand Down Expand Up @@ -305,6 +306,7 @@ func TestInboxNotifications_List(t *testing.T) {
// I skip these tests specifically on windows as for now they are flaky - only on Windows.
// For now the idea is that the runner takes too long to insert the entries, could be worth
// investigating a manual Tx.
// see: https://github.com/coder/internal/issues/503
if runtime.GOOS == "windows" {
t.Skip("our runners are randomly taking too long to insert entries")
}
Expand Down Expand Up @@ -588,6 +590,7 @@ func TestInboxNotifications_ReadStatus(t *testing.T) {
// I skip these tests specifically on windows as for now they are flaky - only on Windows.
// For now the idea is that the runner takes too long to insert the entries, could be worth
// investigating a manual Tx.
// see: https://github.com/coder/internal/issues/503
if runtime.GOOS == "windows" {
t.Skip("our runners are randomly taking too long to insert entries")
}
Expand Down Expand Up @@ -723,3 +726,76 @@ func TestInboxNotifications_ReadStatus(t *testing.T) {
require.Empty(t, updatedNotif.Notification)
})
}

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

// I skip these tests specifically on windows as for now they are flaky - only on Windows.
// For now the idea is that the runner takes too long to insert the entries, could be worth
// investigating a manual Tx.
// see: https://github.com/coder/internal/issues/503
if runtime.GOOS == "windows" {
t.Skip("our runners are randomly taking too long to insert entries")
}

t.Run("ok", func(t *testing.T) {
t.Parallel()
client, _, api := coderdtest.NewWithAPI(t, &coderdtest.Options{})
firstUser := coderdtest.CreateFirstUser(t, client)
client, member := coderdtest.CreateAnotherUser(t, client, firstUser.OrganizationID)

ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()

notifs, err := client.ListInboxNotifications(ctx, codersdk.ListInboxNotificationsRequest{})
require.NoError(t, err)
require.NotNil(t, notifs)
require.Equal(t, 0, notifs.UnreadCount)
require.Empty(t, notifs.Notifications)

for i := range 20 {
dbgen.NotificationInbox(t, api.Database, database.InsertInboxNotificationParams{
ID: uuid.New(),
UserID: member.ID,
TemplateID: notifications.TemplateWorkspaceOutOfMemory,
Title: fmt.Sprintf("Notification %d", i),
Actions: json.RawMessage("[]"),
Content: fmt.Sprintf("Content of the notif %d", i),
CreatedAt: dbtime.Now(),
})
}

notifs, err = client.ListInboxNotifications(ctx, codersdk.ListInboxNotificationsRequest{})
require.NoError(t, err)
require.NotNil(t, notifs)
require.Equal(t, 20, notifs.UnreadCount)
require.Len(t, notifs.Notifications, 20)

err = client.MarkAllInboxNotificationsAsRead(ctx)
require.NoError(t, err)

notifs, err = client.ListInboxNotifications(ctx, codersdk.ListInboxNotificationsRequest{})
require.NoError(t, err)
require.NotNil(t, notifs)
require.Equal(t, 0, notifs.UnreadCount)
require.Len(t, notifs.Notifications, 20)

for i := range 10 {
dbgen.NotificationInbox(t, api.Database, database.InsertInboxNotificationParams{
ID: uuid.New(),
UserID: member.ID,
TemplateID: notifications.TemplateWorkspaceOutOfMemory,
Title: fmt.Sprintf("Notification %d", i),
Actions: json.RawMessage("[]"),
Content: fmt.Sprintf("Content of the notif %d", i),
CreatedAt: dbtime.Now(),
})
}

notifs, err = client.ListInboxNotifications(ctx, codersdk.ListInboxNotificationsRequest{})
require.NoError(t, err)
require.NotNil(t, notifs)
require.Equal(t, 10, notifs.UnreadCount)
require.Len(t, notifs.Notifications, 25)
})
}
18 changes: 18 additions & 0 deletions codersdk/inboxnotification.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,3 +109,21 @@ func (c *Client) UpdateInboxNotificationReadStatus(ctx context.Context, notifID
var resp UpdateInboxNotificationReadStatusResponse
return resp, json.NewDecoder(res.Body).Decode(&resp)
}

func (c *Client) MarkAllInboxNotificationsAsRead(ctx context.Context) error {
res, err := c.Request(
ctx, http.MethodPut,
"/api/v2/notifications/inbox/mark-all-as-read",
nil,
)
if err != nil {
return err
}
defer res.Body.Close()

if res.StatusCode != http.StatusNoContent {
return ReadBodyAsError(res)
}

return nil
}
20 changes: 20 additions & 0 deletions docs/reference/api/notifications.md

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

Loading