Files
mirror-3x-ui/internal/web/controller/util.go
T
Hamed 0db9503228 fix(nodes): isolate traffic sync and report client apply outcomes (#7308)
Isolate traffic synchronization with bounded round-robin per-node workers, independent maintenance and publication, cancellation and ordered shutdown drain. Recheck online eligibility inside the serialized writer before merging snapshots and retain the latest valid speed sample per node, with expiry and explicit empty publication.

Report direct per-node applied/pending/failed outcomes without changing local-save success semantics. Propagate downstream pending separately from direct ACKs so acknowledged batch items do not abort subsequent work. Integrate live admission into the existing #7314 ordered dispatcher with separate four-second queue and batch budgets, retaining monotonic dirty generations, exclusive full-delete/reconcile turns, durable deletion outbox, generation-matched settlement, cross-node recreation safeguards and targeted fingerprint invalidation. Preserve legacy peer compatibility and update generated API documentation.

Validation: all 12 CI jobs and Docs CI passed on reviewed head d13850474f (runs 46871519847 and 46871519831). PostgreSQL logs confirm eight ordering regressions, including saturation, lost ACK, cross-node recreation and bulk recovery. Author reports make verify, focused SQLite/PostgreSQL race tests, four mixed-version node E2E pairings and Xray E2E. No independent production-scale latency measurement or universal HTTP timeout guarantee.

Residual follow-ups: possible conservative false-pending result when a final full delete settles an intermediate superseded intent on the same node; add per-logical-operation settlement regression. Verify shutdown drain under a blocked writer/maintenance worker. These static-review concerns remain open for follow-up, not demonstrated data loss or a new deadlock.

Refs #7293
2026-12-02 16:47:26 +03:30

117 lines
3.0 KiB
Go

package controller
import (
"fmt"
"net/http"
"path/filepath"
"runtime"
"strings"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/util/clientip"
"github.com/mhsanaei/3x-ui/v3/internal/web/entity"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
"github.com/gin-gonic/gin"
)
// getRemoteIp is the request's client address, the identity the login limiter keys on.
func getRemoteIp(c *gin.Context) string {
return clientip.Resolve(c.Request.RemoteAddr, c.GetHeader("X-Real-IP"), c.GetHeader("X-Forwarded-For"), trustedProxyCIDRs())
}
func isTrustedForwardedRequest(c *gin.Context) bool {
remoteIP, ok := clientip.Parse(c.Request.RemoteAddr)
return ok && clientip.Trusted(remoteIP, trustedProxyCIDRs())
}
func trustedProxyCIDRs() (trusted string) {
trusted = service.DefaultTrustedProxyCIDRs
defer func() {
_ = recover()
}()
settingService := service.SettingService{}
if value, err := settingService.GetTrustedProxyCIDRs(); err == nil && strings.TrimSpace(value) != "" {
trusted = value
}
return trusted
}
// jsonMsg sends a JSON response with a message and error status.
func jsonMsg(c *gin.Context, msg string, err error) {
jsonMsgObj(c, msg, nil, err)
}
// jsonObj sends a JSON response with an object and error status.
func jsonObj(c *gin.Context, obj any, err error) {
jsonMsgObj(c, "", obj, err)
}
func requestErrorContext(c *gin.Context) string {
handler, loc := callerOutsideUtil()
return fmt.Sprintf("[%s %s handler=%s %s]", c.Request.Method, c.Request.URL.Path, handler, loc)
}
func callerOutsideUtil() (string, string) {
var pcs [12]uintptr
n := runtime.Callers(2, pcs[:])
frames := runtime.CallersFrames(pcs[:n])
for {
frame, more := frames.Next()
base := filepath.Base(frame.File)
if base != "util.go" {
name := frame.Function
if idx := strings.LastIndex(name, "/"); idx >= 0 {
name = name[idx+1:]
}
return name, fmt.Sprintf("%s:%d", base, frame.Line)
}
if !more {
break
}
}
return "unknown", "unknown"
}
// jsonMsgObj sends a JSON response with a message, object, and error status.
func jsonMsgObj(c *gin.Context, msg string, obj any, err error) {
m := entity.Msg{
Obj: obj,
}
if err == nil {
m.Success = true
if msg != "" {
m.Msg = msg
}
} else {
m.Success = false
ctx := requestErrorContext(c)
fail := I18nWeb(c, "fail")
errStr := err.Error()
if errStr != "" {
m.Msg = msg + " (" + errStr + ")"
logger.Warningf("%s %s %s: %v", ctx, msg, fail, err)
} else if msg != "" {
m.Msg = msg
logger.Warningf("%s %s %s", ctx, msg, fail)
} else {
m.Msg = I18nWeb(c, "somethingWentWrong")
logger.Warningf("%s %s %s", ctx, m.Msg, fail)
}
}
c.JSON(http.StatusOK, m)
}
// pureJsonMsg sends a pure JSON message response with custom status code.
func pureJsonMsg(c *gin.Context, statusCode int, success bool, msg string) {
c.JSON(statusCode, entity.Msg{
Success: success,
Msg: msg,
})
}
// isAjax checks if the request is an AJAX request.
func isAjax(c *gin.Context) bool {
return c.GetHeader("X-Requested-With") == "XMLHttpRequest"
}