test(mail): derive the mail sender clock from the current date

This commit is contained in:
shira committed 2026-10-09 17:16:56 +03:00
1 parent a38d7571ea
commit c410636b7f
3 files changed
+105 -4

No files matched your search

+75 -4
View File
@@ -54,10 +54,72 @@ const (
)
var (
mailSenderStart = time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC)
mailSenderStart = mailSenderStartAt(time.Now())
mailSenderTables = []pgx.Identifier{{"mail_quota_reservations"}, {"mail_quota_usage"}}
)
// Bounds of the distance from mailSenderStart to the real clock.
const (
mailSenderStartMinLag = 24 * time.Hour
mailSenderStartMaxLag = 48 * time.Hour
)
// mailSenderStartAt returns the fake application clock at the start of every
// subtest: 12:00 UTC on the latest day whose noon is at least
// mailSenderStartMinLag before now. The database, the lease, and the
// mail-retry command run by the real clock, and some subtests move the fake
// clock to the database clock, so a fixed calendar date would expire the
// tokens issued at the start once the real clock passed it by
// mailSenderTokenLifetime. With the real clock one to two days ahead:
// - the fake and the database clocks never coincide, so a lease measured by
// the wrong one fails;
// - moving the fake clock by up to 24 hours never overtakes the database
// clock, so a due time that takes the later of both is the database one;
// - a token issued at the start outlives the alignment with the database
// clock by about a day;
// - the next midnight UTC, the quota day boundary, is 12 hours ahead.
func mailSenderStartAt(now time.Time) time.Time {
now = now.UTC()
start := time.Date(now.Year(), now.Month(), now.Day()-1, 12, 0, 0, 0, time.UTC)
if now.Sub(start) < mailSenderStartMinLag {
start = start.AddDate(0, 0, -1)
}
return start
}
// TestMailSenderStartFollowsTheCalendar checks the bounds that keep
// TestServiceMailSending independent of the day it runs on, across the times
// of a day and month, year, and leap-day boundaries. It needs no database.
func TestMailSenderStartFollowsTheCalendar(t *testing.T) {
if mailSenderStartMaxLag+mailSenderTestTimeout >= mailSenderTokenLifetime {
t.Fatalf("a token issued at the start (%s) can expire before the subtests align with the database clock (up to %s later)",
mailSenderTokenLifetime, mailSenderStartMaxLag+mailSenderTestTimeout)
}
days := []time.Time{
time.Now().UTC(),
time.Date(2026, 10, 9, 0, 0, 0, 0, time.UTC),
time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC),
time.Date(2026, 12, 31, 0, 0, 0, 0, time.UTC),
time.Date(2027, 1, 1, 0, 0, 0, 0, time.UTC),
time.Date(2028, 2, 29, 0, 0, 0, 0, time.UTC),
time.Date(2028, 3, 1, 0, 0, 0, 0, time.UTC),
}
for _, day := range days {
day = day.Truncate(24 * time.Hour)
for offset := time.Duration(0); offset < 24*time.Hour; offset += 7 * time.Minute {
now := day.Add(offset)
start := mailSenderStartAt(now)
lag := now.Sub(start)
if start.Hour() != 12 || start.Minute() != 0 || start.Second() != 0 || start.Nanosecond() != 0 || start.Location() != time.UTC {
t.Fatalf("start for %s = %s, want 12:00 UTC", now, start)
}
if lag < mailSenderStartMinLag || lag >= mailSenderStartMaxLag {
t.Fatalf("start for %s = %s, %s behind; want %s to %s", now, start, lag, mailSenderStartMinLag, mailSenderStartMaxLag)
}
}
}
}
// testClock is the application clock of the sending tests. Several workers
// read it at once, so it is guarded.
type testClock struct {
@@ -178,6 +240,15 @@ func TestServiceMailSending(t *testing.T) {
clock.Set(mailSenderStart)
fixture.SetClock(clock.Now)
fixture.SetDelay(0)
// A subtest that stops early leaves its scripted answers queued;
// drop them so its failure is not repeated by the next subtests.
// A subtest that passes must have used every answer it scripted.
fixture.ClearScript()
t.Cleanup(func() {
if left := fixture.ClearScript(); left != 0 && !t.Failed() {
t.Errorf("the subtest left %d scripted provider answers unused", left)
}
})
}
t.Run("a service email for an account without C2 is accepted by the local Resend fixture", func(t *testing.T) {
@@ -766,8 +837,8 @@ func TestServiceMailSending(t *testing.T) {
if err != nil || claimed.Delivery.ID() != deliveryID {
t.Fatalf("ClaimDue() = %v, %v; want the enqueued delivery", claimed.Delivery.ID(), err)
}
// The fake application clock is a day apart from the database clock
// at most; the lease must be measured by the database one.
// The fake application clock is one to two days behind the database
// clock; the lease must be measured by the database one.
var live, bounded bool
if err := pool.QueryRow(ctx, `SELECT claimed_until > clock_timestamp(), claimed_until <= clock_timestamp() + interval '3 seconds'
FROM deliveries WHERE id = $1`, deliveryID).Scan(&live, &bounded); err != nil || !live || !bounded {
@@ -1368,7 +1439,7 @@ func TestServiceMailSending(t *testing.T) {
if result.Outcome != inbound.MailPassWaitingQuota || result.DeliveryID != waitingID {
t.Fatalf("second pass = %+v, want waiting_quota for the second delivery", result)
}
midnight := time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC)
midnight := time.Date(mailSenderStart.Year(), mailSenderStart.Month(), mailSenderStart.Day()+1, 0, 0, 0, 0, time.UTC)
status, found, err := notification.NewDeliveryStatusReader(harness.deliveries).LatestForUser(ctx, second.ID, domain.MailKindVerification)
if err != nil || !found || !status.WaitingForQuota() || !status.WaitingUntil.Equal(midnight) {
t.Fatalf("LatestForUser() = %+v, %t, %v; want waiting until %s", status, found, err, midnight)
@@ -140,6 +140,16 @@ func (server *Server) Script(replies ...Reply) {
server.scripted = append(server.scripted, replies...)
}
// ClearScript drops the queued answers that no call has used and returns
// their number, so a test that stops early does not hand them to the next one.
func (server *Server) ClearScript() int {
server.mu.Lock()
defer server.mu.Unlock()
left := len(server.scripted)
server.scripted = nil
return left
}
// SetDelay makes the fixture wait before it answers every later call, so a
// test can act while a send is in flight.
func (server *Server) SetDelay(delay time.Duration) { server.delay.Store(int64(delay)) }
@@ -57,6 +57,26 @@ func TestFixtureAnswersLikeResendForTheLoopbackTransport(t *testing.T) {
}
}
func TestClearScriptDropsUnusedAnswers(t *testing.T) {
fixture := resendfixture.New()
defer fixture.Close()
sender, err := resend.NewLoopbackSender(resendfixture.APIKey, "Lincodex <no-reply@example.com>", 5*time.Second, fixture.URL(), time.Now)
if err != nil {
t.Fatalf("NewLoopbackSender() error = %v", err)
}
fixture.Script(resendfixture.Reply{Status: 429, Name: "daily_quota_exceeded"}, resendfixture.Reply{Status: 500, Name: "application_error"})
if left := fixture.ClearScript(); left != 2 {
t.Fatalf("ClearScript() = %d, want 2", left)
}
if left := fixture.ClearScript(); left != 0 {
t.Fatalf("second ClearScript() = %d, want 0", left)
}
result, err := sender.Send(t.Context(), newMail(t, "Subject", "delivery/1"))
if err != nil || result.Outcome != outbound.MailOutcomeAccepted {
t.Fatalf("Send() after ClearScript() = %+v, %v; want accepted", result, err)
}
}
func TestLoopbackSenderRefusesAnyOtherHost(t *testing.T) {
for _, endpoint := range []string{
"https://api.resend.com/emails",