8	mathrand2 "math/rand/v2"
 
12	"github.com/mjl-/bstore"
 
14	"github.com/mjl-/mox/dns"
 
15	"github.com/mjl-/mox/metrics"
 
16	"github.com/mjl-/mox/mlog"
 
17	"github.com/mjl-/mox/mox-"
 
18	"github.com/mjl-/mox/mtasts"
 
22	interval := 24 * time.Hour
 
23	ticker := time.NewTicker(interval)
 
30		ticker.Reset(interval)
 
32		log := mlog.New("mtastsdb", nil).WithCid(mox.Cid())
 
33		n, err := refresh1(mox.Context, log, dns.StrictResolver{Pkg: "mtastsdb"}, time.Sleep)
 
34		log.Check(err, "periodic refresh of cached mtasts policies")
 
40		case <-mox.Shutdown.Done():
 
47// refresh policies that have not been updated in the past 12 hours and remove
 
48// policies not used for 180 days. We start with the first domain immediately, so
 
49// an admin can see any (configuration) issues that are logged. We spread the
 
50// refreshes evenly over the next 3 hours, randomizing the domains, and we add some
 
51// jitter to the timing. Each refresh is done in a new goroutine, so a single slow
 
52// refresh doesn't mess up the timing.
 
53func refresh1(ctx context.Context, log mlog.Log, resolver dns.Resolver, sleep func(d time.Duration)) (int, error) {
 
55	qdel := bstore.QueryDB[PolicyRecord](ctx, DB)
 
56	qdel.FilterLess("LastUse", now.Add(-180*24*time.Hour))
 
57	if _, err := qdel.Delete(); err != nil {
 
58		return 0, fmt.Errorf("deleting old unused policies: %s", err)
 
61	qup := bstore.QueryDB[PolicyRecord](ctx, DB)
 
62	qup.FilterLess("LastUpdate", now.Add(-12*time.Hour))
 
63	prs, err := qup.List()
 
65		return 0, fmt.Errorf("querying policies to refresh: %s", err)
 
78		j := mathrand2.IntN(i + 1)
 
79		prs[i], prs[j] = prs[j], prs[i]
 
82	// Launch goroutine with the refresh.
 
83	log.Debug("will refresh mta-sts policies over next 3 hours", slog.Int("count", len(prs)))
 
85	for i, pr := range prs {
 
86		go refreshDomain(ctx, log, DB, resolver, pr)
 
88			interval := 3 * int64(time.Hour) / int64(len(prs)-1)
 
89			extra := time.Duration(mathrand2.Int64N(interval) - interval/2)
 
90			next := start.Add(time.Duration(int64(i+1)*interval) + extra)
 
91			d := next.Sub(timeNow())
 
100func refreshDomain(ctx context.Context, log mlog.Log, db *bstore.DB, resolver dns.Resolver, pr PolicyRecord) {
 
104			// Should not happen, but make sure errors don't take down the application.
 
105			log.Error("refresh1", slog.Any("panic", x))
 
107			metrics.PanicInc(metrics.Mtastsdb)
 
111	ctx, cancel := context.WithTimeout(ctx, time.Minute)
 
114	d, err := dns.ParseDomain(pr.Domain)
 
116		log.Errorx("refreshing mta-sts policy: parsing policy domain", err, slog.Any("domain", d))
 
119	log.Debug("refreshing mta-sts policy for domain", slog.Any("domain", d))
 
120	record, _, err := mtasts.LookupRecord(ctx, log.Logger, resolver, d)
 
121	if err == nil && record.ID == pr.RecordID {
 
122		qup := bstore.QueryDB[PolicyRecord](ctx, db)
 
123		qup.FilterNonzero(PolicyRecord{Domain: pr.Domain, LastUpdate: pr.LastUpdate})
 
125		update := PolicyRecord{
 
127			ValidEnd:   now.Add(time.Duration(pr.MaxAgeSeconds) * time.Second),
 
129		if n, err := qup.UpdateNonzero(update); err != nil {
 
130			log.Errorx("updating refreshed, unmodified policy in database", err)
 
132			log.Info("expected to update 1 policy after refresh", slog.Int("count", n))
 
136	if err != nil && pr.Mode == mtasts.ModeNone {
 
137		if errors.Is(err, mtasts.ErrNoRecord) {
 
138			// Policy was in mode "none". Now it doesn't have a policy anymore. Remove from our
 
139			// database so we don't keep refreshing it.
 
140			err := db.Delete(ctx, &pr)
 
141			log.Check(err, "removing mta-sts policy with mode none, dns record is gone")
 
143		// Else, don't bother operator with temporary error about policy none.
 
146	} else if err != nil {
 
147		log.Errorx("looking up mta-sts record for domain", err, slog.Any("domain", d))
 
148		// Try to fetch new policy. It could be just DNS that is down. We don't want to let our policy expire.
 
151	p, _, err := mtasts.FetchPolicy(ctx, log.Logger, d)
 
153		if !errors.Is(err, mtasts.ErrNoPolicy) || pr.Mode != mtasts.ModeNone {
 
154			log.Errorx("refreshing mtasts policy for domain", err, slog.Any("domain", d))
 
159	update := map[string]any{
 
161		"ValidEnd":   now.Add(time.Duration(p.MaxAgeSeconds) * time.Second),
 
166		update["RecordID"] = record.ID
 
168	qup := bstore.QueryDB[PolicyRecord](ctx, db)
 
169	qup.FilterNonzero(PolicyRecord{Domain: pr.Domain, LastUpdate: pr.LastUpdate})
 
170	if n, err := qup.UpdateFields(update); err != nil {
 
171		log.Errorx("updating refreshed, modified policy in database", err)
 
173		log.Info("updating refreshed, did not update 1 policy", slog.Int("count", n))