1
0
mirror of https://github.com/go-kratos/kratos.git synced 2025-09-16 09:16:35 +02:00

fix: honor shutdown timeout when provided context already canceled (#3695)

This commit is contained in:
Nathan Baulch
2025-09-03 12:53:06 +10:00
committed by GitHub
parent 2c5e98d294
commit 5bcf5bbe27
3 changed files with 25 additions and 3 deletions

2
app.go
View File

@@ -102,7 +102,7 @@ func (a *App) Run() error {
server := srv
eg.Go(func() error {
<-ctx.Done() // wait for stop signal
stopCtx := octx
stopCtx := context.WithoutCancel(octx)
if a.opts.stopTimeout > 0 {
var cancel context.CancelFunc
stopCtx, cancel = context.WithTimeout(stopCtx, a.opts.stopTimeout)

View File

@@ -283,3 +283,18 @@ func TestApp_Context(t *testing.T) {
})
}
}
func TestApp_ContextCanceled(t *testing.T) {
ctx, stop := context.WithCancel(context.Background())
stopFn := func(ctx context.Context) error {
select {
case <-ctx.Done():
t.Fatal("context should not be done yet")
default:
}
return nil
}
app := New(Context(ctx), Server(&mockServer{stopFn: stopFn}), StopTimeout(time.Hour))
time.AfterFunc(time.Millisecond*10, stop)
_ = app.Run()
}

View File

@@ -86,10 +86,17 @@ func TestLogger(t *testing.T) {
}
}
type mockServer struct{}
type mockServer struct {
stopFn func(context.Context) error
}
func (m *mockServer) Start(_ context.Context) error { return nil }
func (m *mockServer) Stop(_ context.Context) error { return nil }
func (m *mockServer) Stop(ctx context.Context) error {
if m.stopFn != nil {
return m.stopFn(ctx)
}
return nil
}
func TestServer(t *testing.T) {
o := &options{}