fix(backend): dbErr 503 degradation for connection-class DB errors

This commit is contained in:
2026-09-06 19:53:19 +08:00
parent 04095b5438
commit a11bf28155
8 changed files with 61 additions and 18 deletions
+22
View File
@@ -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")
+1 -3
View File
@@ -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,防用户名枚举时序差
+3 -3
View File
@@ -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)
+1 -3
View File
@@ -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))
+2 -2
View File
@@ -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))
+27
View File
@@ -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)
}
}
}
+4 -6
View File
@@ -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)