- Notifications
You must be signed in to change notification settings - Fork1k
feat(scaletest): add runner for notifications delivery#20091
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
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
Show all changes
8 commits Select commitHold shift + click to select a range
41fce83
Add notification runner to test delivery latency
kacpersaw35017a2
Apply suggestions from code review
kacpersawc5938da
apply review suggestions
kacpersawbfd3cda
add dual barrier support for owner and regular users
kacpersaw3db0798
add ExpectedNotifications map with channel to accurately measure latency
kacpersawe35743f
apply review suggestions
kacpersaw0be8e28
apply review suggestions
kacpersawc643703
apply review suggestions
kacpersawFile filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
71 changes: 71 additions & 0 deletionsscaletest/notifications/config.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
package notifications | ||
import ( | ||
"sync" | ||
"time" | ||
"golang.org/x/xerrors" | ||
"github.com/google/uuid" | ||
"github.com/coder/coder/v2/scaletest/createusers" | ||
) | ||
type Config struct { | ||
// User is the configuration for the user to create. | ||
User createusers.Config `json:"user"` | ||
// Roles are the roles to assign to the user. | ||
Roles []string `json:"roles"` | ||
// NotificationTimeout is how long to wait for notifications after triggering. | ||
NotificationTimeout time.Duration `json:"notification_timeout"` | ||
// DialTimeout is how long to wait for websocket connection. | ||
DialTimeout time.Duration `json:"dial_timeout"` | ||
// ExpectedNotifications maps notification template IDs to channels | ||
// that receive the trigger time for each notification. | ||
ExpectedNotifications map[uuid.UUID]chan time.Time `json:"-"` | ||
Metrics *Metrics `json:"-"` | ||
// DialBarrier ensures all runners are connected before notifications are triggered. | ||
DialBarrier *sync.WaitGroup `json:"-"` | ||
// ReceivingWatchBarrier is the barrier for receiving users. Regular users wait on this to disconnect after receiving users complete. | ||
ReceivingWatchBarrier *sync.WaitGroup `json:"-"` | ||
} | ||
func (c Config) Validate() error { | ||
// The runner always needs an org; ensure we propagate it into the user config. | ||
if c.User.OrganizationID == uuid.Nil { | ||
return xerrors.New("user organization_id must be set") | ||
} | ||
if err := c.User.Validate(); err != nil { | ||
return xerrors.Errorf("user config: %w", err) | ||
} | ||
if c.DialBarrier == nil { | ||
return xerrors.New("dial barrier must be set") | ||
} | ||
if c.ReceivingWatchBarrier == nil { | ||
return xerrors.New("receiving_watch_barrier must be set") | ||
} | ||
if c.NotificationTimeout <= 0 { | ||
return xerrors.New("notification_timeout must be greater than 0") | ||
} | ||
if c.DialTimeout <= 0 { | ||
return xerrors.New("dial_timeout must be greater than 0") | ||
} | ||
if c.Metrics == nil { | ||
return xerrors.New("metrics must be set") | ||
} | ||
return nil | ||
} |
58 changes: 58 additions & 0 deletionsscaletest/notifications/metrics.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
package notifications | ||
import ( | ||
"time" | ||
"github.com/prometheus/client_golang/prometheus" | ||
) | ||
type Metrics struct { | ||
notificationLatency *prometheus.HistogramVec | ||
notificationErrors *prometheus.CounterVec | ||
missedNotifications *prometheus.CounterVec | ||
} | ||
func NewMetrics(reg prometheus.Registerer) *Metrics { | ||
if reg == nil { | ||
reg = prometheus.DefaultRegisterer | ||
} | ||
latency := prometheus.NewHistogramVec(prometheus.HistogramOpts{ | ||
Namespace: "coderd", | ||
Subsystem: "scaletest", | ||
Name: "notification_delivery_latency_seconds", | ||
Help: "Time between notification-creating action and receipt of notification by client", | ||
}, []string{"username", "notification_type"}) | ||
errors := prometheus.NewCounterVec(prometheus.CounterOpts{ | ||
Namespace: "coderd", | ||
Subsystem: "scaletest", | ||
Name: "notification_delivery_errors_total", | ||
Help: "Total number of notification delivery errors", | ||
}, []string{"username", "action"}) | ||
missed := prometheus.NewCounterVec(prometheus.CounterOpts{ | ||
Namespace: "coderd", | ||
Subsystem: "scaletest", | ||
Name: "notification_delivery_missed_total", | ||
Help: "Total number of missed notifications", | ||
}, []string{"username"}) | ||
reg.MustRegister(latency, errors, missed) | ||
return &Metrics{ | ||
notificationLatency: latency, | ||
notificationErrors: errors, | ||
missedNotifications: missed, | ||
} | ||
} | ||
func (m *Metrics) RecordLatency(latency time.Duration, username, notificationType string) { | ||
m.notificationLatency.WithLabelValues(username, notificationType).Observe(latency.Seconds()) | ||
} | ||
func (m *Metrics) AddError(username, action string) { | ||
m.notificationErrors.WithLabelValues(username, action).Inc() | ||
} | ||
func (m *Metrics) RecordMissed(username string) { | ||
m.missedNotifications.WithLabelValues(username).Inc() | ||
} |
263 changes: 263 additions & 0 deletionsscaletest/notifications/run.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,263 @@ | ||
package notifications | ||
import ( | ||
"context" | ||
"encoding/json" | ||
"fmt" | ||
"io" | ||
"net/http" | ||
"time" | ||
"github.com/google/uuid" | ||
"golang.org/x/xerrors" | ||
"cdr.dev/slog" | ||
"cdr.dev/slog/sloggers/sloghuman" | ||
"github.com/coder/coder/v2/coderd/tracing" | ||
"github.com/coder/coder/v2/codersdk" | ||
"github.com/coder/coder/v2/scaletest/createusers" | ||
"github.com/coder/coder/v2/scaletest/harness" | ||
"github.com/coder/coder/v2/scaletest/loadtestutil" | ||
"github.com/coder/websocket" | ||
) | ||
type Runner struct { | ||
client *codersdk.Client | ||
cfg Config | ||
createUserRunner *createusers.Runner | ||
// notificationLatencies stores the latency for each notification type | ||
notificationLatencies map[uuid.UUID]time.Duration | ||
} | ||
func NewRunner(client *codersdk.Client, cfg Config) *Runner { | ||
return &Runner{ | ||
client: client, | ||
cfg: cfg, | ||
notificationLatencies: make(map[uuid.UUID]time.Duration), | ||
} | ||
} | ||
var ( | ||
_ harness.Runnable = &Runner{} | ||
_ harness.Cleanable = &Runner{} | ||
_ harness.Collectable = &Runner{} | ||
) | ||
func (r *Runner) Run(ctx context.Context, id string, logs io.Writer) error { | ||
ctx, span := tracing.StartSpan(ctx) | ||
defer span.End() | ||
reachedBarrier := false | ||
defer func() { | ||
if !reachedBarrier { | ||
r.cfg.DialBarrier.Done() | ||
} | ||
}() | ||
reachedReceivingWatchBarrier := false | ||
defer func() { | ||
if len(r.cfg.ExpectedNotifications) > 0 && !reachedReceivingWatchBarrier { | ||
r.cfg.ReceivingWatchBarrier.Done() | ||
} | ||
}() | ||
logs = loadtestutil.NewSyncWriter(logs) | ||
logger := slog.Make(sloghuman.Sink(logs)).Leveled(slog.LevelDebug) | ||
r.client.SetLogger(logger) | ||
r.client.SetLogBodies(true) | ||
r.createUserRunner = createusers.NewRunner(r.client, r.cfg.User) | ||
newUserAndToken, err := r.createUserRunner.RunReturningUser(ctx, id, logs) | ||
if err != nil { | ||
r.cfg.Metrics.AddError("", "create_user") | ||
return xerrors.Errorf("create user: %w", err) | ||
} | ||
newUser := newUserAndToken.User | ||
newUserClient := codersdk.New(r.client.URL, | ||
codersdk.WithSessionToken(newUserAndToken.SessionToken), | ||
codersdk.WithLogger(logger), | ||
codersdk.WithLogBodies()) | ||
logger.Info(ctx, "runner user created", slog.F("username", newUser.Username), slog.F("user_id", newUser.ID.String())) | ||
if len(r.cfg.Roles) > 0 { | ||
logger.Info(ctx, "assigning roles to user", slog.F("roles", r.cfg.Roles)) | ||
_, err := r.client.UpdateUserRoles(ctx, newUser.ID.String(), codersdk.UpdateRoles{ | ||
Roles: r.cfg.Roles, | ||
}) | ||
if err != nil { | ||
r.cfg.Metrics.AddError(newUser.Username, "assign_roles") | ||
return xerrors.Errorf("assign roles: %w", err) | ||
} | ||
} | ||
logger.Info(ctx, "notification runner is ready") | ||
dialCtx, cancel := context.WithTimeout(ctx, r.cfg.DialTimeout) | ||
defer cancel() | ||
logger.Info(ctx, "connecting to notification websocket") | ||
conn, err := r.dialNotificationWebsocket(dialCtx, newUserClient, newUser, logger) | ||
if err != nil { | ||
return xerrors.Errorf("dial notification websocket: %w", err) | ||
} | ||
defer conn.Close(websocket.StatusNormalClosure, "done") | ||
logger.Info(ctx, "connected to notification websocket") | ||
reachedBarrier = true | ||
r.cfg.DialBarrier.Done() | ||
r.cfg.DialBarrier.Wait() | ||
if len(r.cfg.ExpectedNotifications) == 0 { | ||
logger.Info(ctx, "maintaining websocket connection, waiting for receiving users to complete") | ||
// Wait for receiving users to complete | ||
done := make(chan struct{}) | ||
go func() { | ||
r.cfg.ReceivingWatchBarrier.Wait() | ||
close(done) | ||
}() | ||
select { | ||
case <-done: | ||
logger.Info(ctx, "receiving users complete, closing connection") | ||
case <-ctx.Done(): | ||
logger.Info(ctx, "context canceled, closing connection") | ||
} | ||
return nil | ||
} | ||
logger.Info(ctx, "waiting for notifications", slog.F("timeout", r.cfg.NotificationTimeout)) | ||
watchCtx, cancel := context.WithTimeout(ctx, r.cfg.NotificationTimeout) | ||
defer cancel() | ||
if err := r.watchNotifications(watchCtx, conn, newUser, logger, r.cfg.ExpectedNotifications); err != nil { | ||
return xerrors.Errorf("notification watch failed: %w", err) | ||
} | ||
reachedReceivingWatchBarrier = true | ||
r.cfg.ReceivingWatchBarrier.Done() | ||
return nil | ||
} | ||
func (r *Runner) Cleanup(ctx context.Context, id string, logs io.Writer) error { | ||
if r.createUserRunner != nil { | ||
_, _ = fmt.Fprintln(logs, "Cleaning up user...") | ||
if err := r.createUserRunner.Cleanup(ctx, id, logs); err != nil { | ||
return xerrors.Errorf("cleanup user: %w", err) | ||
} | ||
} | ||
return nil | ||
} | ||
const NotificationDeliveryLatencyMetric = "notification_delivery_latency_seconds" | ||
func (r *Runner) GetMetrics() map[string]any { | ||
return map[string]any{ | ||
NotificationDeliveryLatencyMetric: r.notificationLatencies, | ||
} | ||
} | ||
func (r *Runner) dialNotificationWebsocket(ctx context.Context, client *codersdk.Client, user codersdk.User, logger slog.Logger) (*websocket.Conn, error) { | ||
u, err := client.URL.Parse("/api/v2/notifications/inbox/watch") | ||
if err != nil { | ||
logger.Error(ctx, "parse notification URL", slog.Error(err)) | ||
r.cfg.Metrics.AddError(user.Username, "parse_url") | ||
return nil, xerrors.Errorf("parse notification URL: %w", err) | ||
} | ||
conn, resp, err := websocket.Dial(ctx, u.String(), &websocket.DialOptions{ | ||
HTTPHeader: http.Header{ | ||
"Coder-Session-Token": []string{client.SessionToken()}, | ||
}, | ||
}) | ||
if err != nil { | ||
if resp != nil { | ||
defer resp.Body.Close() | ||
if resp.StatusCode != http.StatusSwitchingProtocols { | ||
err = codersdk.ReadBodyAsError(resp) | ||
} | ||
} | ||
logger.Error(ctx, "dial notification websocket", slog.Error(err)) | ||
r.cfg.Metrics.AddError(user.Username, "dial") | ||
return nil, xerrors.Errorf("dial notification websocket: %w", err) | ||
} | ||
return conn, nil | ||
} | ||
// watchNotifications reads notifications from the websocket and returns error or nil | ||
// once all expected notifications are received. | ||
func (r *Runner) watchNotifications(ctx context.Context, conn *websocket.Conn, user codersdk.User, logger slog.Logger, expectedNotifications map[uuid.UUID]chan time.Time) error { | ||
logger.Info(ctx, "waiting for notifications", | ||
slog.F("username", user.Username), | ||
slog.F("expected_count", len(expectedNotifications))) | ||
receivedNotifications := make(map[uuid.UUID]struct{}) | ||
for { | ||
select { | ||
case <-ctx.Done(): | ||
return xerrors.Errorf("context canceled while waiting for notifications: %w", ctx.Err()) | ||
default: | ||
} | ||
if len(receivedNotifications) == len(expectedNotifications) { | ||
logger.Info(ctx, "received all expected notifications") | ||
return nil | ||
} | ||
notif, err := readNotification(ctx, conn) | ||
if err != nil { | ||
logger.Error(ctx, "read notification", slog.Error(err)) | ||
r.cfg.Metrics.AddError(user.Username, "read_notification") | ||
return xerrors.Errorf("read notification: %w", err) | ||
} | ||
templateID := notif.Notification.TemplateID | ||
if triggerTimeChan, exists := expectedNotifications[templateID]; exists { | ||
if _, exists := receivedNotifications[templateID]; !exists { | ||
receiptTime := time.Now() | ||
select { | ||
case triggerTime := <-triggerTimeChan: | ||
latency := receiptTime.Sub(triggerTime) | ||
r.notificationLatencies[templateID] = latency | ||
r.cfg.Metrics.RecordLatency(latency, user.Username, templateID.String()) | ||
kacpersaw marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
receivedNotifications[templateID] = struct{}{} | ||
logger.Info(ctx, "received expected notification", | ||
slog.F("template_id", templateID), | ||
slog.F("title", notif.Notification.Title), | ||
slog.F("latency", latency)) | ||
case <-ctx.Done(): | ||
return xerrors.Errorf("context canceled while waiting for trigger time: %w", ctx.Err()) | ||
} | ||
} | ||
} else { | ||
logger.Debug(ctx, "received notification not being tested", | ||
slog.F("template_id", templateID), | ||
slog.F("title", notif.Notification.Title)) | ||
} | ||
} | ||
} | ||
func readNotification(ctx context.Context, conn *websocket.Conn) (codersdk.GetInboxNotificationResponse, error) { | ||
_, message, err := conn.Read(ctx) | ||
if err != nil { | ||
return codersdk.GetInboxNotificationResponse{}, err | ||
} | ||
var notif codersdk.GetInboxNotificationResponse | ||
if err := json.Unmarshal(message, ¬if); err != nil { | ||
return codersdk.GetInboxNotificationResponse{}, xerrors.Errorf("unmarshal notification: %w", err) | ||
} | ||
return notif, nil | ||
} |
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.