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(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
kacpersaw merged 8 commits intomainfromkacpersaw/scaletest-notification-runner
Oct 7, 2025
Merged
Show file tree
Hide file tree
Changes fromall 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
71 changes: 71 additions & 0 deletionsscaletest/notifications/config.go
View file
Open in desktop
Original file line numberDiff line numberDiff 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
View file
Open in desktop
Original file line numberDiff line numberDiff 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
View file
Open in desktop
Original file line numberDiff line numberDiff 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())
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, &notif); err != nil {
return codersdk.GetInboxNotificationResponse{}, xerrors.Errorf("unmarshal notification: %w", err)
}

return notif, nil
}
Loading
Loading

[8]ページ先頭

©2009-2025 Movatter.jp