An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Avoid false failure logs during normal shutdown
Daniele1e6c31b57b7
diff --git a/kernel/util/http_shutdown.go b/kernel/util/http_shutdown.goindex 99d5f10e95..27fdf5ad33 100644--- a/kernel/util/http_shutdown.go+++ b/kernel/util/http_shutdown.go@@ -2,6 +2,8 @@ package utilimport ("context"+ "errors"+ "net""net/http""sync"@@ -18,7 +20,9 @@ func ShutdownHTTPServers(ctx context.Context, servers ...*http.Server) {pending.Add(1)go func(server *http.Server) {defer pending.Done()- if err := server.Shutdown(ctx); err != nil {+ // cmux 的 HTTP/HTTPS listener 共用底层监听器,重复关闭会返回 net.ErrClosed。+ // Shutdown 返回该错误前已等待活跃响应完成,无需再强制关闭。+ if err := server.Shutdown(ctx); err != nil && !errors.Is(err, net.ErrClosed) {logging.LogWarnf("graceful HTTP server shutdown failed: %s", err)_ = server.Close()}diff --git a/kernel/util/http_shutdown_test.go b/kernel/util/http_shutdown_test.goindex d5e55eeea9..78eff5918b 100644--- a/kernel/util/http_shutdown_test.go+++ b/kernel/util/http_shutdown_test.go@@ -3,13 +3,34 @@ package utilimport ("context""io"+ "net""net/http""net/http/httptest"+ "os"+ "path/filepath"+ "strings""testing""time"++ "github.com/siyuan-note/logging"+ "github.com/soheilhy/cmux")func TestShutdownHTTPServersWaitsForResponses(t *testing.T) {+ testShutdownHTTPServersWaitsForResponses(t, false)+}++func TestShutdownHTTPServersWaitsForMultiplexedResponses(t *testing.T) {+ testShutdownHTTPServersWaitsForResponses(t, true)+}++func testShutdownHTTPServersWaitsForResponses(t *testing.T, multiplexed bool) {+ t.Helper()+ originalPath := logging.LogPath+ t.Cleanup(func() { logging.SetLogPath(originalPath) })+ logPath := filepath.Join(t.TempDir(), "shutdown.log")+ logging.SetLogPath(logPath)+release := make(chan struct{})started := make(chan struct{}, 2)shutdownStarted := make(chan struct{}, 2)@@ -18,10 +39,36 @@ func TestShutdownHTTPServersWaitsForResponses(t *testing.T) {<-release_, _ = io.WriteString(w, "exit completed")})- httpServer := httptest.NewServer(handler)- httpsServer := httptest.NewTLSServer(handler)+ httpServer := httptest.NewUnstartedServer(handler)+ httpsServer := httptest.NewUnstartedServer(handler)+ if multiplexed {+ listener, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatal(err)+ }+ m := cmux.New(listener)+ _ = httpServer.Listener.Close()+ _ = httpsServer.Listener.Close()+ httpsServer.Listener = m.Match(cmux.TLS())+ httpServer.Listener = m.Match(cmux.Any())+ serveDone := make(chan struct{})+ go func() {+ _ = m.Serve()+ close(serveDone)+ }()+ t.Cleanup(func() {+ _ = listener.Close()+ select {+ case <-serveDone:+ case <-time.After(5 * time.Second):+ t.Error("multiplexer did not stop")+ }+ })+ }t.Cleanup(httpServer.Close)t.Cleanup(httpsServer.Close)+ httpServer.Start()+ httpsServer.StartTLS()for _, server := range []*httptest.Server{httpServer, httpsServer} {server.Config.RegisterOnShutdown(func() { shutdownStarted <- struct{}{} })}@@ -85,6 +132,13 @@ func TestShutdownHTTPServersWaitsForResponses(t *testing.T) {case <-time.After(5 * time.Second):t.Fatal("server shutdown did not finish after exit responses")}+ data, err := os.ReadFile(logPath)+ if err != nil && !os.IsNotExist(err) {+ t.Fatal(err)+ }+ if strings.Contains(string(data), "graceful HTTP server shutdown failed") {+ t.Fatalf("successful shutdown logged as a failure: %s", data)+ }}func TestShutdownHTTPServersClosesOnTimeout(t *testing.T) {diff --git a/kernel/util/websocket.go b/kernel/util/websocket.goindex a4e72a8a46..96f443f0a1 100644--- a/kernel/util/websocket.go+++ b/kernel/util/websocket.go@@ -25,13 +25,18 @@ import ("time""github.com/88250/gulu"+ "github.com/gorilla/websocket""github.com/olahol/melody""github.com/siyuan-note/eventbus""github.com/siyuan-note/logging")-// LogWebSocketError 记录发送缓冲区满导致的消息丢弃,其他连接错误保留在调试日志中。+// LogWebSocketError 忽略正常关闭,记录消息丢弃警告,其他连接错误保留在调试日志中。func LogWebSocketError(session *melody.Session, channel string, err error) {+ var closeErr *websocket.CloseError+ if errors.As(err, &closeErr) && (closeErr.Code == websocket.CloseNormalClosure || closeErr.Code == websocket.CloseGoingAway) {+ return+ }app, _ := session.Get("app")id, _ := session.Get("id")typ, _ := session.Get("type")diff --git a/kernel/util/websocket_test.go b/kernel/util/websocket_test.goindex c6f5ef0cdf..8a735fc653 100644--- a/kernel/util/websocket_test.go+++ b/kernel/util/websocket_test.go@@ -17,13 +17,64 @@package utilimport (+ "fmt"+ "io"+ "os"+ "path/filepath"+ "strings""sync""testing"+ "github.com/gorilla/websocket""github.com/olahol/melody""github.com/siyuan-note/eventbus"+ "github.com/siyuan-note/logging")+func TestLogWebSocketError(t *testing.T) {+ originalPath := logging.LogPath+ t.Cleanup(func() { logging.SetLogPath(originalPath) })+ session := &melody.Session{}+ session.Set("app", "test-app")+ session.Set("id", "test-id")+ session.Set("type", "main")+ for _, test := range []struct {+ name string+ err error+ want string+ }{+ {name: "normal closure", err: &websocket.CloseError{Code: websocket.CloseNormalClosure}},+ {name: "going away", err: &websocket.CloseError{Code: websocket.CloseGoingAway}},+ {name: "wrapped going away", err: fmt.Errorf("read: %w", &websocket.CloseError{Code: websocket.CloseGoingAway})},+ {name: "abnormal closure", err: &websocket.CloseError{Code: websocket.CloseAbnormalClosure}, want: "D "},+ {name: "protocol error", err: &websocket.CloseError{Code: websocket.CloseProtocolError}, want: "D "},+ {name: "read error", err: io.ErrUnexpectedEOF, want: "D "},+ {name: "buffer full", err: melody.ErrMessageBufferFull, want: "W "},+ {name: "wrapped buffer full", err: fmt.Errorf("write: %w", melody.ErrMessageBufferFull), want: "W "},+ } {+ t.Run(test.name, func(t *testing.T) {+ path := filepath.Join(t.TempDir(), "websocket.log")+ logging.SetLogPath(path)+ LogWebSocketError(session, "test-channel", test.err)+ data, err := os.ReadFile(path)+ if os.IsNotExist(err) && test.want == "" {+ return+ }+ if err != nil {+ t.Fatal(err)+ }+ if test.want == "" {+ t.Fatalf("normal closure logged as a failure: %s", data)+ }+ for _, text := range []string{test.want, `channel="test-channel", app=test-app, id=test-id, type=main`, test.err.Error()} {+ if !strings.Contains(string(data), text) {+ t.Fatalf("missing diagnostic %q: %s", text, data)+ }+ }+ })+ }+}+func TestContextPushMsgIgnoresInvalidContext(t *testing.T) {contexts := []map[string]any{nil,