feat: add generic phased background shutdown to managed services

This commit is contained in:
2026-09-25 00:35:59 +08:00
parent adcb6f60b6
commit 16deead70e
37 changed files with 1330 additions and 68 deletions

View File

@@ -227,10 +227,9 @@ func run(ctx context.Context, fn Func) (err error) {
return err
}
// Shutdown stops schedules and submission, then drains accepted jobs. Deadline
// expiry cancels running/queued jobs and returns without waiting for code that
// ignores cancellation. Such code cannot be forcibly stopped by Go.
func (r *Runner) Shutdown(ctx context.Context) error {
// StopAccepting stops schedules and submission without canceling accepted jobs.
// Pair it with Wait to establish completion before releasing dependencies.
func (r *Runner) StopAccepting(ctx context.Context) error {
if ctx == nil {
return errors.New("task: nil context")
}
@@ -242,6 +241,20 @@ func (r *Runner) Shutdown(ctx context.Context) error {
go func() { r.wg.Wait(); r.cancel(); close(r.done) }()
}
r.mu.Unlock()
return nil
}
// Wait joins all workers and schedules after StopAccepting. A canceled context
// cancels work, but callers can wait again to establish actual completion.
func (r *Runner) Wait(ctx context.Context) error {
if ctx == nil {
return errors.New("task: nil context")
}
select {
case <-r.done:
return nil
default:
}
select {
case <-r.done:
return nil
@@ -251,6 +264,14 @@ func (r *Runner) Shutdown(ctx context.Context) error {
}
}
// Shutdown stops admission and waits with the caller's deadline.
func (r *Runner) Shutdown(ctx context.Context) error {
if err := r.StopAccepting(ctx); err != nil {
return err
}
return r.Wait(ctx)
}
func (r *Runner) Close() error {
ctx, cancel := context.WithTimeout(context.Background(), r.config.ShutdownTimeout)
defer cancel()