carlos / platform Public

certwarm-wake

Squashed from certwarm-wake into main.
claude agent, operated by paul@keymail.dev 542ad2c1e3ae40210f346d437c159f7753ca100b parent 4a9a47c
7 files changed, +1,219 −18
  • docs/superpowers/notes/census-proposal-certwarm-wake.md +21 −0
  • internal/edge/certwarm.go +333 −10
  • internal/edge/certwarm_wake_test.go +774 −0
  • internal/edge/edge.go +34 −7
  • internal/edge/homemap.go +49 −1
  • internal/provision/testdata/plan14-root-reads-certwarm-wake.tsv +7 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0

CI passed — run details

diff --git a/docs/superpowers/notes/census-proposal-certwarm-wake.md b/docs/superpowers/notes/census-proposal-certwarm-wake.md
new file mode 100644
index 000000000..6d7b13d34
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-certwarm-wake.md
@@ -0,0 +1,21 @@
+# Census approval: certwarm-wake
+
+Ruling `census-ruling-certwarm-wake`. Every change below keeps the disposition it already has, so it needs an approval, not a decision.
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/edge/edge.go` `Edge.Reload` | body | unchanged (57) | the single reload hook call becomes runReloadHooks(), which runs every registered hook in order (#386); no read added, same 57 sites (56 before #358 landed on main) |
+| `internal/edge/edge.go` `RunWithActivatorReady` | body | unchanged (5) | registers the cert warm's nudge on OnReload and on the home map's new served-hosts wake (#386); nudge only sends on a buffered channel; no read added, same 5 sites |
+
+Envelopes re-pinned: `internal/edge`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Escalate if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. An escalation goes to the census owner as a decision.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/edge/edge.go` `Edge.Reload`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-design-edge-rate-limit-358;basis=each route's upstream entry gains rate: e.parseRateSettings(t), the row's rate_limit column parsed once per reload; the one added site is that whole:Route pass of t (parseRateSettings is a new unit, classified in the decisions overlay); no other read added
+- `internal/edge/edge.go` `RunWithActivatorReady`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input
+
+Seal: `0c4eabfe38e12b098285bdeb5ceb0b16e5333928f5b02e160a6b16b5fd9ce1e0` → `91204fcbc484343c03bd5ae69e3084055bc519a5b317e2ae3dc49880080764e2`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-certwarm-wake.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/internal/edge/certwarm.go b/internal/edge/certwarm.go
index 3e4700a74..eda46391a 100644
--- a/internal/edge/certwarm.go
+++ b/internal/edge/certwarm.go
@@ -55,14 +55,45 @@ const (
// limit are what turn a transient limit into a sustained one, and every
// host in the deployment shares the one ACME account's budget.
warmRateLimitBackoff = 12 * time.Hour
- // warmOrdersPerPass bounds NEW orders per pass. Renewal re-arms are not
+ // warmOrdersPerPass bounds NEW orders per warmCappedDelay, across every
+ // pass in that window and not merely within one: since passes can be
+ // woken (#386), a per-pass count alone would let back-to-back wakes spend
+ // the shared account as fast as reloads arrive. Renewal re-arms are not
// orders and are never capped — they are the reason the pass exists.
// When the cap bites, pass() returns a short delay so a backlog drains
// in minutes rather than trickling out over days (the wildcard pass()
// precedent).
warmOrdersPerPass = 10
- // warmCappedDelay is how soon to come back with capped work remaining.
+ // warmCappedDelay is how soon to come back with capped work remaining,
+ // and the window warmOrdersPerPass is counted over.
warmCappedDelay = time.Minute
+ // The DNS-miss schedule for a NEW host (#386). A customer usually
+ // finishes their DNS a few minutes after attaching, so the first ten
+ // minutes of misses are re-checked every minute and the rest of the first
+ // hour every five. The re-checks are DNS-only (probeDNS): they read
+ // nothing from the bucket beyond the edge set's own reuse window, and a
+ // full pass runs only once a pending host points here. After an hour the
+ // host waits for the hourly pass like everything else.
+ warmDNSRetryFast = time.Minute
+ warmDNSFastFor = 10 * time.Minute
+ warmDNSRetrySlow = 5 * time.Minute
+ warmDNSSlowFor = time.Hour
+ // warmGateRecheck is how often the loop looks at the issuer gate between
+ // passes (#386). The gate is the housekeeper lease, held in memory, so a
+ // look costs nothing; a box that takes the lease over (or takes it BACK
+ // during its hourly wait, having dropped wakes while it was not the
+ // issuer) runs a pass within a minute instead of at its next hourly one.
+ warmGateRecheck = time.Minute
+ // warmEdgeSetTTL is how long the DNS gate reuses the deployment's edge
+ // set. Reading it lists and fetches every box's snapshot and edges file,
+ // and the gate runs once per new host per pass; without the reuse the
+ // fast DNS-miss schedule would multiply that by every pending host.
+ warmEdgeSetTTL = 5 * time.Minute
+ // warmEdgeSetEmptyTTL is how long an EMPTY edge-set read is reused. Short,
+ // because empty means the read failed and the gate is failing closed; long
+ // enough that one pass over many new hosts reads the bucket once, not once
+ // per host, while the bucket is down.
+ warmEdgeSetEmptyTTL = 30 * time.Second
)
// certWarm proactively orders and renews per-host certificates.
@@ -113,6 +144,24 @@ type certWarm struct {
// so a first order can be told from a renewal re-arm for the order cap
// and for logging.
warmed map[string]bool
+ // dnsMisses is the DNS-miss schedule: each never-warmed host that has
+ // failed the DNS gate, with when it first did and when to look again.
+ // Cleared when the host's order goes out and pruned with the set.
+ dnsMisses map[string]dnsMiss
+ // recentOrders stamps the new orders placed in the last warmCappedDelay,
+ // the window warmOrdersPerPass is counted over.
+ recentOrders []time.Time
+
+ // wake asks the loop for an early pass (nudge). Buffered one deep: a
+ // wake already pending covers any that arrive behind it.
+ wake chan struct{}
+ // now is the clock; a field so the DNS-miss schedule is testable.
+ now func() time.Time
+ // gateTick is the loop's gate re-check cadence, warmGateRecheck outside
+ // tests.
+ gateTick time.Duration
+ // passDone, when set, runs after every pass the loop runs. Tests only.
+ passDone func()
lastStandDownLog time.Time
// lastSweep and lastExpirySweep pace the cert sweep (certsweep.go).
@@ -133,9 +182,19 @@ func newCertWarm(hosts func() []string, getCert func(*tls.ClientHelloInfo) (*tls
store: store,
nextAttempt: map[string]time.Time{},
warmed: map[string]bool{},
+ dnsMisses: map[string]dnsMiss{},
+ wake: make(chan struct{}, 1),
+ now: time.Now,
+ gateTick: warmGateRecheck,
}
}
+// dnsMiss is one host's place on the DNS-miss schedule. A zero next means
+// the host has aged out of the schedule and waits for the hourly pass.
+type dnsMiss struct {
+ first, next time.Time
+}
+
// issuerGate is this warm's read of the deployment's gate, ungated default
// applied (see IssuerGate, certsync.go).
func (c *certWarm) issuerGate() (context.Context, bool) {
@@ -145,12 +204,225 @@ func (c *certWarm) issuerGate() (context.Context, bool) {
return c.issuer()
}
-func (c *certWarm) run() {
+func (c *certWarm) run() { c.loop(nil) }
+
+// loop runs a pass, then waits for whichever comes first: the delay that pass
+// asked for, a wake that brings a host the warm has never seen (#386), a
+// pending host's DNS re-check, or the gate tick.
+//
+// Without the wake a custom domain attached between passes waited up to an
+// hour for its certificate: only the issuer orders, latency steering keeps
+// visitors on the other boxes, so no first handshake ever reached the order
+// path either. A wake carrying nothing new is dropped and leaves the schedule
+// alone, because wakes come from every route reload and every home-map change
+// in the fleet, and a pass costs a records LIST and a re-arm of every host. A
+// wake is also dropped when the next pass is due within warmCappedDelay
+// anyway, which is the backlog case: the capped hosts read as new, and that
+// pass is already coming for them.
+//
+// The gate tick runs a pass when this box has just become the issuer, since
+// a wake that arrived while it was not was dropped. A DNS re-check runs a
+// pass only when a pending host now points here.
+//
+// stop ends the loop; nil runs it for the life of the process.
+func (c *certWarm) loop(stop <-chan struct{}) {
+ passDue := time.Now().Add(c.runPass())
+ issuer := c.isIssuer()
+ // gateDue is absolute, not a fresh wait per iteration: wakes arrive with
+ // every reload in the fleet, and a wait restarted by each of them would
+ // put the gate check off for as long as reloads keep coming.
+ gateDue := time.Now().Add(c.gateTick)
+ timer := time.NewTimer(time.Hour)
+ defer timer.Stop()
for {
- time.Sleep(c.pass())
+ wait := min(time.Until(passDue), time.Until(gateDue))
+ // Only the issuer has DNS re-checks to run: probeDNS stands down
+ // without touching the schedule otherwise, and a due re-check it
+ // cannot advance would spin this loop.
+ if d, ok := c.dnsWait(); ok && issuer {
+ wait = min(wait, d)
+ }
+ timer.Reset(max(wait, 0))
+ full := false
+ select {
+ case <-stop:
+ return
+ case <-c.wake:
+ timer.Stop()
+ if !c.isIssuer() {
+ // Dropped, and remembered: this box is not the issuer
+ // right now, so when the lease comes back the gate check
+ // sees a transition and runs the pass this wake asked for.
+ issuer = false
+ break
+ }
+ full = time.Until(passDue) > warmCappedDelay && c.hasNewHost()
+ case <-timer.C:
+ if !time.Now().Before(gateDue) {
+ now := c.isIssuer()
+ if now && !issuer {
+ full = true
+ }
+ issuer = now
+ gateDue = time.Now().Add(c.gateTick)
+ }
+ if !time.Now().Before(passDue) {
+ full = true
+ }
+ if !full && issuer {
+ // Read the gate here too, not only at gateDue: a lease lost
+ // since the last check would make probeDNS stand down
+ // without moving the schedule, and this loop would come
+ // straight back to the same overdue re-check until gateDue.
+ if c.isIssuer() {
+ full = c.probeDNS()
+ } else {
+ issuer = false
+ }
+ }
+ }
+ if full {
+ passDue = time.Now().Add(c.runPass())
+ issuer = c.isIssuer()
+ }
}
}
+func (c *certWarm) runPass() time.Duration {
+ d := c.pass()
+ if c.passDone != nil {
+ c.passDone()
+ }
+ return d
+}
+
+func (c *certWarm) isIssuer() bool {
+ _, ok := c.issuerGate()
+ return ok
+}
+
+// nudge asks for an early pass. It never blocks: it is called from the
+// edge's reload path and the home map's refresh. Safe on a nil warm, which is
+// what a deployment without one has.
+func (c *certWarm) nudge() {
+ if c == nil {
+ return
+ }
+ select {
+ case c.wake <- struct{}{}:
+ default:
+ }
+}
+
+// hasNewHost reports whether a pass now could place an order nobody has
+// scheduled yet: this box is the issuer, and the set holds a host that has
+// never been warmed, is not backing off, and is not already on the DNS-miss
+// schedule. Everything else in the set has its own next pass already.
+func (c *certWarm) hasNewHost() bool {
+ if !c.isIssuer() {
+ return false
+ }
+ now := c.now()
+ hosts := c.hosts()
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ for _, h := range hosts {
+ if c.warmed[h] {
+ continue
+ }
+ if until, ok := c.nextAttempt[h]; ok && now.Before(until) {
+ continue
+ }
+ if _, ok := c.dnsMisses[h]; ok {
+ continue
+ }
+ return true
+ }
+ return false
+}
+
+// dnsMissed puts host on the DNS-miss schedule, or moves it along: its first
+// miss is kept, and its next check is set by how long it has been missing.
+func (c *certWarm) dnsMissed(host string, now time.Time) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ m, ok := c.dnsMisses[host]
+ if !ok {
+ m.first = now
+ }
+ m.next = time.Time{}
+ switch missing := now.Sub(m.first); {
+ case missing < warmDNSFastFor:
+ m.next = now.Add(warmDNSRetryFast)
+ case missing < warmDNSSlowFor:
+ m.next = now.Add(warmDNSRetrySlow)
+ }
+ c.dnsMisses[host] = m
+}
+
+// dnsWait is how long until the soonest scheduled DNS re-check, and false
+// when nothing is scheduled.
+func (c *certWarm) dnsWait() (time.Duration, bool) {
+ now := c.now()
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ var soonest time.Time
+ for _, m := range c.dnsMisses {
+ if !m.next.IsZero() && (soonest.IsZero() || m.next.Before(soonest)) {
+ soonest = m.next
+ }
+ }
+ if soonest.IsZero() {
+ return 0, false
+ }
+ return soonest.Sub(now), true
+}
+
+// probeDNS re-checks the DNS of every pending host whose turn has come, and
+// reports whether any of them now points here, the only case worth a full
+// pass. It reads nothing from the bucket but the edge set, and that only once
+// per reuse window. Every host it checks moves along the schedule whatever
+// the answer, so a host that points but cannot be ordered yet (the order cap)
+// is looked at again on its schedule rather than in a loop.
+func (c *certWarm) probeDNS() bool {
+ if !c.isIssuer() {
+ return false
+ }
+ now := c.now()
+ c.mu.Lock()
+ var due []string
+ for h, m := range c.dnsMisses {
+ if !m.next.IsZero() && !now.Before(m.next) {
+ due = append(due, h)
+ }
+ }
+ c.mu.Unlock()
+ sort.Strings(due)
+ points := false
+ for _, h := range due {
+ if c.pointsHere(h) {
+ points = true
+ }
+ c.dnsMissed(h, now)
+ }
+ return points
+}
+
+// orderBudget is how many new orders the window still allows, after
+// forgetting the stamps that have left it.
+func (c *certWarm) orderBudget(now time.Time) int {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ kept := c.recentOrders[:0]
+ for _, t := range c.recentOrders {
+ if now.Sub(t) < warmCappedDelay {
+ kept = append(kept, t)
+ }
+ }
+ c.recentOrders = kept
+ return warmOrdersPerPass - len(kept)
+}
+
// pass warms every host in the set once and returns how long to wait.
func (c *certWarm) pass() time.Duration {
hosts := c.hosts()
@@ -166,6 +438,9 @@ func (c *certWarm) pass() time.Duration {
return warmInterval
}
if len(hosts) == 0 {
+ c.mu.Lock()
+ clear(c.dnsMisses)
+ c.mu.Unlock()
c.sweep(ctx, time.Now())
return warmInterval
}
@@ -181,8 +456,9 @@ func (c *certWarm) pass() time.Duration {
inSet[h] = true
}
orders, capped := 0, false
+ budget := c.orderBudget(c.now())
for _, h := range hosts {
- now := time.Now()
+ now := c.now()
c.mu.Lock()
until, backing := c.nextAttempt[h]
seen := c.warmed[h]
@@ -204,13 +480,22 @@ func (c *certWarm) pass() time.Duration {
// re-arms the timer that renewal depends on. Gating the re-arm on DNS
// would strand exactly the domain whose resolver is briefly sick.
if !seen {
- if orders >= warmOrdersPerPass {
+ if orders >= budget {
capped = true
continue
}
if !c.pointsHere(h) {
+ c.dnsMissed(h, now)
continue
}
+ c.mu.Lock()
+ delete(c.dnsMisses, h)
+ // Stamped now, after the DNS lookup and just before the order,
+ // not with the pass's per-host now: a slow resolver would
+ // otherwise date the order early and let it leave the window
+ // before its time.
+ c.recentOrders = append(c.recentOrders, c.now())
+ c.mu.Unlock()
orders++
}
if err := c.warmOne(h); err != nil {
@@ -235,11 +520,22 @@ func (c *certWarm) pass() time.Duration {
}
}
c.prune(ctx, records, inSet)
+ c.mu.Lock()
+ for h := range c.dnsMisses {
+ if !inSet[h] {
+ delete(c.dnsMisses, h)
+ }
+ }
+ c.mu.Unlock()
// Housekeeping last: it is the least urgent thing this pass does, and
// running it after the orders means a slow bucket delays litter removal
// rather than certificate issuance (certsweep.go).
c.sweep(ctx, time.Now())
- if capped {
+ // Back soon when the window's budget is spent, whether or not this pass
+ // met a host it had to skip: a host attached a moment later must not be
+ // left for the hourly pass because its wake arrived while the budget was
+ // empty.
+ if capped || (orders > 0 && orders >= budget) {
return warmCappedDelay
}
return warmInterval
@@ -417,12 +713,39 @@ func wildcardCoverer(parents func() []string) func(string) bool {
// domains pass's stand-down: a set we could not read is not evidence about
// anybody's DNS, and the cost of waiting a pass is one hour of delay against
// the cost of burning a shared rate limit.
+//
+// The edge set is reused for warmEdgeSetTTL, and an empty read (the
+// fail-closed case above) only for warmEdgeSetEmptyTTL, so a bucket outage
+// costs one read per half minute rather than one per host.
func dnsGate(resolve func(string) ([]string, error), edgeIPs func() []string) func(string) bool {
- return func(host string) bool {
- set := map[string]bool{}
+ return dnsGateAt(resolve, edgeIPs, time.Now)
+}
+
+func dnsGateAt(resolve func(string) ([]string, error), edgeIPs func() []string, now func() time.Time) func(string) bool {
+ var (
+ mu sync.Mutex
+ cached map[string]bool
+ readAt time.Time
+ )
+ edgeSet := func() map[string]bool {
+ mu.Lock()
+ defer mu.Unlock()
+ ttl := warmEdgeSetTTL
+ if len(cached) == 0 {
+ ttl = warmEdgeSetEmptyTTL
+ }
+ if cached != nil && now().Sub(readAt) < ttl {
+ return cached
+ }
+ cached = map[string]bool{}
for _, ip := range edgeIPs() {
- set[ip] = true
+ cached[ip] = true
}
+ readAt = now()
+ return cached
+ }
+ return func(host string) bool {
+ set := edgeSet()
if len(set) == 0 {
return false
}
diff --git a/internal/edge/certwarm_wake_test.go b/internal/edge/certwarm_wake_test.go
new file mode 100644
index 000000000..b49b9bbfe
--- /dev/null
+++ b/internal/edge/certwarm_wake_test.go
@@ -0,0 +1,774 @@
+package edge
+
+import (
+ "context"
+ "crypto/tls"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// #386: a newly attached custom domain waited for the issuer's next hourly
+// pass (20+ minutes on the flagship), because nothing woke the warm. These
+// pin the wake and the fast DNS-miss retry that replace that wait.
+
+// fakeClock is a settable clock for the DNS-miss schedule.
+type fakeClock struct {
+ mu sync.Mutex
+ t time.Time
+}
+
+func (f *fakeClock) now() time.Time {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.t
+}
+
+func (f *fakeClock) advance(d time.Duration) {
+ f.mu.Lock()
+ f.t = f.t.Add(d)
+ f.mu.Unlock()
+}
+
+// dnsWarm is a warm over one new host whose DNS answer the test controls,
+// on a fake clock, counting DNS checks and orders.
+func dnsWarm(t *testing.T, host string, pointing *atomic.Bool) (*certWarm, *fakeClock, *atomic.Int32, *atomic.Int32) {
+ t.Helper()
+ clock := &fakeClock{t: time.Unix(1_800_000_000, 0)}
+ var checks, orders atomic.Int32
+ w := newCertWarm(
+ func() []string { return []string{host} },
+ func(*tls.ClientHelloInfo) (*tls.Certificate, error) { orders.Add(1); return &tls.Certificate{}, nil },
+ func(string) bool { checks.Add(1); return pointing.Load() },
+ nil,
+ nil,
+ )
+ w.now = clock.now
+ return w, clock, &checks, &orders
+}
+
+// A new host whose DNS does not point here yet is checked again within
+// minutes, not at the next hourly pass. The customer usually finishes their
+// DNS a few minutes after attaching, and every minute after that is a minute
+// their domain is down for no reason. The schedule slows as the miss ages,
+// and a host that has missed for an hour goes back to the hourly pass, so an
+// abandoned attach does not keep the issuer busy.
+func TestWarmSchedulesANewHostsDNSMissWithinMinutes(t *testing.T) {
+ var pointing atomic.Bool
+ w, clock, _, _ := dnsWarm(t, "www.customer.test", &pointing)
+ if d := w.pass(); d != warmInterval {
+ t.Fatalf("pass delay = %s, want %s: the re-check is the probe's, not a pass", d, warmInterval)
+ }
+ if d, ok := w.dnsWait(); !ok || d != warmDNSRetryFast {
+ t.Fatalf("first miss: re-check in %s (%v), want %s", d, ok, warmDNSRetryFast)
+ }
+ clock.advance(warmDNSFastFor + time.Second)
+ w.probeDNS()
+ if d, ok := w.dnsWait(); !ok || d != warmDNSRetrySlow {
+ t.Fatalf("after %s of misses: re-check in %s (%v), want %s", warmDNSFastFor, d, ok, warmDNSRetrySlow)
+ }
+ clock.advance(warmDNSSlowFor)
+ w.probeDNS()
+ if d, ok := w.dnsWait(); ok {
+ t.Fatalf("after an hour of misses a re-check is still scheduled in %s; want the hourly pass only", d)
+ }
+}
+
+// The miss clock starts at the FIRST miss, not at every check: a host that
+// keeps missing must age into the slower schedule.
+func TestWarmDNSMissClockStartsAtTheFirstMiss(t *testing.T) {
+ var pointing atomic.Bool
+ w, clock, _, _ := dnsWarm(t, "www.customer.test", &pointing)
+ w.pass()
+ for i := 0; i < int(warmDNSFastFor/warmDNSRetryFast); i++ {
+ clock.advance(warmDNSRetryFast)
+ w.probeDNS()
+ }
+ // The last check came warmDNSFastFor after the first miss, so the host
+ // is now on the slow schedule. Measured from each check instead, it
+ // would still be on the fast one.
+ if d, ok := w.dnsWait(); !ok || d != warmDNSRetrySlow {
+ t.Fatalf("after %s of one-minute checks: re-check in %s (%v), want %s", warmDNSFastFor, d, ok, warmDNSRetrySlow)
+ }
+}
+
+// The probe is DNS-only. A host not yet due is not looked up, a due host
+// still missing runs no pass, and only a due host that now points asks for
+// one. None of it orders anything: ordering is the pass's job.
+func TestWarmProbeChecksOnlyDueHostsAndOrdersNothing(t *testing.T) {
+ var pointing atomic.Bool
+ w, clock, checks, orders := dnsWarm(t, "www.customer.test", &pointing)
+ w.pass()
+ if checks.Load() != 1 {
+ t.Fatalf("checks after the pass = %d, want 1", checks.Load())
+ }
+ if w.probeDNS() || checks.Load() != 1 {
+ t.Fatalf("a probe before the host was due looked it up (checks %d)", checks.Load())
+ }
+ clock.advance(warmDNSRetryFast)
+ if w.probeDNS() {
+ t.Fatal("a probe of a host still missing asked for a pass")
+ }
+ if checks.Load() != 2 {
+ t.Fatalf("checks = %d, want 2", checks.Load())
+ }
+ pointing.Store(true)
+ clock.advance(warmDNSRetryFast)
+ if !w.probeDNS() {
+ t.Fatal("a probe of a host that now points did not ask for a pass")
+ }
+ if orders.Load() != 0 {
+ t.Fatalf("the probe ordered %d time(s)", orders.Load())
+ }
+ // It moved the host along even though it points: a host the pass then
+ // cannot order (the cap) is looked at on its schedule, not in a loop.
+ if d, ok := w.dnsWait(); !ok || d <= 0 {
+ t.Fatalf("after a pointing probe: re-check in %s (%v), want a future one", d, ok)
+ }
+}
+
+// A non-issuer's probe looks nothing up.
+func TestWarmProbeOnANonIssuerChecksNothing(t *testing.T) {
+ var pointing atomic.Bool
+ w, clock, checks, _ := dnsWarm(t, "www.customer.test", &pointing)
+ w.pass()
+ w.issuer = func() (context.Context, bool) { return nil, false }
+ clock.advance(warmDNSRetryFast)
+ if w.probeDNS() || checks.Load() != 1 {
+ t.Fatalf("a non-issuer's probe looked up DNS (checks %d)", checks.Load())
+ }
+}
+
+// Once the name points here and the order goes out, its miss history is
+// gone: a later miss (the host leaves and comes back) starts a fresh fast
+// schedule rather than inheriting an old one.
+func TestWarmDNSMissClockClearsWhenTheOrderGoesOut(t *testing.T) {
+ var pointing atomic.Bool
+ w, clock, _, orders := dnsWarm(t, "www.customer.test", &pointing)
+ w.pass()
+ pointing.Store(true)
+ clock.advance(time.Minute)
+ w.pass()
+ if orders.Load() != 1 {
+ t.Fatalf("orders = %d, want 1", orders.Load())
+ }
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ if len(w.dnsMisses) != 0 {
+ t.Fatalf("miss history survived the order: %v", w.dnsMisses)
+ }
+}
+
+// A host that leaves the set takes its miss history with it.
+func TestWarmDNSMissHistoryIsPrunedWithTheSet(t *testing.T) {
+ hosts := []string{"gone.customer.test"}
+ w := newCertWarm(
+ func() []string { return hosts },
+ func(*tls.ClientHelloInfo) (*tls.Certificate, error) { return &tls.Certificate{}, nil },
+ func(string) bool { return false },
+ nil,
+ nil,
+ )
+ w.pass()
+ hosts = []string{"other.customer.test"}
+ w.pass()
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ if _, ok := w.dnsMisses["gone.customer.test"]; ok {
+ t.Fatal("a host that left the set kept its miss history")
+ }
+}
+
+// The schedule is for NEW orders only. A warmed host's re-arm ignores DNS
+// (TestWarmRenewalReArmIgnoresTheDNSGate), so its resolver being sick must
+// not put it on the schedule either.
+func TestWarmDNSScheduleDoesNotApplyToWarmedHosts(t *testing.T) {
+ pointing := true
+ w := newCertWarm(
+ func() []string { return []string{"www.customer.test"} },
+ func(*tls.ClientHelloInfo) (*tls.Certificate, error) { return &tls.Certificate{}, nil },
+ func(string) bool { return pointing },
+ nil,
+ nil,
+ )
+ w.pass()
+ pointing = false
+ w.pass()
+ if d, ok := w.dnsWait(); ok {
+ t.Fatalf("a warmed host was put on the DNS schedule (re-check in %s)", d)
+ }
+}
+
+// An order is dated when it is placed, after its DNS lookup, not when the
+// pass reached the host: a resolver that takes seconds must not let the
+// order leave the window early.
+func TestWarmOrderIsStampedAfterItsDNSLookup(t *testing.T) {
+ clock := &fakeClock{t: time.Unix(1_800_000_000, 0)}
+ w := newCertWarm(
+ func() []string { return []string{"slow.customer.test"} },
+ func(*tls.ClientHelloInfo) (*tls.Certificate, error) { return &tls.Certificate{}, nil },
+ func(string) bool { clock.advance(10 * time.Second); return true },
+ nil,
+ nil,
+ )
+ w.now = clock.now
+ w.pass()
+ // 61 s after the pass began, 51 s after the order went out.
+ clock.advance(51 * time.Second)
+ if got := w.orderBudget(clock.now()); got != warmOrdersPerPass-1 {
+ t.Fatalf("budget = %d, want %d: the order left the window early", got, warmOrdersPerPass-1)
+ }
+}
+
+// The order cap is a rate over warmCappedDelay, not a count per pass: a
+// second pass straight after a full one places nothing, and comes back soon.
+func TestWarmOrderBudgetSpansPasses(t *testing.T) {
+ clock := &fakeClock{t: time.Unix(1_800_000_000, 0)}
+ var hosts []string
+ for i := 0; i < warmOrdersPerPass; i++ {
+ hosts = append(hosts, string(rune('a'+i))+".customer.test")
+ }
+ // orders counts FIRST asks per host; later asks are renewal re-arms,
+ // which are never capped.
+ var mu sync.Mutex
+ asked := map[string]bool{}
+ var orders atomic.Int32
+ w := newCertWarm(
+ func() []string { return hosts },
+ func(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
+ mu.Lock()
+ defer mu.Unlock()
+ if !asked[h.ServerName] {
+ asked[h.ServerName] = true
+ orders.Add(1)
+ }
+ return &tls.Certificate{}, nil
+ },
+ func(string) bool { return true },
+ nil,
+ nil,
+ )
+ w.now = clock.now
+ // Exactly the budget, nothing skipped: still back soon, because a host
+ // attached a moment later would otherwise wait for the hourly pass.
+ if d := w.pass(); d != warmCappedDelay || orders.Load() != warmOrdersPerPass {
+ t.Fatalf("first pass: delay %s, orders %d; want %s and %d", d, orders.Load(), warmCappedDelay, warmOrdersPerPass)
+ }
+ hosts = append(hosts, "late.customer.test")
+ clock.advance(time.Second)
+ if d := w.pass(); d != warmCappedDelay || orders.Load() != warmOrdersPerPass {
+ t.Fatalf("second pass inside the window: delay %s, orders %d; want %s and still %d", d, orders.Load(), warmCappedDelay, warmOrdersPerPass)
+ }
+ clock.advance(warmCappedDelay)
+ if d := w.pass(); d != warmInterval || orders.Load() != warmOrdersPerPass+1 {
+ t.Fatalf("pass after the window: delay %s, orders %d; want %s and %d", d, orders.Load(), warmInterval, warmOrdersPerPass+1)
+ }
+}
+
+// startWarm runs the warm's loop until the test ends.
+func startWarm(t *testing.T, w *certWarm) {
+ t.Helper()
+ stop := make(chan struct{})
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ w.loop(stop)
+ }()
+ t.Cleanup(func() {
+ close(stop)
+ <-done
+ })
+}
+
+// waitCount polls an atomic counter until it reaches want.
+func waitCount(t *testing.T, n *atomic.Int32, want int32, what string) {
+ t.Helper()
+ deadline := time.Now().Add(2 * time.Second)
+ for n.Load() < want {
+ if time.Now().After(deadline) {
+ t.Fatalf("%s = %d; want %d", what, n.Load(), want)
+ }
+ time.Sleep(time.Millisecond)
+ }
+}
+
+// THE fix. A host that appears in the set between hourly passes is ordered
+// when the warm is woken, not an hour later.
+func TestWarmWakeOrdersANewHostAtOnce(t *testing.T) {
+ var mu sync.Mutex
+ hosts := []string{}
+ var orders atomic.Int32
+ w := newCertWarm(
+ func() []string {
+ mu.Lock()
+ defer mu.Unlock()
+ return append([]string(nil), hosts...)
+ },
+ func(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
+ if h.ServerName == "new.customer.test" {
+ orders.Add(1)
+ }
+ return &tls.Certificate{}, nil
+ },
+ func(string) bool { return true },
+ nil,
+ nil,
+ )
+ var passes atomic.Int32
+ w.passDone = func() { passes.Add(1) }
+ startWarm(t, w)
+ // The boot pass, over an empty set, has FINISHED: passDone runs after
+ // pass() returns, so the host added below cannot be in its snapshot and
+ // only a working wake can order it.
+ waitCount(t, &passes, 1, "passes")
+ mu.Lock()
+ hosts = []string{"new.customer.test"}
+ mu.Unlock()
+ w.nudge()
+ waitCount(t, &orders, 1, "orders for the new host")
+}
+
+// A wake with nothing new in the set runs no pass. Reloads happen on every
+// deploy anywhere in the fleet; each one must not cost a records LIST and a
+// re-arm of every host.
+func TestWarmWakeWithNothingNewRunsNoPass(t *testing.T) {
+ w := newCertWarm(
+ func() []string { return []string{"www.customer.test"} },
+ func(*tls.ClientHelloInfo) (*tls.Certificate, error) { return &tls.Certificate{}, nil },
+ func(string) bool { return true },
+ nil,
+ nil,
+ )
+ var passes atomic.Int32
+ w.passDone = func() { passes.Add(1) }
+ startWarm(t, w)
+ waitCount(t, &passes, 1, "passes")
+ for i := 0; i < 5; i++ {
+ w.nudge()
+ time.Sleep(5 * time.Millisecond)
+ }
+ time.Sleep(20 * time.Millisecond)
+ if got := passes.Load(); got != 1 {
+ t.Fatalf("passes = %d, want 1 — a wake over an already-warmed set ran a pass", got)
+ }
+}
+
+// A non-issuer orders nothing, so a wake there must not run a pass at all.
+func TestWarmWakeOnANonIssuerRunsNoPass(t *testing.T) {
+ w := newCertWarm(
+ func() []string { return []string{"www.customer.test"} },
+ func(*tls.ClientHelloInfo) (*tls.Certificate, error) { return &tls.Certificate{}, nil },
+ func(string) bool { return true },
+ func() (context.Context, bool) { return nil, false },
+ nil,
+ )
+ var passes atomic.Int32
+ w.passDone = func() { passes.Add(1) }
+ startWarm(t, w)
+ waitCount(t, &passes, 1, "passes")
+ w.nudge()
+ time.Sleep(30 * time.Millisecond)
+ if got := passes.Load(); got != 1 {
+ t.Fatalf("passes = %d, want 1 — a non-issuer ran a pass on a wake", got)
+ }
+}
+
+// A host already waiting on its DNS has its own retry schedule. A wake must
+// not run an extra pass for it, or every reload in the fleet would re-check
+// a domain whose owner has not finished their DNS.
+func TestWarmWakeIgnoresAHostAlreadyWaitingOnDNS(t *testing.T) {
+ w := newCertWarm(
+ func() []string { return []string{"www.customer.test"} },
+ func(*tls.ClientHelloInfo) (*tls.Certificate, error) { return &tls.Certificate{}, nil },
+ func(string) bool { return false },
+ nil,
+ nil,
+ )
+ var passes atomic.Int32
+ w.passDone = func() { passes.Add(1) }
+ startWarm(t, w)
+ waitCount(t, &passes, 1, "passes")
+ w.nudge()
+ time.Sleep(30 * time.Millisecond)
+ if got := passes.Load(); got != 1 {
+ t.Fatalf("passes = %d, want 1 — a wake re-checked a host already on its DNS schedule", got)
+ }
+}
+
+// A host in failure backoff is not new either.
+func TestWarmWakeIgnoresAHostInBackoff(t *testing.T) {
+ w := newCertWarm(
+ func() []string { return []string{"bad.customer.test"} },
+ func(*tls.ClientHelloInfo) (*tls.Certificate, error) { return nil, context.DeadlineExceeded },
+ func(string) bool { return true },
+ nil,
+ nil,
+ )
+ var passes atomic.Int32
+ w.passDone = func() { passes.Add(1) }
+ startWarm(t, w)
+ waitCount(t, &passes, 1, "passes")
+ w.nudge()
+ time.Sleep(30 * time.Millisecond)
+ if got := passes.Load(); got != 1 {
+ t.Fatalf("passes = %d, want 1 — a wake retried a host inside its backoff", got)
+ }
+}
+
+// The per-pass order cap is a rate. Hosts the cap skipped look new, so a
+// wake during a backlog must not start another batch before the capped
+// pass's own short delay is up: reloads happen all over the fleet, and each
+// one would otherwise spend another warmOrdersPerPass of the shared ACME
+// account.
+func TestWarmWakeDuringACappedBacklogRunsNoPass(t *testing.T) {
+ var hosts []string
+ for i := 0; i < warmOrdersPerPass+5; i++ {
+ hosts = append(hosts, string(rune('a'+i))+".customer.test")
+ }
+ var orders atomic.Int32
+ w := newCertWarm(
+ func() []string { return hosts },
+ func(*tls.ClientHelloInfo) (*tls.Certificate, error) { orders.Add(1); return &tls.Certificate{}, nil },
+ func(string) bool { return true },
+ nil,
+ nil,
+ )
+ var passes atomic.Int32
+ w.passDone = func() { passes.Add(1) }
+ startWarm(t, w)
+ waitCount(t, &passes, 1, "passes")
+ if !w.hasNewHost() {
+ t.Fatal("precondition: the capped hosts should read as new")
+ }
+ for i := 0; i < 5; i++ {
+ w.nudge()
+ time.Sleep(5 * time.Millisecond)
+ }
+ time.Sleep(20 * time.Millisecond)
+ if got := passes.Load(); got != 1 {
+ t.Fatalf("passes = %d, want 1 — a wake drained the capped backlog early", got)
+ }
+ if got := orders.Load(); got != warmOrdersPerPass {
+ t.Fatalf("orders = %d, want the cap of %d", got, warmOrdersPerPass)
+ }
+}
+
+// The DNS gate reuses the edge set rather than re-reading it from the bucket
+// for every host on every pass. Reading it lists and fetches every box's
+// snapshot and edges file; with the fast DNS-miss schedule, a per-host read
+// would multiply that by every pending domain, every minute.
+func TestDNSGateReusesTheEdgeSet(t *testing.T) {
+ clock := &fakeClock{t: time.Unix(1_800_000_000, 0)}
+ reads := 0
+ gate := dnsGateAt(
+ func(string) ([]string, error) { return []string{"203.0.113.9"}, nil },
+ func() []string { reads++; return []string{"203.0.113.7"} },
+ clock.now,
+ )
+ for i := 0; i < 20; i++ {
+ gate("h" + string(rune('a'+i)) + ".customer.test")
+ }
+ clock.advance(warmEdgeSetTTL - time.Second)
+ gate("again.customer.test")
+ if reads != 1 {
+ t.Fatalf("edge set read %d times inside its TTL, want 1", reads)
+ }
+ clock.advance(2 * time.Second)
+ gate("later.customer.test")
+ if reads != 2 {
+ t.Fatalf("edge set read %d times after its TTL, want 2", reads)
+ }
+}
+
+// An empty edge set read is the fail-closed case. It is reused only briefly,
+// so one pass over many new hosts reads the bucket once while it is down,
+// and the gate opens again soon after the bucket comes back.
+func TestDNSGateReusesAnEmptyEdgeSetOnlyBriefly(t *testing.T) {
+ clock := &fakeClock{t: time.Unix(1_800_000_000, 0)}
+ var set []string
+ reads := 0
+ gate := dnsGateAt(
+ func(string) ([]string, error) { return []string{"203.0.113.7"}, nil },
+ func() []string { reads++; return set },
+ clock.now,
+ )
+ for i := 0; i < 10; i++ {
+ if gate("h" + string(rune('a'+i)) + ".customer.test") {
+ t.Fatal("an empty edge set opened the gate")
+ }
+ }
+ if reads != 1 {
+ t.Fatalf("an empty edge set was read %d times in one burst, want 1", reads)
+ }
+ set = []string{"203.0.113.7"}
+ clock.advance(warmEdgeSetEmptyTTL)
+ if !gate("www.customer.test") {
+ t.Fatal("the empty read was reused past its short window: the gate stayed shut after the edge set came back")
+ }
+}
+
+// loopWarm runs the loop with a fast gate tick, so a test can watch what the
+// tick does without waiting a minute.
+func loopWarm(t *testing.T, w *certWarm) *atomic.Int32 {
+ t.Helper()
+ w.gateTick = 5 * time.Millisecond
+ var passes atomic.Int32
+ w.passDone = func() { passes.Add(1) }
+ startWarm(t, w)
+ waitCount(t, &passes, 1, "passes")
+ return &passes
+}
+
+// leaseWarm is a warm over one already-warmed host plus whatever the test
+// adds, with an issuer gate the test flips. lostSeen is signalled each time
+// the gate is read while the lease is away.
+func leaseWarm(t *testing.T) (w *certWarm, add func(string), issuer *atomic.Bool, lostSeen chan struct{}, orders *atomic.Int32) {
+ t.Helper()
+ var mu sync.Mutex
+ hosts := []string{"old.customer.test"}
+ issuer = &atomic.Bool{}
+ issuer.Store(true)
+ lostSeen = make(chan struct{}, 1)
+ orders = &atomic.Int32{}
+ w = newCertWarm(
+ func() []string {
+ mu.Lock()
+ defer mu.Unlock()
+ return append([]string(nil), hosts...)
+ },
+ func(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
+ if h.ServerName != "old.customer.test" {
+ orders.Add(1)
+ }
+ return &tls.Certificate{}, nil
+ },
+ func(string) bool { return true },
+ func() (context.Context, bool) {
+ if !issuer.Load() {
+ select {
+ case lostSeen <- struct{}{}:
+ default:
+ }
+ return nil, false
+ }
+ return context.Background(), true
+ },
+ nil,
+ )
+ add = func(h string) {
+ mu.Lock()
+ hosts = append(hosts, h)
+ mu.Unlock()
+ }
+ return w, add, issuer, lostSeen, orders
+}
+
+// A box that takes the issuer lease orders within a gate tick, not at its
+// next hourly pass. The hard case is the one a dropped wake leaves behind:
+// the lease goes away, a new host's wake arrives and is refused, and the
+// lease comes back before any gate tick saw it go. The refused wake itself
+// has to count as seeing it go.
+func TestWarmOrdersWhenTheLeaseComesBackBetweenTicks(t *testing.T) {
+ w, add, issuer, lostSeen, orders := leaseWarm(t)
+ w.gateTick = 100 * time.Millisecond
+ var passes atomic.Int32
+ w.passDone = func() { passes.Add(1) }
+ startWarm(t, w)
+ waitCount(t, &passes, 1, "passes")
+ issuer.Store(false)
+ add("new.customer.test")
+ w.nudge()
+ select {
+ case <-lostSeen: // the wake read the gate while the lease was away
+ case <-time.After(2 * time.Second):
+ t.Fatal("the wake never read the gate")
+ }
+ issuer.Store(true)
+ waitCount(t, orders, 1, "orders after the lease came back")
+ waitCount(t, &passes, 2, "passes")
+}
+
+// The gate check keeps its own deadline. Reloads all over the fleet wake the
+// loop far more often than once a minute; if each wake restarted the gate
+// wait, a box that had just taken the lease would never look, and a host
+// already on the DNS schedule (which a wake does not count as new) would
+// wait for the hourly pass.
+func TestWarmGateCheckIsNotPostponedByWakes(t *testing.T) {
+ w, add, issuer, _, orders := leaseWarm(t)
+ w.gateTick = 50 * time.Millisecond
+ var passes atomic.Int32
+ w.passDone = func() { passes.Add(1) }
+ pointing := atomic.Bool{}
+ w.pointsHere = func(h string) bool { return h == "old.customer.test" || pointing.Load() }
+ startWarm(t, w)
+ waitCount(t, &passes, 1, "passes")
+ // A host that misses DNS while this box is the issuer: it goes on the
+ // schedule, a minute out, so a wake does not count it as new.
+ add("pending.customer.test")
+ issuer.Store(false)
+ time.Sleep(150 * time.Millisecond) // a gate tick sees the lease go
+ w.mu.Lock()
+ w.dnsMisses["pending.customer.test"] = dnsMiss{first: time.Now(), next: time.Now().Add(time.Hour)}
+ w.mu.Unlock()
+ pointing.Store(true)
+ issuer.Store(true)
+ stop := make(chan struct{})
+ defer close(stop)
+ go func() {
+ for {
+ select {
+ case <-stop:
+ return
+ case <-time.After(10 * time.Millisecond):
+ w.nudge()
+ }
+ }
+ }()
+ waitCount(t, orders, 1, "orders while wakes kept arriving")
+}
+
+// The loop's DNS probe is what turns a customer finishing their DNS into an
+// order: once the pending host points here, a pass runs and orders it.
+func TestWarmLoopOrdersOnceAPendingHostPoints(t *testing.T) {
+ var pointing atomic.Bool
+ w, clock, _, orders := dnsWarm(t, "www.customer.test", &pointing)
+ passes := loopWarm(t, w)
+ time.Sleep(20 * time.Millisecond)
+ if passes.Load() != 1 {
+ t.Fatalf("passes = %d before the host was due, want 1", passes.Load())
+ }
+ pointing.Store(true)
+ clock.advance(warmDNSRetryFast)
+ waitCount(t, orders, 1, "orders once the host points")
+}
+
+// Losing the lease with a DNS re-check due must not spin the loop until the
+// next gate tick. probeDNS stands down without moving the schedule, so the
+// loop has to stop counting a re-check it cannot run.
+func TestWarmLoopDoesNotSpinOnADueProbeAfterLosingTheLease(t *testing.T) {
+ var issuer atomic.Bool
+ issuer.Store(true)
+ var gateReads atomic.Int32
+ w := newCertWarm(
+ func() []string { return []string{"www.customer.test"} },
+ func(*tls.ClientHelloInfo) (*tls.Certificate, error) { return &tls.Certificate{}, nil },
+ func(string) bool { return false },
+ func() (context.Context, bool) {
+ gateReads.Add(1)
+ return context.Background(), issuer.Load()
+ },
+ nil,
+ )
+ w.gateTick = time.Hour
+ var passes atomic.Int32
+ w.passDone = func() { passes.Add(1) }
+ startWarm(t, w)
+ waitCount(t, &passes, 1, "passes")
+ // Bring the boot pass's re-check forward to just ahead, then make the
+ // loop take its new wait: a wake while still the issuer is dropped (the
+ // host is on the schedule), and the loop recomputes.
+ w.mu.Lock()
+ m := w.dnsMisses["www.customer.test"]
+ m.next = time.Now().Add(40 * time.Millisecond)
+ w.dnsMisses["www.customer.test"] = m
+ w.mu.Unlock()
+ w.nudge()
+ time.Sleep(10 * time.Millisecond)
+ issuer.Store(false) // lost before the re-check comes due
+ time.Sleep(80 * time.Millisecond)
+ before := gateReads.Load()
+ time.Sleep(100 * time.Millisecond)
+ if n := gateReads.Load() - before; n > 5 {
+ t.Fatalf("the gate was read %d times in 100ms: the loop is spinning on a re-check it cannot run", n)
+ }
+}
+
+// A pending host that keeps missing never runs a pass: the probe is DNS-only.
+func TestWarmLoopProbeOfAMissingHostRunsNoPass(t *testing.T) {
+ var pointing atomic.Bool
+ w, clock, checks, _ := dnsWarm(t, "www.customer.test", &pointing)
+ passes := loopWarm(t, w)
+ for i := 0; i < 3; i++ {
+ clock.advance(warmDNSRetryFast)
+ waitCount(t, checks, int32(i+2), "DNS checks")
+ }
+ if passes.Load() != 1 {
+ t.Fatalf("passes = %d, want 1 — probing a missing host ran a full pass", passes.Load())
+ }
+}
+
+// nudge is called from the reload path and the home map's refresh; it must
+// never block them, with or without a loop running.
+func TestWarmNudgeNeverBlocks(t *testing.T) {
+ w := newCertWarm(nil, nil, nil, nil, nil)
+ done := make(chan struct{})
+ go func() {
+ for i := 0; i < 100; i++ {
+ w.nudge()
+ }
+ close(done)
+ }()
+ select {
+ case <-done:
+ case <-time.After(2 * time.Second):
+ t.Fatal("nudge blocked")
+ }
+ var nilWarm *certWarm
+ nilWarm.nudge() // no panic
+}
+
+// The reload hook was a single slot the wildcard manager held. Both it and
+// the warm need it now, so registering a second hook must not drop the first.
+func TestOnReloadKeepsEveryHook(t *testing.T) {
+ e := &Edge{}
+ var a, b atomic.Int32
+ e.OnReload(func() { a.Add(1) })
+ e.OnReload(func() { b.Add(1) })
+ e.runReloadHooks()
+ if a.Load() != 1 || b.Load() != 1 {
+ t.Fatalf("hooks ran a=%d b=%d, want 1 each", a.Load(), b.Load())
+ }
+}
+
+// The home map wakes the warm when the set of hosts homed ELSEWHERE changes.
+// That is how the issuer hears about a custom domain attached on another
+// box: setHostsWake only fires on platform-class names, which never include
+// a custom domain.
+func TestHomeMapServedWakeFiresOnACustomDomain(t *testing.T) {
+ s := meshTestStore(t)
+ putJSON(t, s, "control/edges/annie.json", `{"v":1,"box":"annie","eip":"1.1.1.1","hosts":{}}`)
+ putJSON(t, s, "control/edges/betty.json", `{"v":1,"box":"betty","eip":"2.2.2.2","hosts":{"app.acct.apps.test":{"role":"home","platform":true}}}`)
+ m := newHomeMap(s, "annie")
+ var woke atomic.Int32
+ m.setServedWake(func() { woke.Add(1) })
+ refreshHomeMap(t, m)
+ waitWoke(t, &woke, 1)
+ refreshHomeMap(t, m) // unchanged: no wake
+ time.Sleep(20 * time.Millisecond)
+ if woke.Load() != 1 {
+ t.Fatalf("an unchanged refresh woke the warm (%d)", woke.Load())
+ }
+ // A custom domain attached on betty: unclassed, exact, dialable.
+ putJSON(t, s, "control/edges/betty.json", `{"v":1,"box":"betty","eip":"2.2.2.2","hosts":{"app.acct.apps.test":{"role":"home","platform":true},"www.customer.test":{"role":"home","alias":true}}}`)
+ refreshHomeMap(t, m)
+ waitWoke(t, &woke, 2)
+ // Betty's address moving changes no name: no wake.
+ putJSON(t, s, "control/edges/betty.json", `{"v":1,"box":"betty","eip":"3.3.3.3","hosts":{"app.acct.apps.test":{"role":"home","platform":true},"www.customer.test":{"role":"home","alias":true}}}`)
+ refreshHomeMap(t, m)
+ time.Sleep(20 * time.Millisecond)
+ if woke.Load() != 2 {
+ t.Fatalf("a moved address woke the warm (%d)", woke.Load())
+ }
+ // The platform-class wake and the served wake are separate hooks: setting
+ // one must not replace the other.
+ var platform atomic.Int32
+ m.setHostsWake(func() { platform.Add(1) })
+ putJSON(t, s, "control/edges/betty.json", `{"v":1,"box":"betty","eip":"3.3.3.3","hosts":{"app.acct.apps.test":{"role":"home","platform":true},"www.customer.test":{"role":"home","alias":true},"two.acct.apps.test":{"role":"home","platform":true}}}`)
+ refreshHomeMap(t, m)
+ waitWoke(t, &woke, 3)
+ waitWoke(t, &platform, 1)
+
+ var nilMap *homeMap
+ nilMap.setServedWake(func() {}) // no panic
+}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index c399977de..c7ffc02d2 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -231,11 +231,12 @@ type Edge struct {
// created under logMu.
logMu sync.Mutex
logN map[string]int
- // reloadHook, when set (OnReload), runs after every successful route
- // swap — the wildcard manager recomputes its parent set from it. Atomic
+ // reloadHooks (OnReload) run after every successful route swap: the
+ // wildcard manager recomputes its parent set from them and the cert warm
+ // looks for new hosts (#386). Copy-on-write behind an atomic pointer
// because registration happens in RunWithActivator after Watch may
// already be reloading.
- reloadHook atomic.Pointer[func()]
+ reloadHooks atomic.Pointer[[]func()]
// probers owns the health-probe goroutines for multi-upstream addr routes
// (prober.go) and the live set multiProxy picks from. Created in New,
// BEFORE the startup Reload — Reload calls Sync on it unconditionally and
@@ -1041,16 +1042,36 @@ func (e *Edge) Reload() error {
if e.act != nil {
e.act.RetireExcept(managed)
}
- if fn := e.reloadHook.Load(); fn != nil {
- (*fn)()
- }
+ e.runReloadHooks()
return nil
}
// OnReload registers fn to run after every successful Reload — after the new
// route set is swapped in, so fn sees the post-reload table via current().
+// Additive: every registered hook runs, in registration order. It was a
+// single slot until the cert warm needed it beside the wildcard manager
+// (#386), and a second registration silently dropping the first is exactly
+// the failure that would leave one of them deaf.
func (e *Edge) OnReload(fn func()) {
- e.reloadHook.Store(&fn)
+ for {
+ old := e.reloadHooks.Load()
+ var next []func()
+ if old != nil {
+ next = append(next, (*old)...)
+ }
+ next = append(next, fn)
+ if e.reloadHooks.CompareAndSwap(old, &next) {
+ return
+ }
+ }
+}
+
+func (e *Edge) runReloadHooks() {
+ if hooks := e.reloadHooks.Load(); hooks != nil {
+ for _, fn := range *hooks {
+ fn()
+ }
+ }
}
// logThrottled logs msg the first time key occurs and every 300th time after
@@ -3495,6 +3516,12 @@ func RunWithActivatorReady(args []string, act Activator, cache *Cache, ready fun
e.issuerGate,
store,
)
+ // Woken when its set may have grown (#386), so a custom domain is
+ // ordered seconds after it reaches this box rather than at the next
+ // hourly pass: a local route reload, or a change in the names other
+ // boxes home. A wake with nothing new in the set is dropped.
+ e.OnReload(warm.nudge)
+ e.homes.Load().setServedWake(warm.nudge)
go warm.run()
log.Printf("edge: cert warm on (%s pass) — custom domains are ordered and renewed proactively, not on first handshake", warmInterval)
}
diff --git a/internal/edge/homemap.go b/internal/edge/homemap.go
index 532517459..ab1d9c604 100644
--- a/internal/edge/homemap.go
+++ b/internal/edge/homemap.go
@@ -251,6 +251,12 @@ type homeMap struct {
snap *homeSnapshot
// hostsWake fires after a Refresh that changed the NAME set (setHostsWake).
hostsWake func()
+ // servedWake fires after a Refresh that changed the ServedHosts set
+ // (setServedWake): the cert warm's cue that a custom domain was attached
+ // on another box (#386). Separate from hostsWake because their filters
+ // are opposites: hostsWake ignores exactly the unclassed rows a custom
+ // domain arrives as.
+ servedWake func()
// partialPolls counts polls that could not read (or parse) every object,
// for the first-and-every-tenth log cadence.
partialPolls int
@@ -493,6 +499,7 @@ func (m *homeMap) refreshHosts(ctx context.Context) error {
m.mu.Lock()
m.snap = snap
wake := m.hostsWake
+ served := m.servedWake
m.mu.Unlock()
// A partial read reflects no generation: the file it could not read or
// parse is retried on the next poll, as it always was.
@@ -506,9 +513,39 @@ func (m *homeMap) refreshHosts(ctx context.Context) error {
// that.
go wake()
}
+ if served != nil && !sameServedSet(prev.hosts, snap.hosts) {
+ go served()
+ }
return nil
}
+// sameServedSet reports whether two folds serve the same exact names, by
+// ServedHosts' filter. Addresses and owners moving change nothing here: the
+// warm's question is only which names exist.
+func sameServedSet(a, b map[string]homeEntry) bool {
+ n := 0
+ for h, e := range a {
+ if !servedInput(h, e) {
+ continue
+ }
+ n++
+ if eb, ok := b[h]; !ok || !servedInput(h, eb) {
+ return false
+ }
+ }
+ for h, e := range b {
+ if servedInput(h, e) {
+ n--
+ }
+ }
+ return n == 0
+}
+
+// servedInput is ServedHosts' filter: a dialable, exact name.
+func servedInput(host string, e homeEntry) bool {
+ return e.dial && !strings.HasPrefix(host, "*.")
+}
+
// samePlatformSet reports whether two folds name the same PLATFORM hosts —
// the only names that can move a wildcard parent (homes may differ; an
// unclassed name may come and go).
@@ -626,7 +663,7 @@ func (m *homeMap) ServedHosts() []string {
snap := m.snapshot()
out := make([]string, 0, len(snap.hosts))
for h, e := range snap.hosts {
- if !e.dial || strings.HasPrefix(h, "*.") {
+ if !servedInput(h, e) {
continue
}
out = append(out, h)
@@ -647,6 +684,17 @@ func (m *homeMap) setHostsWake(fn func()) {
m.mu.Unlock()
}
+// setServedWake installs the callback a changed ServedHosts set fires
+// (Refresh), on the same terms as setHostsWake.
+func (m *homeMap) setServedWake(fn func()) {
+ if m == nil {
+ return
+ }
+ m.mu.Lock()
+ m.servedWake = fn
+ m.mu.Unlock()
+}
+
// parseEdgesFile decodes one box's file. A parse failure gets the same
// treatment an unreadable object gets — carry the last good parse forward —
// because a half-written body is no more usable than a body that never
diff --git a/internal/provision/testdata/plan14-root-reads-certwarm-wake.tsv b/internal/provision/testdata/plan14-root-reads-certwarm-wake.tsv
new file mode 100644
index 000000000..5ff2316a4
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-certwarm-wake.tsv
@@ -0,0 +1,7 @@
+# Census overlay certwarm-wake, written by census-propose (#369). census-ruling-certwarm-wake, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-certwarm-wake.md.
+# 2 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@legacy 97744cb60b9da6a17fa7cda135a4be5089e7063c223dc6e747505237fcda681f internal/edge/edge.go Edge.Reload legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-design-edge-rate-limit-358;basis=each route's upstream entry gains rate: e.parseRateSettings(t), the row's rate_limit column parsed once per reload; the one added site is that whole:Route pass of t (parseRateSettings is a new unit, classified in the decisions overlay); no other read added;rev3=census-ruling-certwarm-wake;basis=the single reload hook call becomes runReloadHooks(), which runs every registered hook in order (#386); no read added, same 57 sites (56 before #358 landed on main) registry:Account@18112,registry:Alias@16421,registry:Alias@16508,registry:Alias@16604,registry:FleetBox@5526,registry:Health@7689,registry:Health@7807,registry:Hibernate@12450,registry:Hibernate@14360,registry:Hibernate@6049,registry:Host@12498,registry:Host@14422,registry:Host@14730,registry:Host@14757,registry:Host@15558,registry:Host@15824,registry:Host@16547,registry:Host@6098,registry:Host@8290,registry:Host@8385,registry:Host@8665,registry:Host@8691,registry:Host@8743,registry:Kind@10975,registry:Kind@10997,registry:Kind@12426,registry:Kind@14336,registry:Kind@6025,registry:Kind@8831,registry:Kind@8891,registry:Name@18102,registry:Prefix@15799,registry:Region@2252,registry:Socket@14738,registry:Socket@5633,registry:Socket@6162,registry:Status@1835,registry:Target@15811,registry:Tunnel@4574,registry:Tunnel@4630,registry:Version@10956,registry:Version@11058,whole:Fleet@18052,whole:Fleet@18081,whole:Route@130,whole:Route@14790,whole:Route@14797,whole:Route@14893,whole:Route@4692,whole:Route@5590,whole:Route@6218,whole:Route@648,whole:Route@8808,whole:Route@8881,whole:Route@8941,whole:RouteAlias@16392,whole:RoutePath@15536 95a566d451c6d9c752b64f9d4571129c5f8845e8ce3d52b40bc571019d0be6b8
+@legacy c49a58e4a9e22fcb2a45b4a5d7318e95481fe7743a7ea2941e56b16dd950a802 internal/edge/edge.go RunWithActivatorReady legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-certwarm-wake;basis=registers the cert warm's nudge on OnReload and on the home map's new served-hosts wake (#386); nudge only sends on a buffered channel; no read added, same 5 sites data-literal@129,data-literal@148,data-literal@284,data-literal@417,file:Open@1013 4508e59aa6f0b1107a9a87a5ae02fb1b8933f2a4c13a257d12fad20a8d66e9e8
+internal/edge/edge.go Edge.Reload legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-design-edge-rate-limit-358;basis=each route's upstream entry gains rate: e.parseRateSettings(t), the row's rate_limit column parsed once per reload; the one added site is that whole:Route pass of t (parseRateSettings is a new unit, classified in the decisions overlay); no other read added;rev3=census-ruling-certwarm-wake;basis=the single reload hook call becomes runReloadHooks(), which runs every registered hook in order (#386); no read added, same 57 sites (56 before #358 landed on main) registry:Account@18112,registry:Alias@16421,registry:Alias@16508,registry:Alias@16604,registry:FleetBox@5526,registry:Health@7689,registry:Health@7807,registry:Hibernate@12450,registry:Hibernate@14360,registry:Hibernate@6049,registry:Host@12498,registry:Host@14422,registry:Host@14730,registry:Host@14757,registry:Host@15558,registry:Host@15824,registry:Host@16547,registry:Host@6098,registry:Host@8290,registry:Host@8385,registry:Host@8665,registry:Host@8691,registry:Host@8743,registry:Kind@10975,registry:Kind@10997,registry:Kind@12426,registry:Kind@14336,registry:Kind@6025,registry:Kind@8831,registry:Kind@8891,registry:Name@18102,registry:Prefix@15799,registry:Region@2252,registry:Socket@14738,registry:Socket@5633,registry:Socket@6162,registry:Status@1835,registry:Target@15811,registry:Tunnel@4574,registry:Tunnel@4630,registry:Version@10956,registry:Version@11058,whole:Fleet@18052,whole:Fleet@18081,whole:Route@130,whole:Route@14790,whole:Route@14797,whole:Route@14893,whole:Route@4692,whole:Route@5590,whole:Route@6218,whole:Route@648,whole:Route@8808,whole:Route@8881,whole:Route@8941,whole:RouteAlias@16392,whole:RoutePath@15536 95a566d451c6d9c752b64f9d4571129c5f8845e8ce3d52b40bc571019d0be6b8
+internal/edge/edge.go RunWithActivatorReady legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-certwarm-wake;basis=registers the cert warm's nudge on OnReload and on the home map's new served-hosts wake (#386); nudge only sends on a buffered channel; no read added, same 5 sites data-literal@129,data-literal@148,data-literal@284,data-literal@417,file:Open@1013 4508e59aa6f0b1107a9a87a5ae02fb1b8933f2a4c13a257d12fad20a8d66e9e8
+@coverage internal/edge d6bfcfe62a7530b9e7e13638d0d0851a485e6fb6996b0b85839118c9c01b3c42
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 2256066ba..57f37ea6e 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -24,3 +24,4 @@ plan14-root-reads-plans-4-notices-grace.tsv 43e430a3b3edf9333bfe2c64f24ca9e4c044
plan14-root-reads-design-edge-rate-limit-358-decisions.tsv a067dcd9e32e6be2b7dd9c6a8256d1252ac4c737fd058c430823e382add340c4
plan14-root-reads-design-edge-rate-limit-358.tsv 0c4eabfe38e12b098285bdeb5ceb0b16e5333928f5b02e160a6b16b5fd9ce1e0
plan14-root-reads-plans-4b-after-grace.tsv 0c4eabfe38e12b098285bdeb5ceb0b16e5333928f5b02e160a6b16b5fd9ce1e0
+plan14-root-reads-certwarm-wake.tsv 91204fcbc484343c03bd5ae69e3084055bc519a5b317e2ae3dc49880080764e2