完善续期调度生命周期和Web开关配置

This commit is contained in:
xuans committed 2026-08-31 01:09:04 +08:00
1 parent 1f987eb8be
commit f6ce85b174
7 files changed
+129 -5

No files matched your search

+38 -4
View File
@@ -36,6 +36,8 @@ type RenewalScheduler struct {
policyMu sync.RWMutex
runMu sync.Mutex
running bool
cancel context.CancelFunc
done chan struct{}
wake chan struct{}
}
@@ -138,20 +140,31 @@ func (s *RenewalScheduler) Start(ctx context.Context) {
if s == nil {
return
}
if ctx == nil {
ctx = context.Background()
}
runCtx, cancel := context.WithCancel(ctx)
s.mu.Lock()
if s.running {
s.mu.Unlock()
cancel()
return
}
s.running = true
s.cancel = cancel
s.done = make(chan struct{})
done := s.done
s.mu.Unlock()
go func() {
defer func() {
s.mu.Lock()
s.running = false
s.cancel = nil
s.done = nil
s.mu.Unlock()
close(done)
}()
report, err := s.RunOnce(ctx)
report, err := s.RunOnce(runCtx)
for {
interval := s.Policy().CheckInterval
if err == nil && report.NearExpiry > 0 {
@@ -159,7 +172,7 @@ func (s *RenewalScheduler) Start(ctx context.Context) {
}
timer := time.NewTimer(interval)
select {
case <-ctx.Done():
case <-runCtx.Done():
if !timer.Stop() {
<-timer.C
}
@@ -167,14 +180,35 @@ func (s *RenewalScheduler) Start(ctx context.Context) {
case <-timer.C:
case <-s.wake:
}
if ctx.Err() != nil {
if runCtx.Err() != nil {
return
}
report, err = s.RunOnce(ctx)
report, err = s.RunOnce(runCtx)
}
}()
}
// Stop 停止后台续期调度并等待当前检查安全退出。
func (s *RenewalScheduler) Stop() {
if s == nil {
return
}
s.mu.Lock()
if !s.running {
s.mu.Unlock()
return
}
cancel := s.cancel
done := s.done
s.mu.Unlock()
if cancel != nil {
cancel()
}
if done != nil {
<-done
}
}
func (s *RenewalScheduler) issueWithRetry(ctx context.Context, domainID string, urgent bool, policy RenewalPolicy) error {
attempts := 1
if urgent {
@@ -165,3 +165,34 @@ func TestRenewalSchedulerUpdatePolicyWakesRunningScheduler(t *testing.T) {
t.Fatal("\u66f4\u65b0\u7eed\u671f\u7b56\u7565\u540e\u8c03\u5ea6\u5668\u672a\u88ab\u7acb\u5373\u5524\u9192")
}
}
func TestRenewalSchedulerStopStopsRunningScheduler(t *testing.T) {
lister := &wakeRenewalLister{calls: make(chan struct{}, 4)}
scheduler := NewRenewalSchedulerWithPolicy(lister, &renewalService{}, RenewalPolicy{
CheckInterval: time.Hour,
RetryInterval: time.Nanosecond,
})
scheduler.Start(context.Background())
select {
case <-lister.calls:
case <-time.After(time.Second):
t.Fatal("续期调度器启动后未执行首次检查")
}
scheduler.Stop()
scheduler.UpdatePolicy(RenewalPolicy{CheckInterval: time.Hour})
select {
case <-lister.calls:
t.Fatal("续期调度器停止后不应继续执行检查")
case <-time.After(30 * time.Millisecond):
}
}
func TestRenewalSchedulerStopIsIdempotent(t *testing.T) {
scheduler := NewRenewalSchedulerWithPolicy(&wakeRenewalLister{calls: make(chan struct{}, 1)}, &renewalService{}, RenewalPolicy{CheckInterval: time.Hour})
scheduler.Stop()
scheduler.Stop()
scheduler.Start(context.Background())
scheduler.Stop()
scheduler.Stop()
}