mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-04 16:34:52 +03:00
fix(inbounds): refresh write deadlines for peer exports
This commit is contained in:
@@ -88,7 +88,7 @@ func (a *InboundController) initRouter(g *gin.RouterGroup) {
|
||||
g.GET("/allLinks", a.getAllInboundLinks)
|
||||
g.GET("/get/:id", a.getInbound)
|
||||
g.GET("/:id/info", a.getInboundInfo)
|
||||
g.GET("/:id/peerExport", a.exportInboundPeers)
|
||||
g.GET(inboundPeerExportRoute, a.exportInboundPeers)
|
||||
g.GET("/:id/fallbacks", a.getFallbacks)
|
||||
g.GET("/amneziawgKernelReadiness", a.getAmneziaWGKernelReadiness)
|
||||
|
||||
|
||||
@@ -2,9 +2,12 @@ package controller
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
@@ -13,6 +16,23 @@ import (
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/session"
|
||||
)
|
||||
|
||||
const (
|
||||
inboundPeerExportRoute = "/:id/peerExport"
|
||||
peerExportWriterKey = "inboundPeerExportResponseController"
|
||||
peerExportWriteTimeout = 30 * time.Second
|
||||
)
|
||||
|
||||
// CaptureInboundPeerExportWriter preserves access to the transport's deadlines.
|
||||
// Register it before gzip, whose writer does not expose the underlying writer.
|
||||
func CaptureInboundPeerExportWriter(basePath string) gin.HandlerFunc {
|
||||
route := strings.TrimRight(basePath, "/") + "/panel/api/inbounds" + inboundPeerExportRoute
|
||||
return func(c *gin.Context) {
|
||||
if c.FullPath() == route {
|
||||
c.Set(peerExportWriterKey, http.NewResponseController(c.Writer))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *InboundController) getInboundInfo(c *gin.Context) {
|
||||
user := session.GetLoginUser(c)
|
||||
if user == nil {
|
||||
@@ -42,14 +62,24 @@ func (a *InboundController) exportInboundPeers(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
c.Header("Cache-Control", "no-store")
|
||||
response, _ := c.Get(peerExportWriterKey)
|
||||
deadlines, _ := response.(*http.ResponseController)
|
||||
if deadlines == nil {
|
||||
deadlines = http.NewResponseController(c.Writer)
|
||||
}
|
||||
enc := json.NewEncoder(c.Writer)
|
||||
err = a.inboundService.WalkInboundPeerPages(c.Request.Context(), user.Id, id, func(page *service.InboundInfoPage) error {
|
||||
// A slow but progressing export can exceed the server's whole-response
|
||||
// deadline. Refresh the budget for each page, including its flush.
|
||||
if err := deadlines.SetWriteDeadline(time.Now().Add(peerExportWriteTimeout)); err != nil && !errors.Is(err, http.ErrNotSupported) {
|
||||
return err
|
||||
}
|
||||
c.Header("Content-Type", "application/x-ndjson")
|
||||
if err := enc.Encode(page); err != nil {
|
||||
return err
|
||||
}
|
||||
c.Writer.Flush()
|
||||
return nil
|
||||
return c.Request.Context().Err()
|
||||
})
|
||||
if err == nil || c.Request.Context().Err() != nil {
|
||||
return
|
||||
|
||||
@@ -1,18 +1,23 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
gingzip "github.com/gin-contrib/gzip"
|
||||
"github.com/gin-contrib/sessions"
|
||||
"github.com/gin-contrib/sessions/cookie"
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -25,7 +30,7 @@ import (
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/session"
|
||||
)
|
||||
|
||||
func newInboundInfoTestRouter(t *testing.T) *gin.Engine {
|
||||
func newInboundInfoTestRouter(t *testing.T, middleware ...gin.HandlerFunc) *gin.Engine {
|
||||
t.Helper()
|
||||
cleanup, err := testpg.IsolatePackage("inbound_info")
|
||||
if err != nil {
|
||||
@@ -34,6 +39,7 @@ func newInboundInfoTestRouter(t *testing.T) *gin.Engine {
|
||||
t.Cleanup(cleanup)
|
||||
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
|
||||
router := gin.New()
|
||||
router.Use(middleware...)
|
||||
router.Use(sessions.Sessions("3x-ui", cookie.NewStore([]byte("inbound-info-test-secret"))))
|
||||
router.Use(func(c *gin.Context) {
|
||||
if c.Query("anonymous") != "true" {
|
||||
@@ -44,6 +50,103 @@ func newInboundInfoTestRouter(t *testing.T) *gin.Engine {
|
||||
return router
|
||||
}
|
||||
|
||||
type delayedExportListener struct {
|
||||
net.Listener
|
||||
delay time.Duration
|
||||
}
|
||||
|
||||
func (l delayedExportListener) Accept() (net.Conn, error) {
|
||||
conn, err := l.Listener.Accept()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &delayedExportConn{Conn: conn, delay: l.delay}, nil
|
||||
}
|
||||
|
||||
type delayedExportConn struct {
|
||||
net.Conn
|
||||
firstWrite sync.Once
|
||||
delay time.Duration
|
||||
}
|
||||
|
||||
func (c *delayedExportConn) Write(p []byte) (int, error) {
|
||||
c.firstWrite.Do(func() { time.Sleep(c.delay) })
|
||||
return c.Conn.Write(p)
|
||||
}
|
||||
|
||||
func TestInboundPeerExportOutlastsServerWriteTimeout(t *testing.T) {
|
||||
router := newInboundInfoTestRouter(t, CaptureInboundPeerExportWriter("/"), gingzip.Gzip(gingzip.DefaultCompression))
|
||||
var payload strings.Builder
|
||||
payload.WriteString(`{"secretKey":"server-key","clients":[`)
|
||||
for i := range 103 {
|
||||
if i > 0 {
|
||||
payload.WriteByte(',')
|
||||
}
|
||||
fmt.Fprintf(&payload, `{"email":"client-%05d","privateKey":"secret-%05d"}`, i, i)
|
||||
}
|
||||
payload.WriteString(`]}`)
|
||||
inbound := model.Inbound{UserId: 1, Protocol: model.WireGuard, Tag: "slow-peer-export", Port: 50134, Settings: payload.String()}
|
||||
if err := database.GetDB().Create(&inbound).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
const serverTimeout = 200 * time.Millisecond
|
||||
for _, encoding := range []string{"identity", "gzip"} {
|
||||
t.Run(encoding, func(t *testing.T) {
|
||||
server := httptest.NewUnstartedServer(router)
|
||||
server.Config.WriteTimeout = serverTimeout
|
||||
// Delay the first network write beyond the server's regular deadline.
|
||||
server.Listener = delayedExportListener{Listener: server.Listener, delay: 2 * serverTimeout}
|
||||
server.Start()
|
||||
defer server.Close()
|
||||
client := server.Client()
|
||||
client.Timeout = 5 * time.Second
|
||||
req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, fmt.Sprintf("%s/panel/api/inbounds/%d/peerExport", server.URL, inbound.Id), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Accept-Encoding", encoding)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("export failed after the regular write timeout: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK || resp.Header.Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("export response: status %d, headers %v", resp.StatusCode, resp.Header)
|
||||
}
|
||||
|
||||
var body io.Reader = resp.Body
|
||||
if encoding == "gzip" {
|
||||
if resp.Header.Get("Content-Encoding") != "gzip" {
|
||||
t.Fatal("export did not retain gzip compression")
|
||||
}
|
||||
compressed, err := gzip.NewReader(body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer compressed.Close()
|
||||
body = compressed
|
||||
}
|
||||
d := json.NewDecoder(body)
|
||||
received := 0
|
||||
for {
|
||||
var page service.InboundInfoPage
|
||||
err := d.Decode(&page)
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
if err != nil || page.PeerOffset != received || page.TotalPeers != 103 {
|
||||
t.Fatalf("export lost its position at %d: %v", received, err)
|
||||
}
|
||||
received += checkInboundPeerPage(t, page, received)
|
||||
}
|
||||
if received != 103 {
|
||||
t.Fatalf("export returned %d peers, want 103", received)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func getInboundInfoTestResponse(router *gin.Engine, tail string) *httptest.ResponseRecorder {
|
||||
out := httptest.NewRecorder()
|
||||
router.ServeHTTP(out, httptest.NewRequest(http.MethodGet, "/panel/api/inbounds/"+tail, nil))
|
||||
|
||||
@@ -207,6 +207,7 @@ func (s *Server) initRouter() (*gin.Engine, error) {
|
||||
return nil, err
|
||||
}
|
||||
assetsBasePath := basePath + "assets/"
|
||||
engine.Use(controller.CaptureInboundPeerExportWriter(basePath))
|
||||
// The bundles are served below from a gzip copy made once per file: compressing them
|
||||
// per request lets every stalled download pin its own compressor until WriteTimeout.
|
||||
engine.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithExcludedPaths([]string{assetsBasePath})))
|
||||
|
||||
Reference in New Issue
Block a user