diff --git a/backend/go.mod b/backend/go.mod index 8ce6304..2d32a42 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -6,6 +6,7 @@ require ( github.com/gin-gonic/gin v1.12.0 github.com/golang-jwt/jwt/v5 v5.3.1 github.com/jackc/pgx/v5 v5.10.0 + github.com/jackc/puddle/v2 v2.2.2 github.com/redis/go-redis/v9 v9.22.0 golang.org/x/crypto v0.56.0 ) @@ -25,7 +26,6 @@ require ( github.com/goccy/go-yaml v1.19.2 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect - github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect diff --git a/backend/internal/api/api.go b/backend/internal/api/api.go index 3fe1740..b4ab45b 100644 --- a/backend/internal/api/api.go +++ b/backend/internal/api/api.go @@ -1,10 +1,17 @@ package api import ( + "errors" + "io" + "log" + "net" "net/http" "strings" + "syscall" "github.com/gin-gonic/gin" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/puddle/v2" "booklib/internal/auth" "booklib/internal/config" @@ -24,6 +31,21 @@ func err(c *gin.Context, status int, code, msg string) { c.AbortWithStatusJSON(status, gin.H{"error": gin.H{"code": code, "message": msg}}) } +// dbErr 统一处理 store 层失败:记日志;连接类错误 503(Service Unavailable),其余 500 +// 注:brief 里的 pgxpool.ErrClosedPool 在 pgx v5 不存在,实际由 puddle 原样透出,用它替代; +// PG 停机时池内连接先收到 SQLSTATE 57P01(administrator shutdown),故把 08xx/57Pxx 也归为 503 +func dbErr(c *gin.Context, e error) { + log.Printf("db: %v", e) + status, code := http.StatusInternalServerError, "internal" + var pgErr *pgconn.PgError + connClass := errors.As(e, &pgErr) && (strings.HasPrefix(pgErr.Code, "08") || strings.HasPrefix(pgErr.Code, "57P")) + if connClass || errors.Is(e, syscall.ECONNREFUSED) || errors.Is(e, io.ErrUnexpectedEOF) || + errors.Is(e, net.ErrClosed) || errors.Is(e, puddle.ErrClosedPool) { + status, code = http.StatusServiceUnavailable, "unavailable" + } + err(c, status, code, "db error") +} + func (a *api) authMw() gin.HandlerFunc { return func(c *gin.Context) { h := c.GetHeader("Authorization") diff --git a/backend/internal/api/auth.go b/backend/internal/api/auth.go index d793521..4330d37 100644 --- a/backend/internal/api/auth.go +++ b/backend/internal/api/auth.go @@ -2,7 +2,6 @@ package api import ( "errors" - "log" "net/http" "time" @@ -28,8 +27,7 @@ func (a *api) login(c *gin.Context) { u, qerr := a.st.GetUserByName(c, req.Username) if qerr != nil { if !errors.Is(qerr, pgx.ErrNoRows) { - log.Printf("db: %v", qerr) - err(c, http.StatusInternalServerError, "internal", "db error") + dbErr(c, qerr) return } // 用户不存在也走一次 bcrypt,防用户名枚举时序差 diff --git a/backend/internal/api/books.go b/backend/internal/api/books.go index c921bca..65a6bd6 100644 --- a/backend/internal/api/books.go +++ b/backend/internal/api/books.go @@ -24,7 +24,7 @@ func (a *api) getBookRow(c *gin.Context, id int64) (store.Book, bool) { err(c, http.StatusNotFound, "not_found", "no such book") return store.Book{}, false } - err(c, http.StatusInternalServerError, "internal", "db error") + dbErr(c, e) return store.Book{}, false } return b, true @@ -87,7 +87,7 @@ func (a *api) listBooks(c *gin.Context) { libID, _ := strconv.ParseInt(c.Query("library"), 10, 64) views, e := a.st.ListBooks(c, libID, c.Query("q"), c.Query("prefix"), uid(c)) if e != nil { - err(c, http.StatusInternalServerError, "internal", "db error") + dbErr(c, e) return } out := make([]gin.H, 0, len(views)) @@ -133,7 +133,7 @@ func (a *api) deleteBook(c *gin.Context) { os.RemoveAll(bookfile.CoverDir(a.cfg.CacheDir, key)) os.RemoveAll(bookfile.PagesDir(a.cfg.CacheDir, key)) if e := a.st.DeleteBook(c, b.ID); e != nil { - err(c, http.StatusInternalServerError, "internal", "db error") + dbErr(c, e) return } c.Status(http.StatusNoContent) diff --git a/backend/internal/api/libraries.go b/backend/internal/api/libraries.go index 171f889..1077587 100644 --- a/backend/internal/api/libraries.go +++ b/backend/internal/api/libraries.go @@ -3,7 +3,6 @@ package api import ( "context" "io" - "log" "net/http" "os" "path/filepath" @@ -31,8 +30,7 @@ func (a *api) libRoot(c *gin.Context, lib store.Library) (string, bool) { func (a *api) listLibraries(c *gin.Context) { libs, e := a.st.ListLibraries(c) if e != nil { - log.Printf("db: %v", e) - err(c, http.StatusInternalServerError, "internal", "db error") + dbErr(c, e) return } out := make([]gin.H, 0, len(libs)) diff --git a/backend/internal/api/progress.go b/backend/internal/api/progress.go index 9aa7337..2252876 100644 --- a/backend/internal/api/progress.go +++ b/backend/internal/api/progress.go @@ -33,7 +33,7 @@ func (a *api) putProgress(c *gin.Context) { return } if e := a.st.UpsertProgress(c, uid(c), b.LibraryID, b.Path, req.Locator, req.Percent); e != nil { - err(c, http.StatusInternalServerError, "internal", "db error") + dbErr(c, e) return } c.Status(http.StatusNoContent) @@ -42,7 +42,7 @@ func (a *api) putProgress(c *gin.Context) { func (a *api) listProgress(c *gin.Context) { rows, e := a.st.ListProgress(c, uid(c)) if e != nil { - err(c, http.StatusInternalServerError, "internal", "db error") + dbErr(c, e) return } out := make([]gin.H, 0, len(rows)) diff --git a/backend/internal/api/router_test.go b/backend/internal/api/router_test.go index 3ca7450..6eb9c1f 100644 --- a/backend/internal/api/router_test.go +++ b/backend/internal/api/router_test.go @@ -1,11 +1,18 @@ package api import ( + "errors" + "fmt" "net/http" "net/http/httptest" + "syscall" "testing" "time" + "github.com/gin-gonic/gin" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/puddle/v2" + "booklib/internal/config" "booklib/internal/redispkg" ) @@ -23,3 +30,23 @@ func TestHealthz(t *testing.T) { t.Fatalf("healthz = %d, want 200", w.Code) } } + +func TestDBErrStatus(t *testing.T) { + for _, tc := range []struct { + e error + want int + }{ + {&pgconn.PgError{Code: "57P01"}, http.StatusServiceUnavailable}, // PG 停机:池内连接被服务端断 + {&pgconn.PgError{Code: "08006"}, http.StatusServiceUnavailable}, + {fmt.Errorf("dial: %w", syscall.ECONNREFUSED), http.StatusServiceUnavailable}, + {puddle.ErrClosedPool, http.StatusServiceUnavailable}, + {errors.New("boom"), http.StatusInternalServerError}, + } { + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + dbErr(c, tc.e) + if w.Code != tc.want { + t.Errorf("dbErr(%v) = %d, want %d", tc.e, w.Code, tc.want) + } + } +} diff --git a/backend/internal/api/users.go b/backend/internal/api/users.go index 2778d90..c589d57 100644 --- a/backend/internal/api/users.go +++ b/backend/internal/api/users.go @@ -2,7 +2,6 @@ package api import ( "errors" - "log" "net/http" "strconv" "time" @@ -22,8 +21,7 @@ func isUnique(e error) bool { func (a *api) listUsers(c *gin.Context) { users, e := a.st.ListUsers(c) if e != nil { - log.Printf("db: %v", e) - err(c, http.StatusInternalServerError, "internal", "db error") + dbErr(c, e) return } out := make([]gin.H, 0, len(users)) @@ -59,7 +57,7 @@ func (a *api) createUser(c *gin.Context) { err(c, http.StatusConflict, "exists", "username taken") return } - err(c, http.StatusBadRequest, "bad_request", "invalid input") + dbErr(c, e) return } c.JSON(http.StatusCreated, gin.H{"id": id, "username": req.Username, "role": req.Role}) @@ -81,7 +79,7 @@ func (a *api) deleteUser(c *gin.Context) { err(c, http.StatusNotFound, "not_found", "no such user") return } - err(c, http.StatusInternalServerError, "internal", "db error") + dbErr(c, e) return } if target.Role == "admin" { @@ -92,7 +90,7 @@ func (a *api) deleteUser(c *gin.Context) { } } if e := a.st.DeleteUser(c, id); e != nil { - err(c, http.StatusInternalServerError, "internal", "db error") + dbErr(c, e) return } c.Status(http.StatusNoContent)