diff --git a/coderd/notifications/notifier.go b/coderd/notifications/notifier.go index e17243e3b6e..6add2f1a71c 100644 --- a/coderd/notifications/notifier.go +++ b/coderd/notifications/notifier.go @@ -101,6 +101,12 @@ func (n *notifier) run(success chan<- dispatchResult, failure chan<- dispatchRes // run the ticker with the graceful context, so we stop fetching after stop() is called tick := n.clock.TickerFunc(n.gracefulCtx, n.cfg.FetchInterval.Value(), func() error { + // The ticker can deliver one more tick after the graceful context is + // canceled, so do not start a new fetch during shutdown. + if n.gracefulCtx.Err() != nil { + return nil + } + // Check if notifier is not paused. ok, err := n.ensureRunning(n.outerCtx) if err != nil { diff --git a/coderd/notifications/notifier_internal_test.go b/coderd/notifications/notifier_internal_test.go new file mode 100644 index 00000000000..5d08c82befe --- /dev/null +++ b/coderd/notifications/notifier_internal_test.go @@ -0,0 +1,59 @@ +package notifications + +import ( + "context" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" + + "github.com/coder/coder/v2/coderd/database/dbmock" + "github.com/coder/coder/v2/codersdk" + "github.com/coder/coder/v2/testutil" + "github.com/coder/quartz" +) + +func TestNotifier_NoFetchAfterGracefulStop(t *testing.T) { + t.Parallel() + + ctx := testutil.Context(t, testutil.WaitShort) + // The mock store fails the test on any call, which is how a fetch + // would show up. + store := dbmock.NewMockStore(gomock.NewController(t)) + clock := &lateTickClock{Clock: quartz.NewMock(t), fetch: make(chan func() error, 1)} + + n := newNotifier(ctx, codersdk.NotificationsConfig{}, uuid.New(), testutil.Logger(t), store, nil, nil, nil, clock) + runErr := make(chan error, 1) + go func() { + runErr <- n.run(nil, nil) + }() + fetch := testutil.TryReceive(ctx, t, clock.fetch) + + n.stop() + + require.NoError(t, fetch()) + require.NoError(t, testutil.TryReceive(ctx, t, runErr)) +} + +// lateTickClock hands the ticker callback to the test, so the test can +// deliver a tick after the ticker's context is canceled. +type lateTickClock struct { + quartz.Clock + fetch chan func() error +} + +func (c *lateTickClock) TickerFunc(ctx context.Context, _ time.Duration, f func() error, _ ...string) quartz.Waiter { + c.fetch <- f + return contextWaiter{ctx: ctx} +} + +type contextWaiter struct { + ctx context.Context +} + +func (w contextWaiter) Wait(...string) error { + <-w.ctx.Done() + return w.ctx.Err() +}